Created
May 25, 2021 01:34
-
-
Save bgoonz/36edf2915f3961ba378719e086900f79 to your computer and use it in GitHub Desktop.
python scripts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Mixed sorting | |
""" | |
Given a list of integers nums, sort the array such that: | |
All even numbers are sorted in increasing order | |
All odd numbers are sorted in decreasing order | |
The relative positions of the even and odd numbers remain the same | |
Example 1 | |
Input | |
nums = [8, 13, 11, 90, -5, 4] | |
Output | |
[4, 13, 11, 8, -5, 90] | |
Explanation | |
The even numbers are sorted in increasing order, the odd numbers are sorted in | |
decreasing number, and the relative positions were | |
[even, odd, odd, even, odd, even] and remain the same after sorting. | |
""" | |
# solution | |
import unittest | |
def mixed_sorting(nums): | |
positions = [] | |
odd = [] | |
even = [] | |
sorted_list = [] | |
for i in nums: | |
if i%2 == 0: | |
even.append(i) | |
positions.append("E") | |
else: | |
odd.append(i) | |
positions.append("O") | |
even.sort() | |
odd.sort() | |
odd.reverse() | |
j,k = 0,0 | |
for i in range(len(nums)): | |
if positions[i] == "E": | |
while j < len(even): | |
sorted_list.append(even[j]) | |
j += 1 | |
break | |
else: | |
while k < len(odd): | |
sorted_list.append(odd[k]) | |
k += 1 | |
break | |
return sorted_list | |
# DO NOT TOUCH THE BELOW CODE | |
class TestMixedSorting(unittest.TestCase): | |
def test_1(self): | |
self.assertEqual(mixed_sorting( | |
[8, 13, 11, 90, -5, 4]), [4, 13, 11, 8, -5, 90]) | |
def test_2(self): | |
self.assertEqual(mixed_sorting([1, 2, 3, 6, 5, 4]), [5, 2, 3, 4, 1, 6]) | |
if __name__ == '__main__': | |
unittest.main(verbosity=2) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import turtle | |
t = turtle.Turtle() | |
t.circle(20) | |
t1=turtle.Turtle() | |
t1.circle(25) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
t = turtle.Turtle() | |
t.circle(50) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Problem: | |
The prime factors of 13195 are 5,7,13 and 29. What is the largest prime factor | |
of a given number N? | |
e.g. for 10, largest prime factor = 5. For 17, largest prime factor = 17. | |
""" | |
# def solution(n: int) -> int: | |
def solution(n: int = 600851475143) -> int: | |
"""Returns the largest prime factor of a given number n. | |
>>> solution(13195) | |
29 | |
>>> solution(10) | |
5 | |
>>> solution(17) | |
17 | |
>>> solution(3.4) | |
3 | |
>>> solution(0) | |
Traceback (most recent call last): | |
... | |
ValueError: Parameter n must be greater or equal to one. | |
>>> solution(-17) | |
Traceback (most recent call last): | |
... | |
ValueError: Parameter n must be greater or equal to one. | |
>>> solution([]) | |
Traceback (most recent call last): | |
... | |
TypeError: Parameter n must be int or passive of cast to int. | |
>>> solution("asd") | |
Traceback (most recent call last): | |
... | |
TypeError: Parameter n must be int or passive of cast to int. | |
""" | |
try: | |
n = int(n) | |
except (TypeError, ValueError): | |
raise TypeError("Parameter n must be int or passive of cast to int.") | |
if n <= 0: | |
raise ValueError("Parameter n must be greater or equal to one.") | |
i = 2 | |
ans = 0 | |
if n == 2: | |
return 2 | |
while n > 2: | |
while n % i != 0: | |
i += 1 | |
ans = i | |
while n % i == 0: | |
n = n / i | |
i += 1 | |
return int(ans) | |
if __name__ == "__main__": | |
# print(solution(int(input().strip()))) | |
import doctest | |
doctest.testmod() | |
print(solution(int(input().strip()))) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
pwd="AKS2608" #any password u want to set | |
def IInd_func(): | |
count1=0 | |
for j in range(5): | |
a=0 | |
count=0 | |
user_pwd = input("") #password you remember | |
for i in range(len(pwd)): | |
if user_pwd[i] == pwd[a]: #comparing remembered pwd with fixed pwd | |
a +=1 | |
count+=1 | |
if count==len(pwd): | |
print("correct pwd") | |
break | |
else: | |
count1 += 1 | |
print("not correct") | |
if count1==5: | |
time.sleep(30) | |
IInd_func() | |
IInd_func() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Python3 program to add two numbers | |
number1 = input("First number: ") | |
number2 = input("\nSecond number: ") | |
# Adding two numbers | |
# User might also enter float numbers | |
sum = float(number1) + float(number2) | |
# Display the sum | |
# will print value in float | |
print("The sum of {0} and {1} is {2}" .format(number1, number2, sum)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
num1 = 15 | |
num2 = 12 | |
# Adding two nos | |
sum = num1 + num2 | |
# printing values | |
print("Sum of {0} and {1} is {2}" .format(num1, num2, sum)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This program adds two numbers | |
num1 = 1.5 | |
num2 = 6.3 | |
# Add two numbers | |
sum = num1 + num2 | |
# Display the sum | |
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
num1 = 1.5 | |
num2 = 6.3 | |
sum = num1 + num2 | |
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This program adds two numbers | |
num1 = 1.5 | |
num2 = 6.3 | |
# Add two numbers | |
sum = num1 + num2 | |
# Display the sum | |
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This program adds two numbers | |
num1 = 1.5 | |
num2 = 6.3 | |
# Add two numbers | |
sum = num1 + num2 | |
# Display the sum | |
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node: | |
def __init__(self, data): | |
self.data = data | |
self.next = None | |
class Linked_List: | |
def __init__(self): | |
self.head = None | |
def Insert_At_Beginning(self, new_data): | |
new_node = Node(new_data) | |
if self.head is None: | |
self.head = new_node | |
return | |
new_node.next = self.head | |
self.head = new_node | |
def Add_two_no(self, First, Second): | |
prev = None | |
temp = None | |
carry = 0 | |
while First is not None or Second is not None: | |
first_data = 0 if First is None else First.data | |
second_data = 0 if Second is None else Second.data | |
Sum = carry+first_data+second_data | |
carry = 1 if Sum >= 10 else 0 | |
Sum = Sum if Sum < 10 else Sum % 10 | |
temp = Node(Sum) | |
if self.head is None: | |
self.head = temp | |
else: | |
prev.next = temp | |
prev = temp | |
if First is not None: | |
First = First.next | |
if Second is not None: | |
Second = Second.next | |
if carry > 0: | |
temp.next = Node(carry) | |
def Display(self): | |
temp = self.head | |
while(temp): | |
print(temp.data, "->", end=" ") | |
temp = temp.next | |
print("None") | |
if __name__ == "__main__": | |
First = Linked_List() | |
Second = Linked_List() | |
First.Insert_At_Beginning(6) | |
First.Insert_At_Beginning(4) | |
First.Insert_At_Beginning(9) | |
Second.Insert_At_Beginning(2) | |
Second.Insert_At_Beginning(2) | |
print("First Linked List: ") | |
First.Display() | |
print("Second Linked List: ") | |
Second.Display() | |
Result = Linked_List() | |
Result.Add_two_no(First.head, Second.head) | |
print("Final Result: ") | |
Result.Display() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
print() | |
print() | |
a=True | |
while a==True: | |
number1=int(input("enter first number:")) | |
number2=int(input("enter second number:")) | |
number3=int(input("enter third number:")) | |
sum=number1+number2+number3 | |
print() | |
print("\t\t======================================") | |
print() | |
print("Addition of three numbers is"," :-- ",sum) | |
print() | |
print("\t\t======================================") | |
print() | |
d=input("Do tou want to do it again ?? Y / N -- ").lower() | |
if d=='y': | |
print() | |
print("\t\t======================================") | |
print() | |
continue | |
else: | |
exit() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Python Program to Add Two Numbers | |
a = int(input("enter first number: ")) | |
b = int(input("enter second number: ")) | |
sum = a + b | |
print("sum:", sum) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def Repeat(x): | |
_size = len(x) | |
repeated = [] | |
for i in range(_size): | |
k = i + 1 | |
for j in range(k, _size): | |
if x[i] == x[j] and x[i] not in repeated: | |
repeated.append(x[i]) | |
return repeated | |
list1 = [10, 20, 30, 20, 20, 30, 40, | |
50, -20, 60, 60, -20, -20] | |
print(Repeat(list1)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import time | |
import requests | |
import unidecode | |
from flask import Flask | |
from flask_ask import Ask, question, statement | |
app = Flask(__name__) | |
ask = Ask(app, "/reddit_reader") | |
def get_headlines(): | |
user_pass_dict = {'user': 'USERNAME', 'passwd': "PASSWORD", 'api_type': 'json'} | |
sess = requests.Session() | |
sess.headers.update({'User-Agent': 'I am testing Alexa: nobi'}) | |
sess.post("https://www.reddit.com/api/login/", data=user_pass_dict) | |
time.sleep(1) | |
url = "https://reddit.com/r/worldnews/.json?limit=10" | |
html = sess.get(url) | |
data = json.loads(html.content.decode("utf-8")) | |
titles = [unidecode.unidecode(listing['data']['title']) for listing in data['data']['children']] | |
titles = '... '.join([i for i in titles]) | |
return titles | |
@app.route("/") | |
def homepage(): | |
return "hi there!" | |
@ask.launch | |
def start_skill(): | |
welcome_message = "Hello there, would you like to hear the news?" | |
return question(welcome_message) | |
@ask.intent("YesIntent") | |
def share_headlines(): | |
headlines = get_headlines() | |
headline_msg = "The current world news headlines are {}".format(headlines) | |
return statement(headline_msg) | |
@ask.intent("NooIntent") | |
def no_intent(): | |
bye_text = "I am not sure why you then turned me on. Anyways, bye for now!" | |
return statement(bye_text) | |
if __name__ == "__main__": | |
app.run(port=8000, debug=True) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
a = 5 | |
b = 6 | |
c = 7 | |
# a = float(input('Enter first side: ')) | |
# b = float(input('Enter second side: ')) | |
# c = float(input('Enter third side: ')) | |
# calculate the semi-perimeter | |
s = (a + b + c) / 2 | |
# calculate the area | |
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5 | |
print('The area of the triangle is %0.2f' %area) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Python Program to find the area of triangle when all three side-lengths are known! | |
a = 5 | |
b = 6 | |
c = 7 | |
# Uncomment below to take inputs from the user | |
# a = float(input('Enter first side: ')) | |
# b = float(input('Enter second side: ')) | |
# c = float(input('Enter third side: ')) | |
# calculate the semi-perimeter | |
s = (a + b + c) / 2 | |
# calculate the area | |
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5 | |
print('The area of the triangle is %0.2f' %area) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def sumOfSeries(n): | |
x = (n * (n + 1) / 2) | |
return (int)(x * x) | |
# Driver Function | |
n = 5 | |
print(sumOfSeries(n)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
num=int(input("enter 1-digit number:")) | |
f=num | |
sum=0 | |
while (f>0): | |
a=f%10 | |
f=int(f/10) | |
sum=sum+(a**3) | |
if(sum==num): | |
print("it is an armstrong number:",num) | |
else: | |
print("it is not an armstrong number:",num) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
num=int(input("Enter a number:")) | |
sum=0 | |
temp=num | |
while temp>0: | |
digit=temp%10 | |
sum+=digit**3 | |
temp//=10 | |
if num==sum: | |
print(num,"is an Armstrong number") | |
else: | |
print(num,"is not an Armstrong number") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Python program to check if the number is an Armstrong number or not | |
# take input from the user | |
num = int(input("Enter a number: ")) | |
# initialize sum | |
sum = 0 | |
# find the sum of the cube of each digit | |
temp = num | |
while temp > 0: | |
digit = temp % 10 | |
sum += digit ** 3 | |
temp //= 10 | |
# display the result | |
if num == sum: | |
print(num,"is an Armstrong number") | |
else: | |
print(num,"is not an Armstrong number") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Program to find the ASCII value of the given character | |
c = 'p' | |
print("The ASCII value of '" + c + "' is", ord(c)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import print_function | |
import sys | |
lines = [] # contains the lines of the file. | |
tokens = [] # contains all tokens of the source code. | |
# register eax, ebx,..., ecx | |
eax = 0 | |
ebx = 0 | |
ecx = 0 | |
edx = 0 | |
# status register | |
zeroFlag = False | |
# stack data structure | |
# push --> append | |
# pop --> pop | |
stack = [] | |
# jump link table | |
jumps = {} | |
# variable table | |
variables = {} | |
# return stack for subprograms | |
returnStack = [] | |
# simple exception class | |
class InvalidSyntax(Exception): | |
def __init__(self): | |
pass | |
# class for represent a token | |
class Token(): | |
def __init__(self, token, t): | |
self.token = token | |
self.t = t | |
# def initRegister(): | |
# global register | |
# for i in range(9): | |
# register.append(0) | |
def loadFile(fileName): | |
""" | |
loadFile: This function loads the file and reads its lines. | |
""" | |
global lines | |
fo = open(fileName) | |
for line in fo: | |
lines.append(line) | |
fo.close() | |
def scanner(string): | |
""" | |
scanner: This function builds the tokens by the content of the file. | |
The tokens will be saved in list 'tokens' | |
""" | |
global tokens | |
token = "" | |
state = 0 # init state | |
for ch in string: | |
if state == 0: | |
if ch == 'm': # catch mov-command | |
state = 1 | |
token += 'm' | |
elif ch == 'e': # catch register | |
state = 4 | |
token += 'e' | |
elif (ch >= '1' and ch <= '9') or ch == '-': # catch a number | |
state = 6 | |
token += ch | |
elif ch == '0': # catch a number or hex-code | |
state = 17 | |
token += ch | |
elif ch == 'a': # catch add-command | |
state = 7 | |
token += ch | |
elif ch == 's': # catch sub command | |
state = 10 | |
token += ch | |
elif ch == 'i': # capture int command | |
state = 14 | |
token += ch | |
elif ch == 'p': # capture push or pop command | |
state = 19 | |
token += ch | |
elif ch == 'l': # capture label | |
state = 25 | |
token += ch | |
elif ch == 'j': # capture jmp command | |
state = 26 | |
token += ch | |
elif ch == 'c': # catch cmp-command | |
state = 29 | |
token += ch | |
elif ch == ';': # capture comment | |
state = 33 | |
elif ch == '"': # catch a string | |
state = 34 | |
# without " | |
elif ch.isupper(): # capture identifier | |
state = 35 | |
token += ch | |
elif ch == 'd': # capture db keyword | |
state = 36 | |
token += ch | |
elif ch == "$": # catch variable with prefix $ | |
state = 38 | |
# not catching $ | |
elif ch == '_': # catch label for subprogram | |
state = 40 | |
# not catches the character _ | |
elif ch == 'r': # catch ret-command | |
state = 44 | |
token += ch | |
else: # other characters like space-characters etc. | |
state = 0 | |
token = "" | |
elif state == 1: # state 1 | |
if ch == 'o': | |
state = 2 | |
token += ch | |
elif ch == 'u': | |
state = 47 | |
token += ch | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 2: # state 2 | |
if ch == 'v': | |
state = 3 | |
token += 'v' | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 3: # state 3 | |
if ch.isspace(): | |
state = 0 | |
tokens.append(Token(token, "command")) | |
token = "" | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 4: # state 4 | |
if (ch >= 'a' and ch <= 'd'): | |
state = 5 | |
token += ch | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 5: # state 5 | |
if ch == 'x': | |
state = 13 | |
token += ch | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 6: # state 6 | |
if ch.isdigit(): | |
state = 6 | |
token += ch | |
elif ch.isspace(): | |
state = 0 | |
tokens.append(Token(token, "value")) | |
token = "" | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 7: # state 7 | |
if ch == 'd': | |
state = 8 | |
token += ch | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 8: # state 8 | |
if ch == 'd': | |
state = 9 | |
token += ch | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 9: # state 9 | |
if ch.isspace(): | |
state = 0 | |
tokens.append(Token(token, "command")) | |
token = "" | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 10: # state 10 | |
if ch == 'u': | |
state = 11 | |
token += ch | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 11: # state 11 | |
if ch == 'b': | |
state = 12 | |
token += ch | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 12: # state 12 | |
if ch.isspace(): | |
state = 0 | |
tokens.append(Token(token, "command")) | |
token = "" | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 13: # state 13 | |
if ch == ',' or ch.isspace(): | |
state = 0 | |
tokens.append(Token(token, "register")) | |
token = "" | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 14: # state 14 | |
if ch == 'n': | |
state = 15 | |
token += ch | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 15: # state 15 | |
if ch == 't': | |
state = 16 | |
token += ch | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 16: # state 16 | |
if ch.isspace(): | |
state = 0 | |
tokens.append(Token(token, "command")) | |
token = "" | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 17: # state 17 | |
if ch == 'x': | |
state = 18 | |
token += ch | |
elif ch.isspace(): | |
state = 0 | |
tokens.append(Token(token, "value")) | |
token = "" | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 18: # state 18 | |
if ch.isdigit() or (ch >= 'a' and ch <= 'f'): | |
state = 18 | |
token += ch | |
elif ch.isspace(): | |
state = 0 | |
tokens.append(Token(token, "value")) | |
token = "" | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 19: # state 19 | |
if ch == 'u': | |
state = 20 | |
token += ch | |
elif ch == 'o': | |
state = 23 | |
token += ch | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 20: # state 20 | |
if ch == 's': | |
state = 21 | |
token += ch | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 21: # state 21 | |
if ch == 'h': | |
state = 22 | |
token += ch | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 22: # state 22 | |
if ch.isspace(): | |
state = 0 | |
tokens.append(Token(token, "command")) | |
token = "" | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 23: # state 23 | |
if ch == 'p': | |
state = 24 | |
token += ch | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 24: # state 24 | |
if ch.isspace(): | |
state = 0 | |
tokens.append(Token(token, "command")) | |
token = "" | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 25: # state 25 | |
if ch.isdigit(): | |
state = 25 | |
token += ch | |
elif ch == ':' or ch.isspace(): | |
state = 0 | |
tokens.append(Token(token, "label")) | |
token = "" | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 26: # state 26 | |
if ch == 'm': | |
state = 27 | |
token += ch | |
elif ch == 'e': # catch je command | |
state = 32 | |
token += ch | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 27: # state 27 | |
if ch == 'p': | |
state = 28 | |
token += ch | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 28: # state 28 | |
if ch.isspace(): | |
state = 0 | |
tokens.append(Token(token, "command")) | |
token = "" | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 29: # state 29 | |
if ch == 'm': | |
state = 30 | |
token += ch | |
elif ch == 'a': # catch call-command | |
state = 41 | |
token += ch | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 30: # state 30 | |
if ch == 'p': | |
state = 31 | |
token += ch | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 31: # state 31 | |
if ch.isspace(): | |
state = 0 | |
tokens.append(Token(token, "command")) | |
token = "" | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 32: # state 32 | |
if ch.isspace(): | |
state = 0 | |
tokens.append(Token(token, "command")) | |
token = "" | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 33: # state 33 | |
if ch.isdigit() or ch.isalpha() or (ch.isspace() and ch != '\n') \ | |
or ch == '"': | |
state = 33 | |
elif ch == '\n': | |
state = 0 | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 34: # state 34 | |
if ch.isdigit() or ch.isalpha() or ch.isspace(): | |
state = 34 | |
token += ch | |
elif ch == '"': | |
state = 0 | |
tokens.append(Token(token, "string")) | |
token = "" | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 35: # state 35 | |
if ch.isdigit() or ch.isupper(): | |
state = 35 | |
token += ch | |
elif ch == ' ' or ch == '\n': | |
state = 0 | |
tokens.append(Token(token, "identifier")) | |
token = "" | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 36: # state 36 | |
if ch == 'b': | |
state = 37 | |
token += ch | |
elif ch == 'i': | |
state = 49 | |
token += ch | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 37: # state 37 | |
if ch.isspace(): | |
state = 0 | |
tokens.append(Token(token, "command")) | |
token = "" | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 38: # state 38 | |
if ch.isalpha(): | |
state = 39 | |
token += ch | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 39: # state 39 | |
if ch.isalpha() or ch.isdigit(): | |
state = 39 | |
token += ch | |
elif ch.isspace(): | |
state = 0 | |
tokens.append(Token(token, "identifier")) | |
token = "" | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 40: # state 40 | |
if (ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z') or (ch >= '0' and ch <= '9'): | |
state = 40 | |
token += ch | |
elif ch == ':' or ch.isspace(): | |
state = 0 | |
tokens.append(Token(token, "subprogram")) | |
token = "" | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 41: # state 41 | |
if ch == 'l': | |
state = 42 | |
token += ch | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 42: # state 42 | |
if ch == 'l': | |
state = 43 | |
token += ch | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 43: # state 43 | |
if ch.isspace(): | |
state = 0 | |
tokens.append(Token(token, "command")) | |
token = "" | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 44: # state 44 | |
if ch == 'e': | |
state = 45 | |
token += ch | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 45: # state 45 | |
if ch == 't': | |
state = 46 | |
token += ch | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 46: # state 46 | |
if ch.isspace(): | |
state = 0 | |
tokens.append(Token(token, "command")) | |
token = "" | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 47: # state 47 | |
if ch == 'l': | |
state = 48 | |
token += ch | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 48: # state 48 | |
if ch.isspace(): | |
state = 0 | |
tokens.append(Token(token, "command")) | |
token = "" | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 49: # state 49 | |
if ch == 'v': | |
state = 50 | |
token += ch | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
elif state == 50: # state 50 | |
if ch.isspace(): | |
state = 0 | |
tokens.append(Token(token, "command")) | |
token = "" | |
else: # error case | |
state = 0 | |
token = "" | |
raise InvalidSyntax() | |
def scan(): | |
""" | |
scan: applys function scanner() to each line of the source code. | |
""" | |
global lines | |
assert len(lines) > 0, "no lines" | |
for line in lines: | |
try: | |
scanner(line) | |
except InvalidSyntax: | |
print("line=", line) | |
def parser(): | |
""" | |
parser: parses the tokens of the list 'tokens' | |
""" | |
global tokens | |
global eax, ebx, ecx, edx | |
assert len(tokens) > 0, "no tokens" | |
pointer = 0 # pointer for tokens | |
token = Token("", "") | |
tmpToken = Token("", "") | |
while pointer < len(tokens): | |
token = tokens[pointer] | |
if token.token == "mov": # mov commando | |
# it must follow a register | |
if pointer + 1 < len(tokens): | |
pointer += 1 | |
token = tokens[pointer] | |
else: | |
print("Error: Not found argument!") | |
return | |
# TODO use token.t for this stuff | |
if token.t == "register": | |
tmpToken = token | |
# it must follow a value / string / register / variable | |
if pointer + 1 < len(tokens): | |
pointer += 1 | |
token = tokens[pointer] | |
else: | |
print("Error: Not found argument!") | |
return | |
# converts the token into float, if token contains only digits. | |
# TODO response of float | |
if token.t == "identifier": # for variables | |
# check of exists of variable | |
if token.token in variables: | |
token.token = variables[token.token] | |
else: | |
print("Error: undefine variable! --> " + token.token) | |
return | |
elif token.t == "string": | |
pass | |
elif isinstance(token.token, float): | |
pass | |
elif token.token.isdigit(): | |
token.token = float(token.token) | |
elif token.token[0] == '-' and token.token[1:].isdigit(): | |
token.token = float(token.token[1:]) | |
token.token *= -1 | |
elif token.t == "register": # loads out of register | |
if token.token == "eax": | |
token.token = eax | |
elif token.token == "ebx": | |
token.token = ebx | |
elif token.token == "ecx": | |
token.token = ecx | |
elif token.token == "edx": | |
token.token = edx | |
if tmpToken.token == "eax": | |
eax = token.token | |
elif tmpToken.token == "ebx": | |
ebx = token.token | |
elif tmpToken.token == "ecx": | |
ecx = token.token | |
elif tmpToken.token == "edx": | |
edx = token.token | |
else: | |
print("Error: No found register!") | |
return | |
elif token.token == "add": # add commando | |
pointer += 1 | |
token = tokens[pointer] | |
if token.t == "register": | |
tmpToken = token | |
if pointer + 1 < len(tokens): | |
pointer += 1 | |
token = tokens[pointer] | |
else: | |
print("Error: Not found number!") | |
return | |
# converts the token into float, if token contains only digits. | |
if token.t == "register": | |
# for the case that token is register | |
if token.token == "eax": | |
token.token = eax | |
elif token.token == "ebx": | |
token.token = ebx | |
elif token.token == "ecx": | |
token.token = ecx | |
elif token.token == "edx": | |
token.token = edx | |
elif token.token.isdigit(): | |
token.token = float(token.token) | |
elif token.token[0] == '-' and token.token[1:].isdigit(): | |
token.token = float(token.token[1:]) | |
token.token *= -1 | |
else: | |
print("Error: ", token, " is not a number!") | |
return | |
if tmpToken.token == "eax": | |
eax += token.token | |
# update zero flag | |
if eax == 0: | |
zeroFlag = True | |
else: | |
zeroFlag = False | |
elif tmpToken.token == "ebx": | |
ebx += token.token | |
# update zero flag | |
if ebx == 0: | |
zeroFlag = True | |
else: | |
zeroFlag = False | |
elif tmpToken.token == "ecx": | |
ecx += token.token | |
# update zero flag | |
if ecx == 0: | |
zeroFlag = True | |
else: | |
zeroFlag = False | |
elif tmpToken.token == "edx": | |
edx += token.token | |
# update zero flag | |
if edx == 0: | |
zeroFlag = True | |
else: | |
zeroFlag = False | |
else: | |
print("Error: Not found register!") | |
return | |
elif token.token == "sub": # sub commando | |
pointer += 1 | |
token = tokens[pointer] | |
if token.t == "register": | |
tmpToken = token | |
if pointer + 1 < len(tokens): | |
pointer += 1 | |
token = tokens[pointer] | |
else: | |
print("Error: Not found number!") | |
return | |
# converts the token into float, if token contains only digits. | |
if token.t == "register": | |
# for the case that token is register | |
if token.token == "eax": | |
token.token = eax | |
elif token.token == "ebx": | |
token.token = ebx | |
elif token.token == "ecx": | |
token.token = ecx | |
elif token.token == "edx": | |
token.token = edx | |
elif isinstance(token.token, float): | |
pass | |
elif token.token.isdigit(): | |
token.token = float(token.token) | |
elif token.token[0] == '-' and token.token[1:].isdigit(): | |
token.token = float(token.token[1:]) | |
token.token *= -1 | |
else: | |
print("Error: ", token.token, " is not a number!") | |
return | |
if tmpToken.token == "eax": | |
eax -= token.token | |
# updated zero flag | |
if eax == 0: | |
zeroFlag = True | |
else: | |
zeroFlag = False | |
elif tmpToken.token == "ebx": | |
ebx -= token.token | |
# update zero flag | |
if ebx == 0: | |
zeroFlag = True | |
else: | |
zeroFlag = False | |
elif tmpToken.token == "ecx": | |
ecx -= token.token | |
# update zero flag | |
if ecx == 0: | |
zeroFlag = True | |
else: | |
zeroFlag = False | |
elif tmpToken.token == "edx": | |
edx -= token.token | |
# update zero flag | |
if edx == 0: | |
zeroFlag = True | |
else: | |
zeroFlag = False | |
else: | |
print("Error: No found register!") | |
return | |
elif token.token == "int": # int commando | |
tmpToken = token | |
if pointer + 1 < len(tokens): | |
pointer += 1 | |
token = tokens[pointer] | |
else: | |
print("Error: Not found argument!") | |
return | |
if token.token == "0x80": # system interrupt 0x80 | |
if eax == 1: # exit program | |
if ebx == 0: | |
print("END PROGRAM") | |
return | |
else: | |
print("END PROGRAM WITH ERRORS") | |
return | |
elif eax == 3: | |
ecx = float(input(">> ")) | |
elif eax == 4: # output informations | |
print(ecx) | |
elif token.token == "push": # push commando | |
tmpToken = token | |
# it must follow a register | |
if pointer + 1 < len(tokens): | |
pointer += 1 | |
token = tokens[pointer] | |
else: | |
print("Error: Not found register!") | |
return | |
# pushing register on the stack | |
if token.token == "eax": | |
stack.append(eax) | |
elif token.token == "ebx": | |
stack.append(ebx) | |
elif token.token == "ecx": | |
stack.append(ecx) | |
elif token.token == "edx": | |
stack.append(edx) | |
elif token.token == "pop": # pop commando | |
tmpToken = token | |
# it must follow a register | |
if pointer + 1 < len(tokens): | |
pointer += 1 | |
token = tokens[pointer] | |
else: | |
print("Error: Not found register!") | |
return | |
# pop register from stack | |
if token.token == "eax": | |
eax = stack.pop() | |
elif token.token == "ebx": | |
ebx = stack.pop() | |
elif token.token == "ecx": | |
ecx = stack.pop() | |
elif token.token == "edx": | |
edx = stack.pop() | |
elif token.t == "label": # capture label | |
jumps[token.token] = pointer | |
elif token.token == "jmp": # capture jmp command | |
# it must follow a label | |
if pointer + 1 < len(tokens): | |
pointer += 1 | |
token = tokens[pointer] | |
else: | |
print("Error: Not found label!") | |
return | |
if token.t == "label": | |
pointer = jumps[token.token] | |
else: | |
print("Error: expected a label!") | |
elif token.token == "cmp": | |
# TODO | |
# it must follow a register | |
if pointer + 1 < len(tokens): | |
pointer += 1 | |
token = tokens[pointer] | |
else: | |
print("Error: Not found argument!") | |
return | |
if token.t == "register": | |
# it must follow a register | |
if pointer + 1 < len(tokens): | |
pointer += 1 | |
tmpToken = tokens[pointer] # next register | |
else: | |
print("Error: Not found register!") | |
return | |
# actual comparing | |
if token.token == "eax": | |
if tmpToken.token == "eax": | |
if eax == eax: | |
zeroFlag = True | |
else: | |
zeroFlag = False | |
elif tmpToken.token == "ebx": | |
if eax == ebx: | |
zeroFlag = True | |
else: | |
zeroFlag = False | |
elif tmpToken.token == "ecx": | |
if eax == ecx: | |
zeroFlag = True | |
else: | |
zeroFlag = False | |
elif tmpToken.token == "edx": | |
if eax == edx: | |
zeroFlag = True | |
else: | |
zeroFlag = False | |
elif token.token == "ebx": | |
if tmpToken.token == "eax": | |
if ebx == eax: | |
zeroFlag = True | |
else: | |
zeroFlag = False | |
elif tmpToken.token == "ebx": | |
if ebx == ebx: | |
zeroFlag = True | |
else: | |
zeroFlag = False | |
elif tmpToken.token == "ecx": | |
if ebx == ecx: | |
zeroFlag = True | |
else: | |
zeroFlag = False | |
elif tmpToken.token == "edx": | |
if ebx == edx: | |
zeroFlag = True | |
else: | |
zeroFlag = False | |
elif token.token == "ecx": | |
if tmpToken.token == "eax": | |
if ecx == eax: | |
zeroFlag = True | |
else: | |
zeroFlag = False | |
elif tmpToken.token == "ebx": | |
if ecx == ebx: | |
zeroFlag = True | |
else: | |
zeroFlag = False | |
elif tmpToken.token == "ecx": | |
if ecx == ecx: | |
zeroFlag = True | |
else: | |
zeroFlag = False | |
elif tmpToken.token == "edx": | |
if ecx == edx: | |
zeroFlag = True | |
else: | |
zeroFlag = False | |
elif token.token == "edx": | |
if tmpToken.token == "eax": | |
if edx == eax: | |
zeroFlag = True | |
else: | |
zeroFlag = False | |
elif tmpToken.token == "ebx": | |
if edx == ebx: | |
zeroFlag = True | |
else: | |
zeroFlag = False | |
elif tmpToken.token == "ecx": | |
if edx == ecx: | |
zeroFlag = True | |
else: | |
zeroFlag = False | |
elif tmpToken.token == "edx": | |
if edx == edx: | |
zeroFlag = True | |
else: | |
zeroFlag = False | |
else: | |
print("Error: Not found register!") | |
return | |
elif token.token == "je": | |
# it must follow a label | |
if pointer + 1 < len(tokens): | |
pointer += 1 | |
token = tokens[pointer] # next register | |
else: | |
print("Error: Not found argument") | |
return | |
# check of label | |
if token.t == "label": | |
# actual jump | |
if zeroFlag: | |
pointer = jumps[token.token] | |
else: | |
print("Error: Not found label") | |
return | |
elif token.t == "identifier": | |
# check whether identifier is in variables-table | |
if token.token not in variables: | |
# it must follow a command | |
if pointer + 1 < len(tokens): | |
pointer += 1 | |
tmpToken = tokens[pointer] # next register | |
else: | |
print("Error: Not found argument") | |
return | |
if tmpToken.t == "command" and tmpToken.token == "db": | |
# it must follow a value (string) | |
if pointer + 1 < len(tokens): | |
pointer += 1 | |
tmpToken = tokens[pointer] # next register | |
else: | |
print("Error: Not found argument") | |
return | |
if tmpToken.t == "value" or tmpToken.t == "string": | |
if tmpToken.t == "value": | |
variables[token.token] = float(tmpToken.token) | |
elif tmpToken.t == "string": | |
variables[token.token] = tmpToken.token | |
else: | |
print("Error: Not found db-keyword") | |
return | |
elif token.token == "call": # catch the call-command | |
# it must follow a subprogram label | |
if pointer + 1 < len(tokens): | |
pointer += 1 | |
token = tokens[pointer] # next register | |
else: | |
print("Error: Not found subprogram label") | |
return | |
if token.t == "subprogram": | |
if token.token in jumps: | |
# save the current pointer | |
returnStack.append(pointer) # eventuell pointer + 1 | |
# jump to the subprogram | |
pointer = jumps[token.token] | |
else: # error case | |
print("Error: Unknow subprogram!") | |
return | |
else: # error case | |
print("Error: Not found subprogram") | |
return | |
elif token.token == "ret": # catch the ret-command | |
if len(returnStack) >= 1: | |
pointer = returnStack.pop() | |
else: # error case | |
print("Error: No return adress on stack") | |
return | |
elif token.t == "subprogram": | |
pass | |
elif token.token == "mul": # catch mul-command | |
# it must follow a register | |
if pointer + 1 < len(tokens): | |
pointer += 1 | |
token = tokens[pointer] # next register | |
else: | |
print("Error: Not found argument") | |
return | |
if token.t == "register": | |
if token.token == "eax": | |
eax *= eax | |
elif token.token == "ebx": | |
eax *= ebx | |
elif token.token == "ecx": | |
eax *= ecx | |
elif token.token == "edx": | |
eax *= edx | |
else: | |
print("Error: Not found register") | |
return | |
elif token.token == "div": | |
# it must follow a register | |
if pointer + 1 < len(tokens): | |
pointer += 1 | |
token = tokens[pointer] # next register | |
else: | |
print("Error: Not found argument") | |
return | |
if token.t == "register": | |
if token.token == "eax": | |
eax /= eax | |
elif token.token == "ebx": | |
eax /= ebx | |
elif token.token == "ecx": | |
eax /= ecx | |
elif token.token == "edx": | |
eax /= edx | |
else: | |
print("Error: Not found register") | |
return | |
# increment pointer for fetching next token. | |
pointer += 1 | |
def registerLabels(): | |
""" | |
This function search for labels / subprogram-labels and registers this in the 'jumps' list. | |
""" | |
for i in range(len(tokens)): | |
if (tokens[i].t == "label"): | |
jumps[tokens[i].token] = i | |
elif tokens[i].t == "subprogram": | |
jumps[tokens[i].token] = i | |
def resetInterpreter(): | |
""" | |
resets the interpreter mind. | |
""" | |
global eax, ebx, ecx, edx, zeroFlag, stack | |
global variables, jumps, lines, tokens, returnStack | |
eax = 0 | |
ebx = 0 | |
ecx = 0 | |
edx = 0 | |
zeroFlag = False | |
stack = [] | |
jumps = {} | |
variables = {} | |
lines = [] | |
tokens = [] | |
returnStack = [] | |
# DEBUG FUNCTION | |
# def printTokens(): | |
# for token in tokens: | |
# print(token.token, " --> ", token.t) | |
# main program | |
def main(): | |
""" | |
reads textfiles from the command-line and interprets them. | |
""" | |
# [1:] because the first argument is the program itself. | |
for arg in sys.argv[1:]: | |
resetInterpreter() # resets interpreter mind | |
try: | |
loadFile(arg) | |
scan() | |
registerLabels() | |
parser() | |
except: | |
print("Error: File %s not found!" % (arg)) | |
if __name__ == "__main__": | |
main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
It's example of usage asyncio+aiohttp to downloading. | |
You should install aiohttp for using: | |
(You can use virtualenv to testing) | |
pip install -r /path/to/requirements.txt | |
""" | |
import aiohttp # type: ignore | |
import asyncio | |
from os.path import basename | |
def download(ways): | |
if not ways: | |
print('Ways list is empty. Downloading is impossible') | |
return | |
print('downloading..') | |
success_files = set() | |
failure_files = set() | |
event_loop = asyncio.get_event_loop() | |
try: | |
event_loop.run_until_complete( | |
async_downloader(ways, event_loop, success_files, failure_files) | |
) | |
finally: | |
event_loop.close() | |
print('Download complete') | |
print('-' * 100) | |
if success_files: | |
print('success:') | |
for file in success_files: | |
print(file) | |
if failure_files: | |
print('failure:') | |
for file in failure_files: | |
print(file) | |
async def async_downloader(ways, loop, success_files, failure_files): | |
async with aiohttp.ClientSession() as session: | |
coroutines = [ | |
download_file_by_url( | |
url, | |
session=session, | |
) for url in ways] | |
for task in asyncio.as_completed(coroutines): | |
fail, url = await task | |
if fail: | |
failure_files.add(url) | |
else: | |
success_files.add(url) | |
async def download_file_by_url(url, session=None): | |
fail = True | |
file_name = basename(url) | |
assert session | |
try: | |
async with session.get(url) as response: | |
if response.status == 404: | |
print('\t{} from {} : Failed : {}'.format( | |
file_name, url, '404 - Not found')) | |
return fail, url | |
if not response.status == 200: | |
print('\t{} from {} : Failed : HTTP response {}'.format( | |
file_name, url, response.status)) | |
return fail, url | |
data = await response.read() | |
with open(file_name, 'wb') as file: | |
file.write(data) | |
except asyncio.TimeoutError: | |
print('\t{} from {}: Failed : {}'.format( | |
file_name, url, 'Timeout error')) | |
except aiohttp.client_exceptions.ClientConnectionError: | |
print('\t{} from {}: Failed : {}'.format( | |
file_name, url, 'Client connection error')) | |
else: | |
print('\t{} from {} : Success'.format(file_name, url)) | |
fail = False | |
return fail, url | |
def test(): | |
ways = ['https://www.wikipedia.org', | |
'https://www.ya.ru', | |
'https://www.duckduckgo.com', | |
'https://www.fail-path.unknown', | |
] | |
download(ways) | |
if __name__ == "__main__": | |
test() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import PyPDF2 | |
import pyttsx3 | |
book = open(input('Enter the book name: '), 'rb') | |
pg_no = int(input("Enter the page number from which you want the system to start reading text: ")) | |
pdf_Reader = PyPDF2.PdfFileReader(book) | |
pages = pdf_Reader.numPages | |
speaker = pyttsx3.init() | |
for num in range((pg_no-1), pages): | |
page = pdf_Reader.getPage(num) | |
text = page.extractText() | |
speaker.say(text) | |
speaker.runAndWait() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fh = open('mbox-short.txt') | |
#The 'mbox-short.txt' file can be downloaded from the link: https://www.py4e.com/code3/mbox-short.txt | |
sum = 0 | |
count = 0 | |
for fx in fh: | |
fx = fx.rstrip() | |
if not fx.startswith("X-DSPAM-Confidence:") : | |
continue | |
fy = fx[19:] | |
count = count + 1 | |
sum = sum + float(fy) | |
print ('Average spam confidence: ',sum/count) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sqlite3 | |
# making connection with database | |
def connect_database(): | |
global conn | |
global cur | |
conn = sqlite3.connect("bankmanaging.db") | |
cur = conn.cursor() | |
cur.execute( | |
"create table if not exists bank (acc_no int, name text, age int, address text, balance int, account_type text, mobile_number int)") | |
cur.execute("create table if not exists staff (name text, pass text,salary int, position text)") | |
cur.execute("create table if not exists admin (name text, pass text)") | |
cur.execute("insert into admin values('arpit','123')") | |
conn.commit() | |
cur.execute("select acc_no from bank") | |
acc = cur.fetchall() | |
global acc_no | |
if len(acc) == 0: | |
acc_no = 1 | |
else: | |
acc_no = int(acc[-1][0]) + 1 | |
# check admin dtails in database | |
def check_admin(name, password): | |
cur.execute("select * from admin") | |
data = cur.fetchall() | |
if data[0][0] == name and data[0][1] == password: | |
return True | |
return | |
# create employee in database | |
def create_employee(name, password, salary, positon): | |
print(password) | |
cur.execute("insert into staff values(?,?,?,?)", (name, password, salary, positon)) | |
conn.commit() | |
# check employee details in dabase for employee login | |
def check_employee(name, password): | |
print(password) | |
print(name) | |
cur.execute("select name,pass from staff") | |
data = cur.fetchall() | |
print(data) | |
if len(data) == 0: | |
return False | |
for i in range(len(data)): | |
if data[i][0] == name and data[i][1] == password: | |
return True | |
return False | |
# create customer details in database | |
def create_customer(name, age, address, balance, acc_type, mobile_number): | |
global acc_no | |
cur.execute("insert into bank values(?,?,?,?,?,?,?)", | |
(acc_no, name, age, address, balance, acc_type, mobile_number)) | |
conn.commit() | |
acc_no = acc_no + 1 | |
return acc_no - 1 | |
# check account in database | |
def check_acc_no(acc_no): | |
cur.execute("select acc_no from bank") | |
list_acc_no = cur.fetchall() | |
for i in range(len(list_acc_no)): | |
if list_acc_no[i][0] == int(acc_no): | |
return True | |
return False | |
# get all details of a particular customer from database | |
def get_details(acc_no): | |
cur.execute("select * from bank where acc_no=?", (acc_no)) | |
global detail | |
detail = cur.fetchall() | |
print(detail) | |
if len(detail) == 0: | |
return False | |
else: | |
return (detail[0][0], detail[0][1], detail[0][2], detail[0][3], detail[0][4], detail[0][5], detail[0][6]) | |
# add new balance of customer in bank database | |
def update_balance(new_money, acc_no): | |
cur.execute("select balance from bank where acc_no=?", (acc_no,)) | |
bal = cur.fetchall() | |
bal = bal[0][0] | |
new_bal = bal + int(new_money) | |
cur.execute("update bank set balance=? where acc_no=?", (new_bal, acc_no)) | |
conn.commit() | |
# deduct balance from customer bank database | |
def deduct_balance(new_money, acc_no): | |
cur.execute("select balance from bank where acc_no=?", (acc_no,)) | |
bal = cur.fetchall() | |
bal = bal[0][0] | |
if bal < int(new_money): | |
return False | |
else: | |
new_bal = bal - int(new_money) | |
cur.execute("update bank set balance=? where acc_no=?", (new_bal, acc_no)) | |
conn.commit() | |
return True | |
# gave balance of a particular account number from database | |
def check_balance(acc_no): | |
cur.execute("select balance from bank where acc_no=?", (acc_no)) | |
bal = cur.fetchall() | |
return bal[0][0] | |
# update_name_in_bank_table | |
def update_name_in_bank_table(new_name, acc_no): | |
print(new_name) | |
conn.execute("update bank set name='{}' where acc_no={}".format(new_name, acc_no)) | |
conn.commit() | |
# update_age_in_bank_table | |
def update_age_in_bank_table(new_name, acc_no): | |
print(new_name) | |
conn.execute("update bank set age={} where acc_no={}".format(new_name, acc_no)) | |
conn.commit() | |
# update_address_in_bank_table | |
def update_address_in_bank_table(new_name, acc_no): | |
print(new_name) | |
conn.execute("update bank set address='{}' where acc_no={}".format(new_name, acc_no)) | |
conn.commit() | |
# list of all customers in bank | |
def list_all_customers(): | |
cur.execute("select * from bank") | |
deatil = cur.fetchall() | |
return deatil | |
# delete account from database | |
def delete_acc(acc_no): | |
cur.execute("delete from bank where acc_no=?", (acc_no)) | |
conn.commit() | |
# show employees detail from staff table | |
def show_employees(): | |
cur.execute("select name, salary, position,pass from staff") | |
detail = cur.fetchall() | |
return detail | |
# return all money in bank | |
def all_money(): | |
cur.execute("select balance from bank") | |
bal = cur.fetchall() | |
print(bal) | |
if len(bal) == 0: | |
return False | |
else: | |
total = 0 | |
for i in bal: | |
total = total + i[0] | |
return total | |
# return a list of all employees name | |
def show_employees_for_update(): | |
cur.execute("select * from staff") | |
detail = cur.fetchall() | |
return detail | |
# update employee name from data base | |
def update_employee_name(new_name, old_name): | |
print(new_name, old_name) | |
cur.execute("update staff set name='{}' where name='{}'".format(new_name, old_name)) | |
conn.commit() | |
def update_employee_password(new_pass, old_name): | |
print(new_pass, old_name) | |
cur.execute("update staff set pass='{}' where name='{}'".format(new_pass, old_name)) | |
conn.commit() | |
def update_employee_salary(new_salary, old_name): | |
print(new_salary, old_name) | |
cur.execute("update staff set salary={} where name='{}'".format(new_salary, old_name)) | |
conn.commit() | |
def update_employee_position(new_pos, old_name): | |
print(new_pos, old_name) | |
cur.execute("update staff set position='{}' where name='{}'".format(new_pos, old_name)) | |
conn.commit() | |
# get name and balance from bank of a particular account number | |
def get_detail(acc_no): | |
cur.execute("select name, balance from bank where acc_no=?", (acc_no)) | |
details = cur.fetchall() | |
return details | |
def check_name_in_staff(name): | |
cur = conn.cursor() | |
cur.execute("select name from staff") | |
details = cur.fetchall() | |
for i in details: | |
if i[0] == name: | |
return True | |
return False |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from tkinter import Tk, Canvas | |
from PIL.Image import open as openImage | |
from PIL.ImageTk import PhotoImage | |
class Background(Canvas): | |
""" | |
Classe para gerar um plano de fundo animado | |
""" | |
__background = [] | |
__stop = False | |
def __init__(self, tk_instance, *geometry, fp="background.png", animation_speed=50): | |
# Verifica se o parâmetro tk_instance é uma instância de Tk | |
if not isinstance(tk_instance, Tk): raise TypeError("The tk_instance argument must be an instance of Tk.") | |
# Recebe o caminho de imagem e a velocidade da animação | |
self.image_path = fp | |
self.animation_speed = animation_speed | |
# Recebe a largura e altura do widget | |
self.__width = geometry[0] | |
self.__height = geometry[1] | |
# Inicializa o construtor da classe Canvas | |
Canvas.__init__(self, master=tk_instance, width=self.__width, height=self.__height) | |
# Carrega a imagem que será usada no plano de fundo | |
self.__bg_image = \ | |
self.getPhotoImage(image_path=self.image_path, width=self.__width, height=self.__height, closeAfter=True)[0] | |
# Cria uma imagem que será fixa, ou seja, que não fará parte da animação e serve em situações de bugs na animação | |
self.__background_default = self.create_image(self.__width // 2, self.__height // 2, image=self.__bg_image) | |
# Cria as imagens que serão utilizadas na animação do background | |
self.__background.append(self.create_image(self.__width // 2, self.__height // 2, image=self.__bg_image)) | |
self.__background.append( | |
self.create_image(self.__width + (self.__width // 2), self.__height // 2, image=self.__bg_image)) | |
def getBackgroundID(self): | |
""" | |
Retorna os id's das imagens de background | |
""" | |
return [self.__background_default, *self.__background] | |
@staticmethod | |
def getPhotoImage(image=None, image_path=None, width=None, height=None, closeAfter=False): | |
""" | |
Retorna um objeto da classe PIL.ImageTk.PhotoImage de uma imagem e as imagens criadas de PIL.Image | |
(photoImage, new, original) | |
@param image: Instância de PIL.Image.open | |
@param image_path: Diretório da imagem | |
@param width: Largura da imagem | |
@param height: Altura da imagem | |
@param closeAfter: Se True, a imagem será fechada após ser criado um PhotoImage da mesma | |
""" | |
if not image: | |
if not image_path: return | |
# Abre a imagem utilizando o caminho dela | |
image = openImage(image_path) | |
# Será redimesionada a imagem somente se existir um width ou height | |
if not width: width = image.width | |
if not height: height = image.height | |
# Cria uma nova imagem já redimensionada | |
newImage = image.resize([width, height]) | |
# Cria um photoImage | |
photoImage = PhotoImage(newImage) | |
# Se closeAfter for True, ele fecha as imagens | |
if closeAfter: | |
# Fecha a imagem nova | |
newImage.close() | |
newImage = None | |
# Fecha a imagem original | |
image.close() | |
image = None | |
# Retorna o PhotoImage da imagem,a nova imagem que foi utilizada e a imagem original | |
return photoImage, newImage, image | |
def reset(self): | |
""" | |
Método para resetar o background, apagando todos os itens que não sejam o plano de fundo | |
""" | |
# Deleta todos os itens do canvas | |
self.delete("all") | |
# Para a animação passando False para o atributo "stop" | |
self.__stop = False | |
# Limpa a lista de imagens usadas na animação | |
self.__background.clear() | |
# Cria uma imagem que será fixa, ou seja, que não fará parte da animação e serve em situações de bugs na animação | |
self.__background_default = self.create_image(self.__width // 2, self.__height // 2, image=self.__bg_image) | |
# Cria as imagens que serão utilizadas na animação do background | |
self.__background.append(self.create_image(self.__width // 2, self.__height // 2, image=self.__bg_image)) | |
self.__background.append( | |
self.create_image(self.__width + (self.__width // 2), self.__height // 2, image=self.__bg_image)) | |
def run(self): | |
""" | |
Método para iniciar a animação do background | |
""" | |
# Enquanto o atributo "stop" for False, a animação continuará em um loop infinito | |
if not self.__stop: | |
# Move as imagens de background na posição X | |
self.move(self.__background[0], -10, 0) | |
self.move(self.__background[1], -10, 0) | |
self.tag_lower(self.__background[0]) | |
self.tag_lower(self.__background[1]) | |
self.tag_lower(self.__background_default) | |
# Se a primeira imagem da lista tiver saído da área do widget, uma nova será criada depois da segunda imagem | |
if self.bbox(self.__background[0])[2] <= 0: | |
# Deleta a primeira imagem da lista (imagem que saiu da área do widget) | |
self.delete(self.__background[0]) | |
self.__background.remove(self.__background[0]) | |
# Cria uma nova imagem a partir da última imagem da animação | |
width = self.bbox(self.__background[0])[2] + self.__width // 2 | |
self.__background.append(self.create_image(width, self.__height // 2, image=self.__bg_image)) | |
# Executa novamente o método depois de um certo tempo | |
self.after(self.animation_speed, self.run) | |
def stop(self): | |
""" | |
Método para parar a animação do background | |
""" | |
self.__stop = True |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Script Name : backup_automater_services.py | |
# Author : Craig Richards | |
# Created : 24th October 2012 | |
# Last Modified : 13th February 2016 | |
# Version : 1.0.1 | |
# Modifications : 1.0.1 - Tidy up the comments and syntax | |
# Description : This will go through and backup all my automator services workflows | |
import datetime # Load the library module | |
import os # Load the library module | |
import shutil # Load the library module | |
today = datetime.date.today() # Get Today's date | |
todaystr = today.isoformat() # Format it so we can use the format to create the directory | |
confdir = os.getenv("my_config") # Set the variable by getting the value from the OS setting | |
dropbox = os.getenv("dropbox") # Set the variable by getting the value from the OS setting | |
conffile = 'services.conf' # Set the variable as the name of the configuration file | |
conffilename = os.path.join(confdir, conffile) # Set the variable by combining the path and the file name | |
sourcedir = os.path.expanduser('~/Library/Services/') # Source directory of where the scripts are located | |
# Combine several settings to create | |
destdir = os.path.join(dropbox, "My_backups" + "/" + "Automater_services" + todaystr + "/") | |
# the destination backup directory | |
for file_name in open(conffilename): # Walk through the configuration file | |
fname = file_name.strip() # Strip out the blank lines from the configuration file | |
if fname: # For the lines that are not blank | |
sourcefile = os.path.join(sourcedir, fname) # Get the name of the source files to backup | |
destfile = os.path.join(destdir, fname) # Get the name of the destination file names | |
shutil.copytree(sourcefile, destfile) # Copy the directories |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Stack: | |
def __init__(self): | |
self.items = [] | |
def push(self, item): | |
self.items.append(item) | |
def pop(self): | |
return self.items.pop() | |
def is_empty(self): | |
return self.items == [] | |
def peek(self): | |
return self.items[-1] | |
def display(self): | |
return self.items | |
def is_same(p1, p2): | |
if p1 == '(' and p2 == ')': | |
return True | |
elif p1 == '[' and p2 == ']': | |
return True | |
elif p1 == '{' and p2 == '}': | |
return True | |
else: | |
return False | |
def is_balanced(check_string): | |
s = Stack() | |
index = 0 | |
is_bal = True | |
while index < len(check_string) and is_bal: | |
paren = check_string[index] | |
if paren in '{[(': | |
s.push(paren) | |
else: | |
if s.is_empty(): | |
is_bal = False | |
else: | |
top = s.pop() | |
if not is_same(top, paren): | |
is_bal = False | |
index += 1 | |
if s.is_empty() and is_bal: | |
return True | |
else: | |
return False | |
print(is_balanced('[((())})]')) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ./PongPong/pong/ball.py | |
import pyglet | |
import random | |
from typing import Tuple | |
class BallObject(pyglet.shapes.Circle): | |
def __init__(self, *args, **kwargs): | |
super(BallObject, self).__init__(*args, **kwargs) | |
self.color = (255, 180, 0) | |
self.velocity_x, self.velocity_y = 0.0, 0.0 | |
def update(self, win_size: Tuple, border: Tuple, other_object, dt) -> None: | |
speed = [2.37, 2.49, 2.54, 2.62, 2.71, 2.85, 2.96, 3.08, 3.17, 3.25] # more choices more randomness | |
rn = random.choice(speed) | |
newx = self.x + self.velocity_x | |
newy = self.y + self.velocity_y | |
if newx < border + self.radius or newx > win_size[0] - border - self.radius: | |
self.velocity_x = -(self.velocity_x/abs(self.velocity_x))*rn | |
elif newy > win_size[1] - border - self.radius: | |
self.velocity_y = -(self.velocity_y/abs(self.velocity_y))*rn | |
elif (newy-self.radius < other_object.height) and (other_object.x <= newx <= other_object.rightx): | |
self.velocity_y = -(self.velocity_y/abs(self.velocity_y))*rn | |
else: | |
self.x = newx | |
self.y = newy |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def base_check(xnumber, xbase): | |
for char in xnumber[len(xnumber ) -1]: | |
if int(char) >= int(xbase): | |
return False | |
return True | |
def convert_from_10(xnumber, xbase, arr, ybase): | |
if int(xbase) == 2 or int(xbase) == 4 or int(xbase) == 6 or int(xbase) == 8: | |
if xnumber == 0: | |
return arr | |
else: | |
quotient = int(xnumber) // int(xbase) | |
remainder = int(xnumber) % int(xbase) | |
arr.append(remainder) | |
dividend = quotient | |
convert_from_10(dividend, xbase, arr, base) | |
elif int(xbase) == 16: | |
if int(xnumber) == 0: | |
return arr | |
else: | |
quotient = int(xnumber) // int(xbase) | |
remainder = int(xnumber) % int(xbase) | |
if remainder > 9: | |
if remainder == 10: remainder = 'A' | |
if remainder == 11: remainder = 'B' | |
if remainder == 12: remainder = 'C' | |
if remainder == 13: remainder = 'D' | |
if remainder == 14: remainder = 'E' | |
if remainder == 15: remainder = 'F' | |
arr.append(remainder) | |
dividend = quotient | |
convert_from_10(dividend, xbase, arr, ybase) | |
def convert_to_10(xnumber, xbase, arr, ybase): | |
if int(xbase) == 10: | |
for char in xnumber: | |
arr.append(char) | |
flipped = arr[::-1] | |
ans = 0 | |
j = 0 | |
for i in flipped: | |
ans = ans + (int(i) * (int(ybase) ** j)) | |
j = j + 1 | |
return ans | |
arrayfrom = [] | |
arrayto = [] | |
is_base_possible = False | |
number = input("Enter the number you would like to convert: ") | |
while not is_base_possible: | |
base = input("What is the base of this number? ") | |
is_base_possible = base_check(number, base) | |
if not is_base_possible: | |
print(f"The number {number} is not a base {base} number") | |
base = input | |
else: | |
break | |
dBase = input("What is the base you would like to convert to? ") | |
if int(base) == 10: | |
convert_from_10(number, dBase, arrayfrom, base) | |
answer = arrayfrom[::-1] # reverses the array | |
print(f"In base {dBase} this number is: ") | |
print(*answer, sep='') | |
elif int(dBase) == 10: | |
answer = convert_to_10(number, dBase, arrayto, base) | |
print(f"In base {dBase} this number is: {answer} ") | |
else: | |
number = convert_to_10(number, 10, arrayto, base) | |
convert_from_10(number, dBase, arrayfrom, base) | |
answer = arrayfrom[::-1] | |
print(f"In base {dBase} this number is: ") | |
print(*answer, sep='') | |
© 2020 GitHub, Inc. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Example: Kilometers to Miles | |
# Taking kilometers input from the user | |
kilometers = float(input("Enter value in kilometers: ")) | |
# conversion factor | |
conv_fac = 0.621371 | |
# calculate miles | |
miles = kilometers * conv_fac | |
print('%0.2f kilometers is equal to %0.2f miles' %(kilometers,miles)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from fpdf import FPDF | |
# Author: @NavonilDas | |
pdf = FPDF() | |
# Set Author Name of the PDF | |
pdf.set_author('@NavonilDas') | |
# Set Subject of The PDF | |
pdf.set_subject('python') | |
# Set the Title of the PDF | |
pdf.set_title('Generating PDF with Python') | |
pdf.add_page() | |
# Set Font family Courier with font size 28 | |
pdf.set_font("Courier", '', 18) | |
# Add Text at (0,50) | |
pdf.text(0, 50, "Example to generate PDF in python.") | |
# Set Font Family Courier with italic and font size 28 | |
pdf.set_font("Courier", 'i', 28) | |
pdf.text(0, 60, "This is an italic text") # Write text at 0,60 | |
# Draw a Rectangle at (10,100) with Width 60,30 | |
pdf.rect(10, 100, 60, 30, 'D') | |
# Set Fill color | |
pdf.set_fill_color(255, 0, 0) # Red = (255,0,0) | |
# Draw a Circle at (10,135) with diameter 50 | |
pdf.ellipse(10, 135, 50, 50, 'F') | |
# Save the Output at Local File | |
pdf.output('output.pdf', 'F') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# batch_file_rename.py | |
# Created: 6th August 2012 | |
""" | |
This will batch rename a group of files in a given directory, | |
once you pass the current and new extensions | |
""" | |
# just checking | |
__author__ = 'Craig Richards' | |
__version__ = '1.0' | |
import argparse | |
import os | |
def batch_rename(work_dir, old_ext, new_ext): | |
""" | |
This will batch rename a group of files in a given directory, | |
once you pass the current and new extensions | |
""" | |
# files = os.listdir(work_dir) | |
for filename in os.listdir(work_dir): | |
# Get the file extension | |
split_file = os.path.splitext(filename) | |
# Unpack tuple element | |
root_name, file_ext = split_file | |
# Start of the logic to check the file extensions, if old_ext = file_ext | |
if old_ext == file_ext: | |
# Returns changed name of the file with new extention | |
newfile = root_name + new_ext | |
# Write the files | |
os.rename( | |
os.path.join(work_dir, filename), | |
os.path.join(work_dir, newfile) | |
) | |
print("rename is done!") | |
print(os.listdir(work_dir)) | |
def get_parser(): | |
parser = argparse.ArgumentParser(description='change extension of files in a working directory') | |
parser.add_argument('work_dir', metavar='WORK_DIR', type=str, nargs=1, | |
help='the directory where to change extension') | |
parser.add_argument('old_ext', metavar='OLD_EXT', type=str, nargs=1, help='old extension') | |
parser.add_argument('new_ext', metavar='NEW_EXT', type=str, nargs=1, help='new extension') | |
return parser | |
def main(): | |
""" | |
This will be called if the script is directly invoked. | |
""" | |
# adding command line argument | |
parser = get_parser() | |
args = vars(parser.parse_args()) | |
# Set the variable work_dir with the first argument passed | |
work_dir = args['work_dir'][0] | |
# Set the variable old_ext with the second argument passed | |
old_ext = args['old_ext'][0] | |
if old_ext and old_ext[0] != '.': | |
old_ext = '.' + old_ext | |
# Set the variable new_ext with the third argument passed | |
new_ext = args['new_ext'][0] | |
if new_ext and new_ext[0] != '.': | |
new_ext = '.' + new_ext | |
batch_rename(work_dir, old_ext, new_ext) | |
if __name__ == '__main__': | |
main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def pascal_triangle(lineNumber): | |
list1 = list() | |
list1.append([1]) | |
i = 1 | |
while (i <= lineNumber): | |
j = 1 | |
l = [] | |
l.append(1) | |
while (j < i): | |
l.append(list1[i - 1][j] + list1[i - 1][j - 1]) | |
j = j + 1 | |
l.append(1) | |
list1.append(l) | |
i = i + 1 | |
return list1 | |
def binomial_coef(n, k): | |
pascalTriangle = pascal_triangle(n) | |
return (pascalTriangle[n][k - 1]) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def binarySearchAppr (arr, start, end, x): | |
# check condition | |
if end >= start: | |
mid = start + (end- start)//2 | |
# If element is present at the middle | |
if arr[mid] == x: | |
return mid | |
# If element is smaller than mid | |
elif arr[mid] > x: | |
return binarySearchAppr(arr, start, mid-1, x) | |
# Else the element greator than mid | |
else: | |
return binarySearchAppr(arr, mid+1, end, x) | |
else: | |
# Element is not found in the array | |
return -1 | |
arr = sorted(['t','u','t','o','r','i','a','l']) | |
x ='r' | |
result = binarySearchAppr(arr, 0, len(arr)-1, x) | |
if result != -1: | |
print ("Element is present at index "+str(result)) | |
else: | |
print ("Element is not present in array") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def Binary_Search(Test_arr, low, high, k): | |
if high >= low: | |
Mid = (low+high)//2 | |
if Test_arr[Mid] < k: | |
return Binary_Search(Test_arr, Mid+1, high, k) | |
elif Test_arr[Mid] > k: | |
return Binary_Search(Test_arr, low, Mid-1, k) | |
else: | |
return Mid | |
else: | |
return low | |
def Insertion_Sort(Test_arr): | |
for i in range(1, len(Test_arr)): | |
val = Test_arr[i] | |
j = Binary_Search(Test_arr[:i], 0, len(Test_arr[:i])-1, val) | |
Test_arr.pop(i) | |
Test_arr.insert(j, val) | |
return Test_arr | |
if __name__ == "__main__": | |
Test_list = input("Enter the list of Numbers: ").split() | |
Test_list = [int(i) for i in Test_list] | |
print(f"Binary Insertion Sort: {Insertion_Sort(Test_list)}") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# It returns location of x in given array arr | |
# if present, else returns -1 | |
def binarySearch(arr, l, r, x): | |
while l <= r: | |
mid = l + (r - l) / 2 #extracting the middle element from the array | |
mid=int(mid) #it has to be integer | |
# Check if x is present at mid | |
if arr[mid] == x: | |
return mid | |
# If x is greater, ignore left half | |
elif arr[mid] < x: | |
l = mid + 1 #l is initialised to the rightmost element of the middle so that the search could be started from there the next time | |
# If x is smaller, ignore right half | |
elif x<arr[mid]: | |
r = mid - 1 #r is initialised to the leftmost element of the middle so that the search goes till there only the next time | |
# If we reach here, then the element was not present | |
return -1 | |
# Main Function | |
if __name__ == "__main__": | |
# User input array | |
print("Enter the array with comma separated in which element will be searched") | |
arr =[int(x) for x in input().split(',')] #the input array will of int type with each element seperated with a comma due to the split fucntion | |
#map function returns a list of results after applying the given function to each item | |
x = eval(input("Enter the element you want to search in given array")) | |
# Function call | |
result = binarySearch(arr, 0, len(arr) - 1, x) | |
#printing the output | |
if result != -1: | |
print("Element is present at index {}".format(result)) | |
else: | |
print("Element is not present in array") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
class Node: | |
"""Class for node of a tree""" | |
def __init__(self, info): | |
"""Initialising a node""" | |
self.info = info | |
self.left = None | |
self.right = None | |
# self.level = None | |
def __str__(self): | |
return str(self.info) | |
def __del__(self): | |
del self | |
class BinarySearchTree: | |
"""Class for BST""" | |
def __init__(self): | |
"""Initialising a BST""" | |
self.root = None | |
def insert(self, val): | |
"""Creating a BST with root value as val""" | |
# Check if tree has root with None value | |
if self.root is None: | |
self.root = Node(val) | |
# Here the tree already has one root | |
else: | |
current = self.root | |
while True: | |
if val < current.info: | |
if current.left: | |
current = current.left | |
else: | |
current.left = Node(val) | |
break | |
elif val > current.info: | |
if current.right: | |
current = current.right | |
else: | |
current.right = Node(val) | |
break | |
else: | |
break | |
def search(self, val, to_delete = False): | |
current = self.root | |
prev = -1 | |
while current: | |
if val < current.info: | |
prev = current | |
current = current.left | |
elif val > current.info: | |
prev = current | |
current = current.right | |
elif current.info == val: | |
if not to_delete: | |
return 'Match Found' | |
return prev | |
else: | |
break | |
if not to_delete: | |
return 'Not Found' | |
# Method to delete a tree-node if it exists, else error message will be returned. | |
def delete(self, val): | |
prev = self.search(val, True) | |
# Check if node exists | |
if prev is not None: | |
# Check if node is the Root node | |
if prev == -1: | |
temp = self.root.left | |
prev2 = None | |
while temp.right: | |
prev2 = temp | |
temp = temp.right | |
if prev2 is None: | |
self.root.left = temp.left | |
self.root.info = temp.info | |
else: | |
prev2.right = None | |
self.root.info = temp.info | |
print('Deleted Root ', val) | |
# Check if node is to left of its parent | |
elif prev.left and prev.left.info == val: | |
# Check if node is leaf node | |
if prev.left.left is prev.left.right: | |
prev.left = None | |
print('Deleted Node ', val) | |
# Check if node has child at left and None at right | |
elif prev.left.left and prev.left.right is None: | |
prev.left = prev.left.left | |
print('Deleted Node ', val) | |
# Check if node has child at right and None at left | |
elif prev.left.left is None and prev.left.right: | |
prev.left = prev.left.right | |
print('Deleted Node ', val) | |
# Here node to be deleted has 2 children | |
elif prev.left.left and prev.left.right: | |
temp = prev.left | |
while temp.right is not None: | |
prev2 = temp | |
temp = temp.right | |
prev2.right = None | |
prev.left.info = temp.info | |
print('Deleted Node ', val) | |
else: | |
print('Error Left') | |
# Check if node is to right of its parent | |
elif prev.right.info == val: | |
flag = 0 | |
# Check is node is a leaf node | |
if prev.right.left is prev.right.right: | |
prev.right = None | |
flag = 1 | |
print('Deleted Node ', val) | |
# Check if node has left child at None at right | |
if prev.right and prev.right.left and prev.right.right is None: | |
prev.right = prev.right.left | |
print('Deleted Node ', val) | |
# Check if node has right child at None at left | |
elif prev.right and prev.right.left is None and prev.right.right: | |
prev.right = prev.right.right | |
print('Deleted Node ', val) | |
elif prev.right and prev.right.left and prev.right.right: | |
temp = prev.right | |
while temp.left is not None: | |
prev2 = temp | |
temp = temp.left | |
prev2.left = None | |
prev.right.info = temp.info | |
print('Deleted Node ', val) | |
else: | |
if flag == 0: | |
print("Error") | |
else: | |
print("Node doesn't exists") | |
def __str__(self): | |
return 'Not able to print tree yet' | |
def is_bst(node, lower_lim=None, upper_lim=None): | |
"""Function to find is a binary tree is a binary search tree.""" | |
if lower_lim is not None and node.info < lower_lim: | |
return False | |
if upper_lim is not None and node.info > upper_lim: | |
return False | |
is_left_bst = True | |
is_right_bst = True | |
if node.left is not None: | |
is_left_bst = is_bst(node.left, lower_lim, node.info) | |
if is_left_bst and node.right is not None: | |
is_right_bst = is_bst(node.right, node.info, upper_lim) | |
return is_left_bst and is_right_bst | |
def postorder(node): | |
# L R N : Left , Right, Node | |
if node is None: | |
return | |
if node.left: | |
postorder(node.left) | |
if node.right: | |
postorder(node.right) | |
print(node.info) | |
def inorder(node): | |
# L N R : Left, Node , Right | |
if node is None: | |
return | |
if node.left: | |
inorder(node.left) | |
print(node.info) | |
if node.right: | |
inorder(node.right) | |
def preorder(node): | |
# N L R : Node , Left, Right | |
if node is None: | |
return | |
print(node.info) | |
if node.left: | |
preorder(node.left) | |
if node.right: | |
preorder(node.right) | |
# Levelwise | |
def bfs(node): | |
queue = [] | |
if node: | |
queue.append(node) | |
while queue != []: | |
temp = queue.pop(0) | |
print(temp.info) | |
if temp.left: | |
queue.append(temp.left) | |
if temp.right: | |
queue.append(temp.right) | |
def preorder_itr(node): | |
# N L R : Node, Left , Right | |
stack = [node] | |
values = [] | |
while stack != []: | |
temp = stack.pop() | |
print(temp.info) | |
values.append(temp.info) | |
if temp.right: | |
stack.append(temp.right) | |
if temp.left: | |
stack.append(temp.left) | |
return values | |
def inorder_itr(node): | |
# L N R : Left, Node, Right | |
# 1) Create an empty stack S. | |
# 2) Initialize current node as root | |
# 3) Push the current node to S and set current = current->left until current is NULL | |
# 4) If current is NULL and stack is not empty then | |
# a) Pop the top item from stack. | |
# b) Print the popped item, set current = popped_item->right | |
# c) Go to step 3. | |
# 5) If current is NULL and stack is empty then we are done. | |
stack = [] | |
current = node | |
while True: | |
if current != None: | |
stack.append(current) # L | |
current = current.left | |
elif stack != []: | |
temp = stack.pop() | |
print(temp.info) # N | |
current = temp.right # R | |
else: | |
break | |
def postorder_itr(node): | |
# L R N | |
# 1. Push root to first stack. | |
# 2. Loop while first stack is not empty | |
# 2.1 Pop a node from first stack and push it to second stack | |
# 2.2 Push left and right children of the popped node to first stack | |
# 3. Print contents of second stack | |
s1, s2 = [node], [] | |
while s1 != []: | |
temp = s1.pop() | |
s2.append(temp) | |
if temp.left: | |
s1.append(temp.left) | |
if temp.right: | |
s1.append(temp.right) | |
print(*(s2[::-1])) | |
def bst_frm_pre(pre_list): | |
box = Node(pre_list[0]) | |
if len(pre_list) > 1: | |
if len(pre_list) == 2: | |
if pre_list[1] > pre_list[0]: | |
box.right = Node(pre_list[1]) | |
else: | |
box.left = Node(pre_list[1]) | |
else: | |
all_less = False | |
for i in range(1, len(pre_list)): | |
if pre_list[i] > pre_list[0]: | |
break | |
else: | |
all_less = True | |
if i != 1: | |
box.left = bst_frm_pre(pre_list[1 : i]) | |
if not all_less: | |
box.right = bst_frm_pre(pre_list[i:]) | |
return box | |
# Function to find the lowest common ancestor of nodes with values c1 and c2. | |
# It return value in the lowest common ancestor, -1 indicates value returned for None. | |
# Note that both values v1 and v2 should be present in the bst. | |
def lca(t_node, c1, c2): | |
if c1 == c2: | |
return c1 | |
current = t_node | |
while current: | |
if c1 < current.info and c2 < current.info: | |
current = current.left | |
elif c1 > current.info and c2 > current.info: | |
current = current.right | |
else: | |
return current.info | |
return -1 | |
# Function to print element vertically which lie just below the root node | |
def vertical_middle_level(t_node): | |
e = (t_node, 0) # 0 indicates level 0, to left we have -ve and to right +ve | |
queue = [e] | |
ans = [] | |
# Do a level-order traversal and assign level-value to each node | |
while queue != []: | |
temp, level = queue.pop(0) | |
if level == 0: | |
ans.append(str(temp.info)) | |
if temp.left: | |
queue.append((temp.left, level - 1)) | |
if temp.right: | |
queue.append((temp.right, level + 1)) | |
return ' '.join(ans) | |
def get_level(n, val): | |
c_level = 0 | |
while n.info != val: | |
if val < n.info: | |
n = n.left | |
elif val > n.info: | |
n = n.right | |
c_level += 1 | |
if n is None: | |
return -1 | |
return c_level | |
def depth(node): | |
if node is None: | |
return 0 | |
l_depth, r_depth = 0, 0 | |
if node.left: | |
l_depth = depth(node.left) | |
if node.right: | |
r_depth = depth(node.right) | |
# print(node.info, l_depth, r_depth) | |
return 1 + max(l_depth, r_depth) | |
t = BinarySearchTree() | |
t.insert(10) | |
t.insert(5) | |
t.insert(15) | |
t.insert(3) | |
t.insert(1) | |
t.insert(0) | |
t.insert(2) | |
t.insert(7) | |
t.insert(12) | |
t.insert(18) | |
t.insert(19) | |
print(depth(t.root)) | |
# inorder(t.root) | |
# print() | |
# print(t.search(5)) | |
# t.delete(7) | |
# t.delete(5) | |
# t.delete(3) | |
# t.delete(15) | |
# inorder(t.root) | |
# print() | |
# t.delete(2) | |
# t.delete(3) | |
# t.delete(7) | |
# t.delete(19) | |
# t.delete(1) | |
# inorder(t.root) | |
# b = BinarySearchTree() | |
# b.root = bst_frm_pre(preorder_itr(t.root)) | |
# print(preorder_itr(b.root) == preorder_itr(t.root)) | |
# print(lca(t.root, 3, 18)) | |
# print(vertical_middle_level(t.root)) | |
# print(get_level(t.root, 1)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Program to convert binary to decimal | |
def binaryToDecimal(binary): | |
""" | |
>>> binaryToDecimal(111110000) | |
496 | |
>>> binaryToDecimal(10100) | |
20 | |
>>> binaryToDecimal(101011) | |
43 | |
""" | |
decimal, i, n = 0, 0, 0 | |
while(binary != 0): | |
dec = binary % 10 | |
decimal = decimal + dec * pow(2, i) | |
binary = binary//10 | |
i += 1 | |
print(decimal) | |
binaryToDecimal(100) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# patch-1 | |
import os #The OS module in python provides functions for interacting with the operating system | |
# patch-3 | |
# function to check if 'binod' is present in the file. | |
# def checkBinod(file): | |
# ======= | |
# def checkBinod(file): #this function will check there is any 'Binod' text in file or not | |
# with open(file, "r") as f: #we are opening file in read mode and using 'with' so need to take care of close() | |
# ======= | |
import time | |
import os | |
#Importing our Bindoer | |
print("To Kaise Hai Ap Log!") | |
time.sleep(1) | |
print("Chaliye Binod Karte Hai!") | |
def checkBinod(file):#Trying to find Binod In File Insted Of Manohar Ka Kotha | |
# master | |
with open(file, "r") as f: | |
# master | |
fileContent = f.read() | |
if 'binod' in fileContent.lower(): | |
print( | |
f'**************Congratulations Binod found in {f}********************') | |
return True | |
else: | |
return False | |
if __name__ == '__main__': | |
print("************binod Detector********************") | |
dir_contents = os.listdir() | |
for item in dir_contents: | |
if item.endswith('txt'): | |
ans = checkBinod(item) | |
if(ans is False): | |
print('Binod not found Try Looking In Manohar Ka Kotha!!') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from threading import Thread | |
from Background import Background | |
from PIL.Image import open as openImage | |
from PIL.ImageTk import PhotoImage | |
class Bird(Thread): | |
""" | |
Classe para criar um pássaro | |
""" | |
__tag = "Bird" | |
__isAlive = None | |
__going_up = False | |
__going_down = 0 | |
__times_skipped = 0 | |
__running = False | |
decends = 0.00390625 | |
climbsUp = 0.0911458333 | |
def __init__(self, background, gameover_function, *screen_geometry, fp="bird.png", event="<Up>", descend_speed=5): | |
# Verifica se "background" é uma instância de Background e se o "gamerover_method" é chamável | |
if not isinstance(background, Background): raise TypeError( | |
"The background argument must be an instance of Background.") | |
if not callable(gameover_function): raise TypeError("The gameover_method argument must be a callable object.") | |
# Instância os parâmetros | |
self.__canvas = background | |
self.image_path = fp | |
self.__descend_speed = descend_speed | |
self.gameover_method = gameover_function | |
# Recebe a largura e altura do background | |
self.__width = screen_geometry[0] | |
self.__height = screen_geometry[1] | |
# Define a decida e subida do pássaro com base na altura do background | |
self.decends *= self.__height | |
self.decends = int(self.decends + 0.5) | |
self.climbsUp *= self.__height | |
self.climbsUp = int(self.climbsUp + 0.5) | |
# Invoca o método construtor de Thread | |
Thread.__init__(self) | |
# Calcula o tamanho do pássaro com base na largura e altura da janela | |
self.width = (self.__width // 100) * 6 | |
self.height = (self.__height // 100) * 11 | |
# Carrega e cria a imagem do pássaro no background | |
self.__canvas.bird_image = \ | |
self.getPhotoImage(image_path=self.image_path, width=self.width, height=self.height, closeAfter=True)[0] | |
self.__birdID = self.__canvas.create_image(self.__width // 2, self.__height // 2, | |
image=self.__canvas.bird_image, tag=self.__tag) | |
# Define evento para fazer o pássaro subir | |
self.__canvas.focus_force() | |
self.__canvas.bind(event, self.jumps) | |
self.__isAlive = True | |
def birdIsAlive(self): | |
""" | |
Método para verificar se o pássaro está vivo | |
""" | |
return self.__isAlive | |
def checkCollision(self): | |
""" | |
Método para verificar se o pássaro ultrapassou a borda da janela ou colidiu com algo | |
""" | |
# Recebe a posição do pássaro no background | |
position = list(self.__canvas.bbox(self.__tag)) | |
# Se o pássaro tiver ultrapassado a borda de baixo do background, ele será declarado morto | |
if position[3] >= self.__height + 20: | |
self.__isAlive = False | |
# Se o pássaro tiver ultrapassado a borda de cima do background, ele será declarado morto | |
if position[1] <= -20: | |
self.__isAlive = False | |
# Dá uma margem de erro ao pássaro de X pixels | |
position[0] += int(25 / 78 * self.width) | |
position[1] += int(25 / 77 * self.height) | |
position[2] -= int(20 / 78 * self.width) | |
position[3] -= int(10 / 77 * self.width) | |
# Define os objetos a serem ignorados em colisões | |
ignored_collisions = self.__canvas.getBackgroundID() | |
ignored_collisions.append(self.__birdID) | |
# Verifica possíveis colisões com o pássaro | |
possible_collisions = list(self.__canvas.find_overlapping(*position)) | |
# Remove das possíveis colisões os objetos ignorados | |
for _id in ignored_collisions: | |
try: | |
possible_collisions.remove(_id) | |
except: | |
continue | |
# Se houver alguma colisão o pássaro morre | |
if len(possible_collisions) >= 1: | |
self.__isAlive = False | |
return not self.__isAlive | |
def getTag(self): | |
""" | |
Método para retornar a tag do pássaro | |
""" | |
return self.__tag | |
@staticmethod | |
def getPhotoImage(image=None, image_path=None, width=None, height=None, closeAfter=False): | |
""" | |
Retorna um objeto da classe PIL.ImageTk.PhotoImage de uma imagem e as imagens criadas de PIL.Image | |
(photoImage, new, original) | |
@param image: Instância de PIL.Image.open | |
@param image_path: Diretório da imagem | |
@param width: Largura da imagem | |
@param height: Altura da imagem | |
@param closeAfter: Se True, a imagem será fechada após ser criado um PhotoImage da mesma | |
""" | |
if not image: | |
if not image_path: return | |
# Abre a imagem utilizando o caminho dela | |
image = openImage(image_path) | |
# Será redimesionada a imagem somente se existir um width ou height | |
if not width: width = image.width | |
if not height: height = image.height | |
# Cria uma nova imagem já redimensionada | |
newImage = image.resize([width, height]) | |
# Cria um photoImage | |
photoImage = PhotoImage(newImage) | |
# Se closeAfter for True, ele fecha as imagens | |
if closeAfter: | |
# Fecha a imagem nova | |
newImage.close() | |
newImage = None | |
# Fecha a imagem original | |
image.close() | |
image = None | |
# Retorna o PhotoImage da imagem,a nova imagem que foi utilizada e a imagem original | |
return photoImage, newImage, image | |
def jumps(self, event=None): | |
""" | |
Método para fazer o pássaro pular | |
""" | |
# Verifica se o pássaro saiu da área do background | |
self.checkCollision() | |
# Se o pássaro estiver morto, esse método não pode ser executado | |
if not self.__isAlive or not self.__running: | |
self.__going_up = False | |
return | |
# Declara que o pássaro está subindo | |
self.__going_up = True | |
self.__going_down = 0 | |
# Move o pássaro enquanto o limite de subida por animação não tiver excedido | |
if self.__times_skipped < self.climbsUp: | |
# Move o pássaro para cima | |
self.__canvas.move(self.__tag, 0, -1) | |
self.__times_skipped += 1 | |
# Executa o método novamente | |
self.__canvas.after(3, self.jumps) | |
else: | |
# Declara que o pássaro não está mais subindo | |
self.__going_up = False | |
self.__times_skipped = 0 | |
def kill(self): | |
""" | |
Método para matar o pássaro | |
""" | |
self.__isAlive = False | |
def run(self): | |
""" | |
#Método para iniciar a animação do passáro caindo | |
""" | |
self.__running = True | |
# Verifica se o pássaro saiu da área do background | |
self.checkCollision() | |
# Enquanto o pássaro não tiver chegado em sua velocidade máxima, a velocidade aumentará em 0.05 | |
if self.__going_down < self.decends: | |
self.__going_down += 0.05 | |
# Executa a animação de descida somente se o pássaro estiver vivo | |
if self.__isAlive: | |
# Executa a animação de descida somente se o pássaro não estiver subindo | |
if not self.__going_up: | |
# Move o pássaro para baixo | |
self.__canvas.move(self.__tag, 0, self.__going_down) | |
# Executa novamente o método | |
self.__canvas.after(self.__descend_speed, self.run) | |
# Se o pássaro estiver morto, será executado um método de fim de jogo | |
else: | |
self.__running = False | |
self.gameover_method() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4'} | |
while True: | |
print('Enter a name: (blank to quit)') | |
name = input() | |
if name == '': | |
break | |
if name in birthdays: | |
print(birthdays[name] + ' is the birthday of ' + name) | |
else: | |
print('I do not have birthday information for ' + name) | |
print('What is their birthday?') | |
bday = input() | |
birthdays[name] = bday | |
print('Birthday database updated.') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# BLACK JACK - CASINO | |
import random | |
deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11] * 4 | |
random.shuffle(deck) | |
print( | |
" ********************************************************** ") | |
print( | |
" Welcome to the game Casino - BLACK JACK ! ") | |
print( | |
" ********************************************************** ") | |
d_cards = [] # Initialising dealer's cards | |
p_cards = [] # Initialising player's cards | |
while len(d_cards) != 2: | |
random.shuffle(deck) | |
d_cards.append(deck.pop()) | |
if len(d_cards) == 2: | |
print('The cards dealer has are X ', d_cards[1]) | |
# Displaying the Player's cards | |
while len(p_cards) != 2: | |
random.shuffle(deck) | |
p_cards.append(deck.pop()) | |
if len(p_cards) == 2: | |
print("The total of player is ", sum(p_cards)) | |
print("The cards Player has are ", p_cards) | |
if sum(p_cards) > 21: | |
print("You are BUSTED !\n **************Dealer Wins !!******************\n") | |
exit() | |
if sum(d_cards) > 21: | |
print("Dealer is BUSTED !\n ************** You are the Winner !!******************\n") | |
exit() | |
if sum(d_cards) == 21: | |
print("***********************Dealer is the Winner !!******************") | |
exit() | |
if sum(d_cards) == 21 and sum(p_cards) == 21: | |
print("*****************The match is tie !!*************************") | |
exit() | |
def dealer_choice(): | |
if sum(d_cards) < 17: | |
while sum(d_cards) < 17: | |
random.shuffle(deck) | |
d_cards.append(deck.pop()) | |
print("Dealer has total " + str(sum(d_cards)) + "with the cards ", d_cards) | |
if sum(p_cards) == sum(d_cards): | |
print("***************The match is tie !!****************") | |
exit() | |
if sum(d_cards) == 21: | |
if sum(p_cards) < 21: | |
print("***********************Dealer is the Winner !!******************") | |
elif sum(p_cards) == 21: | |
print("********************There is tie !!**************************") | |
else: | |
print("***********************Dealer is the Winner !!******************") | |
elif sum(d_cards) < 21: | |
if sum(p_cards) < 21 and sum(p_cards) < sum(d_cards): | |
print("***********************Dealer is the Winner !!******************") | |
if sum(p_cards) == 21: | |
print("**********************Player is winner !!**********************") | |
if sum(p_cards) < 21 and sum(p_cards) > sum(d_cards): | |
print("**********************Player is winner !!**********************") | |
else: | |
if sum(p_cards) < 21: | |
print("**********************Player is winner !!**********************") | |
elif sum(p_cards) == 21: | |
print("**********************Player is winner !!**********************") | |
else: | |
print("***********************Dealer is the Winner !!******************") | |
while sum(p_cards) < 21: | |
k = input('Want to hit or stay?\n Press 1 for hit and 0 for stay ') | |
if k == 1: | |
random.shuffle(deck) | |
p_cards.append(deck.pop()) | |
print('You have a total of ' + str(sum(p_cards)) | |
+ ' with the cards ', p_cards) | |
if sum(p_cards) > 21: | |
print('*************You are BUSTED !*************\n Dealer Wins !!') | |
if sum(p_cards) == 21: | |
print('*******************You are the Winner !!*****************************') | |
else: | |
dealer_choice() | |
break |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
class Colour: | |
BLACK = '\033[30m' | |
RED = '\033[91m' | |
GREEN = '\033[32m' | |
END = '\033[0m' | |
suits = (Colour.RED + 'Hearts' + Colour.END, Colour.RED + 'Diamonds' + Colour.END, Colour.BLACK + 'Spades' + Colour.END, Colour.BLACK + 'Clubs' + Colour.END) | |
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace') | |
values = {'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8, | |
'Nine': 9, 'Ten': 10, 'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 11} | |
playing = True | |
class Card: | |
def __init__(self, suit, rank): | |
self.suit = suit | |
self.rank = rank | |
def __str__(self): | |
return self.rank + ' of ' + self.suit | |
class Deck: | |
def __init__(self): | |
self.deck = [] | |
for suit in suits: | |
for rank in ranks: | |
self.deck.append(Card(suit, rank)) | |
def __str__(self): | |
deck_comp = '' | |
for card in self.deck: | |
deck_comp += '\n ' + card.__str__() | |
def shuffle(self): | |
random.shuffle(self.deck) | |
def deal(self): | |
single_card = self.deck.pop() | |
return single_card | |
class Hand: | |
def __init__(self): | |
self.cards = [] | |
self.value = 0 | |
self.aces = 0 # to keep track of aces | |
def add_card(self, card): | |
self.cards.append(card) | |
self.value += values[card.rank] | |
if card.rank == 'Ace': | |
self.aces += 1 | |
def adjust_for_ace(self): | |
while self.value > 21 and self.aces: | |
self.value -= 10 | |
self.aces -= 1 | |
class Chips: | |
def __init__(self): | |
self.total = 100 | |
self.bet = 0 | |
def win_bet(self): | |
self.total += self.bet | |
def lose_bet(self): | |
self.total -= self.bet | |
def take_bet(chips): | |
while True: | |
try: | |
chips.bet = int(input('How many chips would you like to bet? ')) | |
except ValueError: | |
print('Your bet must be an integer! Try again.') | |
else: | |
if chips.bet > chips.total or chips.bet <= 0: | |
print( | |
"Your bet cannot exceed your balance and you have to enter a positive bet! Your current balance is: ", | |
chips.total) | |
else: | |
break | |
def hit(deck, hand): | |
hand.add_card(deck.deal()) | |
hand.adjust_for_ace() | |
def hit_or_stand(deck, hand): | |
global playing | |
while True: | |
x = input("Would you like to Hit or Stand? Enter '1' or '0' ") | |
if x.lower() == '1': | |
hit(deck, hand) | |
elif x.lower() == '0': | |
print("You chose to stand. Dealer will hit.") | |
playing = False | |
else: | |
print("Wrong input, please try again.") | |
continue | |
break | |
def show_some(player, dealer): | |
print("\nDealer's Hand:") | |
print(" { hidden card }") | |
print('', dealer.cards[1]) | |
print("\nYour Hand:", *player.cards, sep='\n ') | |
def show_all(player, dealer): | |
print("\nDealer's Hand:", *dealer.cards, sep='\n ') | |
print("Dealer's Hand =", dealer.value) | |
print("\nYour Hand:", *player.cards, sep='\n ') | |
print("Your Hand =", player.value) | |
def player_busts(player, dealer, chips): | |
print("You are BUSTED !") | |
chips.lose_bet() | |
def player_wins(player, dealer, chips): | |
print("You are the winner!") | |
chips.win_bet() | |
def dealer_busts(player, dealer, chips): | |
print("Dealer has BUSTED !") | |
chips.win_bet() | |
def dealer_wins(player, dealer, chips): | |
print("Dealer is the winner!") | |
chips.lose_bet() | |
def push(player, dealer): | |
print("The match is tie !") | |
# GAMEPLAY | |
player_chips = Chips() | |
while True: | |
print("\t **********************************************************") | |
print( | |
"\t Welcome to the game Casino - BLACK JACK ! ") | |
print("\t **********************************************************") | |
print(Colour.BLACK + "\t ***************") | |
print("\t * A *") | |
print("\t * *") | |
print("\t * * *") | |
print("\t * *** *") | |
print("\t * ***** *") | |
print("\t * *** *") | |
print("\t * * *") | |
print("\t * *") | |
print("\t * *") | |
print("\t ***************" + Colour.END) | |
print('\nRULES: Get as close to 21 as you can but if you get more than 21 you will lose!\n Aces count as 1 or 11.') | |
deck = Deck() | |
deck.shuffle() | |
player_hand = Hand() | |
player_hand.add_card(deck.deal()) | |
player_hand.add_card(deck.deal()) | |
dealer_hand = Hand() | |
dealer_hand.add_card(deck.deal()) | |
dealer_hand.add_card(deck.deal()) | |
take_bet(player_chips) | |
show_some(player_hand, dealer_hand) | |
while playing: | |
hit_or_stand(deck, player_hand) | |
show_some(player_hand, dealer_hand) | |
if player_hand.value > 21: | |
player_busts(player_hand, dealer_hand, player_chips) | |
break | |
if player_hand.value <= 21: | |
while dealer_hand.value < 17: | |
hit(deck, dealer_hand) | |
show_all(player_hand, dealer_hand) | |
if dealer_hand.value > 21: | |
dealer_busts(player_hand, dealer_hand, player_chips) | |
elif dealer_hand.value > player_hand.value: | |
dealer_wins(player_hand, dealer_hand, player_chips) | |
elif dealer_hand.value < player_hand.value: | |
player_wins(player_hand, dealer_hand, player_chips) | |
else: | |
push(player_hand, dealer_hand) | |
print("\nYour current balance stands at", player_chips.total) | |
if player_chips.total > 0: | |
new_game = input("Would you like to play another hand? Enter '1' or '0' ") | |
if new_game.lower() == '1': | |
playing = True | |
continue | |
else: | |
print( | |
"Thanks for playing!\n" + Colour.GREEN + "\t$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n \t Congratulations! You won " + str(player_chips.total) + " coins!\n\t$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n " + Colour.END) | |
break | |
else: | |
print( | |
"Oops! You have bet all your chips and we are sorry you can't play more.\nThanks for playing! Do come again to Casino BLACK JACK!") | |
break |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import print_function | |
import random | |
import simplegui | |
CARD_SIZE = (72, 96) | |
CARD_CENTER = (36, 48) | |
card_images = simplegui.load_image("http://storage.googleapis.com/codeskulptor-assets/cards_jfitz.png") | |
in_play = False | |
outcome = "" | |
score = 0 | |
SUITS = ('C', 'S', 'H', 'D') | |
RANKS = ('A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K') | |
VALUES = {'A': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'T': 10, 'J': 10, 'Q': 10, 'K': 10} | |
class Card: | |
def __init__(self, suit, rank): | |
if (suit in SUITS) and (rank in RANKS): | |
self.suit = suit | |
self.rank = rank | |
else: | |
self.suit = None | |
self.rank = None | |
print(("Invalid card: ", suit, rank)) | |
def __str__(self): | |
return self.suit + self.rank | |
def get_suit(self): | |
return self.suit | |
def get_rank(self): | |
return self.rank | |
def draw(self, canvas, pos): | |
card_loc = (CARD_CENTER[0] + CARD_SIZE[0] * RANKS.index(self.rank), | |
CARD_CENTER[1] + CARD_SIZE[1] * SUITS.index(self.suit)) | |
canvas.draw_image(card_images, card_loc, CARD_SIZE, [pos[0] + CARD_CENTER[0], pos[1] + CARD_CENTER[1]], | |
CARD_SIZE) | |
def string_list_join(string, string_list): | |
ans = string + " contains " | |
for i in range(len(string_list)): | |
ans += str(string_list[i]) + " " | |
return ans | |
class Hand: | |
def __init__(self): | |
self.hand = [] | |
def __str__(self): | |
return string_list_join("Hand", self.hand) | |
def add_card(self, card): | |
self.hand.append(card) | |
def get_value(self): | |
var = [] | |
self.hand_value = 0 | |
for card in self.hand: | |
card = str(card) | |
if card[1] in VALUES: | |
self.hand_value += VALUES[card[1]] | |
var.append(card[1]) | |
if 'A' not in var: | |
return self.hand_value | |
if self.hand_value + 10 <= 21: | |
return self.hand_value + 10 | |
else: | |
return self.hand_value | |
def draw(self, canvas, pos): | |
for card in self.hand: | |
card = str(card) | |
Card(card[0], card[1]).draw(canvas, pos) | |
pos[0] += 36 | |
class Deck: | |
def __init__(self): | |
self.Deck = [Card(suit, rank) for suit in SUITS for rank in RANKS] | |
def shuffle(self): | |
random.shuffle(self.Deck) | |
def deal_card(self): | |
return random.choice(self.Deck) | |
def __str__(self): | |
return string_list_join("Deck", self.Deck) | |
def deal(): | |
global outcome, in_play, score1, score2, player_card, dealer_card, deck | |
outcome = "" | |
player_card = Hand() | |
dealer_card = Hand() | |
deck = Deck() | |
for i in range(2): | |
player_card.add_card(deck.deal_card()) | |
dealer_card.add_card(deck.deal_card()) | |
in_play = True | |
score1 = str(player_card.get_value()) | |
score2 = str(dealer_card.get_value()) | |
def stand(): | |
if in_play == True: | |
while dealer_card.get_value() < 17: | |
dealer_card.add_card(deck.deal_card()) | |
if dealer_card.get_value() > 21: | |
outcome = "you won!!" | |
elif player_card.get_value() <= dealer_card.get_value(): | |
outcome = "you lose" | |
else: | |
outcome = "you won!!" | |
score1 = str(player_card.get_value()) | |
score2 = str(dealer_card.get_value()) | |
def hit(): | |
global outcome, in_play, score1, score2, player_card, dealer_card, deck | |
if in_play == True: | |
player_card.add_card(deck.deal_card()) | |
if player_card.get_value() > 21: | |
outcome = "you are busted" | |
in_play = False | |
score1 = str(player_card.get_value()) | |
score2 = str(dealer_card.get_value()) | |
def draw(canvas): | |
canvas.draw_text(outcome, [250, 150], 25, 'White') | |
canvas.draw_text("BlackJack", [250, 50], 40, 'Black') | |
canvas.draw_text(score1, [100, 100], 40, 'Red') | |
player_card.draw(canvas, [20, 300]) | |
dealer_card.draw(canvas, [300, 300]) | |
canvas.draw_text(score2, [400, 100], 40, 'Red') | |
frame = simplegui.create_frame("Blackjack", 600, 600) | |
frame.set_canvas_background("Green") | |
frame.add_button("Deal", deal, 200) | |
frame.add_button("Hit", hit, 200) | |
frame.add_button("Stand", stand, 200) | |
frame.set_draw_handler(draw) | |
deal() | |
frame.start() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import mysql.connector as mys | |
mycon=mys.connect(host='localhost',user='root',passwd='Yksrocks',database='book_store_management') | |
if mycon.is_connected(): | |
print() | |
print('successfully connected') | |
mycur=mycon.cursor() | |
def DBZ(): | |
# IF NO. OF BOOKS IS ZERO(0) THAN DELETE IT AUTOMATICALLY | |
display="select * from books" | |
mycur.execute(display) | |
data2=mycur.fetchall() | |
for y in data2: | |
if y[6]<=0: | |
delete="delete from books where Numbers_of_book<=0" | |
mycur.execute(delete) | |
mycon.commit() | |
def separator(): | |
print() | |
print("\t\t========================================") | |
print() | |
def end_separator(): | |
print() | |
print() | |
def login(): | |
user_name=input(" USER NAME --- ") | |
passw=input(" PASSWORD --- ") | |
display='select * from login' | |
mycur.execute(display) | |
data2=mycur.fetchall() | |
for y in data2: | |
if y[1]==user_name and y[2]==passw: | |
pass | |
else: | |
separator() | |
print(" Username or Password is Incorrect Try Again") | |
separator() | |
user_name=input(" USER NAME --- ") | |
passw=input(" PASSWORD --- ") | |
if y[1]==user_name and y[2]==passw: | |
pass | |
else: | |
separator() | |
print(" Username or Password is Again Incorrect") | |
exit() | |
def ViewAll(): | |
print("\u0332".join("BOOK NAMES~~")) | |
print("------------------------------------") | |
display='select * from books' | |
mycur.execute(display) | |
data2=mycur.fetchall() | |
c=0 | |
for y in data2: | |
c=c+1 | |
print(c,"-->",y[1]) | |
def CNB1(): | |
if y[6]==0: | |
separator() | |
print(" NOW THIS BOOK IS NOT AVAILABLE ") | |
elif y[6]>0 and y[6]<=8: | |
separator() | |
print("WARNING!!!!!!!!!!!!!!!!!!!!!!!") | |
print("NO. OF THIS BOOK IS LOW","\tONLY",y[6]-1,"LEFT") | |
print() | |
print() | |
elif y[6]>8: | |
separator() | |
print("NO. OF BOOKS LEFT IS ",y[6]-1) | |
print() | |
print() | |
def CNB2(): | |
if y[6]<=8: | |
separator() | |
print("WARNING!!!!!!!!!!!!!!!!!!!!!!!") | |
print("NO. OF THIS BOOK IS LOW","\tONLY",y[6],"LEFT") | |
else: | |
separator() | |
print("NO. OF BOOKS LEFT IS ",y[6]) | |
separator() | |
# LOGIN | |
display12='select * from visit' | |
mycur.execute(display12) | |
data2222=mycur.fetchall() | |
for m in data2222: | |
if m[0]==0: | |
c=m[0] | |
display11='select * from login' | |
mycur.execute(display11) | |
data222=mycur.fetchall() | |
if c==0: | |
if c==0: | |
print("\t\t\t\t REGESTER ") | |
print("\t\t\t\t----------------------------") | |
print() | |
print() | |
user_name=input("ENTER USER NAME -- ") | |
passw=input("ENTER PASSWORD limit 8-20 -- ") | |
lenght=len(passw) | |
if lenght>=8 and lenght<=20: | |
c=c+1 | |
insert55=(c,user_name,passw) | |
insert22="insert into login values(%s,%s,%s)" | |
mycur.execute(insert22,insert55) | |
mycon.commit() | |
separator() | |
login() | |
else: | |
if lenght<8: | |
separator() | |
print(" Password Is less than 8 Characters Enter Again") | |
separator() | |
user_name2=input("ENTER USER NAME -- ") | |
passw2=input("ENTER PASSWORD AGAIN (limit 8-20) -- ") | |
lenght1=len(passw2) | |
if lenght1>=8 and lenght1<=20: | |
c=c+1 | |
insert555=(c,user_name2,passw2) | |
insert222="insert into login values(%s,%s,%s)" | |
mycur.execute(insert222,insert555) | |
mycon.commit() | |
separator() | |
login() | |
elif lenght>20: | |
separator() | |
print(" Password Is Greater than 20 Characters Enter Again") | |
separator() | |
user_name=input("ENTER USER NAME -- ") | |
passw=input("ENTER PASSWORD AGAIN (limit 8-20) -- ") | |
lenght=len(passw) | |
if lenght>=8 and lenght>=20: | |
c=c+1 | |
insert55=(c,user_name,passw) | |
insert22="insert into login values(%s,%s,%s)" | |
mycur.execute(insert22,insert55) | |
mycon.commit() | |
separator() | |
login() | |
update33="update visit set visits=%s"%(c) | |
mycur.execute(update33) | |
mycon.commit() | |
elif m[0]==1: | |
if m[0]==1: | |
login() | |
separator() | |
DBZ() | |
# REPETITION | |
a=True | |
while a==True: | |
# PROGRAM STARTED | |
print(" *TO VIEW ALL ENTER 1") | |
print(" *TO SEARCH and BUY BOOK ENTER 2") | |
print(" *TO ADD BOOK ENTER 3") | |
print(" *TO UPDATE ENTER 4") | |
print(" *TO DELETE BOOK ENTER 5") | |
print(" *TO CLOSE ENTER 6") | |
print() | |
choice=int(input("ENTER YOUR CHOICE -- ")) | |
separator() | |
#VIEW | |
if choice==1: | |
print() | |
ViewAll() | |
separator() | |
rep=input("Do You Want To Restart ?? yes / no -- ").lower() | |
if rep=="yes": | |
end_separator() | |
separator() | |
DBZ() | |
continue | |
else: | |
end_separator() | |
DBZ() | |
os._exit(0) | |
end_separator() | |
#SEARCH / BUY | |
if choice==2: | |
book_name=input("ENTER BOOK NAME ---- ") | |
separator() | |
display="select * from books where Name='%s'"%(book_name) | |
mycur.execute(display) | |
data2=mycur.fetchone() | |
if data2!=None: | |
print("BOOK IS AVAILABLE") | |
#BUY OR NOT | |
separator() | |
print("\t*WANT TO BUY PRESS 1") | |
print("\t*IF NOT PRESS 2") | |
print() | |
choice2=int(input("ENTER YOUR CHOICE -- ")) | |
if choice2==1: | |
#BUY 1 OR MORE | |
separator() | |
print("\t*IF YOU WANT ONE BOOK PRESS 1") | |
print("\t*IF YOU WANT MORE THAN ONE BOOK PRESS 2") | |
print() | |
choice3=int(input("ENTER YOUR CHOICE -- ")) | |
if choice3==1: | |
display='select * from books' | |
mycur.execute(display) | |
data2=mycur.fetchall() | |
for y in data2: | |
if y[1]==book_name: | |
if y[6]>0: | |
separator() | |
u="update books set Numbers_of_book=Numbers_of_book - 1 where name='%s';"%(book_name) | |
mycur.execute(u) | |
mycon.commit() | |
print("BOOK WAS BOUGHT") | |
separator() | |
print("THANKS FOR COMING") | |
CNB1() | |
separator() | |
rep=input("Do You Want To Restart ?? yes / no -- ").lower() | |
if rep=="yes": | |
end_separator() | |
separator() | |
DBZ() | |
continue | |
else: | |
end_separator() | |
DBZ() | |
os._exit(0) | |
if choice3==2: | |
separator() | |
wb=int(input("ENTER NO. OF BOOKS -- ")) | |
separator() | |
display='select * from books' | |
mycur.execute(display) | |
data2=mycur.fetchall() | |
for y in data2: | |
if y[1]==book_name: | |
if wb>y[6]: | |
if y[6]>0: | |
print("YOU CAN'T BUT THAT MUCH BOOKS") | |
separator() | |
print("BUT YOU CAN BUY",y[6],"BOOKS MAX") | |
separator() | |
choice44=input("DO YOU WANT TO BUY BOOK ? Y/N -- ") | |
separator() | |
k=y[6] | |
if choice44=="y" or choice44=="Y": | |
u2="update books set numbers_of_book=numbers_of_book -%s where name='%s'"%(k,book_name) | |
mycur.execute(u2) | |
mycon.commit() | |
print("BOOK WAS BOUGHT") | |
separator() | |
print("THANKS FOR COMING") | |
separator() | |
display='select * from books' | |
mycur.execute(display) | |
data2=mycur.fetchall() | |
for y in data2: | |
if y[1]==book_name: | |
if y[6]<=8: | |
print("WARNING!!!!!!!!!!!!!!!!!!!!!!!") | |
print("NO. OF THIS BOOK IS LOW","\tONLY",y[6],"LEFT") | |
end_separator() | |
break | |
separator() | |
rep=input("Do You Want To Restart ?? yes / no -- ").lower() | |
if rep=="yes": | |
end_separator() | |
separator() | |
DBZ() | |
continue | |
else: | |
end_separator() | |
DBZ() | |
os._exit(0) | |
elif choice44=="n" or choice44=="N": | |
print("SORRY FOR INCONVENIENCE WE WILL TRY TO FULLFILL YOUR REQUIREMENT AS SOON AS POSSIBLE") | |
end_separator() | |
separator() | |
rep=input("Do You Want To Restart ?? yes / no -- ").lower() | |
if rep=="yes": | |
separator() | |
DBZ() | |
continue | |
else: | |
end_separator() | |
DBZ() | |
os._exit(0) | |
elif y[6]==0: | |
print("SORRY NO BOOK LEFT WE WILL TRY TO FULLFILL YOUR REQUIREMENT AS SOON AS POSSIBLE") | |
end_separator() | |
separator() | |
rep=input("Do You Want To Restart ?? yes / no -- ").lower() | |
if rep=="yes": | |
separator() | |
DBZ() | |
continue | |
else: | |
end_separator() | |
DBZ() | |
os._exit(0) | |
else: | |
u2="update books set numbers_of_book=numbers_of_book -%s where name='%s'"%(wb,book_name) | |
mycur.execute(u2) | |
mycon.commit() | |
print("BOOK WAS BOUGHT") | |
separator() | |
print("THANKS FOR COMING") | |
display='select * from books' | |
mycur.execute(display) | |
data2=mycur.fetchall() | |
for y in data2: | |
if y[1]==book_name: | |
CNB2() | |
separator() | |
rep=input("Do You Want To Restart ?? yes / no -- ").lower() | |
if rep=="yes": | |
separator() | |
DBZ() | |
continue | |
else: | |
end_separator() | |
DBZ() | |
os._exit(0) | |
else: | |
separator() | |
print("NO BOOK IS BOUGHT") | |
end_separator() | |
separator() | |
rep=input("Do You Want To Restart ?? yes / no -- ").lower() | |
if rep=="yes": | |
separator() | |
DBZ() | |
continue | |
else: | |
end_separator() | |
DBZ() | |
os._exit(0) | |
else: | |
separator() | |
print("SORRY NO BOOK WITH THIS NAME EXIST / NAME IS INCORRECT") | |
end_separator() | |
separator() | |
rep=input("Do You Want To Restart ?? yes / no -- ").lower() | |
if rep=="yes": | |
separator() | |
DBZ() | |
continue | |
else: | |
end_separator() | |
DBZ() | |
os._exit(0) | |
# ADDING BOOK | |
if choice==3: | |
q10=int(input("ENTER NO. OF BOOKS TO ADD -- ")) | |
separator() | |
for k in range(q10): | |
SNo10=int(input("ENTER SNo OF BOOK -- ")) | |
name10=input("ENTER NAME OF BOOK --- ") | |
author10=input("ENTER NAME OF AUTHOR -- ") | |
year10=int(input("ENTER YEAR OF PUBLISHING -- ")) | |
ISBN10=input("ENTER ISBN OF BOOK -- ") | |
price10=int(input("ENTER PRICE OF BOOK -- ")) | |
nob10=int(input("ENTER NO. OF BOOKS -- ")) | |
display10="select * from books where ISBN='%s'"%(ISBN10) | |
mycur.execute(display10) | |
data20=mycur.fetchone() | |
if data20!=None: | |
print("This ISBN Already Exists") | |
os._exit(0) | |
else: | |
insert=(SNo10,name10,author10,year10,ISBN10,price10,nob10) | |
insert20="insert into books values(%s,%s,%s,%s,%s,%s,%s)" | |
mycur.execute(insert20,insert) | |
mycon.commit() | |
separator() | |
print("BOOK IS ADDED") | |
separator() | |
rep=input("Do You Want To Restart ?? yes / no -- ").lower() | |
if rep=="yes": | |
separator() | |
DBZ() | |
continue | |
else: | |
end_separator() | |
DBZ() | |
os._exit(0) | |
# UPDATING BOOK | |
if choice==4: | |
choice4=input("ENTER ISBN OF BOOK -- ") | |
separator() | |
display="select * from books where ISBN='%s'"%(choice4) | |
mycur.execute(display) | |
data2=mycur.fetchone() | |
if data2!=None: | |
SNo1=int(input("ENTER NEW SNo OF BOOK -- ")) | |
name1=input("ENTER NEW NAME OF BOOK --- ") | |
author1=input("ENTER NEW NAME OF AUTHOR -- ") | |
year1=int(input("ENTER NEW YEAR OF PUBLISHING -- ")) | |
ISBN1=input("ENTER NEW ISBN OF BOOK -- ") | |
price1=int(input("ENTER NEW PRICE OF BOOK -- ")) | |
nob=int(input("ENTER NEW NO. OF BOOKS -- ")) | |
insert=(SNo1,name1,author1,year1,ISBN1,price1,nob,choice4) | |
update="update books set SNo=%s,Name=%s,Author=%s,Year=%s,ISBN=%s,Price=%s,numbers_of_book=%s where ISBN=%s" | |
mycur.execute(update,insert) | |
mycon.commit() | |
separator() | |
print("BOOK IS UPDATED") | |
separator() | |
rep=input("Do You Want To Restart ?? yes / no -- ").lower() | |
if rep=="yes": | |
separator() | |
DBZ() | |
continue | |
else: | |
end_separator() | |
DBZ() | |
os._exit(0) | |
else: | |
print("SORRY NO BOOK WITH THIS ISBN IS EXIST / INCORRECT ISBN") | |
print() | |
print() | |
separator() | |
rep=input("Do You Want To Restart ?? yes / no -- ").lower() | |
if rep=="yes": | |
separator() | |
DBZ() | |
continue | |
else: | |
end_separator() | |
DBZ() | |
os._exit(0) | |
# DELETING A BOOK | |
if choice==5: | |
ISBN1=input("ENTER ISBN OF THAT BOOK THAT YOU WANT TO DELETE -- ") | |
display="select * from books where ISBN='%s'"%(ISBN1) | |
mycur.execute(display) | |
data2=mycur.fetchone() | |
if data2!=None: | |
separator() | |
choice5=input("ARE YOU SURE TO DELETE THIS BOOK ENTER Y/N -- ") | |
if choice5=='Y' or choice5=='y': | |
separator() | |
ISBN2=input("PLEASE ENTER ISBN AGAIN -- ") | |
delete="delete from books where ISBN='%s'"%(ISBN2) | |
mycur.execute(delete) | |
mycon.commit() | |
separator() | |
print("BOOK IS DELETED") | |
print() | |
print() | |
separator() | |
rep=input("Do You Want To Restart ?? yes / no -- ").lower() | |
if rep=="yes": | |
separator() | |
DBZ() | |
continue | |
else: | |
end_separator() | |
DBZ() | |
os._exit(0) | |
else: | |
separator() | |
print("NO BOOK IS DELETED") | |
print() | |
print() | |
separator() | |
rep=input("Do You Want To Restart ?? yes / no -- ").lower() | |
if rep=="yes": | |
separator() | |
DBZ() | |
continue | |
else: | |
end_separator() | |
DBZ() | |
os._exit(0) | |
else: | |
separator() | |
print("SORRY NO BOOK WITH THIS ISBN AVAILABLE / ISBN IS INCORRECT") | |
print() | |
print() | |
separator() | |
rep=input("Do You Want To Restart ?? yes / no -- ").lower() | |
if rep=="yes": | |
separator() | |
DBZ() | |
continue | |
else: | |
end_separator() | |
DBZ() | |
os._exit(0) | |
# CLOSE | |
if choice==6: | |
exit() | |
os._exit(0) | |
# IF NO. OF BOOKS IS ZERO( 0 ) THAN DELETE IT AUTOMATICALLY | |
display="select * from books" | |
mycur.execute(display) | |
data2=mycur.fetchall() | |
for y in data2: | |
if y[6]<=0: | |
delete="delete from books where Numbers_of_book<=0" | |
mycur.execute(delete) | |
mycon.commit() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Pygame base template for opening a window | |
Sample Python/Pygame Programs | |
Simpson College Computer Science | |
http://programarcadegames.com/ | |
http://simpson.edu/computer-science/ | |
Explanation video: http://youtu.be/vRB_983kUMc | |
------------------------------------------------- | |
Author for the Brickout game is Christian Bender | |
That includes the classes Ball, Paddle, Brick, and BrickWall. | |
""" | |
import random | |
#using pygame python GUI | |
import pygame | |
# Define Four Colours | |
BLACK = (0, 0, 0) | |
WHITE = (255, 255, 255) | |
GREEN = (0, 255, 0) | |
RED = (255, 0, 0) | |
pygame.init() | |
# Setting the width and height of the screen [width, height] | |
size = (700, 500) | |
screen = pygame.display.set_mode(size) | |
""" | |
This is a simple Ball class for respresenting a ball | |
in the game. | |
""" | |
class Ball(object): | |
def __init__(self, screen, radius, x, y): | |
self.__screen = screen | |
self._radius = radius | |
self._xLoc = x | |
self._yLoc = y | |
self.__xVel = 7 | |
self.__yVel = 2 | |
w, h = pygame.display.get_surface().get_size() | |
self.__width = w | |
self.__height = h | |
def getXVel(self): | |
return self.__xVel | |
def getYVel(self): | |
return self.__yVel | |
def draw(self): | |
""" | |
draws the ball onto screen. | |
""" | |
pygame.draw.circle(screen, (255, 0, 0), (self._xLoc, self._yLoc), self._radius) | |
def update(self, paddle, brickwall): | |
""" | |
moves the ball at the screen. | |
contains some collision detection. | |
""" | |
self._xLoc += self.__xVel | |
self._yLoc += self.__yVel | |
# left screen wall bounce | |
if self._xLoc <= self._radius: | |
self.__xVel *= -1 | |
# right screen wall bounce | |
elif self._xLoc >= self.__width - self._radius: | |
self.__xVel *= -1 | |
# top wall bounce | |
if self._yLoc <= self._radius: | |
self.__yVel *= -1 | |
# bottom drop out | |
elif self._yLoc >= self.__width - self._radius: | |
return True | |
# for bouncing off the bricks. | |
if brickwall.collide(self): | |
self.__yVel *= -1 | |
# collision detection between ball and paddle | |
paddleY = paddle._yLoc | |
paddleW = paddle._width | |
paddleH = paddle._height | |
paddleX = paddle._xLoc | |
ballX = self._xLoc | |
ballY = self._yLoc | |
if ((ballX + self._radius) >= paddleX and ballX <= (paddleX + paddleW)) \ | |
and ((ballY + self._radius) >= paddleY and ballY <= (paddleY + paddleH)): | |
self.__yVel *= -1 | |
return False | |
""" | |
Simple class for representing a paddle | |
""" | |
class Paddle(object): | |
def __init__(self, screen, width, height, x, y): | |
self.__screen = screen | |
self._width = width | |
self._height = height | |
self._xLoc = x | |
self._yLoc = y | |
w, h = pygame.display.get_surface().get_size() | |
self.__W = w | |
self.__H = h | |
def draw(self): | |
""" | |
draws the paddle onto screen. | |
""" | |
pygame.draw.rect(screen, (0, 0, 0), (self._xLoc, self._yLoc, self._width, self._height), 0) | |
def update(self): | |
""" | |
moves the paddle at the screen via mouse | |
""" | |
x, y = pygame.mouse.get_pos() | |
if x >= 0 and x <= (self.__W - self._width): | |
self._xLoc = x | |
""" | |
This class represents a simple Brick class. | |
For representing bricks onto screen. | |
""" | |
class Brick(pygame.sprite.Sprite): | |
def __init__(self, screen, width, height, x, y): | |
self.__screen = screen | |
self._width = width | |
self._height = height | |
self._xLoc = x | |
self._yLoc = y | |
w, h = pygame.display.get_surface().get_size() | |
self.__W = w | |
self.__H = h | |
self.__isInGroup = False | |
def draw(self): | |
""" | |
draws the brick onto screen. | |
color: rgb(56, 177, 237) | |
""" | |
pygame.draw.rect(screen, (56, 177, 237), (self._xLoc, self._yLoc, self._width, self._height), 0) | |
def add(self, group): | |
""" | |
adds this brick to a given group. | |
""" | |
group.add(self) | |
self.__isInGroup = True | |
def remove(self, group): | |
""" | |
removes this brick from the given group. | |
""" | |
group.remove(self) | |
self.__isInGroup = False | |
def alive(self): | |
""" | |
returns true when this brick belongs to the brick wall. | |
otherwise false | |
""" | |
return self.__isInGroup | |
def collide(self, ball): | |
""" | |
collision detection between ball and this brick | |
""" | |
brickX = self._xLoc | |
brickY = self._yLoc | |
brickW = self._width | |
brickH = self._height | |
ballX = ball._xLoc | |
ballY = ball._yLoc | |
ballXVel = ball.getXVel() | |
ballYVel = ball.getYVel() | |
if ((ballX + ball._radius) >= brickX and (ballX + ball._radius) <= (brickX + brickW)) \ | |
and ((ballY - ball._radius) >= brickY and (ballY - ball._radius) \ | |
<= (brickY + brickH)): | |
return True | |
else: | |
return False | |
""" | |
This is a simple class for representing a | |
brick wall. | |
""" | |
class BrickWall(pygame.sprite.Group): | |
def __init__(self, screen, x, y, width, height): | |
self.__screen = screen | |
self._x = x | |
self._y = y | |
self._width = width | |
self._height = height | |
self._bricks = [] | |
X = x | |
Y = y | |
for i in range(3): | |
for j in range(4): | |
self._bricks.append(Brick(screen, width, height, X, Y)) | |
X += width + (width / 7.0) | |
Y += height + (height / 7.0) | |
X = x | |
def add(self, brick): | |
""" | |
adds a brick to this BrickWall (group) | |
""" | |
self._bricks.append(brick) | |
def remove(self, brick): | |
""" | |
removes a brick from this BrickWall (group) | |
""" | |
self._bricks.remove(brick) | |
def draw(self): | |
""" | |
draws all bricks onto screen. | |
""" | |
for brick in self._bricks: | |
if brick != None: | |
brick.draw() | |
def update(self, ball): | |
""" | |
checks collision between ball and bricks. | |
""" | |
for i in range(len(self._bricks)): | |
if ((self._bricks[i] != None) and self._bricks[i].collide(ball)): | |
self._bricks[i] = None | |
# removes the None-elements from the brick list. | |
for brick in self._bricks: | |
if brick == None: | |
self._bricks.remove(brick) | |
def hasWin(self): | |
""" | |
Has player win the game? | |
""" | |
return len(self._bricks) == 0 | |
def collide(self, ball): | |
""" | |
check collisions between the ball and | |
any of the bricks. | |
""" | |
for brick in self._bricks: | |
if brick.collide(ball): | |
return True | |
return False | |
# The game objects ball, paddle and brick wall | |
ball = Ball(screen, 25, random.randint(1, 700), 250) | |
paddle = Paddle(screen, 100, 20, 250, 450) | |
brickWall = BrickWall(screen, 25, 25, 150, 50) | |
isGameOver = False # determines whether game is lose | |
gameStatus = True # game is still running | |
score = 0 # score for the game. | |
pygame.display.set_caption("Brickout-game") | |
# Loop until the user clicks the close button. | |
done = False | |
# Used to manage how fast the screen updates | |
clock = pygame.time.Clock() | |
# for displaying text in the game | |
pygame.font.init() # you have to call this at the start, | |
# if you want to use this module. | |
# message for game over | |
mgGameOver = pygame.font.SysFont('Comic Sans MS', 40) | |
# message for winning the game. | |
mgWin = pygame.font.SysFont('Comic Sans MS', 40) | |
# message for score | |
mgScore = pygame.font.SysFont('Comic Sans MS', 40) | |
textsurfaceGameOver = mgGameOver.render('Game Over!', False, (0, 0, 0)) | |
textsurfaceWin = mgWin.render("You win!", False, (0, 0, 0)) | |
textsurfaceScore = mgScore.render("score: " + str(score), False, (0, 0, 0)) | |
# -------- Main Program Loop ----------- | |
while not done: | |
# --- Main event loop | |
for event in pygame.event.get(): | |
if event.type == pygame.QUIT: | |
done = True | |
# --- Game logic should go here | |
# --- Screen-clearing code goes here | |
# Here, we clear the screen to white. Don't put other drawing commands | |
# above this, or they will be erased with this command. | |
# If you want a background image, replace this clear with blit'ing the | |
# background image. | |
screen.fill(WHITE) | |
# --- Drawing code should go here | |
""" | |
Because I use OOP in the game logic and the drawing code, | |
are both in the same section. | |
""" | |
if gameStatus: | |
# first draws ball for appropriate displaying the score. | |
brickWall.draw() | |
# for counting and displaying the score | |
if brickWall.collide(ball): | |
score += 10 | |
textsurfaceScore = mgScore.render("score: " + str(score), False, (0, 0, 0)) | |
screen.blit(textsurfaceScore, (300, 0)) | |
# after scoring. because hit bricks are removed in the update-method | |
brickWall.update(ball) | |
paddle.draw() | |
paddle.update() | |
if ball.update(paddle, brickWall): | |
isGameOver = True | |
gameStatus = False | |
if brickWall.hasWin(): | |
gameStatus = False | |
ball.draw() | |
else: # game isn't running. | |
if isGameOver: # player lose | |
screen.blit(textsurfaceGameOver, (0, 0)) | |
textsurfaceScore = mgScore.render("score: " + str(score), False, (0, 0, 0)) | |
screen.blit(textsurfaceScore, (300, 0)) | |
elif brickWall.hasWin(): # player win | |
screen.blit(textsurfaceWin, (0, 0)) | |
textsurfaceScore = mgScore.render("score: " + str(score), False, (0, 0, 0)) | |
screen.blit(textsurfaceScore, (300, 0)) | |
# --- Go ahead and update the screen with what we've drawn. | |
pygame.display.flip() | |
# --- Limit to 60 frames per second | |
clock.tick(60) | |
# Close the window and quit. | |
pygame.quit() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Python Program to implement | |
# Odd-Even / Brick Sort | |
def oddEvenSort(arr, n): | |
# Initially array is unsorted | |
isSorted = 0 | |
while isSorted == 0: | |
isSorted = 1 | |
temp = 0 | |
for i in range(1, n-1, 2): | |
if arr[i] > arr[i+1]: | |
arr[i], arr[i+1] = arr[i+1], arr[i] | |
isSorted = 0 | |
for i in range(0, n-1, 2): | |
if arr[i] > arr[i+1]: | |
arr[i], arr[i+1] = arr[i+1], arr[i] | |
isSorted = 0 | |
return | |
arr = [34, 2, 10, -9] | |
n = len(arr) | |
oddEvenSort(arr, n); | |
for i in range(0, n): | |
print(arr[i], end =" ") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import psutil | |
from obs import watcher | |
browsers=["chrome.exe","firefox.exe","edge.exe","iexplore.exe"] | |
#ADD DOWNLOADS PATH HERE::: r is for raw string enter the path | |
#Example: path_to_watch=r"C:\Users\Xyz\Downloads" | |
#find downloads path . | |
path_to_watch=r" " | |
for browser in browsers: | |
while browser in (process.name() for process in psutil.process_iter()): | |
watcher(path_to_watch) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from itertools import product | |
def findPassword(chars, function, show=50, format_="%s"): | |
password = None | |
attempts = 0 | |
size = 1 | |
stop = False | |
while not stop: | |
# Obtém todas as combinações possíveis com os dígitos do parâmetro "chars". | |
for pw in product(chars, repeat=size): | |
password = "".join(pw) | |
# Imprime a senha que será tentada. | |
if attempts % show == 0: | |
print(format_ % password) | |
# Verifica se a senha é a correta. | |
if function(password): | |
stop = True | |
break | |
else: | |
attempts += 1 | |
size += 1 | |
return password, attempts | |
def getChars(): | |
""" | |
Método para obter uma lista contendo todas as | |
letras do alfabeto e números. | |
""" | |
chars = [] | |
# Acrescenta à lista todas as letras maiúsculas | |
for id_ in range(ord("A"), ord("Z") + 1): | |
chars.append(chr(id_)) | |
# Acrescenta à lista todas as letras minúsculas | |
for id_ in range(ord("a"), ord("z") + 1): | |
chars.append(chr(id_)) | |
# Acrescenta à lista todos os números | |
for number in range(10): | |
chars.append(str(number)) | |
return chars | |
# Se este módulo não for importado, o programa será testado. | |
# Para realizar o teste, o usuário deverá inserir uma senha para ser encontrada. | |
if __name__ == "__main__": | |
import datetime | |
import time | |
# Pede ao usuário uma senha | |
pw = input("\n Type a password: ") | |
print("\n") | |
def testFunction(password): | |
global pw | |
if password == pw: | |
return True | |
else: | |
return False | |
# Obtém os dígitos que uma senha pode ter | |
chars = getChars() | |
t = time.process_time() | |
# Obtém a senha encontrada e o múmero de tentativas | |
password, attempts = findPassword(chars, testFunction, show=1000, format_=" Trying %s") | |
t = datetime.timedelta(seconds=int(time.process_time() - t)) | |
input(f"\n\n Password found: {password}\n Attempts: {attempts}\n Time: {t}\n") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def bubble_sort(Lists): | |
for i in range(len(Lists)): | |
for j in range(len(Lists)-1): | |
# We check whether the adjecent number is greater or not | |
if Lists[j]>Lists[j+1]: | |
Lists[j], Lists[j+1] = Lists[j+1], Lists[j] | |
#Lets the user enter values of an array and verify by himself/herself | |
array = [] | |
array_length = int(input(print("Enter the number of elements of array or enter the length of array"))) | |
for i in range(array_length): | |
value = int(input(print("Enter the value in the array"))) | |
array.append(value) | |
bubble_sort(array) | |
print(array) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def bubblesort(list): | |
# Swap the elements to arrange in order | |
for iter_num in range(len(list)-1,0,-1): | |
for idx in range(iter_num): | |
if list[idx]>list[idx+1]: | |
temp = list[idx] | |
list[idx] = list[idx+1] | |
list[idx+1] = temp | |
list = [19,2,31,45,6,11,121,27] | |
bubblesort(list) | |
print(list) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'''Bubble Sort | |
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order. | |
Example: | |
First Pass: | |
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1. | |
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4 | |
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2 | |
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them. | |
Second Pass: | |
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ) | |
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2 | |
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) | |
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) | |
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted. | |
Third Pass: | |
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) | |
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) | |
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) | |
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )''' | |
# Python program for implementation of Bubble Sort | |
def bubbleSort(arr): | |
n = len(arr) | |
# Traverse through all array elements | |
for i in range(n): | |
not_swap = True | |
# Last i elements are already in place | |
for j in range(0, n-i-1): | |
# traverse the array from 0 to n-i-1 | |
# Swap if the element found is greater | |
# than the next element | |
if arr[j] > arr[j+1] : | |
arr[j], arr[j+1] = arr[j+1], arr[j] | |
not_swap = False | |
if not_swap: | |
break | |
# Driver code to test above | |
arr = [64, 34, 25, 12, 22, 11, 90] | |
bubbleSort(arr) | |
print ("Sorted array is:") | |
for i in range(len(arr)): | |
print ("%d" %arr[i]), |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Author: PrajaktaSathe | |
# Program to calculate the area of - square, rectangle, circle, and triangle - | |
shape = int(input("Enter 1 for square, 2 for rectangle, 3 for circle, or 4 for triangle: ")) | |
if shape == 1: | |
side = float(input("Enter length of side: ")) | |
print("Area of square = " + str(side**2)) | |
elif shape == 2: | |
l = float(input("Enter length: ")) | |
b = float(input("Enter breadth: ")) | |
print("Area of rectangle = " + str(l*b)) | |
elif shape == 3: | |
r = float(input("Enter radius: ")) | |
print("Area of circle = " + str(3.14*r*r)) | |
elif shape == 4: | |
base = float(input("Enter base: ")) | |
h = float(input("Enter height: ")) | |
print("Area of rectangle = " + str(0.5*base*h)) | |
else: | |
print("You have selected wrong choice.") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def res(R1, R2): | |
sum = R1 + R2 | |
if (option =="series"): | |
return sum | |
else: | |
return (R1 * R2)/(R1 + R2) | |
Resistance1 = int(input("Enter R1 : ")) | |
Resistance2 = int(input("Enter R2 : ")) | |
option = str(input("Enter series or parallel :")) | |
print("\n") | |
R = res(Resistance1,Resistance2 ) | |
print("The total resistance is", R) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Written by : Shreyas Daniel - github.com/shreydan | |
Description : Uses Pythons eval() function | |
as a way to implement calculator. | |
Functions available are: | |
-------------------------------------------- | |
+ : addition | |
- : subtraction | |
* : multiplication | |
/ : division | |
% : percentage | |
e : 2.718281... | |
pi : 3.141592... | |
sine : sin(rad) | |
cosine : cos(rad) | |
exponent: x^y | |
tangent : tan(rad) | |
remainder : XmodY | |
square root : sqrt(n) | |
round to nearest integer : round(n) | |
convert degrees to radians : rad(deg) | |
absolute value : aval(n) | |
""" | |
import sys | |
import math | |
## Imported math library to run sin(), cos(), tan() and other such functions in the calculator | |
from fileinfo import raw_input | |
def calc(term): | |
""" | |
input: term of type str | |
output: returns the result of the computed term. | |
purpose: This function is the actual calculator and the heart of the application | |
""" | |
# This part is for reading and converting arithmetic terms. | |
term = term.replace(' ', '') | |
term = term.replace('^', '**') | |
term = term.replace('=', '') | |
term = term.replace('?', '') | |
term = term.replace('%', '/100.00') | |
term = term.replace('rad', 'radians') | |
term = term.replace('mod', '%') | |
term = term.replace('aval', 'abs') | |
functions = ['sin', 'cos', 'tan', 'pow', 'cosh', 'sinh', 'tanh', 'sqrt', 'pi', 'radians', 'e'] | |
# This part is for reading and converting function expressions. | |
term = term.lower() | |
for func in functions: | |
if func in term: | |
withmath = 'math.' + func | |
term = term.replace(func, withmath) | |
try: | |
# here goes the actual evaluating. | |
term = eval(term) | |
# here goes to the error cases. | |
except ZeroDivisionError: | |
print("Can't divide by 0. Please try again.") | |
except NameError: | |
print('Invalid input. Please try again') | |
except AttributeError: | |
print('Please check usage method and try again.') | |
except TypeError: | |
print("please enter inputs of correct datatype ") | |
return term | |
def result(term): | |
""" | |
input: term of type str | |
output: none | |
purpose: passes the argument to the function calc(...) and | |
prints the result onto console. | |
""" | |
print("\n" + str(calc(term))) | |
def main(): | |
""" | |
main-program | |
purpose: handles user input and prints | |
information to the console. | |
""" | |
print("\nScientific Calculator\n\nFor Example: sin(rad(90)) + 50% * (sqrt(16)) + round(1.42^2)" + | |
"- 12mod3\n\nEnter quit to exit") | |
if sys.version_info.major >= 3: | |
while True: | |
k = input("\nWhat is ") | |
if k == 'quit': | |
break | |
result(k) | |
else: | |
while True: | |
k = raw_input("\nWhat is ") | |
if k == 'quit': | |
break | |
result(k) | |
if __name__ == '__main__': | |
main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Program make a simple calculator | |
def add(x, y): | |
return x + y | |
def subtract(x, y): | |
return x - y | |
def multiply(x, y): | |
return x * y | |
def divide(x, y): | |
return x / y | |
print("Select operation.") | |
print("1.Add") | |
print("2.Subtract") | |
print("3.Multiply") | |
print("4.Divide") | |
while True: | |
# Take input from the user | |
choice = input("Enter choice(1/2/3/4): ") | |
# Check if choice is one of the four options | |
if choice in ('1', '2', '3', '4'): | |
num1 = float(input("Enter first number: ")) | |
num2 = float(input("Enter second number: ")) | |
if choice == '1': | |
print(num1, "+", num2, "=", add(num1, num2)) | |
elif choice == '2': | |
print(num1, "-", num2, "=", subtract(num1, num2)) | |
elif choice == '3': | |
print(num1, "*", num2, "=", multiply(num1, num2)) | |
elif choice == '4': | |
print(num1, "/", num2, "=", divide(num1, num2)) | |
break | |
else: | |
print("Invalid Input") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from tkinter import * | |
import calendar | |
root = Tk() | |
# root.geometry("400x300") | |
root.title("Calendar") | |
# Function | |
def text(): | |
month_int = int(month.get()) | |
year_int = int(year.get()) | |
cal = calendar.month(year_int, month_int) | |
textfield.delete(0.0, END) | |
textfield.insert(INSERT, cal) | |
# Creating Labels | |
label1 = Label(root, text="Month:") | |
label1.grid(row=0, column=0) | |
label2 = Label(root, text="Year:") | |
label2.grid(row=0, column=1) | |
# Creating spinbox | |
month = Spinbox(root, from_=1, to=12, width=8) | |
month.grid(row=1, column=0, padx=5) | |
year = Spinbox(root, from_=2000, to=2100, width=10) | |
year.grid(row=1, column=1, padx=10) | |
# Creating Button | |
button = Button(root, text="Go", command=text) | |
button.grid(row=1, column=2, padx=10) | |
# Creating Textfield | |
textfield = Text(root, width=25, height=10, fg="red") | |
textfield.grid(row=2, columnspan=2) | |
root.mainloop() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#The project automates calls for people from the firebase cloud database and the schedular keeps it running and checks for entries | |
#every 1 hour using aps scedular | |
#The project can be used to set 5 min before reminder calls to a set of people for doing a particular job | |
import os | |
from firebase_admin import credentials, firestore, initialize_app | |
from datetime import datetime,timedelta | |
import time | |
from time import gmtime, strftime | |
import twilio | |
from twilio.rest import Client | |
#twilio credentials | |
acc_sid="" | |
auth_token="" | |
client=Client(acc_sid, auth_token) | |
#firebase credentials | |
#key.json is your certificate of firebase project | |
cred = credentials.Certificate('key.json') | |
default_app = initialize_app(cred) | |
db = firestore.client() | |
database_reference = db.collection('on_call') | |
#Here the collection name is on_call which has documents with fields phone , from (%H:%M:%S time to call the person),date | |
#gets data from cloud database and calls 5 min prior the time (from time) alloted in the database | |
def search(): | |
calling_time = datetime.now() | |
one_hours_from_now = (calling_time + timedelta(hours=1)).strftime('%H:%M:%S') | |
current_date=str(strftime("%d-%m-%Y", gmtime())) | |
docs = db.collection(u'on_call').where(u'date',u'==',current_date).stream() | |
list_of_docs=[] | |
for doc in docs: | |
c=doc.to_dict() | |
if (calling_time).strftime('%H:%M:%S')<=c['from']<=one_hours_from_now: | |
list_of_docs.append(c) | |
print(list_of_docs) | |
while(list_of_docs): | |
timestamp=datetime.now().strftime('%H:%M') | |
five_minutes_prior= (timestamp + timedelta(minutes=5)).strftime('%H:%M') | |
for doc in list_of_docs: | |
if doc['from'][0:5]==five_minutes_prior: | |
phone_number= doc['phone'] | |
call = client.calls.create( | |
to=phone_number, | |
from_="add your twilio number", | |
url="http://demo.twilio.com/docs/voice.xml" | |
) | |
list_of_docs.remove(doc) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Author- RIZWAN AHMAD | |
# Simple python Script to change mac address of linux generate random or enter mac address | |
import random | |
from subprocess import PIPE, Popen | |
# function for returning terminal command | |
def cret(command): | |
process = Popen( | |
args=command, | |
stdout=PIPE, | |
shell=True | |
) | |
return process.communicate()[0] | |
# function for genrate mac address random | |
def randmac(): | |
return [0x00, 0x16, 0x3e, | |
random.randint(0x00, 0x7f), | |
random.randint(0x00, 0xff), | |
random.randint(0x00, 0xff)] | |
def retrandmac(mac): | |
return ':'.join(map(lambda x: "%02x" % x, mac)) | |
print(" +-+-+-+ +-+-+-+-+-+-+-+") | |
print(" |M|A|C| |c|h|a|n|g|e|r|") | |
print(" +-+-+-+ +-+-+-+-+-+-+-+") | |
# finding wireless interface name that should start with wl e.g.-wlan0,wlp3s0 | |
infname = cret('ifconfig -a | egrep "^[wl-wl]+" | sed "s/: .*//" | grep -v "lo"') | |
# INTERFACE NAME 6 character so return 6 last character | |
infname = infname[:6] | |
infname = infname.decode('utf-8') | |
# GETTING MAC Address from /sys/class/net/wlan0/address directory | |
cmdgetmac = ('cat /sys/class/net/' + infname + '/address') | |
crrntmac = cret("cat /sys/class/net/" + infname + "/address") | |
crrntmac = crrntmac.decode('utf-8') | |
print( | |
"Your Current mac address = " + crrntmac + "\nEnter Option to change Your MAC:\n1. Enter MAC address manually \n2. Automatic Random MAC address") | |
opt = int(input()) | |
if opt == 1: | |
print("Please Enter Your New MAC address: \nExmple: 46:d2:f4:0c:2a:50") | |
newmac = input() | |
print("Please wait changing mac address..................") | |
# first turn off wifi | |
cret('nmcli radio wifi off') | |
changemaccmd = "sudo ip link set dev " + infname + " address " + newmac | |
# executing command with new mac address | |
cret(changemaccmd) | |
# turning on wifi | |
cret('nmcli radio wifi on') | |
# GETTING MAC Address from /sys/class/net/wlan0/address directory | |
cr = cret("cat /sys/class/net/" + infname + "/address") | |
cr = cr.decode('utf-8') | |
print("\nNow Your Current mac address = " + cr) | |
elif opt == 2: | |
genmac = retrandmac(randmac()) | |
print("Please wait generating new mac address.....................") | |
cret('nmcli radio wifi off') | |
changemaccmd = "sudo ip link set dev " + infname + " address " + genmac | |
cret(changemaccmd) | |
cret('nmcli radio wifi on') | |
cr = cret("cat /sys/class/net/" + infname + "/address") | |
cr = cr.decode('utf-8') | |
print("Now Your Current mac address = " + cr) | |
else: | |
print("You Have Selected wrong Option") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# A simple program illustrating chaotic behaviour | |
def main(): | |
print("This program illustrates a chaotic function") | |
while True: | |
try: | |
x = float((input("Enter a number between 0 and 1: "))) | |
if (0 < x and x < 1): | |
break | |
else: | |
print("Please enter correct number") | |
except Exception as e: | |
print("Please enter correct number") | |
for i in range(10): | |
x = 3.9 * x * (1 - x) | |
print(x) | |
if __name__ == '__main__': | |
main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
num = float(input("Enter a number: ")) | |
if num > 0: | |
print("Positive number") | |
elif num == 0: | |
print("Zero") | |
else: | |
print("Negative number") | |
num = float(input("Enter a number: ")) | |
if num >= 0: | |
if num == 0: | |
print("Zero") | |
else: | |
print("Positive number") | |
else: | |
print("Negative number") | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def palindrome(a): | |
mid = (len(a)-1)//2 | |
start = 0 | |
last = len(a)-1 | |
flag = 0 | |
while(start<mid): | |
if (a[start]== a[last]): | |
start += 1 | |
last -= 1 | |
else: | |
flag = 1 | |
break; | |
if flag == 0: | |
print("The entered string is palindrome") | |
else: | |
print("The entered string is not palindrome") | |
def symmetry(a): | |
n = len(a) | |
flag = 0 | |
if n%2: | |
mid = n//2 +1 | |
else: | |
mid = n//2 | |
start1 = 0 | |
start2 = mid | |
while(start1 < mid and start2 < n): | |
if (a[start1]== a[start2]): | |
start1 = start1 + 1 | |
start2 = start2 + 1 | |
else: | |
flag = 1 | |
break | |
if flag == 0: | |
print("The entered string is symmetrical") | |
else: | |
print("The entered string is not symmetrical") | |
string = 'amaama' | |
palindrome(string) | |
symmetry(string) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Script Name : check_file.py | |
# Author : Craig Richards | |
# Created : 20 May 2013 | |
# Last Modified : | |
# Version : 1.0 | |
# Modifications : with statement added to ensure correct file closure | |
# Description : Check a file exists and that we can read the file | |
from __future__ import print_function | |
import os # Import the Modules | |
import sys # Import the Modules | |
# Prints usage if not appropriate length of arguments are provided | |
def usage(): | |
print('[-] Usage: python check_file.py [filename1] [filename2] ... [filenameN]') | |
# Readfile Functions which open the file that is passed to the script | |
def readfile(filename): | |
with open(filename, 'r') as f: # Ensure file is correctly closed under | |
read_file = f.read() # all circumstances | |
print(read_file) | |
print() | |
print('#' * 80) | |
print() | |
def main(): | |
# Check the arguments passed to the script | |
if len(sys.argv) >= 2: | |
file_names = sys.argv[1:] | |
filteredfilenames_1 = list(file_names) # To counter changing in the same list which you are iterating | |
filteredfilenames_2 = list(file_names) | |
# Iterate for each filename passed in command line argument | |
for filename in filteredfilenames_1: | |
if not os.path.isfile(filename): # Check the File exists | |
print('[-] ' + filename + ' does not exist.') | |
filteredfilenames_2.remove(filename) # remove non existing files from fileNames list | |
continue | |
# Check you can read the file | |
if not os.access(filename, os.R_OK): | |
print('[-] ' + filename + ' access denied') | |
# remove non readable fileNames | |
filteredfilenames_2.remove(filename) | |
continue | |
# Read the content of each file that both exists and is readable | |
for filename in filteredfilenames_2: | |
# Display Message and read the file contents | |
print('[+] Reading from : ' + filename) | |
readfile(filename) | |
else: | |
usage() # Print usage if not all parameters passed/Checked | |
if __name__ == '__main__': | |
main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Script Name : check_for_sqlite_files.py | |
# Author : Craig Richards | |
# Created : 07 June 2013 | |
# Last Modified : 14 February 2016 | |
# Version : 1.0.1 | |
# Modifications : 1.0.1 - Remove unecessary line and variable on Line 21 | |
# Description : Scans directories to check if there are any sqlite files in there | |
from __future__ import print_function | |
import os | |
def isSQLite3(filename): | |
from os.path import isfile, getsize | |
if not isfile(filename): | |
return False | |
if getsize(filename) < 100: # SQLite database file header is 100 bytes | |
return False | |
else: | |
fd = open(filename, 'rb') | |
header = fd.read(100) | |
fd.close() | |
if header[0:16] == 'SQLite format 3\000': | |
return True | |
else: | |
return False | |
log = open('sqlite_audit.txt', 'w') | |
for r, d, f in os.walk(r'.'): | |
for files in f: | |
if isSQLite3(files): | |
print(files) | |
print("[+] '%s' **** is a SQLITE database file **** " % os.path.join(r, files)) | |
log.write("[+] '%s' **** is a SQLITE database file **** " % files + '\n') | |
else: | |
log.write("[-] '%s' is NOT a sqlite database file" % os.path.join(r, files) + '\n') | |
log.write("[-] '%s' is NOT a sqlite database file" % files + '\n') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def get_user_input(start, end): | |
""" | |
input: two integer values | |
lower limit 'start' and maximum 'end' | |
the arguments aren't inclusive. | |
output: if reading successful then returns the read integer. | |
purpose: reads from command-line a integer in the given bounds. | |
while input invalid asks user again | |
""" | |
loop = True # controls while-loop | |
while loop: | |
try: | |
# reads and converts the input from the console. | |
user_input = int(input("Enter Your choice: ")) | |
# checks whether input is in the given bounds. | |
if user_input > end or user_input < start: | |
# error case | |
print("Please try again. Not in valid bounds.") | |
else: | |
# valid case | |
loop = False # aborts while-loop | |
except ValueError: | |
# error case | |
print("Please try again. Only numbers") | |
return user_input | |
x = get_user_input(1, 6) | |
print(x) | |
# Asks user to enter something, ie. a number option from a menu. | |
# While type != interger, and not in the given range, | |
# Program gives error message and asks for new input. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sys import argv | |
try: | |
# For Python 3.0 and later | |
from urllib.error import URLError | |
from urllib.request import urlopen | |
except ImportError: | |
# Fall back to Python 2's urllib2 | |
from urllib2 import URLError, urlopen | |
def checkInternetConnectivity(): | |
try: | |
url = argv[1] | |
if 'https://' or 'http://' not in url: | |
url = 'https://' + url | |
except: | |
url = 'https://google.com' | |
try: | |
urlopen(url, timeout=2) | |
print("Connection to \""+ url + "\" is working") | |
except URLError as E: | |
print("Connection error:%s" % E.reason) | |
checkInternetConnectivity() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
Author : Dhruv B Kakadiya | |
''' | |
import pygame as pg | |
from .checker_board import * | |
from .statics import * | |
from .pieces import * | |
class checker: | |
def __init__(self, window): | |
self._init() | |
self.window = window | |
# to update the position | |
def update (self): | |
self.board.draw(self.window) | |
self.draw_moves(self.valid_moves) | |
pg.display.update() | |
def _init(self): | |
self.select = None | |
self.board = checker_board() | |
self.turn = black | |
self.valid_moves = {} | |
# to reset the position | |
def reset (self): | |
self._init() | |
# select row and column | |
def selectrc(self, row, col): | |
if (self.select): | |
result = self._move(row, col) | |
if (not result): | |
self.select = None | |
piece = self.board.get_piece(row, col) | |
if ((piece != 0) and (piece.color == self.turn)): | |
self.select = piece | |
self.valid_moves = self.board.get_valid_moves(piece) | |
return True | |
return False | |
# to move the pieces | |
def _move(self, row, col): | |
piece = self.board.get_piece(row, col) | |
if ((self.select) and (piece == 0) and (row, col) in self.valid_moves): | |
self.board.move(self.select, row, col) | |
skip = self.valid_moves[(row, col)] | |
if (skip): | |
self.board.remove(skip) | |
self.chg_turn() | |
else: | |
return False | |
return True | |
# to draw next possible move | |
def draw_moves (self, moves): | |
for move in moves: | |
row, col = move | |
pg.draw.circle(self.window, red, (col * sq_size + sq_size // 2, row * sq_size + sq_size // 2), 15) | |
# for changing the turn | |
def chg_turn (self): | |
self.valid_moves = {} | |
if (self.turn == black): | |
self.turn = white | |
else: | |
self.turn = black |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
Author : Dhruv B Kakadiya | |
''' | |
import pygame as pg | |
from .statics import * | |
from .pieces import * | |
# checker board creation | |
class checker_board: | |
def __init__(self): | |
self.board = [] | |
self.selected = None | |
self.black_l = self.white_l = 12 | |
self.black_k = self.white_k = 0 | |
self.create_board() | |
# to design the board | |
def draw_cubes(self, window): | |
window.fill(green) | |
for row in range(rows): | |
for col in range(row % 2, cols, 2): | |
pg.draw.rect(window, yellow, (row * sq_size, col * sq_size, sq_size, sq_size)) | |
def move (self, piece, row, col): | |
self.board[piece.row][piece.col], self.board[row][col] = self.board[row][col], self.board[piece.row][piece.col] | |
piece.move(row, col) | |
if (row == rows - 1 or row == 0): | |
piece.make_king() | |
if (piece.color == white): | |
self.white_k += 1 | |
else: | |
self.black_k += 1 | |
# to get piece whatever they want | |
def get_piece (self, row, col): | |
return self.board[row][col] | |
def create_board(self): | |
for row in range(rows): | |
self.board.append([]) | |
for col in range(cols): | |
if ( col % 2 == ((row + 1) % 2) ): | |
if (row < 3): | |
self.board[row].append(pieces(row, col, white)) | |
elif (row > 4): | |
self.board[row].append(pieces(row, col, black)) | |
else: | |
self.board[row].append(0) | |
else: | |
self.board[row].append(0) | |
def draw (self, window): | |
self.draw_cubes(window) | |
for row in range(rows): | |
for col in range(cols): | |
piece = self.board[row][col] | |
if (piece != 0): | |
piece.draw(window) | |
def get_valid_moves(self, piece): | |
moves = {} | |
l = piece.col - 1 | |
r = piece.col + 1 | |
row = piece.row | |
if (piece.color == black or piece.king): | |
moves.update(self._traverse_l(row - 1, max(row - 3, -1), -1, piece.color, l)) | |
moves.update(self._traverse_r(row - 1, max(row - 3, -1), -1, piece.color, r)) | |
if (piece.color == white or piece.king): | |
moves.update(self._traverse_l(row + 1, min(row + 3, rows), 1, piece.color, l)) | |
moves.update(self._traverse_r(row + 1, min(row + 3, rows), 1, piece.color, r)) | |
return moves | |
def remove (self, pieces): | |
for piece in pieces: | |
self.board[piece.row][piece.col] = 0 | |
if (piece != 0): | |
if (piece.color == black): | |
self.black_l -= 1 | |
else: | |
self.white_l -= 1 | |
def winner (self): | |
if (self.black_l <= 0): | |
return white | |
elif (self.white_l <= 0): | |
return black | |
return None | |
# Traversal Left | |
def _traverse_l (self, start, stop, step, color, l, skip = []): | |
moves = {} | |
last = [] | |
for r in range(start, stop, step): | |
if (l < 0): | |
break | |
current = self.board[r][l] | |
if (current == 0): | |
if (skip and not last): | |
break | |
elif (skip): | |
moves[(r, l)] = last + skip | |
else: | |
moves[(r, l)] = last | |
if (last): | |
if (step == -1): | |
row = max(r - 3, 0) | |
else: | |
row = min(r + 3, rows) | |
moves.update(self._traverse_l(r + step, row, step, color, l - 1, skip = last)) | |
moves.update(self._traverse_r(r + step, row, step, color, l + 1, skip = last)) | |
break | |
elif (current.color == color): | |
break | |
else: | |
last = [current] | |
l -= 1 | |
return moves | |
# Traversal Right | |
def _traverse_r (self, start, stop, step, color, right, skip = []): | |
moves = {} | |
last = [] | |
for r in range(start, stop, step): | |
if (right >= cols): | |
break | |
current = self.board[r][right] | |
if (current == 0): | |
if (skip and not last): | |
break | |
elif (skip): | |
moves[(r, right)] = last + skip | |
else: | |
moves[(r, right)] = last | |
if (last): | |
if (step == -1): | |
row = max(r - 3, 0) | |
else: | |
row = min(r + 3, rows) | |
moves.update(self._traverse_l(r + step, row, step, color, right - 1, skip = last)) | |
moves.update(self._traverse_r(r + step, row, step, color, right + 1, skip = last)) | |
break | |
elif (current.color == color): | |
break | |
else: | |
last = [current] | |
right += 1 | |
return moves |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Author Anurag Kumar(mailto:anuragkumarak95@gmail.com) | |
Module to solve a classic ancient Chinese puzzle: | |
We count 35 heads and 94 legs among the chickens and rabbits in a farm. | |
How many rabbits and how many chickens do we have? | |
""" | |
def solve(num_heads, num_legs): | |
ns = 'No solutions!' | |
for i in range(num_heads + 1): | |
j = num_heads - i | |
if 2 * i + 4 * j == num_legs: | |
return i, j | |
return ns, ns | |
if __name__ == "__main__": | |
numheads = 35 | |
numlegs = 94 | |
solutions = solve(numheads, numlegs) | |
print(solutions) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pyautogui # pip install pyautogui | |
from PIL import Image, ImageGrab # pip install pillow | |
# from numpy import asarray | |
import time | |
def hit(key): | |
pyautogui.press(key) | |
return | |
def isCollide(data): | |
# for cactus | |
for i in range(329, 425): | |
for j in range(550, 650): | |
if data[i, j] < 100: | |
hit("up") | |
return | |
# Draw the rectangle for birds | |
# for i in range(310, 425): | |
# for j in range(390, 550): | |
# if data[i, j] < 100: | |
# hit("down") | |
# return | |
# return | |
if __name__ == "__main__": | |
print("Hey.. Dino game about to start in 3 seconds") | |
time.sleep(2) | |
# hit('up') | |
while True: | |
image = ImageGrab.grab().convert('L') | |
data = image.load() | |
isCollide(data) | |
# print(aarray(image)) | |
# Draw the rectangle for cactus | |
# for i in range(315, 425): | |
# for j in range(550, 650): | |
# data[i, j] = 0 | |
# # # # # Draw the rectangle for birds | |
# for i in range(310, 425): | |
# for j in range(390, 550): | |
# data[i, j] = 171 | |
# image.show() | |
# break |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
import time | |
SUITS = ('C', 'S', 'H', 'D') | |
RANKS = ('A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K') | |
VALUES = {'A': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'T': 10, 'J': 10, 'Q': 10, 'K': 10} | |
class card: | |
def __init__(self, suit, rank): | |
if (suit in SUITS) and (rank in RANKS): | |
self.suit = suit | |
self.rank = rank | |
else: | |
self.suit = None | |
self.rank = None | |
print("Invalid card: ", suit, rank) | |
def __str__(self): | |
return self.suit + self.rank | |
def getRank(self): | |
return self.rank | |
def getSuit(self): | |
return self.suit | |
class deck: | |
def __init__(self): | |
self.deck = [card(suit, rank) for suit in SUITS for rank in RANKS] | |
def shuffle(self): | |
random.shuffle(self.deck) | |
def dealCard(self): | |
return random.choice(self.deck) | |
def __str__(self): | |
print(self.deck) | |
# Begin play | |
# create two decks, one for each player. | |
print("Gathering brand new two decks of cards............\n") | |
deck1 = deck() | |
deck2 = deck() | |
time.sleep(5) | |
print('..........decks ready!!!\n') | |
print('Combining and shuffling both the decks..') | |
time.sleep(10) | |
# Shuffle the decks | |
deck1.shuffle() | |
deck2.shuffle() | |
# combine both the shuffled decks | |
combinedDeck = deck1.deck + deck2.deck | |
# ReShuffle the combined deck, cut it and distribute to two players. | |
random.shuffle(combinedDeck) | |
print("....decks have been combined and shuffled...\n") | |
print("------------------------------------------\n") | |
input("Enter a key to cut the deck..\n") | |
player1 = combinedDeck[0:52] | |
player2 = combinedDeck[52:] | |
print("Deck has been split into two and Human get a half and computer gets the other...\n") | |
# Begin play: | |
print("------------------------------------------\n") | |
print("player1 == Human\n") | |
print("player2 == Computer\n") | |
print("------------------------------------------\n") | |
print("player1 goes first...hit any key to place the card on the pile..\n") | |
centerPile = [] | |
currentPlayer2Card = None | |
while len(player1) != 0 and len(player2) != 0: # this needs a fix as it goes on an infinite loop on a success. | |
switchPlayer = True | |
while switchPlayer == True: | |
for card in range(len(player1)): | |
input("Enter any key to place a card!!!\n") | |
currentPlayer1Card = player1[card].rank | |
print("Your current card's rank: {}".format(currentPlayer1Card)) | |
centerPile.append(player1[card]) | |
player1.pop(card) | |
switchPlayer = False | |
if currentPlayer2Card == currentPlayer1Card: | |
player1 = player1 + centerPile | |
print("The human got a match and takes all the cards from center pile..") | |
break | |
while switchPlayer == False: | |
for card in range(len(player2)): | |
currentPlayer2Card = player2[card].rank | |
print("Computer's current card's rank: {}".format(currentPlayer2Card)) | |
centerPile.append(player2[card]) | |
player2.pop(card) | |
switchPlayer = True | |
if currentPlayer1Card == currentPlayer2Card: | |
player2 = player2 + centerPile | |
print("Computer got a match and takes all the cards from center pile..") | |
break | |
print("GAME OVER!!!\n") | |
print("Human has {} cards and computer has {}..".format(len(player1), len(player2))) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pickle | |
import tensorflow as tf | |
model = tf.keras.models.Sequential([tf.keras.layers.Conv2D(16, (3, 3), activation='relu', input_shape=(200, 200, 3)), | |
tf.keras.layers.MaxPooling2D(2, 2), | |
tf.keras.layers.Conv2D(16, (3, 3), activation='relu'), | |
tf.keras.layers.MaxPooling2D(2, 2), | |
tf.keras.layers.Conv2D(16, (3, 3), activation='relu'), | |
tf.keras.layers.MaxPooling2D(2, 2), | |
tf.keras.layers.Flatten(), | |
tf.keras.layers.Dense(512, activation='relu'), | |
tf.keras.layers.Dense(1, activation="sigmoid") | |
]) | |
model.summary() | |
from tensorflow.keras.optimizers import RMSprop | |
model.compile(optimizer=RMSprop(lr=0.001), loss='binary_crossentropy', metrics=['acc']) | |
from tensorflow.keras.preprocessing.image import ImageDataGenerator | |
train_datagen = ImageDataGenerator(rescale=1 / 255) | |
train_generator = train_datagen.flow_from_directory('../Classification_human-or-horse', | |
target_size=(200, 200), | |
batch_size=222, | |
class_mode='binary') | |
model.fit_generator(train_generator, steps_per_epoch=6, epochs=1, verbose=1) | |
filename = "myTf1.sav" | |
pickle.dump(model, open(filename, 'wb')) | |
from tkinter import Tk | |
from tkinter.filedialog import askopenfilename | |
from keras.preprocessing import image | |
import numpy as np | |
Tk().withdraw() | |
filename = askopenfilename() | |
print(filename) | |
img = image.load_img(filename, target_size=(200, 200)) | |
x = image.img_to_array(img) | |
x = np.expand_dims(x, axis=0) | |
images = np.vstack([x]) | |
classes = model.predict(images, batch_size=10) | |
print(classes[0]) | |
if classes[0] > 0.5: | |
print(filename + " is a human") | |
else: | |
print(filename + " is a horse") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Note :- Client and Server Must be connected to same Network | |
# import socket modules | |
import socket | |
# create TCP/IP socket | |
s = socket.socket() | |
# take user input ip of server | |
server = input("Enter Server IP: ") | |
# bind the socket to the port 12345, and connect | |
s.connect((server, 12345)) | |
# receive message from server connection successfully established | |
data = s.recv(1024).decode("utf-8") | |
print(server + ": " + data) | |
while True: | |
# send message to server | |
new_data = str(input("You: ")).encode("utf-8") | |
s.sendall(new_data) | |
# receive message from server | |
data = s.recv(1024).decode("utf-8") | |
print(server + ": " + data) | |
# close connection | |
s.close() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# libraraies | |
import pytube | |
import sys | |
class YouTubeDownloder: | |
def __init__(self): | |
self.url = str(input("Enter the url of video : ")) | |
self.youtube = pytube.YouTube( | |
self.url, on_progress_callback=YouTubeDownloder.onProgress) | |
self.showTitle() | |
def showTitle(self): | |
print("title : {0}\n".format(self.youtube.title)) | |
self.showStreams() | |
def showStreams(self): | |
self.streamNo = 1 | |
for stream in self.youtube.streams: | |
print("{0} => resolution:{1}/fps:{2}/type:{3}".format(self.streamNo, | |
stream.resolution, stream.fps, stream.type)) | |
self.streamNo += 1 | |
self.chooseStream() | |
def chooseStream(self): | |
self.choose = int(input("please select one : ")) | |
self.validateChooseValue() | |
def validateChooseValue(self): | |
if self.choose in range(1, self.streamNo): | |
self.getStream() | |
else: | |
print("please enter a correct option on the list.") | |
self.chooseStream() | |
def getStream(self): | |
self.stream = self.youtube.streams[self.choose-1] | |
self.getFileSize() | |
def getFileSize(self): | |
global file_size | |
file_size = self.stream.filesize / 1000000 | |
self.getPermisionToContinue() | |
def getPermisionToContinue(self): | |
print("\n title : {0} \n author : {1} \n size : {2:.2f}MB \n resolution : {3} \n fps : {4} \n ".format( | |
self.youtube.title, self.youtube.author, file_size, self.stream.resolution, self.stream.fps)) | |
if input("do you want it ?(defualt = (y)es) or (n)o ") == "n": | |
self.showStreams() | |
else: | |
self.main() | |
def download(self): | |
self.stream.download() | |
@staticmethod | |
def onProgress(stream=None, chunk=None, remaining=None): | |
file_downloaded = (file_size-(remaining/1000000)) | |
print( | |
f"downloading ... {file_downloaded/file_size*100:0.2f} % [{file_downloaded:.1f}MB of {file_size:.1f}MB]", end="\r") | |
def main(self): | |
try: | |
self.download() | |
except KeyboardInterrupt: | |
print("Canceled. ") | |
sys.exit(0) | |
if __name__ == "__main__": | |
try: | |
YouTubeDownloder() | |
except KeyboardInterrupt: | |
pass | |
except Exception as e: | |
print(e) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import tkinter | |
# retrieve system's time | |
from time import strftime | |
#------------------main code----------------------- | |
#initializing the main UI object | |
top = tkinter.Tk() | |
#setting title of the App | |
top.title('Clock') | |
#restricting the resizable property | |
top.resizable(0,0) | |
def time(): | |
string = strftime('%H:%M:%S %p') | |
clockTime.config(text = string) | |
clockTime.after(1000, time) | |
clockTime = tkinter.Label(top, font = ('calibri', 40, 'bold'), background = 'black', foreground = 'white') | |
clockTime.pack(anchor = 'center') | |
time() | |
top.mainloop() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Python program to copy or clone a list | |
# Using the Slice Operator | |
def Cloning(li1): | |
li_copy = li1[:] | |
return li_copy | |
# Driver Code | |
li1 = [4, 8, 2, 10, 15, 18] | |
li2 = Cloning(li1) | |
print("Original List:", li1) | |
print("After Cloning:", li2) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
host = "localhost" | |
mongoPort = 27017 | |
SOCKS5_PROXY_PORT = 1080 | |
auth = "" | |
passcode = "" | |
# if proxy is not working please update the auth and passcode |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment