blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
e18e81c8986c383ac6d6cec86017d3bf948af5b3
tasver/python_course
/lab6_1.py
719
4.21875
4
#! /usr/bin/python3 # -*- coding: utf-8 -*- import math def input_par() -> list: """ This function make input of data""" a, b, c = map(float, input('Enter 3 numbers: ').split()) return [a, b, c] def check_triangle(a:list) -> bool: """ This function check exists triangle""" if (((a[0] + a[1]) > a[2]) and ((a[0] + a[2]) > a[1]) and ((a[2] + a[1] > a[0]))): return True else: return False def calculate(a:list) -> float: """ This function calculate area triangle """ if check_triangle(a): half_perimetr = (a[0]+a[1]+a[2])/2 area = math.sqrt(half_perimetr*(half_perimetr-a[0])*(half_perimetr-a[1])*(half_perimetr-a[2])) return area else: return 'Triangle not exists' print(calculate(input_par()))
d90d53e6c36ea8baebc8c65e476e7d930a9d2851
JonNData/Graphs
/objectives/graph-intro/lect_example.py
2,052
4.09375
4
class Queue: def __init__(self, ls=[]): self.size = 0 self.storage = [] def __len__(self): if self.size <= 0: return 0 else: return self.size def enqueue(self, value): self.size +=1 return self.storage.append(value) def dequeue(self): if self.size == 0: return None else: self.size += -1 return self.storage.pop(0) class Graph: def __init__(self): self.vertices = { } def add_vertex(self, vertex_id): self.vertices[vertex_id] = set() # holds the edges def add_edge(self, vert1, vert2): if vert1 and vert2: self.vertices[vert1].add(vert2) # set.add() else: raise IndexError("nonexistant vert") def get_neighbors(self, vertex_id): return self.vertices[vertex_id] def breadth_first_traversal(self, start_id): # This uses a queue, tracks what is visited until completely explored. # while the queue is not empty, dequeue and keep going. # Visit, add all neighbors into the queue, order doesn't matter. # Create a q, create a set to store visited q = Queue() visited = set() # init: enqueue starting node q.enqueue(start_id) # while queue isn't empty while q.size > 0: # dequeue first item v = q.dequeue() # if not visited: if v not in visited: # mark as fvisited visited.add(v) print("Visited: ", v) # add neighbors to queue for next_vert in self.get_neighbors(v): q.enqueue(next_vert) g = Graph() g.add_vertex("A") g.add_vertex("B") g.add_vertex("C") g.add_vertex("D") g.add_edge("A", "B") g.add_edge("A", "C") g.add_edge("B", "A") g.add_edge("B", "C") g.add_edge("B","B") g.add_edge("C","D") g.add_edge("D","C") g.breadth_first_traversal("B") """ Translate Build Traverse """
3a5ee700dce71d3f72eb95a8d7b5900e309270ec
ahmetYilmaz88/Introduction-to-Computer-Science-with-Python
/ahmet_yilmaz_hw6_python4_5.py
731
4.125
4
## My name: Ahmet Yilmaz ##Course number and course section: IS 115 - 1001 - 1003 ##Date of completion: 2 hours ##The question is about converting the pseudocode given by instructor to the Python code. ##set the required values count=1 activity= "RESTING" flag="false" ##how many activities numact= int(input(" Enter the number of activities: ")) ##enter the activities as number as numact that the user enter while count < numact: flag= " true " activity= input( "Enter your activity: ") ##display the activity if activity=="RESTING": print ( " I enjoy RESTING too ") else: print ("You enjoy " , activity) count=count+1 if flag== "false": print (" There is no data to process ")
e7aeb456f723ea10f99d185e096b159e3d3de090
BigPieMuchineLearning/python_study_source_code2
/exercise_5_4.py
285
3.78125
4
mult_3=list(set(range(0,1000,3))) mult_4=list(set(range(0,1000,4))) sum=int(len(mult_3))+int(len(mult_4)) print(sum) weekday={'mon','tues','wen','thurs','fri'} weekend={'sat','sun'} n=input() def is_working_day(n): rest= n in weekend print(rest) is_working_day(n)
2eba63c46d8a4f74c5e11d165eb4f8c488dcf174
BigPieMuchineLearning/python_study_source_code2
/exercise_3_3.py
1,072
3.875
4
def print_absolute(): """절댓값을 알려주는 함수""" #독스트링 import math print('정수를 입력하세요') number = int(input()) abnumber=abs(number) print(number,'의 절댓값:',abnumber) print_absolute() help(print_absolute) def print_plus(number1,number2): """두 수를 전달받아 그 합계를 화면에 출력하는 함수""" print("두 수의 합계:",number1+number2) print_plus(100,50) def average_of_4_numbers(num1,num2,num3,num4): result=(num1+num2+num3+num4)/4 print(result) average_of_4_numbers(512,64,256,192) def no_return(): """화면에 메시지를 출력하지만, 값을 반환하지는 않는다.""" print('이 함수에는 반환값이 없습니다.') result = no_return() print(result) #반환값이 없기떄문에 None으로 출력된다. def area_of_triangle(length,height): """밑변과 높이를 입력하면 삼각형 넓이를 출력해준다.""" area=length*height/2 return area result=area_of_triangle(10,8) print(result)
71cc0002a3bbdfe951d3ab035f6f3f5e17654c11
jithendra2002/LAB-15-12-2020
/L7-LinkedList_deleting_element.py
1,425
3.953125
4
class Node: def __init__(self, value): self.data = value self.next = None class LinkedList: def __init__(self): self.head = None def inputs(self,value): if self.head is None: new_node = Node(value) self.head = new_node else: new_node = Node(value) temp = self.head while temp.next!= None: temp = temp.next temp.next = new_node def deleting_node(self,value): temp=self.head if temp is not None: if temp.data==value: temp.next=None return while temp is not None: if temp.data==value: break prev = temp temp = temp.next else: return prev.next = temp.next temp=None def display_LinkedList(self): temp = self.head while temp: print(temp.data) temp = temp.next list1=LinkedList() n=int(input("Enter number of nodes you want add to linkedlist")) for i in range(n): list1.inputs(input(f'Enter the {i}th node value')) d=input("Enter the key u want to remove from the linked list") list1.deleting_node(d) list1. display_LinkedList()
af123d78f63c5ed279e54545959ebdfa55d7d16d
ZuchniakK/PITE-Sensor-Eval
/code/Classifier.py
4,247
3.6875
4
import numpy as np import random import math from sklearn.neighbors import KNeighborsClassifier from sklearn import cross_validation class KNN(): def __init__(self,fakedatapath, sensordatapath, n_sensor_samples=None, n_fake_samples=None): """ Read the data from real sensors and simulated fake data. Analysis may be limited to n_sensor_samples and n_fake_samples if desired ======= params: fakedatapath sensordatapath n_sensor_samples - number of rows to be analysed from the sensor data file n_fake_samples - number of rows to be analysed from the fake data file """ self.from_sensors = np.loadtxt(sensordatapath, delimiter=",") # 42 rows self.fake_data = np.loadtxt(fakedatapath, delimiter=",") #TODO: code: take only n_sensor(fake)_samples; do it randomly if n_sensor_samples is not None: pass if n_fake_samples is not None: pass def TrainAndPredict(self, k=3, train_test_ratio=0.3, weights='distance', metric='minkowski', algorithm='auto'): """ Trains k-nearest neighbours classifier with sensor and simulated (fake) data and checks accuracy of the classifier by comparing its predictions with test samples in two ways: directly and using cross-validation ======= params: k - number of neighbours train_test_ratio - specifies how many samples use for training the algorithm and how many for testing its accuracy weights - pertains to data points (NOT to the attributes!); the closer ones may be regarded as more important (weights='distance'); possible weights: 'uniform', 'distance', [callable]. The [callable] is a user-defined function algorithm - 'auto'; shan't be changed in this little project metric - e.g. 'minkowski' or 'euclidean' or 'mahalanobis' tells the algorithm how to measure the distance """ # how many rows for training num_sensor_train = int(train_test_ratio * len(self.from_sensors)) num_fake_train = int(train_test_ratio * len(self.fake_data)) traindata = np.concatenate((self.from_sensors[:num_sensor_train, :-1], self.fake_data[:num_fake_train, :-1]), axis=0) targetvalues = [1 for i in range(num_sensor_train)] + [0 for i in range(num_fake_train)] # array of 0/1 # TODO: dictionary looks better than lists alone # build a classifier and teach it self.neigh = KNeighborsClassifier(n_neighbors=k, weights=weights, algorithm=algorithm, metric=metric) self.neigh.fit(traindata, targetvalues) # check accuracy with cross-validation # TODO: shuffle split is not bad, but not perfect - it may take same thing as different subsets(!); # it's better to find an alternative method from cross_validation class cv = cross_validation.ShuffleSplit(len(targetvalues), n_iter=10, test_size=10, random_state=0) self.knn_score = cross_validation.cross_val_score(self.neigh, traindata, targetvalues, cv=cv) # summarise all test data (predictions) print "------All params @: {" print "n_neighbors: " + str(k) + " train_test_ratio: " + str(train_test_ratio) + " weights: " + str(weights) + " metric: "+str(metric) + " algorithm: "+str(algorithm) + " }" print "Sensor data prediction: (1 = good, 0 = bad)" + str(self.neigh.predict(self.from_sensors[num_sensor_train:, :-1])) print "Fake data prediction:" + str(self.neigh.predict(self.fake_data[num_fake_train:, :-1])) print "Probability of correct assessment (sensor data):" print "[1st column: bad | 2nd column: good]" print str(self.neigh.predict_proba(self.from_sensors[num_sensor_train:, :-1])) print "Probability of correct assessment (fake data): \n" + str(self.neigh.predict_proba(self.fake_data[num_fake_train:, :-1]))
0c95d6b6ebcda72fcecc1f734faf7d409936713a
Lianyihwei/RobbiLian
/Lcc/pythonrace/PYA801.py
116
3.921875
4
# TODO word = list(input()) for index,value in enumerate(word): print(f"Index of \'{value}\': {index}")
17f8483a8cec72840bc28122cfb872776e196a83
Lianyihwei/RobbiLian
/Lcc/pythonrace/PYA408.py
197
3.65625
4
# TODO evc = 0 odc = 0 for i in range(10): num = eval(input()) if num %2 == 0: evc += 1 else: odc += 1 print("Even numbers:",evc) print("Odd numbers:",odc)
ebd80b7a1750ed164559c89537b5ac64fbf01bd5
Lianyihwei/RobbiLian
/Lcc/pythonrace/PYA710.py
249
3.609375
4
#TODO from tabnanny import check dict = {} while True: key = input("Key: ") if key == "end": break value = input("Value: ") dict[key] = value search_key = input("Search key: ") print(search_key in dict.keys())
8d07696850cc5f7371069a98351c51266b77da6b
lintangsucirochmana03/bigdata
/minggu-02/praktik/src/DefiningFunction.py
913
4.3125
4
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> def fib(n): # write Fibonacci series up to n """Print a Fibonacci series up to n.""" a, b = 0, 1 while a < n: print(a, end=' ') a, b = b, a+b >>> print() >>> # Now call the function we just defined: >>> fib(2000) 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 >>> fib <function fib at 0x02C4CE88> >>> f = fib >>> f(100) 0 1 1 2 3 5 8 13 21 34 55 89 >>> fib(0) >>> print(fib(0)) None >>> def fib2(n): # return Fibonacci series up to n """Return a list containing the Fibonacci series up to n.""" result = [] a, b = 0, 1 while a < n: result.append(a) # see below a, b = b, a+b return result >>> f100 = fib2(100) # call it >>> f100 # write the result [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] >>>
3e8b85dcf36442098a6cf0e1d28afb80b7abaf95
dhivya2nandha/players
/11.py
97
3.6875
4
end=['saturday','sunday'] inp=input() if(inp not in end): print("no") else: print("yes")
d760e08b472dab01b6dae64d20f84fd1ab8547ee
jmswu/learn_python
/english_dict/main.py
177
3.8125
4
from dictionary import Dictionary # make a dictionary dictionary = Dictionary() # user input user_input = input("Please enter word:") print(dictionary.translate(user_input))
d79f3a1c11d9f1afcdcb233fc0653fc70479f3c3
RoCorral/LAB_3_A
/LAB_3_A_ProcessTrees.py
7,419
3.734375
4
""" @author Rocorral ID: 80416750 Instructor: David Aguirre TA: Saha, Manoj Pravakar Assignment:Lab 3-A - AVL,RBT, word Embeddings Last Modification: 11/4/2018 Program Purpose: The purpose of this program is to practice and note the difference in computation times of insertion and retrieval between AVL Trees and Red Black Trees. We are provided with a word embedding file and are required to insert each word and its embedding vector into a tree. After the insertions we must retrieved words based on pairs read from another file and compute the similarity. This is followed by computations of tree size and file output with word lists generated from the tree. """ import AVL import RBT import math def read_f_into_AVL(file): """Recieves glove file with embedings location as a string constructs an AVL tree using nodes with the word as one parameter and the 50 floting point vectors in an array as another. """ CurAVL = AVL.AVLTree() forAVL = open(file,'r+',encoding="UTF-8") for line in forAVL: a = line.split() #Direguards "words" in file that do not begin witch characters from the alphabet if (a[0] >= 'A' and a[0] <= 'Z') or (a[0] >='a' and a[0] <= 'z'): ## did you think about using a is char() for the line above CurAVL.insert(AVL.Node( a[0] , a[1:(len(a))])) return CurAVL def read_f_into_RBT(file): """Recieves glove file with embeddings location as a string constructs a Red Black tree using nodes with the word as one parameter and the 50 floting point vectors in an array as another. """ CurRBT = RBT.RedBlackTree() forRBT = open(file,'r+', encoding="UTF-8") for line in forRBT: a = line.split() #Direguards "words" in file that do not begin witch characters from the alphabet if (a[0] >= 'A' and a[0] <= 'Z') or (a[0] >='a' and a[0] <= 'z'): CurRBT.insert_node(RBT.RBTNode(a[0], a[1:(len(a))],None)) return CurRBT def computeSimilarity(tree,file2): """Recieves a tree root and a file of word pairs. The sin similarity is derived from the vectors associated with the words by retrieving them from the tree and computing the values using the function described in our lab """ forComparison = open(file2, 'r+', encoding="UTF-8") for line in forComparison: dotProduct = 0 denoma = 0 denomb = 0 b = line.split() w0 = tree.search(b[0])#word 1 from pair w1 = tree.search(b[1])#word 2 for i in range(len(w0.vector)): dotProduct = dotProduct + (float(w0.vector[i])*float(w1.vector[i])) denoma = denoma + float(w0.vector[i])*float(w0.vector[i]) denomb = denomb + float(w1.vector[i])*float(w1.vector[i]) denom = math.sqrt(denoma)*math.sqrt(denomb) similarity = dotProduct/denom print(w0.key ," ",w1.key, " similarity: " , similarity ) def user_selection_IF(): """User Interface the origin of calls to the definitions requested by the lab the user is to input values for tree type and depth to print. """ file = "glove.6B.50d.txt" #file with embeddings file2 ="Apendix-word-List.txt" #file with words to compare menu = True while menu: try: print("would you like to USE \n1:AVL(Adelson-Velskii and Landis Tree)\n2:RBT(Red Black Tree)\n3:Exit") selection =input() print("your selection is:", selection) if selection == '1': """process using AVL""" print("reading file into AVL......") tree = read_f_into_AVL(file) print("computing similarities of word pairs in", file2) computeSimilarity(tree,file2) print("Number of Nodes in tree: ",get_numb_nodes(tree.root)) height =get_tree_height(tree.root) print("Tree height: ",height) print("generating file with all nodes in ascending order....") ascend_file = open('ascendingwords.txt','a',encoding = "UTF-8") gen_ascending_order(tree.root, ascend_file) ascend_file.close() print("file complete!") correct_depth =False d = (-1) while correct_depth == False: try: print("enter a depth between 0 and ",height) d = input() if (int(d) < 0 or int(d) > height): raise OSError("wrong input") else: correct_depth = True except OSError as err: #catches input error for range print("------>",d) print("is not a valid input....") except ValueError as err: #catches input error for input type. print("------>",d) print("is not even a Number....") print("generating file with all nodes at depth ",d," in ascending order.....") depth_file = open('words_at_depth_in_inassending_order.txt','a',encoding = "UTF-8") gen_depth_file(tree.root,int(d),depth_file) depth_file.close() print("file complete") print("all tasks complete\n exiting...") menu = False if selection == '2': """process using Red Black Tree""" print("reading file into RBT......") tree = read_f_into_RBT(file) print("computing similarities of word pairs in using a Red Black Tree", file2) computeSimilarity(tree,file2) print("Number of Nodes in tree: ",get_numb_nodes(tree.root)) height =get_tree_height(tree.root) print("Tree height: ",height) print("generating file with all nodes in ascending order....") ascend_file = open('ascendingwords.txt','a',encoding = "UTF-8") gen_ascending_order(tree.root, ascend_file) ascend_file.close() print("file complete!") correct_depth =False d = (-1) while correct_depth == False: try: print("enter a depth between 0 and ",height) d = input() if (int(d) < 0 or int(d)>height): raise OSError("wrong input") else: correct_depth = True except OSError as err: print("------>",d) print("is not a valid input....") except ValueError as err: print("------>",d) print("is not even a Number....") print("generating file with all nodes at depth ",d," in ascending order.....") depth_file = open('words_at_depth_in_inassending_order.txt','a',encoding = "UTF-8") gen_depth_file(tree.root,int(d),depth_file) depth_file.close() print("file complete") print("all tasks complete exiting...") menu = False if selection == '3': print("exiting") menu =False except OSError as err: print("OS error: {0}".format(err)) print("the options are 1,2 or 3.... try again") except ValueError as err: print("------>",selection) print("is not even a Number....") def get_numb_nodes(t): """geven a tree root computes the number of nodes in a tree recursivly""" count = 1 if t.left != None: count = count + get_numb_nodes(t.left) if t.right != None: count = count + get_numb_nodes(t.right) return count def get_tree_height(t): """given a tree roo computes the tree height recursivly""" if t is None: return 0 return 1 + (max(get_tree_height(t.right),get_tree_height(t.left))) def gen_ascending_order(t,file): """given a tree root and a file to write in to generates file with all words in ascending order """ if t is None: return gen_ascending_order(t.left,file) file.write("\n" + t.key) gen_ascending_order(t.right,file) return def gen_depth_file(t,d,file): """given a tree root a user defined depth and a file tgenerates a file with all words at the depth in ascending order """ if t is None: return gen_depth_file(t.left,d-1,file) if d == 0: file.write("\n" + t.key) return gen_depth_file(t.right,d-1,file) return #----------Main----------- user_selection_IF()
fa28503d8d9926d7445464844aff6e2fdd27f5a8
daibogh/lilya
/example1.py
412
3.90625
4
a = input("введите имя и фамилию через пробел: ") a = a.split(" ") print(len(a)) print(type(a))# type(a) выводит тип переменной a print(a[0]) print(a[1]) print(a[-1])# a[-1] = последний элемент a # a[0] = a[0][0].upper() + a[0][1:] # a[1] = a[1][0].upper() + a[1][1:] # print("привет, ", end= "") # print(" ".join(a), end="") # print("!!!")
7bf949a518e62547a7c76501df89cb7a28681e48
phipag/opencv-face-detection-python
/main.py
875
3.765625
4
import cv2 import argparse def main(image_path): # Load image and turn into grayscale img = cv2.imread(image_path) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Use the Haar Cascade classifier to detect faces face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_alt.xml") faces = face_cascade.detectMultiScale(gray) # Draw a rectangle around all found faces for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 4) # Show the result in a UI window cv2.imshow(f"Output of face detection for {image_path}", img) cv2.waitKey(0) cv2.destroyAllWindows() if __name__ == "__main__": parser = argparse.ArgumentParser("Face detection example") parser.add_argument("--image", help="Path to image.", default="philipp.jpg") args = parser.parse_args() main(args.image)
8dc0d965aebeaa2cbb464984a3b58cc314c8aa42
SamirSatpute/newPython
/study/study/8.py
186
3.625
4
''' Created on 29-Dec-2017 @author: samir ''' from platform import python_version print(python_version()) s2,s1 = input("Enter name").split() print("hello world") print(s1) print(s2)
8250f313bf841cebe7ae8d36dba27b3b1675502c
thoan741/lek
/Lek/mcnuggets.py
1,337
3.703125
4
d = 0 #värdet som efterfrågas n = 1 #värdet som testas counter = 0 #räknare s = 0 #variabel som enbart används för att kolla om det finns någon lösning a = 0 b = 0 c = 0 while counter < 6: #kör tills dess att vi hittar 6 tal på följd kan lösas s = 0 #nollställer värdet på s for a in range(0,n): #försöker hitta en lösning for b in range(0,n): #samma som ovan for c in range(0,n): #samma som ovan if 6*a + 9*b + 20*c == n: #ser om det finns en lösning s = 1 #ändrar värde på s om lösning finns if s == 1: #kollar om värdet på ändrats counter = counter + 1 #räknar upp om lösning finns print("delbar") else: #om lösning ej finns gör detta counter = 0 #nollställer räknaren d = n #sparar senaste värde på n som ej hade lösning print("icke delbar") n = n+1 #räknar upp n print(d) #största möjliga värde som ej kan uppnås
5ed41522f413213440b7ffc675c9ffd3e4ad778c
thoan741/lek
/Laborationer/Laboration_7/calcQueue.py
1,378
3.796875
4
# -*- coding: utf-8 -*- class calcQueue: """ Här definieras en klass. I instanser av denna klass kommer värden sparas i en lista. """ def __init__(self): """ Det här är en konstruktor, och denna kommer att skapa en instans av klassen calcQueue när man t.ex. skriver x = calcQueue(). """ self.__Q = [] def full(self): """ Returnerar alltid falskt, kön är aldrig full. """ return False def empty(self): """ En instans av kön är bara tom när den är just en tom lista. Returnerar booleanskt värde. """ return self.__Q == [] def enqueue(self, e): """ enqueue kommer att lägga till ett element sist i en instans av klassen. """ self.__Q.append(e) def dequeue(self): """ Funktionen dequeue kommer att spara det första elementet i instansen, ta bort det elementet ur instansen för att sedan returnera det elementet. """ a = self.__Q[0] self.__Q.pop(0) #del self.__Q[0] return a def show(self): """ Printar kön. """ a = self.__Q print(a) #kö = calcQueue() #kö.show() #kö.enqueue(31.0) #kö.show() #kö.enqueue(15.3) #kö.enqueue('+') #kö.show() #kö.dequeue() #kö.show()
e63d25776063ee323384fb7af74dcfbea5a4774c
thoan741/lek
/Laborationer/Laboration_6_copy/laboration_6_uppgift_3.py
1,073
3.734375
4
TryckString = input("Mata in trycket: ") Sort = input("Mata in sorten: ") NyaSort = input("Vad vill du omvandla till?: ") omvandlingsLista = ["mbar", float(1013), "torr", float(760), "pascal", float(101325), "atm",float(1)] def flerStegsOmvandlare(tryck, sort, newsort, ls): def NextUnit(tryck,sort,aUnit): while newsort != sort: for a in range(0, 8, 2): if a < 6 and sort == aUnit[a]: tryck = tryck * aUnit[a+3] / aUnit[a+1] sort = aUnit[a + 2] break elif a == 6 and sort == aUnit[a]: tryck = tryck * aUnit[1] / aUnit[7] sort = aUnit[0] break print("Tryck =", tryck, sort) if sort in ls: try: tryck = float(tryck) NextUnit(tryck,sort,ls) except ValueError: print("Tryck måste matas in som en siffra") else: print(sort, "är inte en definierad sort") flerStegsOmvandlare(TryckString,Sort,NyaSort, omvandlingsLista)
652990fdc99924c1810dddc60be12a8d81709a6e
ashwani8958/Python
/PyQT and SQLite/M3 - Basics of Programming in Python/program/module/friends.py
379
4.125
4
def food(f, num): """Takes total and no. of people as argument""" tip = 0.1*f #calculates tip f = f + tip #add tip to total return f/num #return the per person value def movie(m, num): """Take total and no. of the people as arguments""" return m/num #returns the per persons value print("The name attribute is: ", __name__)#check for the name attribute
18cfb77c6446b34575ea92d962e26fa5e461c7f0
ashwani8958/Python
/PyQT and SQLite/M3 - Basics of Programming in Python/program/function/5_global_vs_local_variable.py
441
3.78125
4
age = 7 def a(): print("Global varible 'age': ", globals()['age']) #now modifying the GLOBAL varible 'age' INSIDE the function. globals()['age']=27 print("Global variable 'age' modified INSIDE the function: ", globals()['age']) #now creating a LOCAL variable, 'age' INSIDE the function. age = 11 print("local variable 'age': ", age) return a() print("Checking global variable OUTSIDE the function: ", age)
9691a4a5ae601d1584ff81a6b27139bdd19e2ca1
ashwani8958/Python
/PyQT and SQLite/M5 - Connecting to SQLite Database/assignment/assignment/main.py
509
4.03125
4
from add_record import * from search_record import * while True: print("Menu for the database\n1) Add New Record\n2) Search a existing record\n3) Exit") choice = int(input("Enter your choice : ")) if 1 == choice: print("Adding New Record to Database") new_record() elif 2 == choice: print("Searching Database for the existing record") search_record() elif 3 == choice: print("Exit") break else: print("Enter the valid option")
12911df610c449a02f52622633078e729afc8313
ashwani8958/Python
/Image Processing/Computer_Vision_A_Z/Face Recognition/3_FaceRecognitionInImages.py
1,317
3.5
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun May 24 15:14:22 2020 @author: ashwani """ # https://realpython.com/face-recognition-with-python/ import cv2 # Loading the cascades face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml') smile_cascade = cv2.CascadeClassifier('haarcascade_smile.xml') def detect(gray, frame): # detect face faces = face_cascade.detectMultiScale(gray, 1.2, 20) for (x,y,w,h) in faces: cv2.rectangle(frame, (x,y), (x+w, y+h), (255, 0, 0), 2) roi_gray = gray[y:y+h, x:x+w] roi_color = frame[y:y+h, x:x+w] # In face detect eye eyes = eye_cascade.detectMultiScale(roi_gray, 1.1, 7) for (ex, ey, ew, eh) in eyes: cv2.rectangle(roi_color, (ex,ey), (ex+ew, ey+eh), (0, 255, 0), 2) # In face detect smile smile = smile_cascade.detectMultiScale(roi_gray, 1.7, 20) for (sx,sy,sw,sh) in smile: cv2.rectangle(roi_color, (sx, sy), (sx+sw, sy+sh), (0, 0, 255), 2) return frame image = cv2.imread('../images/threeperson.jpg') gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) canvas = detect(gray, image) cv2.imshow("FACE FOUND", canvas) cv2.waitKey(0)
0e9eca5ed6993b1e3a2c4bb9c3ca245b6dd5c5e3
ashwani8958/Python
/PyQT and SQLite/M5 - Connecting to SQLite Database/assignment/some try/original_search_record.py
2,784
3.984375
4
import sqlite3 import re def search_record(): book_list = list() #Connect to existing database MyLibrary = sqlite3.connect('Library.db') #create a cursor object curslibrary = MyLibrary.cursor() while True: #Loop to check for valid Title while True: title = input("Enter the Book title to search from record :- ") if re.search('''[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~0-9]''',title): print("Invalid!! Please enter the valid Title.") else: break sql = "SELECT * FROM Bookdetails WHERE Title = '"+title+"';" curslibrary.execute(sql) record = curslibrary.fetchone()#fetch only the record which is matched if record != None: print("\nBook is available") print(record) book_list.append(record[3]) while True: copies = input("\nEnter the no. of copies :- ") try: copies = int(copies) break except: print("\nPlease enter numberic values only\n") book_list.append(copies) else: print("\nBook that you are searching is not available") choice = input("Do you want to search for another book!! Y/N :- ") if choice == 'y': while True: title = input("Enter the Book title to search from record :- ") if re.search('''[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~0-9]''',title): print("Invalid!! Please enter the valid Title.") else: break sql = "SELECT * FROM Bookdetails WHERE Title = '"+title+"';" curslibrary.execute(sql) record = curslibrary.fetchone()#fetch only the record which is matched if record != None: print("\nBook is available") print(record) book_list.append(record[3]) while True: copies = input("\nEnter the no. of copies :- ") try: copies = int(copies) break except: print("\nPlease enter numberic values only\n") book_list.append(copies) else: print("\nBook that you are searching is not available") else: break print(book_list) i = 0 total_price = 0 while i < len(book_list) - 1: total_price = total_price + book_list[i]* book_list[i + 1] i = i + 2 print("Total Cost {} Rs.".format(total_price))
eda8e23a26733d5cfd1f4712cb9bf1f53294e585
ayhanbasmisirli/wdi_april_2019
/11-working-with-libraries/instructor/todo.py
543
4.0625
4
# let user specify due date for item # datetime.date class # display how much time is left until it's due # today() looks useful # e.g. _____ due in _____ days import arrow import datetime class ToDo: """ Represents an item on a to-do list """ def __init__(self, description, due_date): self.description = description self.completed = False self.due_date = due_date def complete(self): self.completed = True def __str__(self): return "To do: {} - due {}".format(self.description, self.due_date.humanize())
5912bcec4dd22442c46ac13ea361eb54e44d20d5
ayhanbasmisirli/wdi_april_2019
/11-working-with-libraries/instructor/main.py
412
3.59375
4
from todo import ToDo, datetime, Arrow from arrow.arrow import Arrow print('When is this item due?') due_year = 2019 due_month = 5 due_day = 25 due_date = Arrow(due_year, due_month, due_day) todo = ToDo('buy groceries', due_date) print(todo) past_due = Arrow(2019, 5, 12) todo2 = ToDo('dishes', past_due) print(todo2) todays_date = Arrow(2019,5,13) due_today = ToDo('mow lawn', todays_date) print(due_today)
8d33c9452fb32c5da941d4c0761f59c7f3eaa065
SURBHI17/python_daily
/src/quest_9.py
236
3.640625
4
#PF-Prac-9 def generate_dict(number): #start writing your code here new_dict={} i=1 while(i<=number): new_dict.update({i:i*i}) i+=1 return new_dict number=20 print(generate_dict(number))
95e0619eeb977cefe6214f8c50017397ec35af3b
SURBHI17/python_daily
/prog fund/src/assignment40.py
383
4.25
4
#PF-Assgn-40 def is_palindrome(word): word=word.upper() if len(word)<=1: return True else: if word[0]==word[-1]: return is_palindrome(word[1:-1]) else: return False result=is_palindrome("MadAMa") if(result): print("The given word is a Palindrome") else: print("The given word is not a Palindrome")
b4c480356866bb7bfebd5fc540f7cf134ef439b3
SURBHI17/python_daily
/src/quest_12.py
510
3.671875
4
#PF-Prac-12 def generate_sentences(subjects,verbs,objects): #start writing your code here sentence_list=[] sentence="" for el in subjects: for el_2 in verbs: for el_3 in objects: sentence+=el+" "+el_2+" "+el_3 sentence_list.append(sentence) sentence="" return sentence_list subjects=["I","You"] verbs=["love", "play"] objects=["Hockey","Football"] print(generate_sentences(subjects,verbs,objects))
afdd7db2d0487b2cc2af9a6c33bcdc5c61512109
SURBHI17/python_daily
/prog fund/src/day4_class_assign.py
338
4.1875
4
def duplicate(value): dup="" for element in value: if element in dup: #if element not in value: continue # dup+=element else: # dup+=element #return dup return dup value1="popeye" print(duplicate(value1))
40d7c2448928e437701a688d0bc3d991ba89c808
SURBHI17/python_daily
/prog fund/src/assignment21.py
789
3.78125
4
#PF-Tryout def generate_next_date(day,month,year): #Start writing your code here if(day<=29): if(month==2): if(day==28)and((year%4==0 and year%100!=0) or year%400==0): day+=1 else: day=1 month+=1 else: day+=1 elif(day==30 or 31): if(month==1 or 3 or 5 or 7 or 8 or 10)and day==31 : day=1 month+=1 elif(month==4 or 6 or 9 or 11) and day==30: day=1 month+=1 else: day+=1 else: day=1 month=1 year+=1 print(day,"-",month,"-",year) generate_next_date(28,2,2016)
a893a3be9c8715a178c57d1a9c2b6ecb8874ec33
SURBHI17/python_daily
/prog fund/src/exercise22.py
663
3.890625
4
#PF-Exer-22 def generate_ticket(airline,source,destination,no_of_passengers): ticket_number_list=[] count=101 #while(no_of_passengers>0): for i in range(0,no_of_passengers): ticket_number_list.append(airline+":"+source[:3:]+":"+destination[:3:]+":"+str(count)) count=count+1 if len(ticket_number_list)>5: return ticket_number_list[-5::] #Write your logic here #Use the below return statement wherever applicable return ticket_number_list #Provide different values for airline,source,destination,no_of_passengers and test your program print(generate_ticket("AI","Bangalore","London",7))
1105eaac5a28e722be234a440276647401a03b08
SURBHI17/python_daily
/src/quest_16.py
325
3.546875
4
#PF-Prac-16 def rotate_list(input_list,n): #start writing your code here output_list=input_list[:len(input_list)-n] rotate=input_list[len(input_list)-n:] output_list=rotate+output_list return output_list input_list= [1,2,3,4,5,6] output_list=rotate_list(input_list,4) print(output_list)
8ef915f51cf5615969b047dd61e05f4054b44f10
lssergey/projecteuler
/skovorodkin/007_10001st_prime.py
577
3.78125
4
from itertools import count, islice from math import sqrt def nth(iterable, n): return next(islice(iterable, n, None)) def prime_generator(): primes = [2] def is_prime(n): for prime in primes: if prime > sqrt(n): break if n % prime == 0: return False return True yield 2 for i in count(3, 2): if is_prime(i): primes.append(i) yield i def solve(n=10001): return nth(prime_generator(), n - 1) if __name__ == '__main__': print(solve())
cdcab6d17e29620c08c0853e7b667c18e15ad1f5
mylessbennett/reinforcing_exercises_feb20
/exercise1.py
247
4.125
4
def sum_odd_num(numbers): sum_odd = 0 for num in numbers: if num % 2 != 0: sum_odd += num return sum_odd numbers = [] for num in range(1, 21): numbers.append(num) sum_odd = sum_odd_num(numbers) print(sum_odd)
d71bb614afb0a7c248734c9ce444623ef1b29686
psambalkar/Design-2
/hashset.py
1,724
3.859375
4
/ Time Complexity : O(1) // Space Complexity :O(N) // Did this code successfully run on Leetcode :Yes // Any problem you faced while coding this :No class MyHashSet(object): def __init__(self): """ Initialize your data structure here. """ self.primaryArray = [None]* 1000 def getBucket(self,key): return key%1000 def getBucketitems(self,key): return key//1000 def add(self, key): """ :type key: int :rtype: None """ bucket=self.getBucket(key) bucketItem=self.getBucketitems(key) if(self.primaryArray[bucket]==None): if bucket==0: self.primaryArray[0]=[False]*1001 else: self.primaryArray[bucket]=[False]*1000 self.primaryArray[bucket][bucketItem] = True def remove(self, key): """ :type key: int :rtype: None """ bucket=self.getBucket(key) bucketItem=self.getBucketitems(key) if self.primaryArray[bucket] is not None: self.primaryArray[bucket][bucketItem] = False def contains(self, key): """ Returns true if this set contains the specified element :type key: int :rtype: bool """ bucket=self.getBucket(key) bucketItem=self.getBucketitems(key) if self.primaryArray[bucket] is None: return False else: return self.primaryArray[bucket][bucketItem] # Your MyHashSet object will be instantiated and called as such: # obj = MyHashSet() # obj.add(key) # obj.remove(key) # param_3 = obj.contains(key)
de41ac8aac2c33527569eb9cdcce2b0c316d6083
Mauriciods07/practica09
/p09.py
4,764
4.28125
4
#Código de la práctica 09 para comenzar el aprendizaje en Python x = 10 #variable de tipo entero cadena = "Hola Mundo" #varible de tipo cadena print(cadena, x) x = "Hola mundo!" type(x) x = y = z = 10 print(x,y,z) #Cuando una variable tiene un valor constante, por convención, el nombre se escribe en mayúsculas. SEGUNDOS_POR_DIA = 60 * 60 * 24 PI = 3.14 cadena1 = 'Hola ' cadena2 = "Mundo" print(cadena1) print(cadena2) concat_cadenas = cadena1 + cadena2 #Concatenación de cadenas print(concat_cadenas) n = 5 print("Tenemos un número {}".format(n)) print(concat_cadenas + ' ' + str(3)) print(concat_cadenas, n) num_cadena = "Cambiando el orden: {1} {2} {0} #".format(cadena1, cadena2, 3) print(num_cadena) print( 1 + 5 ) print( 6 * 3 ) print( 10 - 4 ) print( 100 / 50 ) print( 10 % 2 ) print( ((20 * 3) + (10 +1)) / 10 ) print( 2**2 ) False and True print (7 < 5) #Falso print (7 > 5) #Verdadero print ((11 * 3)+2 == 36 - 1) #Verdadero print ((11 * 3)+2 >= 36) #Falso print ("curso" != "CuRsO") #Verdadero print("5 + 4 es ", 5+4) print(5 < 4) lista_diasDelMes=[31,28,31,30,31,30,31,31,30,31,30,31] print (lista_diasDelMes) #imprimir la lista completa print (lista_diasDelMes[1]) #imprimir elemento 2 print (lista_diasDelMes[4]) #imprimir elemento 5 print (lista_diasDelMes[10]) #imprimir elemento 11 lista_numeros=[['cero', 0],['uno',1, 'UNO'], ['dos',2], ['tres', 3], ['cuatro',4], ['X',5]] print (lista_numeros) #imprimir lista completa print (lista_numeros[0]) #imprime el elemento 0 de la lista print (lista_numeros[1]) #imprime el elemento 1 de la lista print (lista_numeros[2][0]) #imprime el primer elemento de la lista en la posicion 2 print (lista_numeros[2][1]) #imprime el segundo elemento de la lista en la posicion 2 print (lista_numeros[1][0]) print (lista_numeros[1][1]) print (lista_numeros[0][0]) lista_numeros[5][0] = "cinco" print (lista_numeros[5]) tupla_diasDelMes=(31,28,31,30,31,30,31,31,30,31,30,31) print (tupla_diasDelMes) #imprimir la tupla completa print (tupla_diasDelMes[5]) #imprimir elemento 6 print (tupla_diasDelMes[3]) #imprimir elemento 4 print (tupla_diasDelMes[1]) #imprimir elemento 2 tupla_numeros=(('cero', 0),('uno',1, 'UNO'), ('dos',2), ('tres', 3), ('cuatro',4), ('X',5)) print (tupla_numeros) #imprimir tupla completa print (tupla_numeros[0]) #imprime el elemento 0 de la tupla print (tupla_numeros[1]) #imprime el elemento 1 de la tupla print (tupla_numeros[2][0]) #imprime el primer elemento de la tupla en la posicion 2 print (tupla_numeros[2][1]) #imprime el segundo elemento de la tupla en la posicion 2 print (tupla_numeros[1][0]) print (tupla_numeros[1][1]) print (tupla_numeros[1][2]) from collections import namedtuple planeta = namedtuple('planeta', ['nombre', 'numero']) planeta1 = planeta('Mercurio', 1) print(planeta1) planeta2 = planeta('Venus', 2) print(planeta1.nombre, planeta1.numero) print(planeta2[0], planeta2[1]) print('Campos de la tupla: {}'.format(planeta1._fields)) elementos = { 'hidrogeno': 1, 'helio': 2, 'carbon': 6 } print(elementos) print(elementos['hidrogeno']) print (elementos['helio']) elementos['litio'] = 3 elementos['nitrogeno'] = 8 print (elementos) elementos2 = {} elementos2['H'] = {'name': 'Hydrogen', 'number': 1, 'weight': 1.00794} elementos2['He'] = {'name': 'Helium', 'number': 2, 'weight': 4.002602} print (elementos2) print (elementos2['H']) print (elementos2['H']['name']) print (elementos2['H']['number']) elementos2['H']['weight'] = 4.30 #Cambiando el valor de un elemento print (elementos2['H']['weight']) elementos2['H'].update({'gas noble':True}) print (elementos2['H']) print (elementos2.items()) print (elementos2.keys()) def imprime_nombre(nombre): print("hola "+nombre) imprime_nombre("JJ") def cuadrado(x): return x**2 x = 5 print("El cuadrado de {} es {}".format(x, cuadrado(x))) def varios(x): return x**2, x**3, x**4 val1, val2, val3 = varios(2) print("{} {} {}".format(val1, val2, val3)) def cuadrado_default(x=3): return x**2 cuadrado_default() val4, _, val5 = varios(2) print("{} {}".format(val4, val5)) vg = 'Global' def funcion_v1(): print(vg) funcion_v1() #Imprime la variable global print(vg) def funcion_v2(): vg = "Local" print(vg) funcion_v2() #Imprime valor local #Imprime la variable global print(vg) def funcion_v3(): print(vg) vg = "Local" print(vg) funcion_v3() def funcion_v4(): global vg print(vg) vg = "Local" print(vg) funcion_v4() print(vg) def sumar(x): y = 5 return x + y n = 4 sumar(n)
a76c4a577bc6afdfbd0afe19478cf7eefbd0abe5
shailendrajain2892/ga-learner-dsmp-repo
/MakingYourFirstPrediction/code.py
1,614
3.5
4
# -------------- import pandas as pd import numpy as np from sklearn.cross_validation import train_test_split # code starts here df = pd.read_csv(path) df.head() # all the dependent columns X = df.iloc[:, :-1] y = df.iloc[:, -1] # split the columns into test and training data X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=3) # code ends here # -------------- import matplotlib.pyplot as plt # code starts here cols = X_train.columns print(cols) fig, axes = plt.subplots(nrows=3, ncols=3) for i in range(3): for j in range(3): col = cols[ i * 3 + j] axes[i, j].scatter(df[col], df['list_price']) axes[i, j].set_xlabel(col) fig.set_figheight(15) fig.set_figwidth(15) plt.show() # code ends here # -------------- # Code starts here corr = X_train.corr() X_train = X_train.drop(columns=['play_star_rating', 'val_star_rating']) X_test = X_test.drop(columns=['play_star_rating', 'val_star_rating']) # Code ends here # -------------- from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error, r2_score # Code starts here #Instantiate linear regression model regressor=LinearRegression() # fit the model regressor.fit(X_train,y_train) # predict the result y_pred =regressor.predict(X_test) # Calculate mse mse = mean_squared_error(y_test, y_pred) # print mse print(mse) # Calculate r2_score r2 = r2_score(y_test, y_pred) #print r2 print(r2) # Code ends here # -------------- # Code starts here residual = y_test - y_pred plt.hist(residual) plt.show() # Code ends here
2d4105bc0b4902b24d1eab5560521a2d0c3560ae
kedro-org/kedro-viz
/tools/github_actions/extract_release_notes.py
1,069
3.5625
4
import sys def extract_section(filename, heading): with open(filename, "r") as file: lines = file.readlines() start_line, end_line = None, None for i, line in enumerate(lines): if line.startswith("# "): current_heading = line.strip("#").replace(":", "").strip() if current_heading == heading: start_line = i elif start_line is not None: end_line = i break if start_line is None: return None end_line = end_line or len(lines) section = "".join(lines[start_line + 1 : end_line]).strip() return section if __name__ == "__main__": if len(sys.argv) != 3: raise Exception("Usage: python extract_release_notes.py <filename> <heading>") filename = sys.argv[1] heading = sys.argv[2] section = extract_section(filename, heading) if not section: raise Exception(f"Section not found under the {heading} heading") with open("release_body.txt", "w") as text_file: text_file.write(section)
5b3a302fa6960a1765a5f839d3520ca27ec24735
SergioCaler0/my_first_proyect
/main.py
2,893
3.921875
4
# Juego de adivina el número. import random def generate_random_number(): # creo la funcion que me va a dar un numero aleatorio random_number = random.randint(1, 100) # generamos un numero aleatorio del 1 al 100 y lo meto dentro de una variable return random_number # pido que me devuleva ese nnumero que he generado def ask_user_number(aviso = "Guess the number: "): # creo la funcion mediante la cual el usuario me proprcionara un numero user_number = int(input(aviso)) # creo la variable que va a contener el numero elegido por el usuario return user_number # pido que me devuelva el numero del usuario def check_user_number(user_number, random_number): #creo la funcion con la que voy a manipular las posibilidades que tiene el numero elegido por el usuario if user_number <= 0 or user_number > 100: return "Null" # si el numero es 0, un numero negativo o superior a 100 sera nulo if user_number > random_number: return "Too high" # si el numero es mayor que el seleccionado por la maquina te devolvera el mensaje de que es demasiado alto elif user_number < random_number: return "Too low" # si el numero es mayor que el seleccionado por la maquina te devolvera el mensaje de que es demasiado bajo else: return "congratulations" # si el numero no cumple ninguna de las condiciones anteriores, enhorabuena, has acertado! def executor(): user_congratuled = False start = True while user_congratuled or start: # si se cumple una de las dos variables declaradas antes random_number = generate_random_number() # el ordenador elige un nnumero al azar del 1-100 user_number = ask_user_number() # el usuario selecciona su numero aviso = check_user_number(user_number, random_number) # y dependiendo de los numeros elegidos la consola te indicara while aviso != "congratulations": # mientras no des con el numero correctto print(aviso) # la cosola te dira que sigas intentandolo user_number = ask_user_number("Try again: ") aviso = check_user_number(user_number, random_number) print(aviso) user_congratuled = True executor()
9868e5d6dfcc89302b2da8700b5c105f9d88149e
joshrz/joshrz.github.io
/story.py
7,619
4.25
4
import time print("This story takes place in the abandoned town of Astroworld") time.sleep(3) print('\n') print ("In Astroworld there are many cruel and uninmaginable crimes that have taken place") time.sleep(3) print('\n') print("Over the years there has been a report that over 250 crimes of missing teenagers that end up dead and have been found with broken arms and legs that have been bathed with their own blood from stab wounds") time.sleep(3) print('\n') name = input('Hi what is your name? ') print('\n') print("Hello", name) print('\n') print("Are you interested in going through the cruel story of ASTROWORLD??") time.sleep(3) x = input('Please enter "yes" or "no" ') print('\n') if (x == "yes"): print('Well then lets get started. ') else: print('No? Well then I guess your to weak to go through a scare in you life but your going through it anyway.') print('\n') print('Your friends decide to go walk in the haunted Black Woods of Asrtoworld?') time.sleep(3) x = input('Do you go with your friends "yes" or "no"? ') print('\n') if (x == "yes"): print('You will meet at the enterance of the woods at 2:00 A.M. in the morning. ') else: print('Your friends threaten to publicly embarrass you so your forced to go!') time.sleep(3) print('\n') print('Your walking in the woods and you get the feeling your being watched so you turn on a flashlight to look around but the batteries are dead!') time.sleep(3) x = input('Do you "yes" turn back or "no" keep going? ') print('\n') if (x == "yes"): print('You and your friends keep walking and one of you steps on something which coincidentally happens to be a flashlight but its coverered in blood.') else: print('You guys want to turn back but you see a figure in the shadows coming towards you and you take off running deeper into the woods.') time.sleep(3) print('\n') print("You hear something walking behind you and you take off running.") time.sleep(3) print('\n') print("You stop running after a while and you dont hear or see anything around you anymore. Now you know that your being followed and that leaving the woods is going to be difficult...") time.sleep(3) print('\n') print('You have two options one you can take the risk of going back and getting attacked by whatever is out there or your second option you can continue going ino the woods to try to find shelter untill morning. ') time.sleep (3) print('\n') print("Do you yes turn back or no keep going ") time.sleep(3) x = input('Enter "yes" or "no": ') print('\n') if (x == "yes"): print('Two of your friends end up getting slaughtered by the horrifying monster and the rest of you run away and find a mansion') else: print('You find an abandoned mansion and you and your friends go inside of it.') time.sleep(3) print('\n') print('Your inside the mansion and all of the walls are scratched up and there is a horrible smell coming from deeper in the house.') time.sleep(3) print('\n') print('You start to walk down the hallway and notice that the walls are covered in blood and have scratch marks on them and there are pieces of furniture scattered everywhere') time.sleep(3) print('\n') print('You and your friends are extremely tired and hungry') time.sleep(3) print('\n') print("Your friend comes across the kitchen and finds that theres a refrigerator full of food.") time.sleep(3) print('\n') print("What do you do?") time.sleep(3) print('\n') print("Let your friend eat the food thats in there or do you tell him not to... ") time.sleep(3) x=input('Enter "yes" to let him eat the food thats in there or "no" to tell him not to: ') print('\n') if (x == "Yes"): print("Your friend swallows the first bite and instantly get dizzy and then you realize that the food was posioned and your friend dies after a couple of minutes") else: print("You save your friends life after finding out there was a toxic pill hidden within the food.") time.sleep(3) print('\n') print ("It's currently 4:00 AM and your friends want to sleep!") time.sleep(3) print('\n') print("There are enough beds for your friends and youself") time.sleep(3) print('\n') print("But you see that the door handle is covered in blood and a sign outside the room that reads USE AT YOUR RISK!") time.sleep(3) print('\n') print("So you warn your friends but their to tired and don't listen to you and they open the door") time.sleep(3) print('\n') print('As they all lay on their own beds...') time.sleep(3) print('\n') print("ALL OF A SUDDEN YOUR FRIEND STARTS SCREAMING HIS HEART OUT BECAUSE OF THE NEEDLES THAT WERE CONNECTED TO THE BED AS A TRAP!") time.sleep(3) print('\n') print("You have to make a difficult choice to either leave your friend here and let the scary creature kill him or to take him out carefully and have a higher chance of being chased?") time.sleep(3) x =input('Enter "Yes" to leave your friend and you and the other leave together or "No" to take him out and carry him: ') print('\n') time.sleep(3) if (x == "yes"): print ('You and your friends escape and go find a hiding spot.') else: print("Your injured friend is bleeding out but you stop the bleeding with some cloth laying around but after a few minutes he dies of poisoning from the needles.") time.sleep(3) print('\n') print("The monster heard your friend screaming and now he's on the way to the mansion. ") time.sleep(3) print('\n') print("Do you find a safe hiding spot inside the mansion or escape and run back into the woods.") time.sleep(3) x=input('Enter "yes" to stay inside the mansion and find a safe hiding or "no" try to jump out the window and run back into the woods: ') print('\n') if (x == "yes"): print("The monster enters the house and begins his search to kill you!") else: print('You go to a window in the room and you see that your to high up to jump without hurting yourselves') time.sleep(3) print('\n') print('Now that you have no way to get out you start looking for a place to hide in the mansion.') time.sleep(3) print('\n') print('You open the door to try to sneak out and you see nothing so you and your friends sneak out.') time.sleep(3) print('\n') print('Your walking down a hallway and you hear what sounds like a animal breathing and its getting closer.') time.sleep(3) print('\n') print('You start to look for the nearest room but you find nothing and the hallway lead to a dead end but you see that there is a hatch on the floor and you open it. ') time.sleep(3) print('\n') print('Once you opened it you realized that the horrible smell that you smelled when you first entered the house was coming from here.') time.sleep(3) print('\n') print('You are forced to jump in when you hear the monster extremely close and you hear footsteps.') time.sleep(3) print('\n') print('The smell was so horrible so you start to look around to see what was causing it and find some of the dead bodies that the monster has killed pilled on top of each other.') time.sleep(3) print('\n') print('One of your friends sreams and you cover his mouth to muffle the scream but it was to late! You hear the monster running in the hallway towards you.') time.sleep(3) print('\n') print("Do you quickly try to escape or hide within the bodies buried there?") time.sleep(3) x=input('Enter "yes" to esacpe or "no" to hide: ') print('\n') if (x == "yes"): print('The monster sees you and starts chasing you along with your friends and kills you off one by one. ') else: print('The monster knows that your there and eventually finds you hiding and kills you and your friends Goodbye!')
114dd9807e3e7a111c6e1f97e331a7a98e6e074a
KanuckEO/Number-guessing-game-in-Python
/main.py
1,491
4.28125
4
#number_guessing_game #Kanuck Shah #importing libraries import random from time import sleep #asking the highest and lowest index they can guess low = int(input("Enter lowest number to guess - ")) high = int(input("Enter highest number to guess - ")) #array first = ["first", "second", "third", "fourth", "fifth"] #variables second = 0 #tries counter tries = 1 #array for highest and lowest index that they can guess numbers = [low, high] #choosing random number between array above number = random.randint(low, high) #printting for style print("\n") print("************************************") print("Welcome to the number guessing game.") print("************************************") print("\n") print("You will have to choose a number between", low ,"and", high ,"in eight tries") #delay sleep(1) print(".") sleep(1) print(".") sleep(1) print(".") sleep(1) print("\n") while tries < 8: tries += 1 print("choose your", first[second] ,"number ", end="") ans1 = int(input("")) second += 1 print("You have tried to guess", tries, "times.") if int(number) > ans1: print("\n") print("Too low go higher") elif int(number) < ans1: print("\n") print("Too high go lower") elif int(number) == ans1: print("\n") print("Ding Ding Ding") print("You are right") print("The number was", number) break if tries >= 8: print("\n") print("The number was", number) print("Too many tries session ended") print("Better luck next time :(")
2d8603a4d21955787543691bbeca2bb8858ecb85
Caaddss/livros
/backend.py
2,283
3.609375
4
import sqlite3 import sqlite3 as sql def iniitDB(): database = "minhabiblioteca.db" conn = sqlite3.connect(database) cur = conn.cursor() cur.execute("""CREATE TABLE livros(id INTEGER PRIMARY KEY, titulo TEXT, subtitulo TEXT, editora TEXT, autor1 TEXT, autor2 TEXT, autor3 TEXT, cidade TEXT, ano TEXT, edicao TEXT, paginas TEXT, volume TEXT);""") conn.commit() conn.close() iniitDB() def view(): database = "minhabiblioteca.db" conn = sqlite3.connect(database) cur = conn.cursor() cur.execute("SELECT * FROM livros") for rows in cur.fetchall(): return rows conn.commit() conn.close() def insert (titulo,subtitulo,editora,autor1,autor2,autor3,cidade,ano,edicao,paginas,volume): database = "minhabiblioteca.db" conn = sqlite3.connect(database) cur = conn.cursor() cur.execute("""INSERT INTO livros VALUES(NUll,?,?,?,?,?,?,?,?,?,?,?)""",[titulo,subtitulo,editora,autor1,autor2,autor3,cidade,ano,edicao,paginas,volume]) conn.commit() conn.close() def search(titulo="",subtitulo="",editora="",autor1="",autor2="",autor3="",cidade="",ano="",edicao="",paginas="",volume=""): database = "minhabiblioteca.db" conn = sqlite3.connect(database) cur = conn.cursor() cur.execute("SELECT * FROM livros WHERE titulo=? or subtitulo=? or editora=? or autor1=? or autor2=? or autor3=? or cidade=? or ano=? or edicao=? or paginas=? or volume=?",(titulo,subtitulo,editora,autor1,autor2,autor3,editora,ano,edicao,paginas,volume)) for rows in cur.fetchall(): return rows conn.commit() conn.close() def update(titulo,subtitulo,editora,autor1,autor2,autor3,cidade,ano,edicao,paginas,volume): database = "minhabiblioteca.db" conn = sqlite3.connect(database) cur = conn.cursor() cur.execute("UPDATE livros SET titulo=? or subtitulo=? or editora=? or autor1=? or autor2=? or autor3=? or cidade=? or ano=? or edicao=? or paginas=? or volume=?",(titulo,subtitulo,editora,autor1,autor2,autor3,editora,ano,edicao,paginas,volume,id)) conn.commit() conn.close() def delete(id): database = "minhabiblioteca.db" conn = sqlite3.connect(database) cur = conn.cursor() cur.execute("DELETE FROM livros WHERE id=?",(id,)) conn.commit() conn.close()
6c4d38f9bf65685d9bbae420787da7cd31cc45e2
Bouananhich/Ebec-Paris-Saclay
/user_interface/package/API/queries.py
1,949
3.5625
4
"""Queries used with API.""" def query_city( rad: float, latitude: float, longitude: float, ) -> str: """Create an overpass query to find the nearest city from the point. :param rad: Initial search radius. :param latitude: Latitude of the point. :param longitude: Longitude of the point. return overpass_query : build the query to find the nearest city from your point """ overpass_query = f"""[out:json][timeout:800];(node["place"="town"](around:{rad},{latitude},{longitude});node["place"="city"](around:{rad},{latitude},{longitude});node["place"="village"](around:{rad},{latitude},{longitude}););out body;>;out skel qt;""" return overpass_query def query_street( rad: float, latitude: float, longitude: float, ) -> str: """Create an overpass query to find the nearest street from the point. :param rad: Initial search radius. :param latitude: Latitude of the point. :param longitude: Longitude of the point. return overpass_query : build the query to find the nearest street from your point """ overpass_query = f"[out:json][timeout:800];way(around:{rad},{latitude},{longitude})[name];(._;>;);out;" return overpass_query def query_ways( latitude: float, longitude: float, ) -> str: """.""" overpass_query_get_ways = f"[out:json][timeout:800];way(around:2,{latitude},{longitude})[name];(._;>;);out;" return overpass_query_get_ways def query_nodes( id_node: int, ) -> str: """Create the query to find a node defined by its id. :param id_node: Integer that is a primary key for nodes. return overpass_query_get_node : build the query to get the node associated to the id """ overpass_query_get_node = f"[out:json][timeout:800];node({id_node});out;" return overpass_query_get_node __all__ = ["query_city", "query_street", "query_ways", "query_nodes"]
49a3ed95a43897bf688cb2de2eb1ee3de114f148
inambioinfo/Genomic-Scripts
/assignment6/Polk.py
4,268
3.71875
4
#!/usr/bin/env python3 """ Script that takes in amino acid sequence as input and outputs all possible DNA sequences that could encode this AA. Usage: python3 Polk.py <peptide sequence(s)> <melting temperature> """ # Importing necessary modules import sys # Initializing a list for the number of arguments inputed arg_list = [] # Use a for loop to iterate through the number of arguments inputed for arg in sys.argv[1:]: if arg.isalpha() == True:# IF arg is only letters then arg_list.append(arg)# Append arg to arg_list else:# ELSE temp = float(arg)# Assign arg to the variable temp #Standard table of codons - a dictionary of single-letter #amino acid code to a list of codon choices aa_to_codons = {} aa_to_codons[ "A" ] = ["GCA", "GCC", "GCG", "GCT" ] aa_to_codons[ "C" ] = ["TGC", "TGT" ] aa_to_codons[ "D" ] = ["GAC", "GAT" ] aa_to_codons[ "E" ] = ["GAA", "GAG" ] aa_to_codons[ "F" ] = ["TTC", "TTT" ] aa_to_codons[ "G" ] = ["GGA", "GGC", "GGG", "GGT" ] aa_to_codons[ "H" ] = ["CAC", "CAT" ] aa_to_codons[ "I" ] = ["ATA", "ATC", "ATT" ] aa_to_codons[ "K" ] = ["AAA", "AAG" ] aa_to_codons[ "L" ] = ["CTA", "CTC", "CTG", "CTT", "TTA", "TTG" ] aa_to_codons[ "M" ] = ["ATG" ] aa_to_codons[ "N" ] = ["AAC", "AAT" ] aa_to_codons[ "P" ] = ["CCA", "CCC", "CCG", "CCT" ] aa_to_codons[ "Q" ] = ["CAA", "CAG" ] aa_to_codons[ "R" ] = ["AGA", "AGG", "CGA", "CGC", "CGG", "CGT" ] aa_to_codons[ "S" ] = ["AGC", "AGT", "TCA", "TCC", "TCG", "TCT" ] aa_to_codons[ "T" ] = ["ACA", "ACC", "ACG", "ACT" ] aa_to_codons[ "V" ] = ["GTA", "GTC", "GTG", "GTT" ] aa_to_codons[ "W" ] = ["TGG" ] aa_to_codons[ "Y" ] = ["TAC", "TAT" ] aa_to_codons[ "*" ] = ["TAA", "TAG", "TGA" ] # Inputs: Sequence of dna and amino acids # Outputs: All possible variations of dna sequence that could encode the corresponding amino acid sequence given def check_combinations(dna_string, aa_string, temp): # if this code is confusing to you, uncomment the print statement #print("Input DNA is:",dna_string,"Remaining AAs are:", aa_string, sep='\t') if (len(aa_string) == 0):# If the current length of the amino acid sequence is zero then, #Conduct all filtering steps within this block of code and then print all sequences that pass g_count = dna_string.count('G')# Initializing the variable g_count to track the number of Gs in the dna_string c_count = dna_string.count('C')# Initializing the variable c_count to track the number of Cs in the dna_string dna_temp = (64.9 + (41.0* (g_count + c_count - 16.4)/ len(dna_string) ) )# Initializing the variable dna_temp to calculate the melting temperature of dna_string #IF statement for filtering sequences out of specified tempature range if dna_temp >= temp-0.5 and dna_temp <= temp+0.5:# If dna_temp is within 0.5 degrees of specified temp then continue #IF statement for filtering sequence with restriction sites NdeI, XhoI, TaqI and BfaI if ('CATATG' and 'CTCGAG' and 'TCGA' and 'CTAG') not in dna_string:# If none of these sequences exist within dna_string then continue print(dna_string + '\t' + str(dna_temp) )# Print the dna sequence # Since aa_string still contains some aa continue translating them into dna sequence # Otherwise, else: # Assigning the first index of aa_string to current_AA current_AA = aa_string[0]; # Use a for loop to iterate through all values corresponding to the current_AA in aa_to_codons dictionary for single_codon in aa_to_codons[current_AA]: # Assign new_dna_string to dna_string with the addition of single_codon new_dna_string = dna_string + single_codon # Calling on the function itself (recursively) but using the next index within the aa_string to calculate the next aa check_combinations(new_dna_string, aa_string[1:], temp) ### Main Script ### for oligo in arg_list:# Use a for loop to iterate through arg_list print('The amino acid sequence and melting temperature used.\tOligo: ' + oligo + '\tMT: ' + str(temp))# Print out the current oligo and it's corresponding temperature print('DNA sequence\t\tMelting Temperature')# Print out the header for the sequences and temperatures check_combinations( "", oligo, temp )# Call on check_combinations to convert the current aa sequence to dna sequence and it's corresponding melting temperature
56f1e0d155213301cb7281889c529b5a3d29e9b0
DineshkumarAgrawal4/walk-through-the-subdirs
/countline.py
525
3.640625
4
import subprocess import os import sys #This is a very simple program to count the line of some files with suffix def countlines(directory,suffix): print('lines'+' '+'dir') for (thisdir,subsdir,thisfile) in os.walk(directory): for file in thisfile: if file.endswith(suffix): file=os.path.join(thisdir,file) subprocess.call(['wc','-l',file]) if __name__=='__main__': directory=sys.argv[1] suffix=sys.argv[2] countlines(directory,suffix)
9e776f2abda1037063a92933b4df16a421ea3392
vedaditya/Some-Common-problems
/mancunian and colored tree.py
775
3.65625
4
# -*- coding: utf-8 -*- """ Created on Wed May 13 15:11:03 2020 @author: aryavedaditya question link:- https://www.hackerearth.com/practice/data-structures/trees/binary-and-nary-trees/practice-problems/algorithm/mancunian-and-colored-tree/ """ from collections import defaultdict from sys import stdin n,c=map(int,stdin.readline().split()) tree=[0,0] tree.extend(list(map(int,stdin.readline().split()))) colourlist=list(map(int,stdin.readline().split())) colourdic=defaultdict() for i in range(len(colourlist)): colourdic[i+1]=colourlist[i] res='-1 ' for i in range(2,n+1): colour=colourdic[i] node=tree[i] while colourdic[node]!=colour: node=tree[node] if node==0: node =-1 break; res+=str(node)+' ' print(res)
9407f6a1dacfc2dca38e6b25ec31495357d8ba3b
blankxz/LCOF
/Python语言测试/单例模式2.py
624
3.609375
4
# encoding:utf-8 __author__ = 'Fioman' __time__ = '2019/3/6 13:36' import threading class Singleton(object): _instance_lock = threading.Lock() def __init__(self, *args, **kwargs): pass def __new__(cls, *args, **kwargs): if not hasattr(cls, '_instance'): with Singleton._instance_lock: if not hasattr(cls, '_instance'): Singleton._instance = super().__new__(cls) return Singleton._instance obj1 = Singleton() obj2 = Singleton() print(obj1, obj2) a = {'1':2} print(a.get('2')) a = 1 b = 1 print(id(a)) print(id(b)) print(a is b)
9e3cafdfe5db8541e85c8480f18df920bf743b7b
blankxz/LCOF
/密码锁(3602017秋招真题)/hello.py
280
3.734375
4
data = [] while 1: a = input() data.append(list(a)) if len(data) == 3: temp = data.copy() for i in range(3): data[i] = data[2-i][::-1] if temp == data: print('YES') else: print('NO') data = []
2529dedc764fcca0e923232f9dc8f56cc154ae93
blankxz/LCOF
/Python语言测试/生产消费_多进程.py
593
3.5625
4
from multiprocessing import Process, Queue import time, random def producer(queue): for i in range(10000): tem = random.randint(1,1000) queue.put(tem) print("生产了:"+str(tem)) # time.sleep(1) def consumer(queue): while True: time.sleep(5) tem = queue.get() if not tem: print("队列为空") else: print("消费了:"+str(tem)) if __name__ == "__main__": q = Queue(100) p = Process(target=producer,args=(q,)) c = Process(target=consumer,args=(q,)) p.start() c.start()
d15700d5e54ef4902dac5a4fdeab8419b868866a
blankxz/LCOF
/对称的二叉树/hello.py
637
3.921875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isSymmetric(self, root: TreeNode) -> bool: if not root: return True return self.dfs(root.left,root.right) def dfs(self,l,r): if not l and not r: return True else: if l and r: if l.val!=r.val: return False return self.dfs(l.left,r.right) and self.dfs(l.right,r.left) else: return False
101aaa5c240aca840d1b5db161dfcec53b82c57b
blankxz/LCOF
/Python语言测试/sort_.py
795
3.78125
4
def bubble(arr): for i in range(len(arr)): for j in range(len(arr)-1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] return arr print(bubble([3,6,8,1,2,10,5])) def select(arr): for i in range(len(arr)): min_ind = i for j in range(i+1,len(arr)): if arr[j] < arr[min_ind]: min_ind = j if min_ind != i: arr[i],arr[min_ind] = arr[min_ind],arr[i] return arr print(select([3,6,8,1,2,10,5])) def insert(arr): for i in range(len(arr)): preind = i-1 cur = arr[i] while preind >=0 and arr[preind]>cur: arr[preind+1] = arr[preind] preind -= 1 arr[preind+1] = cur return arr print(insert([3,6,8,1,2,10,5]))
3954ffe60b7440baa5fe64c372da8d8339c2e077
blankxz/LCOF
/重建二叉树/hello.py
703
3.734375
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def buildTree(self, preorder, inorder) -> TreeNode: if len(preorder)>0: root = TreeNode(preorder[0]) ind = inorder.index(preorder[0]) root.left = self.buildTree(preorder[1:1+ind],inorder[:ind]) root.right = self.buildTree(preorder[1+ind:],inorder[ind+1:]) return root s = Solution() a = s.buildTree([3,9,20,15,7],[9,3,15,20,7]) def pri(a): if a == None: return if a != None: print(a.val) pri(a.left) pri(a.right) pri(a)
f1fa5083c061636adff9631207520c81e5681a81
paulogpafilho/machine-learning
/maker-fair-2017/resize_image.py
2,553
3.8125
4
"""Resizes all images from a source_dir to a target_dir. This program reads all images from a folder, --source_dir, resize them based on the --img_width and --img_height arguments, and save them to --target_dir. The --source_dir argument sets the folder where the images to be resized are located. The --target_dir argument sets the folder where the resized images will be saved. The --img_width argument sets the new image width. The --img_height argument sets the new image height. If source_dir is the same as target_dir the original photos will be overwritten by the resized ones. """ import argparse import os from os.path import basename import glob import scipy.misc FLAGS = None def resize_images(src_dir, des_dir, img_w, img_h): '''Reads all images from src_dir, resizes them based on img_w and img_h and saves them to des_dir''' # read each jpg file in src_dir for filename in glob.glob(os.path.join(src_dir, '*.jpg')): # gets the file base name photo = basename(filename) print 'Resizing ' + filename + ' to ' + os.path.join(des_dir, photo) # reads the iamge data array_image = scipy.misc.imread(filename) # resize the image array_resized_image = scipy.misc.imresize(array_image, (img_h, img_w), interp='nearest', mode=None) # saves the resized image to the des_dir with the same base name scipy.misc.imsave(os.path.join(des_dir, photo), array_resized_image) def main(): '''Main function''' src_dir = FLAGS.source_dir des_dir = FLAGS.target_dir img_w = FLAGS.img_width img_h = FLAGS.img_height resize_images(src_dir, des_dir, img_w, img_h) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( '--source_dir', type=str, required=True, default='./', help="""\ The source directory with images to be resized\ """ ) parser.add_argument( '--target_dir', type=str, required=True, default='./', help="""\ The target directory where images will be saved to\ """ ) parser.add_argument( '--img_width', type=int, required=False, default=28, help="""\ The new image width\ """ ) parser.add_argument( '--img_height', type=int, required=False, default=28, help="""\ The new image height\ """ ) FLAGS, _ = parser.parse_known_args() main()
26dc089d77ad91233b9a0d57df9cd2c47ba4f413
mohansn/dsa_assignment
/1_fib.py
257
3.875
4
#!/usr/bin/python def fib(n): """ Returns the the first 'n' Fibonacci numbers """ fibs=[] for i in range(n): if (i == 0 or i == 1): fibs.append(i) else: fibs.append(fibs[i-1]+fibs[i-2]); return fibs
9bab6ff99aa72e668524b63523c2106181049f6f
IamBiasky/pythonProject1
/SelfPractice/function_exponent.py
316
4.34375
4
# Write a function called exponent(base, exp) # that returns an int value of base raises to the power of exp def exponent(base, exp): exp_int = base ** exp return exp_int base = int(input("Please enter a base integer: ")) exp = int(input("Please enter an exponent integer: ")) print(exponent(base, exp))
ed1d712104934ccec97205a06a3daede7352dc29
IamBiasky/pythonProject1
/SelfPractice/phoneBook.py
402
4
4
def user_phonebook(user_name=None, user_age=None, user_no=None): for counter in range(3): user_name = input(str("Please enter your Name: ")) user_age = int(input("Please enter your Age: ")) user_no = int(input("Please enter your Phone Number: ")) contact = {"Name": user_name, "Age": user_age, "Phone Number": user_no} counter += 1 return contact
7b113d95aa328c3fbe74be66f35c03508947d1b9
IamBiasky/pythonProject1
/ChapterThree/Arithmetic_Smallest_Largest_Remake.py
543
4.0625
4
number1 = int(input("Enter first integer: ")) number2 = int(input("Enter second integer: ")) number3 = int(input("Enter third integer: ")) number4 = int(input("Enter fourth integer: ")) smallest_int = min(number1, number2, number3, number4) largest_int = max(number1, number2, number3, number4) sum_int = smallest_int + largest_int product_int = smallest_int * largest_int average_int = (number1 + number2 + number3 + number4) / 4 print("The sum is: ", sum_int) print("The product is: ", product_int) print("The average is: ", average_int)
04fb4ac9117370c5fffe9abbe435fdc1c165e0b0
BSBandme/Decaf-Compiler
/hw1/Number2.py
5,515
3.578125
4
#program submit import sys import string #mode = "test" # test mode input from file mode = "submit" # submit mode keyboard input commands = "" vari = [] value = [] result = "" def labelCheck(label,colon = False): #check label name validness #label the string to check; colon if the label end with colon if colon == True and label[len(label)-1] != ':': return False else: label = label[:len(label)-1] if len(label)==0: if label in string.lowercase: return True else: return False elif label[0] in string.lowercase: for digit in label[1:]: if not (digit.isdigit() or digit in string.lowercase or digit == '_'): return False else: return False return True def inputProcess(): #load the commands and check it's validity global commands global vari tempCommands = [] #load commands if mode == "test": f = open("input1.txt") tempCommands = f.readlines() f.close() else: for line in sys.stdin: tempCommands.append(line) for i in range(0,len(tempCommands),1): if ((tempCommands[i].find('~ ')!=-1)or(tempCommands[i].find('~\n')!=-1)or(tempCommands[i].find('~\t')!=-1)): print('Error: illegal use of ~') exit() #process of comment and combine lines if (tempCommands[i].find(';') != -1 ): tempCommands[i] = tempCommands[i].replace(';',' ; ') semcolonFlag = True else: semcolonFlag = False if (tempCommands[i].find('~') != -1 ): tempCommands[i] = tempCommands[i].replace('~',' ~ ') commands += tempCommands[i] if semcolonFlag == False: print("Error: command not ended with ;") exit() #split base on ' ' commands = commands.split() i = 0 opeNum = 0 numNum = 0 newline = 0 result = 0 startIndex = 0 variNum = 0 while i < len(commands): # syntax check # since all operator has 2 input: #operater = #num + 1 if newline == 0: if not labelCheck(commands[i]): print "Error: Variable name check fail" exit() else: if commands[i] not in vari: vari.append(commands[i]) result = len(vari)-1 value.append("empty") newline += 1 elif newline == 1: if not commands[i] == '=': print("Error: = not found") exit() else: newline = -1 #close the new line process elif commands[i] == ';': if opeNum +1 == numNum: newline = 0 # restart new line process opeNum = 0 numNum = 0 value[result] = "initalized" opeNum = 0 numNum = 0 else: print("Error: operator number and operand number not match") #fix exit() elif commands [i] == '~': if commands [i+1].isdigit(): commands [i+1] = '-' + commands [i+1] numNum += 1 i += 1 else: print("Error: no number after \'~\'") exit() elif commands [i].isdigit(): numNum += 1 elif commands[i] in ['+','-','*','/','%']: opeNum += 1 elif commands[i] in vari: if value[vari.index(commands[i])] == "initalized": numNum += 1 else: print("Error: variable defined but not initalized") exit() else: print(commands[i],commands[i+1]) print("Error: syntax wrong or use variable without initialize") exit() i += 1 for i in range(0, len(commands), 1): if(commands[i] == '~') : commands.remove("~") break #print("syntax check success") def myCompile(): global result,commands lineStart = 0; lineEnd = 0; while lineStart < len(commands): # compile lineEnd = commands.index(";",lineStart) result += "ildc "+str(vari.index(commands[lineStart])) + '\n' # x = linestart = syntaxCheck(lineStart+2) if(linestart != lineEnd): print("Error: Syntax error!") exit() result += "store\n" lineStart = lineEnd + 1 def syntaxCheck(i) : if (i<0): return i global vari,valuen,result op = "" if(commands[i].isdigit() or (len(commands) > 1 and commands[i][0] == '-' and commands[i][1:].isdigit())) : result += "ildc " result += str(int(string.atof(commands[i])))+'\n' return i + 1 elif commands[i] in vari: result += "ildc " + str(vari.index(commands[i]))+'\n' result += "load" + '\n' return i+1 elif commands[i] in ['+','-','*','/','%']: if commands[i] == '+': op = "iadd" if commands[i] == '-': op = "isub" if commands[i] == '*': op = "imul" if commands[i] == '/': op = "idiv" if commands[i] == '%': op = "imod" i = syntaxCheck(i+1) i = syntaxCheck(i) result += op + '\n' return i else: return -1 def output(): global result print(result) inputProcess() myCompile() output()
4cbd2d5b040711aaa6bf3c0e599d04682d177cdc
Radmaster5000/shadowrun
/shadowrun.py
7,180
3.53125
4
import time from missionText import missionText import random def roll(modifier): result = random.randint(1,6) + modifier print(result) return result # Creating the Intro screen def intro(key): # repeats until player presses 1, 2, or 3 while (key != 1 or key != 2 or key != 3): print(""" #### # # #### ### #### # # #### # # # # # # # # # # # # # # # # # # # ## # #### #### #### # # # # # # # #### # # # # # # # # # # # # # # # # # # # # # # # ## #### # # # # ### #### ### ### # # #### # # Welcome to Shadowrun! Take the role of a Decker and choose your run! ************************************************ SELECT AN OPTION: 1 - Start game 2 - How to play 3 - Quit ************************************************ """) try: key = int(input('>>> ')) if (key == 1): return 1 elif (key == 2): rules() elif (key == 3): quit() else: print('ooops! Try again!') except ValueError: print('Type a number, stupid!') # selection 2 from the introduction screen def rules(): print(""" ***************************************** RULES AND STUFF ***************************************** """) print("TODO: write the rules") print() choice = input(" When you're ready, type 'back' to continue...") if (choice == 'back'): return else: print() print() print("That's not the word 'back', is it?...") print() print() time.sleep(1) rules() def mission_choice(): print(""" ***************************************** CHOOSE YOUR MISSION ***************************************** *** FLAVOUR TEXT ABOUT MISSION CHOICE *** SELECT AN OPTION 1 - Find data 2 - Disable security """) mission = 0 while (mission != 1 or mission != 2): try: mission = int(input('>>> ')) if (mission == 1): return 'data' elif (mission == 2): return 'security' else: print('ooops! Try again!') except ValueError: print('Type a number, stupid!') def sneak_inside(mission): print(""" ***************************************** GET INSIDE ***************************************** """ + missionText["sneak_inside_" + mission]) print(""" SELECT AN OPTION 1 - Sneak past guard 2 - Take down guard """) choice = 0 while (choice != 1 or choice != 2): try: choice = int(input('>>> ')) if (choice == 1 or choice == 2): if (choice == 2): attackGuard = True test = roll(modifier) if (test > 3): print('You lay the smacketh down on the guard and bag yourself a keycard. Well done.') return attackGuard, choice else: print('The guard draws his gun and shoots you.') quit() else: attackGuard = False test = roll(modifier) if (test > 3): print('You sneak past the loser stood outside. Well done.') return attackGuard, choice else: print("Oh sh*t, you've been spotted.") attackGuard = True test = roll(modifier) if (test > 3): print('You lay the smacketh down on the guard and bag yourself a keycard. Well done.') return attackGuard, choice else: print('The guard draws his gun and shoots you.') quit() else: print('ooops! Try again!') except ValueError: print('Type a number, stupid!') def initial_log_in(mission, attackGuard): print(""" ***************************************** COMPROMISE SYSTEM ***************************************** """ + missionText["initial_log_in_" + mission]) print(""" SELECT AN OPTION 1 - Brute force password 2 - Use professional crypto program 3 - Use custom program""") #if (choice == 2): if (attackGuard == True): print(" 4 - Use guard's details (HIDDEN)") hack1 = 0 while (hack1 != 1 or hack1 != 2 or hack1 != 3): try: hack1 = int(input('>>> ')) if (hack1 == 1 or hack1 == 2 or hack1 == 3 or hack1 == 4): return hack1 else: print('ooops! Try again!') except ValueError: print('Type a number, stupid!') def searching(mission): print(""" ***************************************** INTEROGATE SYSTEM ***************************************** *** FLAVOUR TEXT ABOUT SEARCHING *** METHODS, CHANCES, AND PENALTIES 1 - Quick search (33% success rate) 1 strike penalty 2 - Moderate search (50% success rate) 2 strike penalty 3 - Full search (75% success rate) 3 strike penalty""") hack2 = 0 while (hack2 != 1 or hack2 != 2 or hack2 != 3): try: hack2 = int(input('>>> ')) if (hack2 == 1 or hack2 == 2 or hack2 == 3): return hack2 else: print('ooops! Try again!') except ValueError: print('Type a number, stupid!') def task(mission): print(""" ***************************************** TASK ***************************************** *** FLAVOUR TEXT ABOUT TASK *** THIS WILL DEPEND ON TASK, SO FOR NOW: 1 - Option 1 2 - Option 2""") hack3 = 0 while (hack3 != 1 or hack3 != 2): try: hack3 = int(input('>>> ')) if (hack3 == 1 or hack3 == 2): return hack3 else: print('ooops! Try again!') except ValueError: print('Type a number, stupid!') def log_out(mission): print(""" ***************************************** QUIT OUT OF SYSTEM ***************************************** *** FLAVOUR TEXT ABOUT LOGGING OUT *** METHODS, CHANCES, AND PENALTIES 1 - Rip and Tear (33% success rate) 2 strike penalty 2 - Calculated shutdown (50% success rate) 1 strike penalty 3 - Light the torch (50% success rate) 3 strike penalty for fail All strikes cleared for success""") hack4 = 0 while (hack4 != 1 or hack4 != 2 or hack4 != 3): try: hack4 = int(input('>>> ')) if (hack4 == 1 or hack4 == 2 or hack4 == 3): return hack4 else: print('ooops! Try again!') except ValueError: print('Type a number, stupid!') def escape(mission): print(""" ***************************************** GET OUT OF DODGE ***************************************** *** FLAVOUR TEXT ABOUT LEAVING *** METHODS, CHANCES, AND PENALTIES 1 - Fake it (33% success rate) 2 strike penalty 2 - Stealth (50% success rate) 1 strike penalty 3 - Guns blazing (50% success rate) 3 strike penalty for fail BONUS PAYMENT FROM EMPLOYER""") hack5 = 0 while (hack5 != 1 or hack5 != 2 or hack5 != 3): try: hack5 = int(input('>>> ')) if (hack5 == 1 or hack5 == 2 or hack5 == 3): return hack5 else: print('ooops! Try again!') except ValueError: print('Type a number, stupid!') modifier = 0 attackGuard = False option = intro(0) mission = mission_choice() attackGuard, choice = sneak_inside(mission) log_in = initial_log_in(mission, attackGuard) search = searching(mission) task_res = task(mission) leave = log_out(mission) run = escape(mission) print("Intro option = " + str(option)) print("Sneak Inside option = " + str(choice)) print("Initial log in option = " + str(log_in)) print("Search option = " + str(search)) print("Task option = " + str(task_res)) print("Log out option = " + str(leave)) print("Escape option = " + str(run))
9f0c9a33209211c9f37bf474cdc2762f60dbf9d6
soumya62/GitCommands
/Vowel.py
166
4.1875
4
VOWELS=("a","e","i","o","u") msg=input("Enter ur msg:") new_msg="" for letter in msg: if letter not in VOWELS: new_msg+=letter print(new_msg)
2d4cf0b46c47fad8a5cc20cdf98ebf9ab379a151
sooryaprakash31/ProgrammingBasics
/OOPS/Exception_Handling/exception_handling.py
1,347
4.125
4
''' Exception Handling: - This helps to avoid the program crash due to a segment of code in the program - Exception handling allows to manage the segments of program which may lead to errors in runtime and avoiding the program crash by handling the errors in runtime. try - represents a block of code that can throw an exception. except - represents a block of code that is executed when a particular exception is thrown. else - represents a block of code that is executed when there is no exception finally - represents a block of code that is always executed irrespective of exceptions raise - The raise statement allows the programmer to force a specific exception to occur. ''' dividend = float(input("Enter dividend ")) divisor = float(input("Enter divisor ")) #runs the code segment which may lead to error try: result = dividend/divisor #executed when there is an exception except ZeroDivisionError: print("Divisor is Zero") #executed when there is no exception else: print(format(result,'.2f')) #always executed finally: print("End of Program") ''' try: if divisor == 0: raise ZeroDivisionError() except ZeroDivisionError: print("Divisor is zero") else: result = dividend/divisor print(format(result, '.2f')) finally: print("End of Program") '''
8997e1b48a911acfdf53c74f7d1eb17fb294308d
sooryaprakash31/ProgrammingBasics
/Data-Structures/Linked_List/Circular/circular.py
4,266
4.3125
4
''' Circular Linked List: - A linear data structure in which the elements are not stored in contiguous memory locations. - The last node will point to the head or first node thus forming a circular list Representation: |--> data|next--> data|next--> data|next --| |------------------------------------------| Operations: 1. Append() 2. Prepend() 3. InsertAt() 4. DeleteAt() 5. PrintAll() ''' class Node: def __init__(self,data=None): self.data=data self.next=None class CircularLinkedList: def __init__(self): self.head = None #appends the node at the end of the list def append(self, node): if self.head is None: self.head=node node.next = self.head print("Appended!") else: temp=self.head #traversing to the end of the list while temp.next!=self.head: temp=temp.next temp.next = node node.next = self.head print("Appended!") #prepends the node at the beginning of the list def prepend(self, node): if self.head is None: self.head = node node.next = self.head else: ptr = self.head while ptr.next != self.head: ptr = ptr.next ptr.next = node node.next = self.head self.head=node print("Prepended!") #inserts node at a position def insertAt(self,node,pos): if self.head is None: print("Position does not exist") return else: if pos == 0: ptr = self.head while ptr.next!=self.head: ptr = ptr.next ptr.next = node node.next = self.head self.head = node else: ptr = self.head count=1 #traversing to the position while count<pos: ptr = ptr.next if ptr==self.head: print("Position does not exist") return count+=1 node.next = ptr.next ptr.next = node print("Inserted!") #deletes the node at a position def deleteAt(self,pos): if self.head is None: print("Position does not exist") return else: if pos == 0: ptr = self.head while ptr.next != self.head: ptr = ptr.next ptr.next = self.head.next self.head = self.head.next else: ptr = self.head count = 1 while count<pos: ptr = ptr.next if ptr==self.head: print("Position does not exist") return count+=1 temp = ptr.next if temp == self.head: ptr.next = self.head else: ptr.next = temp.next print("Deleted!") #prints all the nodes in the list def printAll(self): if self.head is None: print("Empty List") else: l=[] temp = self.head while True: l.append(temp.data) temp=temp.next if temp == self.head: break print(*l) c = CircularLinkedList() choice = 0 while True: print("1.Append\t2.Prepend\t3.InsertAt\t4.DeleteAt\t5.PrintAll\t6.Stop") choice = int(input("Enter choice: ")) node = Node() if choice==1: node.data = int(input("Enter data ")) c.append(node) elif choice == 2: node.data = int(input("Enter data ")) c.prepend(node) elif choice == 3: node.data = int(input("Enter data ")) positon = int(input("Enter position ")) c.insertAt(node,positon) elif choice == 4: positon = int(input("Enter position ")) c.deleteAt(positon) elif choice == 5: c.printAll() else: break
79dda99fe42354f17d03eb33a1aab1ee9ebe61ab
sooryaprakash31/ProgrammingBasics
/Algorithms/Sorting/Quick/quick.py
2,027
4.25
4
''' Quick Sort: - Picks a pivot element (can be the first/last/random element) from the array and places it in the sorted position such that the elements before the pivot are lesser and elements after pivot are greater. - Repeats this until all the elements are placed in the right position - Divide and conquer strategy Example: arr=[3,6,4,5,9] Takes pivot as arr[2] (i.e (first_index+last_index)/2) pivot is 4. After 1st partition arr=[3,4,6,5,9] i) The elements before pivot are lesser then pivot and the elements after pivot are greater than pivot - quick_sort method calls itself for left and right blocks having partition as the midpoint until all the elements are sorted. ''' def partition(arr, left,right,pivot): #left should always less than or equal to right #otherwise it will lead to out of bounds error while left<=right: #finds the first element that is greater than pivot #from the start while arr[left]<pivot: left=left+1 #finds the first element that is lesser than pivot #from the end while arr[right]>pivot: right=right-1 #swapping the elements at indices left and right if left<=right: arr[left],arr[right]=arr[right],arr[left] left=left+1 right=right-1 #returning the current index of the pivot element return left def quick_sort(arr,left,right): #checks if the block contains atleast two elements if left<right: #Middle element is chosen as the pivot pivot=arr[(left+right)//2] #gives the sorted pivot index p = partition(arr,left,right,pivot) #calls quick_sort for elements left to the partition quick_sort(arr,left,p-1) #calls quick_sort for elements right to the partition quick_sort(arr,p,right) arr=list(map(int,input("Enter array ").split())) print("Before sort:",*arr) #calling sort function quick_sort(arr,0,len(arr)-1) print("Sorted array:",*arr)
98648e9554675226787aeb68463d480b46827e7b
sooryaprakash31/ProgrammingBasics
/Algorithms/Searching/Linear/linear.py
389
3.734375
4
''' Linear Search: - Compares every element with the key and returns the index if the check is successful - Simplest searchin algorithm ''' arr=list(map(int,input("Enter array ").split())) key = int(input("Enter key ")) for i in range(len(arr)): if arr[i] == key: print("Found at {} position".format(i+1)) break if i == len(arr)-1: print("Not Found")
2d6f7f9ab17c96341ab645c3716579de46cc6d73
valdirsjr/learning.data
/python/jogo_nim.py
2,468
3.9375
4
def computador_escolhe_jogada(n,m): y = 0 i = 1 if n <= m: y = n else: while i <= m: if (n - i) % (m + 1) == 0: y = i i = i + 1 if y == 0: y = m if y == 1: print("O computador tirou uma peça.") else: print(f"O computador tirou {y} peças.") return y def usuario_escolhe_jogada(n,m): y = m+1 while y > m: jogada = int(input("Quantas peças você vai tirar? ")) if (jogada > m) or (jogada < 1) or (jogada > n): print("Oops! Jogada inválida! Tente de novo.") else: y = m if jogada == 1: print("Você tirou uma peça.") else: print(f"Você tirou {jogada} peças.") return jogada def partida(): jogo = int(input(""" Bem-vindo ao jogo do NIM! Escolha: 1 - para jogar uma partida isolada 2 - para jogar um campeonato """)) if jogo == 1: campeonato = 1 else: campeonato = 3 print("Voce escolheu um campeonato!") rodada = 1 score_pessoa = 0 score_computador = 0 while rodada <= campeonato: if campeonato > 1: print(f"**** Rodada {rodada} ****") n = int(input("Quantas peças? ")) m = int(input("Limite de peças por jogada? ")) if n % (m + 1) == 0: print("Você começa!") player = 1 else: print("Computador começa!") player = 0 while n > 0: if player == 1: n = n - usuario_escolhe_jogada(n,m) player = 0 else: n = n - computador_escolhe_jogada(n,m) player = 1 if n > 1: print(f"Agora restam {n} peças no tabuleiro") elif n == 1: print(f"Agora resta apenas {n} peça no tabuleiro") else: if player == 1: print("Fim do jogo! O computador ganhou!") score_computador = score_computador + 1 else: print("Fim do jogo! Você ganhou!") score_pessoa = score_pessoa + 1 rodada = rodada + 1 if campeonato > 1: print("**** Final do campeonato! ****") print(f"Placar: Você {score_pessoa} X {score_computador} Computador") partida()
3188506e24c4ef4122a8c1dd30601950757f3c9c
sebastian-mutz/integrate
/course/source/exercises/E201/bme280_ssd1306_control_script.py
5,341
3.515625
4
""" author: daniel boateng ([email protected]) This script basically controls the measurement from BME280 sensor, store in an excel sheet (with defined columns for date, time, temperature, humidity and pressure. Not that other parmaters like dewpoint temperature can be calculated from these parameters) and also displays the date and time on attached oled screen for each measurement. """ # The first part of the script is to import all the modules we installed at the previous section required for the devices. In python, # "import" is used to call a package in current script. #importing modules import smbus2 import bme280 import time import datetime from datetime import date from openpyxl import load_workbook import board import busio import digitalio import adafruit_ssd1306 from PIL import Image, ImageDraw, ImageFont # We will set the bme280 object in order use its functions for measurement # define I2C port (normally, I2C has 2 ports (i.e., I2C0, I2C1)). So if you use "i2cdetect -y 1" to check # address of your device, then the devices are on port 1. Likewise "i2cdetect -y 0" if they are connected to port 0 port = 1 # define the address of sensor (as explained from the previous section using "i2cdetect") address = 0x76 # define SMbus instance for controlling the board bus = smbus2.SMBus(port) # Now we will calibrate the sensor using the load_calibrations function, which is attribute of bme280 module # by using the bus and address as input parameters calibration_params = bme280.load_calibration_params(bus, address) # define data class to calculate the readings from the sensor (with the calibrated params) data = bme280.sample(bus, address, calibration_params) # Now each variable can be obtained from the "data class" by calling variable method. But we will take the # firt readings and ignore it since it might not be correct. Then after 1 seconds (this can be increased) # the correct readings can be recored on a specific interval. temperature = data.temperature pressure = data.pressure humidity = data.humidity time.sleep(1) # time interval to wait after the first reading # setting OLED screen # define reset pins by using digit input and output (the board can be any number eg. D5, D6..) oled_reset = digitalio.DigitalInOut(board.D4) # define the right size of your display. Please change it depending on your display size (eg. 128x32) WIDTH = 128 HEIGHT = 64 BORDER = 5 # define I2C i2c = board.I2C() # define the oled display class (using the address and defined paramters) oled = adafruit_ssd1306.SSD1306_I2C(WIDTH, HEIGHT, i2c, addr=0x3c, reset=oled_reset) # Now lets clear the display first oled.fill(0) oled.show() # customizing the screen specifications (we are using default here) width = oled.width height = oled.height # now create blank image to draw your text on it. Not that "1" is for 1-bit color image = Image.new("1", (width, height)) #define object for drawing on the image draw =ImageDraw.Draw(image) # define a black backgroud to draw the image on (note you can use 225 for fill and outline # for white background) draw.rectangle((0,0, width, height), outline=0, fill=0) # define the positon of the text padding=-2 top=padding bottom=height-padding x=0 #define font type (we used default here, you can google it for other styles) font = ImageFont.load_default() #saving data # Now we will load the excel file created on Desktop into memory by using the load_workbook from openpyxl wb = load_workbook("/home/pi/Desktop/Reading_from_bme280.xlsx") sheet = wb["Sheet1"] # Now we will write a loop to continue the measurement until we stop by pressing Ctrl + C print("Please to end the readings from the sensor, kindly press Ctrl + C") # print it for new users to know # So this loop will run until you interupt it (But you can also define it to stop after certain time) try: while True: draw.rectangle((0,0, width, height), outline=0, fill=0) # taking readings from the data class and rounding it once decimal place temperature = round(data.temperature,1) pressure = round(data.pressure,1) humidity = round(data.humidity,1) # check date for measuring today = date.today() # time of measurement now = datetime.datetime.now().time() print("Adding data to the spreadsheet") print(today) print(now) print("{}°C {}hPa {}%".format(temperature, pressure, humidity)) # define the data to be stored in the excel fine on each row (so define the excel as similar !!) row = (today, now, temperature, pressure, humidity) sheet.append(row) wb.save("/home/pi/Desktop/Reading_from_bme280.xlsx") # saving after each measurement # drawing text on the screen with their positions draw.text((x,top+0), str(today), font=font, fill=255) draw.text((x, top+20), str(now), font=font, fill=255) draw.text((x, top+40), "{}°C {}hPa {}%".format(temperature, pressure, humidity), font=font, fill=255) oled.image(image) oled.show() # define waiting time after each measurement (eg. 60 seconds) time.sleep(60) # now make sure it saves everyting after stoping the reading ! finally: wb.save("/home/pi/Desktop/Reading_from_bme280.xlsx") print("Goodbye!")
fb60a0538163955276551a694a4ae667f60023ea
melissabuist/PythonPrograms
/Python/Lab 4/lab4.py
2,944
3.890625
4
#********************************************************************** # Lab 4: <Files> # # Description: # <This program open a file and outputs data based on the file> # # # Author: <Melissa Buist, [email protected]> # Date: <October 26, 2018> # # Input: <a data file> # Output: <average opening, average closing, max and min of opening> # # I pledge that I have completed the programming assignment independently # I have not copied the code from a student or any source. # I have not given my code to any student. # # Sign here: <Melissa Buist> #*********************************************************************/ import sys def lab4 (): #asks the user for the output file name outfileName = input("What file should the info go into? ") #declares infile as name of file infile = "AAPL.csv" #opens infile and outfile for reading and writing infile = open(infile, 'r') outfile = open(outfileName, 'w') #reads the first line line = infile.readline() #declares variables for the while loop maxopening = 0 minopening = sys.maxsize count = 0 openaverage = 0 closingaverage = 0 #runs through all lines of data for lines in infile: #reads the first if count == 0 : #reads the first line infile.readline() #reads the line of data lines = infile.readline() #splits line into a list lines = lines.split (",") #accesses opening opening = lines[1] #declares minopening #minopening = lines[1] #adds up average opening openaverage = openaverage + float(opening) #determines what opening is the smallest if float(opening) < float(minopening) : minopening = float(opening) #determines what opening is the biggest if float(opening) > maxopening : maxopening = float(opening) #accesses the closing number closing = lines[4] #adds up average closing closingaverage = closingaverage + float(closing) #increments count count = count + 1 #calculates the opening average openaverage = openaverage/count #calculates the closing average closingaverage = closingaverage/count #prints data to the output file print ("The average opening price is " + str(openaverage), file=outfile) print ("The average closing price is " + str(closingaverage), file=outfile) print ("The maximun opening price is " + str(maxopening), file=outfile) print ("The minimum opening price is " + str(minopening), file=outfile) #closes both files infile.close() outfile.close() #tells user where the data has been put print("The data has been written to ", outfileName) lab4 ()
a6a8d6d43bd5de7b51c8bd3b0018d6c53a1652a6
BekzhanKassenov/olymp
/informatics.mccme.ru/Python/Chapter 3/C/C.py
90
3.609375
4
n = int(input()) if (n > 0): print(1) elif (n < 0): print(-1) else: print(0)
cb047338515789dcab16172208ccf171a1239f6b
GrisWoldDiablo/Data-Structure-and-Algorithm
/Python/Tree/Tree/TheTree.py
12,327
3.78125
4
""" Author: Alexandre Lepage Date: February 2020 """ from abc import ABC, abstractmethod #region TheNode class TheNode(ABC): """ Custom abstract Tree Node class """ def __init__(self,k): """ Constructor of the Class Initialize left, right and parent node as None Initialize key as received -----PSEUDO CODE----- (k is the value of the node) Node(k) left = NIL right = NIL parent = NIL key = k -----PSEUDO CODE----- Keyword argument: k: the value of the node """ self.left = None # Node on the left of this one self.right = None # Node on the right of this one self.parent = None # Node above/parent of this node self.key = k # Key value this node is holding def predecessor(self): """ Get the predecessing node of the current node -----PSEUDO CODE----- (x is the current node) Predecessor(x) if x.left =/= NIL return TreeMaximum(x) y = x.parent while y =/= NIL and x == y.left x = y y = y.parent return y -----PSEUDO CODE----- Return: TheNode: found node or None """ if self.left is not None: return TheTree.maximum_node(self.left) y = self.parent while y is not None and self is y.left: self = y y = y.parent return y def successor(self): """ Get the successing node of the current node -----PSEUDO CODE----- (x is the current node) Successor(x) if x.right =/= NIL return TreeMinimum(x) y = x.parent while y =/= NIL and x == y.right x = y y = y.parent return y -----PSEUDO CODE----- Return: TheNode: found node or None """ if self.right is not None: return TheTree.minimum_node(self.right) y = self.parent while y is not None and self is y.right: self = y y = y.parent return y def __str__(self): """ Implementing class string representation Return: str: formated represetation of the object variables """ pk = "NIL" lk = "NIL" rk = "NIL" if self.parent is not None: pk = self.parent.key if self.left is not None: lk = self.left.key if self.right is not None: rk = self.right.key return 'Node:(' + str(self.key) + ', Parent=' + str(pk) + ', Left=' + str(lk) + ', Right=' + str(rk) + ')' def height(self): return self._height(self) def _height(self, x): """ get the height of the node -----PSEUDO CODE----- (x is the node) Height(x) if x == NIL return -1 l = Height(x.left) + 1 r = Height(x.right) + 1 if l > r return l else return r -----PSEUDO CODE----- Keyword argument: x:var: the node to get height of Return: int: the height of the node """ if x is None: return -1 leftHeight = self._height(x.left) + 1 rightHeight = self._height(x.right) + 1 if leftHeight > rightHeight: return leftHeight else: return rightHeight #endregion TheNode class #region TheTree class TheTree(ABC): """ Custom abstract Tree class """ def __init__(self): """ Constructor of the Class Initialize left, right and parent node as None Initialize key as received -----PSEUDO CODE----- Tree() root = NIL -----PSEUDO CODE----- """ self.root = None # The node at the root of the tree @abstractmethod def insert_value(self, k): pass @abstractmethod def insert_node(self, z:TheNode): pass @abstractmethod def delete_value(self, k): pass @abstractmethod def delete_node(self, z:TheNode): pass def search_value(self, k): """ Find a node with a specific value -----PSEUDO CODE----- (T is the Tree, k is the value to look for) Search(T,k) return Search(T.root,k) -----PSEUDO CODE----- Keyword argument: k:var: the value to search for Return: TheNode: found node or None """ return self._search(k) def search_node(self, x:TheNode): """ Find a node -----PSEUDO CODE----- (T is the Tree, x is the node to look for) Search(T,x) return Search(T.root,x.key) -----PSEUDO CODE----- Keyword argument: x:TheNode: the node to search for Return: TheNode: found node or None """ if isinstance(x, TheNode) is False: raise TypeError("Wrong type provided") return self._search(x.key) def _search(self, k): """ Find a node with a specific value -----PSEUDO CODE----- (T is the Tree, k is the value to look for) Search(T,k) return Search(T.root,k) -----PSEUDO CODE----- Keyword argument: k:var: the value to search for Return: TheNode: found node or None """ # Here I have made 2 searching methods, # one that uses recursive and the other iterative approach # return self._search_recursive(self.root, k) return self._search_iterative(self.root, k) def _search_recursive(self, x:TheNode, k): """ Find a node with a specific value, using the recursive approach. -----PSEUDO CODE----- (x is the starting point (root) of the search) (k is the value to look for) Search(x,k) if x == NIL or k == x.key return x if k < x.key return Search(x.left,k) else return Search(x.right,k) -----PSEUDO CODE----- Keyword argument: x:TheNode: the starting point (root) of the search k:var: is the value to look for Return: TheNode: found node or None """ if x is None or k == x.key: return x if k < x.key: return self._search_recursive(x.left, k) else: return self._search_recursive(x.right, k) def _search_iterative(self, x:TheNode, k): """ Find a node with a specific value, using the iterative approach. -----PSEUDO CODE----- (x is the starting point (root) of the search) (k is the value to look for) Search(x,k) while x =/= NIL and k =/= x.key if k < x.key x = x.left else x = x.right return x -----PSEUDO CODE----- Keyword argument: x:TheNode: the starting point (root) of the search k:var: is the value to look for Return: TheNode: found node or None """ while x is not None and k != x.key: if k < x.key: x = x.left else: x = x.right return x def minimum(self): """ Find the minimum node in the tree -----PSEUDO CODE----- (T is the Tree) Minimum(T) return Minimum(T.root) -----PSEUDO CODE----- Return: TheNode: minimum node of the tree """ return self.minimum_node(self.root) @staticmethod def minimum_node(x:TheNode): """ Find the minimum node starting from this root -----PSEUDO CODE----- (x is the starting root) Minimum(x) while x.left =/= NIL x = x.left return x -----PSEUDO CODE----- Keyword argument: x: the root to start to Return: TheNode: minimum node of this root """ if isinstance(x, TheNode) is False: raise TypeError("Wrong type provided") while x.left is not None: x = x.left return x def maximum(self): """ Find the maximum node in the tree -----PSEUDO CODE----- (T is the Tree) Maximum(T) return Maximum(T.root) -----PSEUDO CODE----- Return: TheNode: maximum node of the tree """ return self.maximum_node(self.root) @staticmethod def maximum_node(x:TheNode): """ Find the maximum node starting from this root -----PSEUDO CODE----- (x is the starting root) Maximum(x) while x.right =/= NIL x = x.right return x -----PSEUDO CODE----- Keyword argument: x: the root to start to Return: TheNode: maximum node of this root """ if isinstance(x, TheNode) is False: raise TypeError("Wrong type provided") while x.right is not None: x = x.right return x @staticmethod def predecessor(x:TheNode): """ Get the predecessor node of the current node -----PSEUDO CODE----- (x is the current node) Predecessor(x) if x.left =/= NIL return Maximum(x.left) y = x.parent while y =/= NIL and x == y.left x = y y = y.parent return y -----PSEUDO CODE----- Keyword argument: x:TheNode: the current node to look for its predecessor Return: TheNode: found node or None """ if isinstance(x, TheNode) is False: raise TypeError("Wrong type provided") if x.left is not None: return TheTree.maximum_node(x.left) y = x.parent while y is not None and x == y.left: x = y y = y.parent return y @staticmethod def successor(x:TheNode): """ Get the successor node of the current node -----PSEUDO CODE----- (x is the current node) Successor(x) if x.right =/= NIL return Minimum(x.right) y = x.parent while y =/= NIL and x == y.right x = y y = y.parent return y -----PSEUDO CODE----- Keyword argument: x:TheNode: the current node to look for its successor Return: TheNode: found node or None """ if isinstance(x,TheNode) is False: raise TypeError("Wrong type provided") if x.right is not None: return TheTree.minimum_node(x.right) y = x.parent while y is not None and x == y.right: x = y y = y.parent return y def inorder_walk_tree(self): """ Walks through all the nodes in a tree in order and print their keys -----PSEUDO CODE----- (T is the tree) InorderWalkTree(T) InorderWalk(T.root) -----PSEUDO CODE----- """ self._inorder_walk(self.root) def _inorder_walk(self, x:TheNode): """ Walks through all the nodes on the tree, starting at a speficic node in order and print their keys -----PSEUDO CODE----- (x is the root of the tree) InorderWalk(x) if x =/= NIL InorderWalk(x.left) Print x.key InorderWalk(x.right) -----PSEUDO CODE----- Keyword argument: x:TheNode: the root of the tree """ if x is not None: self._inorder_walk(x.left) print(x) self._inorder_walk(x.right) def height(self): """ get the height of the tree -----PSEUDO CODE----- (T is the tree) Height(T) -----PSEUDO CODE----- Return: int: the height of the tree """ return self.root.height() #endregion TheTree class
8c37b00a3c1d1ef62f15d3849165df8dec44a430
abhishekanand10/dataStructurePy3
/mislPy/mergeSort.py
878
3.796875
4
def mergesort(a): if len(a) == 1: return else: # tmp = [] mid = len(a) // 2 ll = a[:mid] rr = a[mid:] mergesort(ll) mergesort(rr) merge(a, ll, rr) return a def merge(a, leftlist, rightlist): ln = len(leftlist) rn = len(rightlist) x = y = z = 0 while x < ln and y < rn: if leftlist[x] <= rightlist[y]: a[z] = leftlist[x] x += 1 else: a[z] = rightlist[y] y += 1 z += 1 if x < len(leftlist): for i in range(x, ln): a[z] = leftlist[x] z += 1 x += 1 elif y < len(rightlist): for i in range(y, rn): a[z] = rightlist[y] z += 1 y += 1 if __name__ == '__main__': lst = [7, 5, 1, 3, 2] print(mergesort(lst))
372ecd89fd5286c2106a7d4bff590768b29121e1
bhaveshpandey29/python_3
/bill_generation.py
937
3.8125
4
while True: count_per = int(input("Please enter the number of persons : ")) total_val = [] for i in range(1,count_per +1): print("\nEnter the details of the person",i,"below:") person_starter = int(input("\nPlease enter the value of breakfast : ")) person_meal = int(input("Please enter the value of meal : ")) person_desert = int(input("Please enter the value for desert : ")) value = (person_desert+person_meal+person_starter) total_val.insert(i,value) print("\nBill for person",i,"is:",value) coupon = str(input("\nGot any coupon?")) total = sum(total_val) if("FIFTY" in coupon): print("Congratulations for 50% OFF!!!\nNow your total Bill is = ",total-(total*.50)) elif("FOURTY" in coupon): print("Congratulations for 40% OFF!!!\nNow your total Bill is = ",total-(total*.40)) else: print("\n\nTotal Bill is = ",total)
155926fcbca6ae4641a76ef9498b91604f176db9
deepaksharmak92/Assignment---Tic-Tac-Toe
/TCGame_Env1.py
4,694
3.734375
4
from gym import spaces import numpy as np import random from itertools import groupby from itertools import product class TicTacToe(): def __init__(self): """initialise the board""" # initialise state as an array self.state = [np.nan for _ in range(9)] # initialises the board position, can initialise to an array or matrix # all possible numbers self.all_possible_numbers = [i for i in range(1, len(self.state) + 1)] # , can initialise to an array or matrix self.reset() def is_winning(self, curr_state): """Takes state as an input and returns whether any row, column or diagonal has winning sum Example: Input state- [1, 2, 3, 4, nan, nan, nan, nan, nan] Output = False""" win_pattern = [(0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)] i=curr_state.copy() if (i[0]+i[1]+i[2]==15) or (i[3]+i[4]+i[5]==15) or (i[6]+i[7]+i[8]==15) or (i[0]+i[3]+i[6]==15) or (i[1]+i[4]+i[7]==15) or (i[2]+i[5]+i[8]==15) or (i[0]+i[4]+i[8]==15) or (i[2]+i[4]+i[6]==15): output=True else: output=False return output def is_terminal(self, curr_state): # Terminal state could be winning state or when the board is filled up if self.is_winning(curr_state) == True: return True, 'Win' elif len(self.allowed_positions(curr_state)) ==0: return True, 'Tie' else: return False, 'Resume' def allowed_positions(self, curr_state): """Takes state as an input and returns all indexes that are blank""" return [i for i, val in enumerate(curr_state) if np.isnan(val)] def allowed_values(self, curr_state): """Takes the current state as input and returns all possible (unused) values that can be placed on the board""" used_values = [val for val in curr_state if not np.isnan(val)] agent_values = [val for val in self.all_possible_numbers if val not in used_values and val % 2 !=0] env_values = [val for val in self.all_possible_numbers if val not in used_values and val % 2 ==0] return (agent_values, env_values) def action_space(self, curr_state): """Takes the current state as input and returns all possible actions, i.e, all combinations of allowed positions and allowed values""" agent_actions = product(self.allowed_positions(curr_state), self.allowed_values(curr_state)[0]) env_actions = product(self.allowed_positions(curr_state), self.allowed_values(curr_state)[1]) return (agent_actions, env_actions) def state_transition(self, curr_state, curr_action): """Takes current state and action and returns the board position just after agent's move. Example: Input state- [1, 2, 3, 4, nan, nan, nan, nan, nan], action- [7, 9] or [position, value] Output = [1, 2, 3, 4, nan, nan, nan, 9, nan] """ obj= curr_state.copy() if (curr_action in self.action_space(curr_state)[0]) or (curr_action in self.action_space(curr_state)[1]): obj[curr_action[0]] = curr_action[1] return obj def step(self, curr_state, curr_action): """Takes current state and action and returns the next state, reward and whether the state is terminal. Hint: First, check the board position after agent's move, whether the game is won/loss/tied. Then incorporate environment's move and again check the board status. Example: Input state- [1, 2, 3, 4, nan, nan, nan, nan, nan], action- [7, 9] or [position, value] Output = ([1, 2, 3, 4, nan, nan, nan, 9, nan], -1, False)""" obj1= curr_state.copy() intermediate_state = self.state_transition(obj1, curr_action) if self.is_terminal(intermediate_state)[1] == 'Resume': e_curr_action = random.choice(list(self.action_space(intermediate_state)[1])) env_state = self.state_transition(intermediate_state, e_curr_action) if self.is_terminal(env_state)[1] == 'Resume': return (env_state, -1, False) elif self.is_terminal(env_state)[1] == 'Tie': return (env_state, 0, True) elif self.is_terminal(env_state)[1] == 'Win': return (env_state, -10, True) elif self.is_terminal(intermediate_state)[1] == 'Tie': return (intermediate_state, 0, True) elif self.is_terminal(intermediate_state)[1] == 'Win': return (intermediate_state, 10, True) def reset(self): return self.state
43e64a75f4f81b31ec821ea2c4d80abfc99eb39f
SSzymkowiak/CDV_PS
/pętle.py
1,021
3.71875
4
#while licznik = 0 while (licznik < 3): licznik = licznik + 1 print("CDV") print(licznik) ############################ licznik = 0 while (licznik < 3): licznik += 1 print(licznik, end="") else: print("Koniec pętli") ############################## ########## FOR lista = ["Jan","Anna","Paweł"] for i in lista: print(i) ############################## text = "Janusz" for i in text: print(i) ############################## slownik = dict() slownik['a'] = 1 slownik ['b'] = 2 for i in slownik: print("%s %d"%(i, slownik[i])) ################################## lista = ["Kebab","Hotdog","Falafel"] for index in range(len(lista)): print(lista[index]) x = range(6) print(x) for i in x: print(i, end=" ") print("\n\n") ################### #for i in range(5 for i in range(1, 5): for j in range(i): print(i,end=" ") print() ################### #użytkownik podaje z klawiatury rozmiar oraz znak jaki ma być wuświetlony print("Podaj rozmiar: ")
89f931044d2ea43a228a802a1ea214d5745c3d4c
Phantom-Eve/Python
/python/demo7/demo7_4.py
1,194
3.5
4
#!/usr/bin/evn python # -*_ coding: utf-8 -*- import functools # 装饰器Decorator print u"\n===================# 在代码运行期间动态增加功能的方式,称之为“装饰器” ===================" def log(text): def decorator(func): @functools.wraps(func) def wrapper(*args, **kw): print '%s %s():' % (text, func.__name__) return func(*args, **kw) return wrapper return decorator def nowBef(): print "2018-08-20" # 使用装饰器装饰函数 @log("excute") def now(): print "2018-08-20" print u"调用装饰器处理前的now函数:" nowBef() print u"调用装饰器处理后的now函数:" now() print u"\n===================# 在函数调用的前后打印出'begin call'和'end call'的日志 ===================" def logs(begin, end): def decorator(func): @functools.wraps(func) def wrapper(*args, **kw): print '%s %s()' % (begin, func.__name__) result = func(*args, **kw) print '%s %s()' % (end, func.__name__) return result return wrapper return decorator @logs("begin call", "end call") def test(): print u"测试前后日志" print u"在函数调用的前后打印日志:" test()
bda6af37cae4aba2f72394089a4353b4a8012d20
Phantom-Eve/Python
/python/demo7/demo7_1.py
2,035
3.75
4
#!/usr/bin/evn python # -*_ coding: utf-8 -*- # map/reduce接收两个参数:1.函数,2.序列 L = [1, 2, 3, 4, 5, 6, 7, 8, 9] print u"\n===================# map将传入的函数依次作用到序列的每个元素 ===================" print u"使用map把数字list转化为字符串:", map(str, L) print u"\n===================# reduce把一个函数作用在一个序列上 ===================" # 集合求和 def add(x, y): return x + y print u"使用reduce对list求和:", reduce(add, L) # 规范名字(首字母大写,其它字母小写) print u"\n利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字" names = ['adam', 'LISA', 'barT'] def format(s): return s.title() print u"输入:", names print u"输出:", map(format, names) print u"\n利用reduce()函数,接受一个list并求积" # 集合求积 prodList = [1, 2, 3, 4, 5] def prod(x, y): return x * y print u"集合:", prodList print u"list求积:", reduce(prod, prodList) print u"\n===================# filter把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素 ===================" def is_odd(n): return n%2 == 1 print u"删掉list中的偶数,只保留奇数:", filter(is_odd, L) # 删除1~100的素数 priList = range(1, 101) def is_prime(n): if n == 1: return True for i in range(2, n): if n % i == 0: return False return True print u"删除1~100的素数:", filter(is_prime, priList) print u"\n===================# sorted()函数可以对list进行排序 ===================" def desc_sort(x, y): if x > y: return -1 if x < y: return 1 print u"实现倒序排序:", sorted([36, 5, 12, 9, 21], desc_sort) # 忽略大小写对字母进行排序 def cmp_ignore_case(x, y): x = x.upper() y = y.upper() if (x > y): return 1 if (x < y): return -1 print u"忽略大小写来比较两个字符串:", sorted(['bob', 'about', 'Zoo', 'Credit'], cmp_ignore_case)
aef025a22d78acf9b7ec392e11c0b2cb2f0339f5
manjoong/python_study
/out/test/python_study/queue.py
944
3.59375
4
# num = int(input()) # command = [" " for _ in range(0, num)] # for i in range(0, num): # command[i] = input() num = 1 command = ["back"] arr = [] def push(x): arr.append(x) def pop(): if len(arr) == 0: print(-1) else: print(arr[0]) del arr[0] def size(): print(len(arr)) def empty(): if len(arr)>0: print(0) else: print(1) def front(): if len(arr) == 0: print(-1) else: print(arr[0]) def back(): if len(arr) == 0: print(-1) else: print(arr[len(arr)-1]) for i in range(0, num): if "push" in command[i]: push(int(command[i].split(" ")[1])) elif "pop" in command[i]: pop() elif "size" in command[i]: size() elif "empty" in command[i]: empty() elif "front" in command[i]: front() elif "back" in command[i]: back()
d7253e332951b7f394a63562ff08ee304dc79b82
manjoong/python_study
/programmers_find_sosu.py
1,165
3.625
4
import itertools def prime(n): if n == 1 or n ==0: return False else: if n == 2: return True else: for i in range(2, n//2+1): if n%i ==0: return False return True def solution(numbers): answer = 0 arr = [i for i in numbers] #문자열을 끊어서 각각의 배열로 # print(arr) combine = [] #각각의 배열을 조합한 조합으로 for i in range(len(arr)): combine.extend(itertools.permutations(arr, i+1)) # print(combine) int_combine = [] #조합형식을 다시 스트링으로 그리고 숫자로 for i in range(len(combine)): int_combine.append(int(''.join(combine[i]))) # print(int_combine) uni_combine = [] #중복을 지우기 위해 집합으로 집합을 다시 리스트로 uni_combine = list(set(int_combine)) # print(uni_combine) result_combine = list(map(prime, uni_combine)) #마지막으로 소수인지 함수 돌린다. # print(result_combine) answer = sum(result_combine) # print(answer) return answer
8d0231814f7b143b468ccda9ee71d62040a7a1f0
lwd19861127/Leetcode
/Leetcode/Linked List Cycle(141).{python3}/LinkedListCycle.py
691
3.921875
4
# Linked List Cycle # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def hasCycle(self, head: ListNode) -> bool: fast = slow = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: return True return False def main(): list = [1,2,3,4,5] head = ListNode(1) point = head for i in range(1, len(list)): point.next = ListNode(list[i]) point = point.next solution = Solution() solution.hasCycle(head) if __name__ == '__main__': main()
9f13a29c757c6cc2ef8f0d7dfe29b37ddec47df0
Dannikk/dfs_bfs_animation_-using-networkx-
/src/graph_reader.py
567
3.921875
4
import os DELIMITER = ':' NODES_DELIMITER = ',' def read_graph(file_path: str): """ Function that reads a graph from a text file Parameters ---------- file_path : str directory to file to read graph Returns ------- generator : yielding node (any hashable object), list of neighbors """ with open(file_path, 'r') as file: for line in file: node, _, neighbors = line.partition(DELIMITER) assert neighbors yield node, neighbors.replace(NODES_DELIMITER, '').split()
39bbe7fce725a7fb6fbc91def71fd88e6373b7e6
endfirst/python
/first_class_function/first_class_function00.py
511
3.515625
4
# -*- coding: utf-8 -*- # 퍼스트클래스 함수란 프로그래밍 언어가 함수 (function) 를 first-class citizen으로 취급하는 것을 뜻합니다. # 쉽게 설명하자면 함수 자체를 인자 (argument) 로써 다른 함수에 전달하거나 다른 함수의 결과값으로 리턴 할수도 있고, # 함수를 변수에 할당하거나 데이터 구조안에 저장할 수 있는 함수를 뜻합니다. def square(x): return x * x print square(5) f = square print square print f
938501b49e1f9678ac3f64094b2cf4eed46c35f6
JasmineBharadiya/pythonBasics
/task_8_guessNo.py
161
3.609375
4
import random a=int(raw_input("guess a no. between 1-10: ")) rA=random.randint(1,10) if(rA==a): print "well guessed" else : print "try again"
91d55cba2c6badcd157aae309c518f6fafcbf9c1
mildzf/zantext
/zantext/zantext.py
671
3.65625
4
# -*- coding: utf-8 -*- """ File: zantext.py Author: Mild Z Ferdinand This program generates random text. """ import random POOL = "abcdefghijklmnopqrstuvwxyz" def word(length=0): if not length or length > 26: length = random.randint(3, 10) else: length = abs(length) word = [random.choice(POOL) for i in range(length)] return ''.join(word) def sentence(words=0, chars=0): words = abs(words) if not words: words = random.randint(3, 10) return " ".join([word() for i in range(words)]) + "." def paragraph(sentences=0, words=0): if not sentences and not words: return " ".join([sentence() for i in range(5)])
4bdde3d9684f505ae85c0446465aa211a012a02d
luizfirmino/python-labs
/Python I/Assigments/Module 5/Ex-2.py
415
4.3125
4
# # Luiz Filho # 3/14/2021 # Module 5 Assignment # 2. In mathematics, the factorial of a number n is defined as n! = 1 ⋅ 2 ⋅ ... ⋅ n (as the product of all integer numbers from 1 to n). # For example, 4! = 1 ⋅ 2 ⋅ 3 ⋅ 4 = 24. Write a recursive function for calculating n! def calculateN(num): if num == 1: return num else: return num * calculateN(num-1) print(calculateN(4))
7372b7c995d2302f29b8443656b50cae298a566b
luizfirmino/python-labs
/Python I/Assigments/Module 6/Ex-4.py
742
4.40625
4
# # Luiz Filho # 3/23/2021 # Module 6 Assignment # 4. Write a Python function to create the HTML string with tags around the word(s). Sample function and result are shown below: # #add_html_tags('h1', 'My First Page') #<h1>My First Page</h1> # #add_html_tags('p', 'This is my first page.') #<p>This is my first page.</p> # #add_html_tags('h2', 'A secondary header.') #<h2>A secondary header.</h2> # #add_html_tags('p', 'Some more text.') #<p>Some more text.</p> def add_html_tags(tag, value): return "<" + tag + ">" + value + "</" + tag + ">" print(add_html_tags('h1', 'My First Page')) print(add_html_tags('p', 'This is my first page.')) print(add_html_tags('h2', 'A secondary header.')) print(add_html_tags('p', 'Some more text.'))
7207ee818fe1cd157874667ae152ee4e8072de3d
luizfirmino/python-labs
/Python Databases/Assigments/Assignment 1/filho_assignment1.py
655
4
4
#!/usr/bin/env python3 # Assignment 1 - Artist List # Author: Luiz Firmino #imports at top of file import sqlite3 def main(): con = sqlite3.connect('chinook.db') cur = con.cursor() #query to select all the elements from the movie table query = '''SELECT * FROM artists''' #run the query cur.execute(query) #save the results in movies artists = cur.fetchall() print("List of Artists: \n") #loop through and print all the movies for artist in artists: print(artist[0] , " " , artist[1]) print("\nDone - See you next time! \n") if con: con.close() if __name__ == "__main__": main()
c13619368c38c41c0dbf8649a3ca88d7f2788ee8
luizfirmino/python-labs
/Python Networking/Assignment 2/Assignment2.py
564
4.21875
4
#!/usr/bin/env python3 # Assignment: 2 - Lists # Author: Luiz Firmino list = [1,2,4,'p','Hello'] #create a list print(list) #print a list list.append(999) #add to end of list print(list) print(list[-1]) #print the last element list.pop() #remove last element print(list) print(list[0]) #print first element list.remove(1) #remove element print(list) del list[3] #remove an element by index print(list) list.insert(0,'Baby') #insert an element at index print(list)
51d1e3a48b954c1de3362ea295d4270a884fea98
luizfirmino/python-labs
/Python I/Assigments/Module 7/Ex-3.py
1,042
4.3125
4
# # Luiz Filho # 4/7/2021 # Module 7 Assignment # 3. Gases consist of atoms or molecules that move at different speeds in random directions. # The root mean square velocity (RMS velocity) is a way to find a single velocity value for the particles. # The average velocity of gas particles is found using the root mean square velocity formula: # # μrms = (3RT/M)½ root mean square velocity in m/sec # # R = ideal gas constant = 8.3145 (kg·m2/sec2)/K·mol # # T = absolute temperature in Kelvin # # M = mass of a mole of the gas in kilograms. molar mass of O2 = 3.2 x 10-2 kg/mol # # T = °C + 273 # # a. By using the decimal module, create a decimal object and apply the sqrt and quantize method (match pattern “1.000”) # and provide the answer to the question: # What is the average velocity or root mean square velocity of a molecule in a sample of oxygen at 25 degrees Celsius? number = 3237945.76 print("{:25,.9f}".format(number)) print("{:.2f}".format(number)) print("{:,.2f}".format(number)) print("{:,.4f}".format(number))
47d783748c562dd3c3f8b7644dda166f37b5f11e
luizfirmino/python-labs
/Python I/Assigments/Module 5/Ex-6.py
238
4.5
4
# # Luiz Filho # 3/14/2021 # Module 5 Assignment # 6. Write a simple function (area_circle) that returns the area of a circle of a given radius. # def area_circle(radius): return 3.1415926535898 * radius * radius print(area_circle(40))
6ca6fbf8e7578b72164ab17030f1c01013604b04
luizfirmino/python-labs
/Python I/Assigments/Module 5/Ex-4.py
549
4.28125
4
# # Luiz Filho # 3/14/2021 # Module 5 Assignment # 4. Explain what happens when the following recursive functions is called with the value “alucard” and 0 as arguments: # print("This recursive function is invalid, the function won't execute due an extra ')' character at line 12 column 29") print("Regardless any value on its parameters this function will not execute or compile.") def semordnilap(aString,index): if index < len(aString): print(aString[index]), end="") semordnilap(aString, index+1) semordnilap("alucard", 0)
796c8bb615635d769a16ae12d9f27f2cfce4631c
luizfirmino/python-labs
/Python I/Assigments/Module 2/Ex-2.py
880
4.53125
5
# # Luiz Filho # 2/16/2021 # Module 2 Assignment # Assume that we execute the following assignment statements # # length = 10.0 , width = 7 # # For each of the following expressions, write the value of the expression and the type (of the value of the expression). # # width//2 # length/2.0 # length/2 # 1 + 4 * 5 # length = 10.0 width = 7 print("-- DEFAULTS --------------") print("Variable width value = " + str(width)) print("Variable length value = " + str(length)) print("--------------------------") print("Result of width//2: " + str(width//2) + " output type:" + str(type(width//2))) print("Result of length/2.0: " + str(length/2.0) + " output type:" + str(type(length/2.0))) print("Result of length/2: " + str(length/2) + " output type:" + str(type(length/2))) print("Result of 1 + 4 * 5: " + str((1 + 4 * 5)) + " output type:" + str(type((1 + 4 * 5))))
6c41276669d4b83b5b79074f60302f370c4eaa80
wuga214/PlanningThroughTensorFlow
/utils/argument.py
388
3.609375
4
import argparse def check_int_positive(value): ivalue = int(value) if ivalue <= 0: raise argparse.ArgumentTypeError("%s is an invalid positive int value" % value) return ivalue def check_float_positive(value): ivalue = float(value) if ivalue < 0: raise argparse.ArgumentTypeError("%s is an invalid positive float value" % value) return ivalue
910a369c1dc5ad07e8e4c1916ef31c0c044f7430
Litao439420999/LeetCodeAlgorithm
/Python/integerBreak.py
701
3.59375
4
#!/usr/bin/env python3 # encoding: utf-8 """ @Filename: integerBreak.py @Function: 整数拆分 动态规划 @Link: https://leetcode-cn.com/problems/integer-break/ @Python Version: 3.8 @Author: Wei Li @Date:2021-07-16 """ class Solution: def integerBreak(self, n: int) -> int: if n < 4: return n - 1 dp = [0] * (n + 1) dp[2] = 1 for i in range(3, n + 1): dp[i] = max(2 * (i - 2), 2 * dp[i - 2], 3 * (i - 3), 3 * dp[i - 3]) return dp[n] # ------------------------- if __name__ == "__main__": n = 2 solution = Solution() max_mul = solution.integerBreak(n) print(f"The solution of this problem is {max_mul}")
78098f3c8900ab45f703158bfefd790be0cfe74b
Litao439420999/LeetCodeAlgorithm
/Python/maxProfitChance.py
799
4
4
#!/usr/bin/env python3 # encoding: utf-8 """ @Filename: maxProfitChance.py @Function: 买卖股票的最佳时机 动态规划 @Link: https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/ @Python Version: 3.8 @Author: Wei Li @Date:2021-07-16 """ from typing import List class Solution: def maxProfit(self, prices: List[int]) -> int: inf = int(1e9) minprice = inf maxprofit = 0 for price in prices: maxprofit = max(price - minprice, maxprofit) minprice = min(price, minprice) return maxprofit # --------------------------- if __name__ == "__main__": prices = [7, 1, 5, 3, 6, 4] solution = Solution() max_profit = solution.maxProfit(prices) print(f"The solution of this problem is {max_profit}")
a5dfcb4f79865d734ddfd7d9cf0c9061fcc6d187
Litao439420999/LeetCodeAlgorithm
/Python/missingNumber.py
611
3.828125
4
#!/usr/bin/env python3 # encoding: utf-8 """ @Filename: missingNumber.py @Function: 丢失的数字 @Link: https://leetcode-cn.com/problems/missing-number/ @Python Version: 3.8 @Author: Wei Li @Date:2021-07-22 """ class Solution: def missingNumber(self, nums): missing = len(nums) for i, num in enumerate(nums): missing ^= i ^ num return missing # ------------------------ if __name__ == "__main__": nums = [1, 2, 3, 4] solution = Solution() missing_number = solution.missingNumber(nums) print(f"The solution of this problem is {missing_number}")
ead8d1adb57d0b887ccd55638e88586230fe2d47
Litao439420999/LeetCodeAlgorithm
/Python/maxArea.py
868
4.03125
4
#!/usr/bin/env python3 # encoding: utf-8 """ @Filename: maxArea.py @Function: 盛最多水的容器 @Link: https://leetcode-cn.com/problems/container-with-most-water/ @Python Version: 3.8 @Author: Wei Li @Date:2021-08-08 """ from typing import List class Solution: def maxArea(self, height: List[int]) -> int: left, right = 0, len(height) - 1 maxArea = 0 while left < right: area = min(height[left], height[right]) * (right - left) maxArea = max(maxArea, area) if height[left] <= height[right]: left += 1 else: right -= 1 return maxArea # ------------------------- if __name__ == "__main__": height = [4,3,2,1,4] solution = Solution() max_area = solution.maxArea(height) print(f"The solution of this problem is : {max_area}")
f0df420f1b26891e1e1483da86615aa651a99815
Litao439420999/LeetCodeAlgorithm
/Python/combinationSum2.py
1,456
3.734375
4
#!/usr/bin/env python3 # encoding: utf-8 """ @Filename: combinationSum2.py @Function: 给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合 @Link: https://leetcode-cn.com/problems/combination-sum-ii/ @Python Version: 3.8 @Author: Wei Li @Date:2021-07-12 """ import collections from typing import List class Solution: def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: def dfs(pos: int, rest: int): nonlocal sequence if rest == 0: ans.append(sequence[:]) return if pos == len(freq) or rest < freq[pos][0]: return dfs(pos + 1, rest) most = min(rest // freq[pos][0], freq[pos][1]) for i in range(1, most + 1): sequence.append(freq[pos][0]) dfs(pos + 1, rest - i * freq[pos][0]) sequence = sequence[:-most] freq = sorted(collections.Counter(candidates).items()) ans = list() sequence = list() dfs(0, target) return ans # ------------------------ if __name__ == "__main__": # candidates = [10, 1, 2, 7, 6, 1, 5] # target = 8 candidates = [2,5,2,1,2] target = 5 solution = Solution() list_combine = solution.combinationSum2(candidates, target) print(f"The solutio of this problem is : {list_combine}")
4cf065dceacbfb09de77b2dba2d1f6879e080362
Litao439420999/LeetCodeAlgorithm
/Python/removeNthFromEnd.py
884
3.9375
4
#!/usr/bin/env python3 # encoding: utf-8 """ @Filename: removeNthFromEnd.py @Function: 删除链表的倒数第 N 个结点 @Link: https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/ @Python Version: 3.8 @Author: Wei Li @Date:2021-07-30 """ # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: dummy = ListNode(0, head) first = head second = dummy for i in range(n): first = first.next while first: first = first.next second = second.next second.next = second.next.next return dummy.next # -------------------------- if __name__ == "__main__": # test on LeetCode online. pass
f5e0250259414bd762064edd430b574d691f7051
Litao439420999/LeetCodeAlgorithm
/Python/isPowerOfThree.py
825
4.09375
4
#!/usr/bin/env python3 # encoding: utf-8 """ @Filename: isPowerOfThree.py @Function: 3的幂 数学问题 @Link: https://leetcode-cn.com/problems/power-of-three/ @Python Version: 3.8 @Author: Wei Li @Date:2021-07-19 """ import math class Solution: def isPowerOfThree(self, n: int) -> bool: if n <= 0: return False res = round(math.log(n, 3), 9) # python 需要精确到小数点 9 位,才能精确判断小数和它转换后的整数是否相等 return res - round(res) == 0 # round不加第二个参数,默认保留为整数 # ---------------------------------- if __name__ == "__main__": # num = 21 num = 27 solution = Solution() bool_power_three = solution.isPowerOfThree(num) print(f"The solution of this problem is {bool_power_three}")