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
47a6f8b87464ffc3a320a6dd9d79b16940d86794
CatonChen/algorithm023
/Week_01/21.合并两个有序链表.py
1,328
3.765625
4
# # @lc app=leetcode.cn id=21 lang=python3 # # [21] 合并两个有序链表 # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: # #递归 # if l1 is None: #l1为空返回l2 # return l2 # elif l2 is None: #l2为空返回l1 # return l1 # elif l1.val < l2.val: #判断l1或l2的大小,递归至其中一个完结 # l1.next = self.mergeTwoLists(l1.next,l2) # return l1 # else: # l2.next = self.mergeTwoLists(l1,l2.next) # return l2 #迭代 prehead = ListNode(0) #空列表 prev=prehead while l1 and l2 : #l1和l2不为空时 if l1.val < l2.val: #l1<l2,prev.next指向l1当前值,l1指针后移一位 prev.next=l1 l1=l1.next else: #反之亦然 prev.next=l2 l2=l2.next prev=prev.next #prev指针后移一位 prev.next=l1 if l1 is not None else l2 #prev指针指向剩余的l1或l2 return prehead.next # @lc code=end
9f006c9beecb29b7474b7bb458ad70ba43ba4bae
Tordensky/laby
/teams/hma030_inf2101_oblig2/src/message.py
766
3.65625
4
# -*- coding: utf-8 -*- class message: """ Class encapsulating messages. Used with the protocolBase for transferring messages between peers. """ def __init__(self): """ Initializes the object with a message (string) if input is given. """ self.msg = [] def add(self, msg): """ Add a message to the list of messages. """ self.msg.append(msg) def get(self, idx): """ Get the message at the given index. """ try: retval = self.msg[idx] except: retval = False print "Index out of range" return retval def size(self): """ Retrieve the number of messages in this meessage. """ return len(self.msg)
08ba6f102fa5e01b3c6c4cd0ec20c7f955261cf0
aj3x/adventofcode2020
/day9/day9.py
1,100
3.515625
4
import userin # # sort range of numbers # while sorting add to key map def convertArr(item): return int(item) preamble = 25 parsedArray = map(convertArr, userin.default.splitlines()) # check numbers between (n/2,n) # binary search sorted array for being in between range # try going up and down till reaching bounds def verifyNumber(key, numarr): lowerBound = key/2 upperBound = key numset = set(numarr) for num in numarr: if numset.__contains__(key - num): return True return False # Solve for Key # for i in range(preamble, len(parsedArray)): # preambleArr = parsedArray[i - preamble:i] # num = parsedArray[i] # if not verifyNumber(num, preambleArr): # print num def checkSumArr(arr, val): for kSum in arr: if kSum == val: return True return False def getSumArr(key, arr): sumArr = [] for i in range(0, len(arr)): curNum = arr[i] sumArr = map(lambda val: val + curNum, sumArr) if checkSumArr(sumArr, key): return arr[sumArr.index(key)] + arr[i - 1] sumArr.append(curNum) print getSumArr(507622668, parsedArray)
58401ce6e6a3876062d2a629d39314432e08b64f
mattling9/Algorithms2
/stack.py
1,685
4.125
4
class Stack(): """a representation of a stack""" def __init__(self, MaxSize): self.MaxSize = MaxSize self.StackPointer = 0 self.List = [] def size(self): StackSize = len(self.List) return StackSize def pop(self): StackSize = self.StackSize() if StackSize > 0: self.items.pop() self.StackPointer = StackSize else: print("There are no items in the stack") def push(self, item ): size() StackSize = self.StackSize() if self.StackSize < MaxSize: self.List.append(item) self.StackPoitner = StackSize else: print("The stack is full") def peek(self): size() StackSize = self.StackSize if StackSize == 0: print(" the stack is empty") else: print("The top item is {0}".format(self.List[StackSize-1])) def main(): CustomStack = Stack(5) Done = False while Done == False: print("Please select an option") print() print("1. Peek") print("2. Push") print("3. Pop") print("4. Exit") choice = int(input()) if choice == 1: CustomStack.peek() elif choice == 2: CustomStack.push() elif choice == 3: CustomStack.pop() elif choice == 4: Done = True while choice < 2 or choice > 4: print("Please enter a valid number") choice=int(input()) if __name__ == "__main__": main()
be8eecacddb448aa1cef0d9a2213178cb2655e80
felixnext/tf-argonaut
/argonaut/models/simple.py
2,386
3.640625
4
''' Defines some simple baseline models. author: Felix Geilert ''' import numpy as np import tensorflow as tf from tensorflow.keras import layers as lyrs class ConvNet(tf.keras.Model): '''Defines a simple convolutional model. Args: num_layers (int): Number of layers to use num_classes (int): Number of classes to use ''' def __init__(self, num_layers, activation=tf.nn.relu): super(ConvNet, self).__init__() self.num_layers = num_layers # define the internal blocks self.layer_names = [] filters = 32 next = 1 for i in range(num_layers - 1): layer_name = "conv_{}".format(i + 1) lyr = lyrs.Conv2D(filters, (3, 3) if (i % 3 == 0) or next == i else (1, 1), 2 if next == i else 1) self.__setattr__(layer_name, lyr) self.__setattr__("{}_act".format(layer_name), lyrs.ReLU()) self.layer_names.append((layer_name, False)) if next == i: filters = filters * 2 next = next + i def call(self, input_tensor, training=False): x = input_tensor for (layer_name, train_only) in self.layer_names: if train_only is True and training is False: continue x = self.__getattribute__(layer_name)(x) x = self.__getattribute__("{}_act".format(layer_name))(x) return x class MLP(tf.keras.Model): '''Defines fully connected layers (multi-layer perceptron). Args: num_layers (int): Number of layers to use num_classes (int): Number of classes to use ''' def __init__(self, num_layers, activation=tf.nn.relu): super(MLP, self).__init__() self.num_layers = num_layers # define the internal blocks self.layer_names = [] features = 32 next = 1 for i in range(num_layers - 1): layer_name = "dense_{}".format(i + 1) self.__setattr__(layer_name, lyrs.Dense(features)) self.__setattr__("{}_act".format(layer_name), lyrs.ReLU()) self.layer_names.append((layer_name, False)) if next == i: features = features * 2 next = next + i def call(self, input_tensor, training=False): x = input_tensor x = lyrs.Reshape((np.prod(x.shape[1:]), ))(x) for (layer_name, train_only) in self.layer_names: if train_only is True and training is False: continue x = self.__getattribute__(layer_name)(x) x = self.__getattribute__("{}_act".format(layer_name))(x) return x
f02c48c3687acd676ab39c789211d8f554652649
iemeka/python
/exercise-lpthw/form.py
850
3.65625
4
from sys import argv script, file = argv prompt = "$$- " print "Hello!" name = raw_input("please enter your name %s" % prompt) print "Welcome %s. How are you?" % name doing = raw_input(prompt) print "Nice to know you're %s" % doing print "I am going to ask a few questions about you if that's ok?" print "Type 'ok' otherwise press crtl-c" raw_input(prompt) print "Thanks for obliging %s" % name print "Loading questions....." raw_input("\"Hit 'enter' to continue\"") print "what are your other names ?" otherNames = raw_input(prompt) print "what is the name of your school?" school = raw_input(prompt) Address = raw_input("home address %s" % prompt) print "That will be all for now. Thanks\nReports loading...." open_file = open(file, "w") open_file.write(("%s\n%s\n%s\n%s\n%s") % (name, doing, otherNames, school, Address)) open_file.close()
a81e12e0195a19d01957ec210feb85aacc461fd8
iemeka/python
/exercise-lpthw/snake4.py
1,746
4.09375
4
#we gave the number value to the variable name "car" cars = 100 #we gave variable name a number value too space_in_a_car = 4.0 #same here with "drivers" drivers = 30.0 #and also with "passengers" passengers = 90 #we created the variable "cars_not_driven" and assigns two variables defined previously to it #the result is the value which has been assigned to them previously then all assigned to the #new variable created. Thus the new variable "cars_not_driven" holds the value of "cars" and "drivers" #which are apparently being divided cars_not_driven = cars - drivers #created a new variable "cars_driven" and assign to it a previously defined variable name #meaning were are assigning whatever value "drivers" hold or has been assigned cars_driven = drivers #the same concept as in the 5th comment but different variable names and assignments #the variable "carpool_capacity" equals the value of the variable "cars_driven" and "space_in_a_car" #which are obviously being multiplied carpool_capacity = cars_driven * space_in_a_car #same idia with the abbove comment but in this case the values are being divided average_passengers_per_car = passengers / cars_driven print "There are", cars, "cars available." print "There are only", drivers, "drivers available." print "There will be", cars_not_driven, "empty cars today." print "We can transport", carpool_capacity, "people today." print "We have", passengers, "to carpool today." print "We need to put about", average_passengers_per_car, " in each car." #the code wont run. in line 8 the "car_pool_capacity" was not assigned any value #and "passenger" too was not assigned any value but "passengers" i = 534.0 x = 443 j = 30.0 z = j + x * i print i * j * x print j / x print z - x
31b272d2675be1ecfd20e9b4bae4759f5b533106
iemeka/python
/exercise-lpthw/snake6.py
1,792
4.21875
4
#declared a variable, assigning the string value to it. #embedded in the string is a format character whose value is a number 10 assigned to it x = "There are %d types of people." % 10 #declared a variable assigning to it the string value binary = "binary" #same as above do_not = "don't" # also same as above but with who format characters whose values variables # hence the value of the two format characters equals the value of the two variables assigned to the format character y = "Those who know %s and those who %s." % (binary, do_not) # told python to print the values of the variable x print x # told python to print the values of the variable y print y # here python has the print a string in which a format character is embedded and whose value is he # the values of he variable x print "I said: %r." % x # same here ...which value is the values of the variable y print " I also said: '%s'. " % y #assigned a boolean to a variable hilarious = False # declared a variable assigning assigning to it a string with an embedded format character joke_evaluation = "Isn't that joke so funny?! %r" # told python to print the value of the variable which is a string which a format character # is embedded in it then assigning the value of the embedde character in the string the value # of another variable. # so python has to print a variable value assigning a variable to the format character in the first variable value print joke_evaluation % hilarious w = "This is the left side of..." e = "a string with a right side." # here python simply joined two stings together using the operator + thats why is makes # a longer string. In javaScript is called concatenation of strings (learnt javaScript initially) tongue out* <(-,-)> print w + e # yes! they are four places fuck you shaw!
ed10b4f7cebef6848b14803ecf76a16b8bc84ca4
iemeka/python
/exercise-lpthw/snake32.py
713
4.40625
4
the_count = [1, 2, 3, 4, 5] fruits = ['apples', 'oranges', 'pears', 'apricots'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] # this first kind of for-loop goes through a list for number in the_count: print "This is count %d" % number # same as above for fruit in fruits: print "A fruit of type: %s" % fruit for i in change: print "I got %r" % i elements = [] # range function to do 0 to 5 counts for i in range(0, 6): print "Adding %d to the list." % i # append is a function that lists understands elements.append(i) print "Element was: %d" % i print elements.pop(0) print elements[1:3] elements[3] = "apple" print elements del elements[2] print elements print len(elements) print elements[2]
bb1a2972bc806e06fe6302c703c158130318bf07
iemeka/python
/exercise-lpthw/snake20.py
1,128
4.21875
4
from sys import argv script, input_file = argv # a function to read the file held and open in the variable 'current_file' and then passed.. # the variable is passed to this functions's arguement def print_all(f): print f.read() # seek takes us to the begining of the file def rewind(f): f.seek(0) # we print the numer of the line we want to read and the we print the content of the line # the comma makes sure the 'print' doesnt end with newline def print_a_line(line_count, f): print line_count, f.readline(), current_file = open(input_file) print "First let's print the whole file:\n" # calling the function print_all' print_all(current_file) print "Now lets rewind, kind of like a tape" # calling the function 'rewind' rewind(current_file) print "Let's print three lines:" #calling functions current_line = 1 print_a_line(current_line, current_file) # current_line = 1 (initially) plus another 1. current lines = 2 current_line +=1 print_a_line(current_line, current_file) # current_line = 2 (from the last global variable) plus another 1. current lines = 3 current_line +=1 print_a_line(current_line, current_file)
d26f6248dedc9e0fa11f461dfaa246e811c17f80
chenshaobin/python_learning_demo
/map_reduce_demo.py
1,520
4
4
#!/usr/bin/python # -*- coding: utf-8 -*- from functools import reduce DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} def str2int(s): def fn(x, y): return x * 10 + y def char2num2(s): return DIGITS[s] return reduce(fn, map(char2num2, s)) # print('将字符串123456转整数',str2int('123456')) def char2num(s): return DIGITS[s] def str2intdemo2(s): return reduce(lambda x, y: x * 10 + y, map(char2num, s)) # print('将字符串123456转整数',str2intdemo2('123456')) def normlize(name): # 利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字 if not isinstance(name, str): raise TypeError("please enter a String") return name[0].upper() + name[1:].lower() def normlizeNameList(list): return map(normlize,list) print(list(normlizeNameList(['ethan','ETHAN','eThan']))) def prod(list): # 接受一个list并利用reduce()求积 return reduce(lambda x, y :x * y,list) # print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9])) def str2float(s): # 利用map和reduce编写一个把字符串'123.456'转换成浮点数123.456的函数 def char2num(s): return DIGITS[s] i = s.find('.') L1 = reduce(lambda x, y:x* 10 + y,map(char2num,s[:i])) # 取'.'之前的数计算 L2 = reduce(lambda x ,y :x/10 + y,map(char2num,s[:i:-1]))/10 #倒数取数 return L1 + L2 print('str2float(\'123.456\')= ',str2float('123.456'))
fc21b2b82f9da9cc41c9e61f709635ddbec7c6da
MelisseCabral/Lab-Prog-1-2014.1
/media_do_maior_e_menor/m.py
499
3.703125
4
# coding: utf-8 # Melisse Cabral, 114110471 # Média do Maior e Menor num = int(raw_input()) maior = num menor = num numeros = [] cont = 0 while num >= 0: num = int(raw_input()) numeros.append(num) if num > maior and num >= 0: maior = num if num < menor and num >= 0: menor = num media = (maior + menor) / 2.0 print "maior: %d" % maior print "menor: %d" % menor print "média: %d" % media for i in numeros: if i < media and i >= 0: cont += 1 print "%d número(s) abaixo da média" % cont
8d5493d6d22701be1f409a5b7f4a7380f731512e
MelisseCabral/Lab-Prog-1-2014.1
/somadiv5/m.py
186
3.828125
4
# coding: utf-8 # Melisse Cabral, 114110471 # Soma Dos Divisiveis por 5 n = int(raw_input()) soma = 0 for i in range(1,n+1): num = int(raw_input()) if num % 5 == 0: soma += num print soma
a5daf669e7bcf9315bbeadf8bb0ead7d8b6d7876
MelisseCabral/Lab-Prog-1-2014.1
/menor_dos_extremos/m.py
520
3.625
4
# coding: utf-8 # Melisse Cabral, 114110471 # Menor dos Extremos n = int(raw_input()) lista = [] menor = 0 cont_menor = 0 cont_maior = 0 for i in range(n): num = int(raw_input()) lista.append(num) if int(lista[0]) >= int(lista[-1]): menor = int(lista[-1]) else: menor = int(lista[0]) for i in lista: if i < menor: cont_menor += 1 elif i > menor: cont_maior += 1 print "Menor dos extremos: %d" % menor print "%d número(s) abaixo do menor" % cont_menor print "%d número(s) acima do menor" % cont_maior
63788308ae2eeefbeb65ec9cf9551d3f8269b421
ajcheon/project_euler
/problem_4.py
240
3.8125
4
# largest palindrome made from the product of two 3-digit numbers palins = [] for i in range (100, 1000): for j in range (100, 1000): prod = str(i * j) if prod == prod[::-1]: palins.append((int)(prod)) print max(palins)
85034cba0c67348981ca40573a5c185743afd565
ajcheon/project_euler
/problem_10_sieve.py
902
3.59375
4
# Find the sum of all the primes below two million. # 1/4/13 import math import time # FOR DEBUGGING ONLY def is_prime(n): for i in range (1, n): if n % i == 0 and i != 1 and i != n: return False return True #--------------------------------------------- #limit = 2000000 limit = 300425737571 nums = [True] * (limit - 1) t0 = time.time() pos = 0 # corresponds to n = 2 while pos < (int)(math.ceil(math.sqrt(limit))): if nums[pos] == False: pos += 1 else: for i in range (2*pos + 2, len(nums), pos + 2): nums[i] = False pos += 1 total = 0 number = 0 for i in range (len(nums)): if nums[i] == True: number = i + 2 total += number print "sum of all primes below", limit, ":", total t1 = time.time() print "time elapsed:", t1 - t0
3d3bb07c0afda8d2c9943a39883cbbee67bfe4b1
icgowtham/Miscellany
/python/sample_programs/tree.py
2,130
4.25
4
"""Tree implementation.""" class Node(object): """Node class.""" def __init__(self, data=None): """Init method.""" self.left = None self.right = None self.data = data # for setting left node def set_left(self, node): """Set left node.""" self.left = node # for setting right node def set_right(self, node): """Set right node.""" self.right = node # for getting the left node def get_left(self): """Get left node.""" return self.left # for getting right node def get_right(self): """Get right node.""" return self.right # for setting data of a node def set_data(self, data): """Set data.""" self.data = data # for getting data of a node def get_data(self): """Get data.""" return self.data # Left -> Root -> Right: ./\. def in_order(node): """In-order traversal (Left->Root->Right).""" if node: in_order(node.get_left()) print(node.get_data(), end=' ') in_order(node.get_right()) return # Root -> Left ->Right: \._. def pre_order(node): """Pre-order traversal (Root->Left->Right).""" if node: print(node.get_data(), end=' ') pre_order(node.get_left()) pre_order(node.get_right()) return # Left -> Right -> Root: ._.\ def post_order(node): """Post-order traversal (Left->Right->Root).""" if node: post_order(node.get_left()) post_order(node.get_right()) print(node.get_data(), end=' ') return if __name__ == '__main__': root = Node(1) root.set_left(Node(2)) root.set_right(Node(3)) root.left.set_left(Node(4)) print('In-order Traversal:') in_order(root) print('\nPre-order Traversal:') pre_order(root) print('\nPost-order Traversal:') post_order(root) # OUTPUT: # Inorder Traversal: # 4 2 1 3 # Preorder Traversal: # 1 2 4 3 # Postorder Traversal: # 4 2 3 1
1eb9a54a4c86c72594064717eb0cd65c6376421d
icgowtham/Miscellany
/python/sample_programs/algorithms/quick_sort_v1.py
1,352
4.125
4
# -*- coding: utf-8 -*- """Quick sort implementation in Python.""" def partition(array, begin, end): """Partition function.""" pivot_idx = begin """ arr = [9, 3, 4, 8, 1] pivot = 0 i = 1, begin = 0 3 <= 9 -> swap -> [3, 9, 4, 8, 1] pivot = 1 i = 2, pivot = 1 4 <= 9 -> swap -> [3, 4, 9, 8, 1] pivot = 2 i = 3, pivot = 2 8 <= 9 -> swap -> [3, 4, 8, 9, 1] pivot = 3 i = 4, pivot = 3 1 <= 9 -> swap -> [3, 4, 8, 1, 9] pivot = 4 i = 5, pivot = 4 """ for i in range(begin + 1, end + 1): if array[i] <= array[begin]: pivot_idx += 1 array[i], array[pivot_idx] = array[pivot_idx], array[i] array[pivot_idx], array[begin] = array[begin], array[pivot_idx] print(array) return pivot_idx def quick_sort_recursion(array, begin, end): """Recursive function.""" if begin >= end: return pivot_idx = partition(array, begin, end) print(pivot_idx) quick_sort_recursion(array, begin, pivot_idx - 1) quick_sort_recursion(array, pivot_idx + 1, end) def quick_sort(array, begin=0, end=None): """Quick sort function.""" if end is None: end = len(array) - 1 return quick_sort_recursion(array, begin, end) if __name__ == '__main__': arr = [9, 3, 4, 8, 1] quick_sort(arr) print(arr)
2395e627570a75a0ea72fdf243cd5b28e155d0e0
TTvanWillegen/AdventOfCode2019
/3/main.py
3,790
3.640625
4
def main(): part_one() part_two() def part_one(): print("Part One") center = (0, 0) with open("input.txt", "r") as input_file: wires = [] for line in input_file: wire = set() actions = line.rstrip().split(",") coord = center for action in actions: direction = action[0] if direction not in ["R", "L", "U", "D"]: break steps = int(action[1:]) if direction == "R": for i in range(0, steps): coord = (coord[0] + 1, coord[1]) wire.add(coord) elif direction == "L": for i in range(0, steps): coord = (coord[0] - 1, coord[1]) wire.add(coord) elif direction == "U": for i in range(0, steps): coord = (coord[0], coord[1] + 1) wire.add(coord) elif direction == "D": for i in range(0, steps): coord = (coord[0], coord[1] - 1) wire.add(coord) wires.append(wire) intersections = wires[0].intersection(wires[1]) min_dist = None for intersection in intersections: min_dist = manhattan_distance(center, intersection) if min_dist is None else min(min_dist, manhattan_distance(center, intersection)) print("Distance: ", min_dist) def part_two(): print("Part Two") center = (0, 0) with open("input.txt", "r") as input_file: wires = [] timings = [] for line in input_file: wire = set() timing = dict() time = 0 actions = line.rstrip().split(",") coord = center for action in actions: direction = action[0] if direction not in ["R", "L", "U", "D"]: break steps = int(action[1:]) if direction == "R": for i in range(0, steps): coord = (coord[0] + 1, coord[1]) time += 1 timing[str(coord)] = timing.get(str(coord), time) wire.add(coord) elif direction == "L": for i in range(0, steps): coord = (coord[0] - 1, coord[1]) time += 1 timing[str(coord)] = timing.get(str(coord), time) wire.add(coord) elif direction == "U": for i in range(0, steps): coord = (coord[0], coord[1] + 1) time += 1 timing[str(coord)] = timing.get(str(coord), time) wire.add(coord) elif direction == "D": for i in range(0, steps): coord = (coord[0], coord[1] - 1) time += 1 timing[str(coord)] = timing.get(str(coord), time) wire.add(coord) wires.append(wire) timings.append(timing) intersections = wires[0].intersection(wires[1]) min_timing = None for intersection in intersections: min_timing = timings[0][str(intersection)] + timings[1][str(intersection)] if min_timing is None else min(min_timing, timings[0][str(intersection)] + timings[1][str(intersection)]) print("Distance: ", min_timing) def manhattan_distance(p1, p2): return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1]) if __name__ == "__main__": main()
cac92e1610c7ce6de0e01393d907ff28837ea12f
smyoung88/Election_Analysis
/PyPoll_Challenge.py
5,404
3.9375
4
# Import 'csv' and 'os' modules import csv import os # Assign a variable to load a file from a path. file_to_load = os.path.join("Resources", "election_results.csv") # Assign a variable to save the file to a path. file_to_save = os.path.join("analysis", "election_results.txt") # Initialize a total vote counter. total_votes = 0 # Initialize candidate and county options candidate_options = [] county_options = [] # Initialize candidate votes and county votes dictionary candidate_votes = {} county_votes = {} # Winning Candidate, Winning Count, Highest County Tracker winning_candidate = "" winning_count = 0 winning_percentage = 0 highest_turnout = "" cwinning_count = 0 cwinning_percentage = 0 # Open the election results and read the file. with open(file_to_load) as election_data: file_reader = csv.reader(election_data) # Read the header row. headers = next(file_reader) # Print each row in the CSV file. for row in file_reader: # Add to the total vote count. total_votes += 1 # Print the candidate name and county for each row candidate_name = row[2] county_name = row[1] # Find list of candidates if candidate_name not in candidate_options: # Add the candidate name to the candidate list candidate_options.append(candidate_name) # Begins tracking that candidate's vote count candidate_votes[candidate_name] = 0 # Add a vote to that candidate's count. candidate_votes[candidate_name] += 1 # Find list of counties if county_name not in county_options: # Add the county name to the county list county_options.append(county_name) #Begins tracking that county's turnout county_votes[county_name] = 0 #Add a vote to that county's count. county_votes[county_name] += 1 #Save the results to our text file. with open(file_to_save, "w") as txt_file: # Print Total Votes to the terminal election_results = ( f"\nElection Results\n" f"-------------------------\n" f"Total Votes: {total_votes:,}\n" f"-------------------------\n") print(election_results, end="") # Save the final vote count to the text file. txt_file.write(election_results) county_turnout = ( f"\nCounty Votes\n") print(county_turnout, end="") # Save the county turnout header to the text file txt_file.write(county_turnout) # Determine the percentage of votes for each county by looping through the counts. # Use a loop to iterate through the county list for counties in county_options: # Retrieve the votes of the candidate from county_votes dictionary cvotes = county_votes[counties] cvote_percent = float(cvotes) / float(total_votes) * 100 county_results = (f'{counties}: {cvote_percent:.1f}% ({cvotes:,})\n') # Print out each county name, percentage of votes in that county, and total votes in the county to the terminal print(county_results) # Save the county results to the text file txt_file.write(county_results) # Print out the county with the highest turnout if (cvotes > cwinning_count) and (cvote_percent > cwinning_percentage): cwinning_count = cvotes cwinning_percentage = cvote_percent highest_turnout = counties highest_turnout_summary = ( f"\n-------------------------\n" f"Largest County Turnout: {highest_turnout}\n" f"-------------------------\n") # Print the county with highest turnout to terminal print(highest_turnout_summary) # Save the county with the highest turnout to the text file txt_file.write(highest_turnout_summary) # Determine the percentage of votes for each candidate by looping through the counts. # Use a loop to iterate through cadidate list for candidates in candidate_options: # Retrieve the votes of the candidate from candidate_votes dictionary votes = candidate_votes[candidates] vote_percent = float(votes) / float(total_votes) * 100 candidate_results = (f'{candidates}: {vote_percent:.1f}% ({votes:,})\n') # Print out each candidate's name, vote count, and percentage of votes to the terminal print(candidate_results) # Save the candidate results to our text file. txt_file.write(candidate_results) # Print out each candidate's name, vote count, and percentage of winning candidate if (votes > winning_count) and (vote_percent > winning_percentage): winning_count = votes winning_percentage = vote_percent winning_candidate = candidates winning_candidate_summary = ( f"-------------------------\n" f"Winner: {winning_candidate}\n" f"Winning Vote Count: {winning_count:,}\n" f"Winning Percentage: {winning_percentage:.1f}%\n" f"-------------------------\n") # Print the winning candidate's results to the terminal print(winning_candidate_summary) # Save the winning candidate's results to the text file. txt_file.write(winning_candidate_summary)
ebd8fcf43f3afc982cee8ca946346f431d3c6232
SlawomirK77/to-lab
/iterator.py
1,714
3.921875
4
from collections import defaultdict from abc import ABCMeta, abstractmethod class Iterator(metaclass=ABCMeta): @staticmethod @abstractmethod def has_next(): """Returns Boolean whether at end of collection or not""" @staticmethod @abstractmethod def next(): """Return the object in collection""" class Graph(Iterator): def __init__(self): self.graph = defaultdict(list) self.index = 0 self.maximum: int def add_edge(self, u, v): self.graph[u].append(v) self.maximum = len(self.graph) def bfs(self, s): visited = [False] * (len(self.graph)) queue = [] queue.append(s) visited[s] = True while queue: s = queue.pop(0) print(s, end=" ") for i in self.graph[s]: if not visited[i]: queue.append(i) visited[i] = True def next(self): if self.index < self.maximum: x = self.index self.index += 1 return self.graph[x] else: raise Exception("AtEndOfIteratorException", "At End Of Iterator") def has_next(self): return self.index < self.maximum if __name__ == "__main__": g = Graph() g.add_edge(0, 1) g.add_edge(1, 0) g.add_edge(0, 2) g.add_edge(2, 0) g.add_edge(3, 4) g.add_edge(4, 3) g.add_edge(4, 5) g.add_edge(5, 4) g.add_edge(1, 2) g.add_edge(2, 1) g.add_edge(2, 3) g.add_edge(3, 2) g.add_edge(3, 3) g.bfs(3) print("\n") print(g.graph) for i in range(6): print(g.graph[i]) while g.has_next(): print(g.next())
a0425a6f44b7adbce69881aac60a34448c6248cc
Copoka11/tkTest
/tkTest/test_12.py
536
3.703125
4
from tkinter import * from tkinter.messagebox import * root = Tk() btn1 = Button(root, text="Info", font=("Tahoma", 20), command = lambda: showinfo("ShowInfo", "Info:")) btn1.grid(row=0, column=0, sticky="ew") btn2 = Button(root, text="Warning", font=("Tahoma", 20), command = lambda: showwarning("ShowWarning", "Warning:")) btn2.grid(row=1, column=0, sticky="ew") btn3 = Button(root, text="Error", font=("Tahoma", 20), command = lambda: showerror("ShowError", "Error:")) btn3.grid(row=2, column=0, sticky="ew") root.mainloop()
9f30c9c040e81a68f30c85fa46a4560dd811f83c
hiteshdua1/codescripter
/pong_the_game.py
6,759
3.984375
4
#Running CodeSkulptor Link ! #http://www.codeskulptor.org/#user23_ePlWtu2yPB_14.py # Implementation of classic arcade game Pong #for left bar use # w-up # s-down #for right bar use # up arraow key-up # down arow key-down import simplegui import random # initialize globals - pos and vel encode vertical info for paddles WIDTH = 600 HEIGHT = 400 BALL_RADIUS = 10 PAD_WIDTH = 8 PAD_HEIGHT = 80 HALF_PAD_WIDTH = PAD_WIDTH / 2 HALF_PAD_HEIGHT = PAD_HEIGHT / 2 paddle1_point_0=[2,0] #Initial point 1 for paddle 1 paddle1_point_1=[2,PAD_HEIGHT] #Initial point 2 for paddle 1 paddle2_point_0=[WIDTH-2,0] #Initial point 1 for paddle 2 paddle2_point_1=[WIDTH-2,PAD_HEIGHT] #Initial point 2 for paddle 2 paddle1_vel=[0,0] #initial velocity for paddle1 paddle2_vel=[0,0] #initial velocity for paddle2 score1=0 score2=0 inc=1.1 #velocity increment speed=3 #speed of paddle # initialize ball_pos and ball_vel for new bal in middle of table ball_pos = [WIDTH / 2, HEIGHT / 2] x = -(random.randrange(120, 240)/60) y = -(random.randrange(60, 180)/60) ball_vel = [x, y] # if direction is RIGHT, the ball's velocity is upper right, else upper left def spawn_ball(direction): global ball_pos, ball_vel # these are vectors stored as lists ball_pos = [WIDTH / 2, HEIGHT / 2] x = random.randrange(120, 240)/60 y = -(random.randrange(60, 180)/60) if(direction=="RIGHT"): ball_vel = [x, y] else: ball_vel = [-x, y] # define event handlers def new_game(): global paddle1_pos, paddle2_pos, paddle1_vel, paddle2_vel # these are numbers global score1, score2,ball_pos,paddle1_point_0,paddle1_point_1 global paddle2_point_0,paddle2_point_1 # these are ints score1=0 score2=0 spawn_ball("LEFT") paddle1_point_0=[2,0] #Initial point 1 for paddle 1 paddle1_point_1=[2,PAD_HEIGHT] #Initial point 2 for paddle 1 paddle2_point_0=[WIDTH-2,0] #Initial point 1 for paddle 2 paddle2_point_1=[WIDTH-2,PAD_HEIGHT] #Initial point 2 for paddle 2 paddle1_vel=[0,0] #initial velocity for paddle1 paddle2_vel=[0,0] #initial velocity for paddle2 def draw(c): global score1, score2, paddle1_pos, paddle2_pos, ball_pos, ball_vel #------------------------------------------------------------- # draw mid line and gutters c.draw_line([WIDTH / 2, 0],[WIDTH / 2, HEIGHT], 1, "White") c.draw_line([PAD_WIDTH, 0],[PAD_WIDTH, HEIGHT], 1, "White") c.draw_line([WIDTH - PAD_WIDTH, 0],[WIDTH - PAD_WIDTH, HEIGHT], 1, "White") #------------------------------------------------------------- # update ball ball_pos[0] += ball_vel[0] ball_pos[1] += ball_vel[1] #------------------------------------------------------------- #update paddles #update paddle 1 paddle1_point_0[1] +=paddle1_vel[1] paddle1_point_1[1] +=paddle1_vel[1] #update paddle 2 paddle2_point_0[1] +=paddle2_vel[1] paddle2_point_1[1] +=paddle2_vel[1] #------------------------------------------------------------- #bouncing the balls of padde1 #left most point if(ball_pos[0] <= BALL_RADIUS+PAD_WIDTH ): if (ball_pos[1] >= paddle1_point_0[1] and ball_pos[1] <= paddle1_point_1[1]): ball_vel[0] = - ball_vel[0]*inc else: spawn_ball("RIGHT") score2 +=1 #right most point if(ball_pos[0]+BALL_RADIUS >= WIDTH-PAD_WIDTH ): if (ball_pos[1] >= paddle2_point_0[1] and ball_pos[1] <= paddle2_point_1[1]): ball_vel[0] = - ball_vel[0]*inc else: spawn_ball("LEFT") score1 +=1 #------------------------------------------------------------- # draw ball c.draw_circle(ball_pos, BALL_RADIUS, 2, "Red", "White") #------------------------------------------------------------- #bouncing off the ball on vertical walls if ( ball_pos[1] <= BALL_RADIUS): ball_vel[1] = -ball_vel[1] elif( ball_pos[1] + BALL_RADIUS >= HEIGHT ): ball_vel[1] = -ball_vel[1] #------------------------------------------------------------- #checking extreme conditions for paddle #paddle 1 #for top most coordinate if paddle1_point_0[1] <= 0: #y coordinate of paddle1 postion of first point paddle1_point_0[1] =0 paddle1_point_1[1] =PAD_HEIGHT #for bottom most coordinate if paddle1_point_1[1] >= HEIGHT : #extreme width of the frame paddle1_point_0[1] =HEIGHT-PAD_HEIGHT paddle1_point_1[1] =HEIGHT #paddle 2 #for top most coordinate if paddle2_point_0[1] <= 0 : #y coordinate of paddle1 postion of first point paddle2_point_0[1] =0 paddle2_point_1[1] =PAD_HEIGHT #for bottom most coordinate if paddle2_point_1[1] >= HEIGHT : #extreme width of the frame paddle2_point_0[1] =HEIGHT-PAD_HEIGHT paddle2_point_1[1] =HEIGHT #------------------------------------------------------------- # draw paddles #paddle 1 c.draw_line(paddle1_point_0,paddle1_point_1, PAD_WIDTH, 'Yellow') #paddle 2 c.draw_line(paddle2_point_0,paddle2_point_1, PAD_WIDTH, 'Red') #------------------------------------------------------------- # draw scores c.draw_text(str(score1), (200, 50), 30, 'Blue', 'serif') c.draw_text(str(score2), (400, 50), 30, 'Blue', 'serif') #------------------------------------------------------------- def keydown(key): global paddle1_vel, paddle2_vel #velocity for paddles #for paddle 1 if key==simplegui.KEY_MAP["s"]: paddle1_vel[1] =speed elif key==simplegui.KEY_MAP["w"]: paddle1_vel[1] =-speed #for paddle 2 if key==simplegui.KEY_MAP["down"]: paddle2_vel[1] =speed elif key==simplegui.KEY_MAP["up"]: paddle2_vel[1] =-speed #------------------------------------------------------------- def keyup(key): global paddle1_vel, paddle2_vel #for paddle 1 if key==simplegui.KEY_MAP["s"]: paddle1_vel[1] =0 elif key==simplegui.KEY_MAP["w"]: paddle1_vel[1] =0 #for paddle 2 if key==simplegui.KEY_MAP["down"]: paddle2_vel[1] =0 elif key==simplegui.KEY_MAP["up"]: paddle2_vel[1] =0 #------------------------------------------------------------- # create frame frame = simplegui.create_frame("Pong", WIDTH, HEIGHT) frame.set_draw_handler(draw) frame.set_keydown_handler(keydown) frame.set_keyup_handler(keyup) button2 = frame.add_button('RESET', new_game, 100) # start frame new_game() frame.start()
5d70ae6c1247088f697a811dc9e5aa5e34eb1660
jes5918/TIL
/Algorithm/SWEA/파이썬SW문제해결 List2/4843_special.py
600
3.5
4
def selectionsort(li, x): for i in range(0, x): min_li = i for j in range(i, N): if li[min_li] > li[j]: min_li = j li[i], li[min_li] = li[min_li], li[i] return li T = int(input()) for tc in range(1, T+1): N = int(input()) lists = list(map(int, input().split())) print(f'#{tc}', end=' ') cnt = 0 sorted_lists = selectionsort(lists, 1) for a in range(N, N//2,-1): print(sorted_lists[a-1], end=' ') print(sorted_lists[N-a], end=' ') cnt += 1 if cnt >= 5: break print()
9caf98a84cf6d290cbaf6ea8fcb816f0a1a113ff
jes5918/TIL
/Algorithm/BEAKJOON/4. while/1110.py
452
3.5
4
import sys def pluscycle(a, b, count): count += 1 c = b d = (a + b) % 10 if digit_10 == c and digit_1 == d: return count else: return pluscycle(c, d, count) number = int(sys.stdin.readline()) count = 0 digit_10 = number // 10 digit_1 = number % 10 if 0 <= number < 100: print(pluscycle(digit_10, digit_1, count)) else: print('0보다 크거나 같고, 99보다 작거나 같은 정수를 입력하세요')
0110bb1681a49709787a9e9658dcd81f5d4f02d4
Manikantha-M/python
/basics/functions.py
186
3.546875
4
def fun(): print('ahh') print('ahh2') fun() def fun2(x): return 2*x a=fun2(3) print(a) print(fun2(9)) def fun3(x,y): return x+y e=fun3(5,4) print(e) print(fun3(6,4))
cc8511249b184b15fb4636f493d4318af11af484
Manikantha-M/python
/programs/lcm-list.py
242
3.53125
4
def lcm(x,y): if x>y: x,y=y,x for i in range(y,(x*y)+1,y): if i%x==0: return i l=list(map(int,input().split())) n1=l[0] n2=l[1] lcmf=lcm(n1,n2) for i in range(2,len(l)): lcmf=lcm(lcmf,l[i]) print(lcmf)
1fc339caacbfcd2082e737dfb99dfe2eef05c23e
Manikantha-M/python
/programs/reverse-str.py
61
3.53125
4
s=input('Enter:') rev='' for i in s: rev=i+rev print(rev)
25765c6183a968c6ef857cce53febe4cec561ee5
Manikantha-M/python
/programs/palindrome-num.py
155
3.796875
4
n=int(input('Enter:')) temp=n rev=0 while temp>0: dig=temp%10 rev=rev*10+dig temp//=10 if rev==n: print('Palindrome') else: print('No')
1f891ba81bc7a351543f93b26b51c9f4f3468500
Manikantha-M/python
/programs/perfectnum.py
196
3.5625
4
n=int(input('Enter:')) if n>0: s=0 for i in range(1,n): if n%i==0: s+=i if s==n: print('Perfect number') else: print('No') else: print('No')
4d3b7ec95a5a0c3523b7724968843c749c7c8cfd
zw161917/python-Study
/基础学习/旧文件/函数调用_1.py
426
3.625
4
#调用函数_1--绝对值 print (abs(100)) print (abs(-100)) print (abs(20),abs(-20)) #调用函数_1——最大值 print (max(1,2,3)) print (max(-3,-2,-3)) #调用函数_1——数据类型转换 print (int('123')) print (int (12.76)) print (str(123)) print (str(12.12)) print (float(1)) print (float('11')) #调用函数_1——转换16进制 n1=255 n2=1000 print (hex(255)) print (hex(n2))
2cc68d9b0c8b59733fa4cece8c1e78a51482b941
zw161917/python-Study
/基础学习/旧文件/函数式编程_匿名函数.py
514
4.03125
4
#直接传入匿名函数 lambda代表匿名函数 import functools print(list(map(lambda x: x * x,[1,2,3,4,5,6,7,8,9]))) #把匿名函数当做变量 f = lambda x: x * x print(f) print(f(5)) #把匿名函数当做返回值返回 def build(x,y): return lambda : x * x + y * y fd = build(1,2) print(fd()) #还可以将函数对象 *args **kw int2 = functools.partial(int,base=2) print(int2('1000')) #把所给的数加在左边 max2 = functools.partial(max,10) print(max2(11 ,2,3))
7b32c55a90309e4b8e658c6108dac9952df5a462
pooja89299/loop
/star.py
565
3.875
4
# n=int(input("enter the number")) # i=1 # while i<n: # j=1 # while j<i: # print("*"*j,end="") # j=j+1 # print() # i=i+1 # num=int(input("enter the num")) # if num>10: # print("your gessing low") # elif num==10: # print("your gesing equal") # else: # print( "your gessing high") # i=0 # num=int(input("enter any number")) # while i<num: # if num<5: # print("you guessing game") # elif num==6: # print("your grssing elow") # else: # print("your gessing hight") # i=i+1
0baeac450af1436820d72eacea3309115fb90dd1
znharpaz/MomandDad
/oldDrawing.py
537
3.5
4
import turtle import random h = 10 wn = turtle.Screen() Zach = turtle.Turtle() Hello = turtle.Turtle() Hello.right(180) Zach.speed(100000) Hello.speed(100000) wn.colormode(255) while True: for i in range(10,100000000, 20): a = random.randint(0,256) b = random.randint(0,256) c = random.randint(0,256) Zach.color(a,b,c) Hello.color(a,b,c) Zach.goto(0,0) Zach.circle(i) Hello.goto(0,0) Hello.circle(i) wn.exitonclick()
292786e5944509904615df89d685a6ae16997dc9
itskeithstudent/CTA-Project
/mainy.py
29,420
4.125
4
#Couple skeleton functions to get started with random num generator to start with import numpy as np import time def random_array_generator(array_size, low=0, high=100): ''' random_array_generator - returns numpy random array of defined size over a defined range size of array defined by array_size, minimum value defined by low (defaults to 0) and max value defined by high (defaults to 100) ''' rng = np.random.default_rng() return rng.integers(low, high, size=array_size) def timer_function(sort_function, array_size): ''' timer_fincution - assists benchmarking for different sorting algorithms, returns average over 10 trials of sorting algorithm sorting function to test defined by argument sort_function size of array to test sorting function with defined by array_size array is randomly generated using random_array_generator function calls to sorting function being tested are enclosed by time.time() calls to measure time spent on the sorting algorithm elapsed time is measured 10 times and the average roudned to 3 decimal places is returned ''' time_elapsed_list = [] #list to track time elapsed over 10 runs for i in range(10): test_array = random_array_generator(array_size,0,1000) #generate random numbers over range of 0 to 1000 print(test_array) start_time = time.time()*1000 #start time before function called, multiplied by 1000 to convert to microseconds test = sort_function(test_array) end_time = time.time()*1000 #end time after function finished, multiplied by 1000 to convert to microseconds print(test_array) time_elapsed = end_time - start_time #total time elapsed time_elapsed_list.append(time_elapsed) avg_time_elapsed = sum(time_elapsed_list)/len(time_elapsed_list) #get the average time elapsed return round(avg_time_elapsed,3) #round to 3 decimal places #based off bubble sort from realpython article - https://realpython.com/sorting-algorithms-python/ def bubble_sort(array): ''' bubble_sort - performs buble sort on an array in place takes single argument for array to be sorted ''' #store the length of the array, this will be used to control the loops arr_len = len(array) #outer for loop loops the length of the array - 1 times, the -1 saves us an unecessary loop as if #we did range(arr_len) it would be already sorted when it does the final loop, -1 removes this issue for i in range(arr_len-1): #finished_sort is reset to true on every iteration of the outer loop #if finished_sort is True after exiting inner loop the outer loop is broken out of and function returns finished_sort = True #as iterator i increases the amount of values to be checked in the inner loop decreases #due to the values at the end of the array being sorted and no longer need to be checked for j in range(arr_len-i-1): #if current index j is greater than next index item swap if array[j] > array[j+1]: array[j], array[j+1] = array[j+1], array[j] #swap values at index j and j+1 #have performed a sort during this loop so set finished_sort flag to false finished_sort = False #exit outer for loop and return array if finished_sort: break return array #based off quick sort from - https://www.askpython.com/python/examples/quicksort-algorithm #for quicksort we will use two functions, one for handling the pivot, second for performing the sort def pivot(input_array, start, end): ''' pivot - auxiliary function used by quick_sort function, sorts array into two halves lower and higher than pivot value and returns the index where pivot point is the array to be pivoted is defined by input_array the starting position for the range to pivot over defined by start the end position for the range to pivot over defined by end it performs it's operations on the array in-place so don't need to return the array but does return the index of where the pivot now sits ''' #pivot on first element in the array pivot = input_array[start] #low position is 1+pivot indexin several low = start + 1 #high is last inex in array high = end while True: #checks low is less than high and that high is greater than the pivot while low <= high and input_array[high] >= pivot: #moves high backwards through array as we have value at index high greater than the pivot high = high - 1 #checks low is less than high and that low is less than the pivot while low <= high and input_array[low] <= pivot: #moves low forwards through array low = low + 1 #low will only go greater than high once it's sorted all values lower than the pivot value if low <= high: #swap values at index low and high with one another input_array[low], input_array[high] = input_array[high], input_array[low] #low has become greater than high therefore array has been sorted into low and high halves so exit the loop else: break #lastly swap the pivot element in the array with value for high, this is last index that is in low half #from the while loop we don't break out of it till low exceeds high input_array[start], input_array[high] = input_array[high], input_array[start] return high #based off quick sort from - https://www.askpython.com/python/examples/quicksort-algorithm def quick_sort(input_array, start=0, end=None): ''' quick_sort - main function for performing quick sort algorithm, takes in array to sort and sorts it in place, returns nothing the array to sort is defined by input_array it takes a start position to sort over defined by start (defaults to 0) an end position to sort over defined by end (defaults to None) this function has optional arguments as it is recursive, on first call to quick_sort function these arguments don't need to be supplied on recursive calls these arguments will be provided as it will be performing quick_sort on either half off the pivot ''' #for using timer_function have applied default arguments for start and end #if end is none set it to 1 minus the length of the input_array, otherwise have applied end in recursive call if end == None: end = len(input_array)-1 if start >= end: return True #call pivot piv = pivot(input_array, start, end) #recursively sort left half of array quick_sort(input_array, start, piv-1) #recursively sort right half of array quick_sort(input_array, piv+1, end) #based off count sort from - https://www.mygreatlearning.com/blog/counting-sort/#t10 def count_sort(input_array, max_value = None): ''' count_sort - this function performs a counting sort on an input array not in-place the array to be sorted is defined by input_array the maximum value is an optional argument defined by max_value (defaults to None) if optional argument not provided it will work this out itself as for counting sort to work it needs to know the max value in the array ''' #if no max_value argument supplied get it using the list function max() if max_value is None: max_value = max(input_array) #some code inspiration from here - https://www.w3resource.com/python-exercises/data-structures-and-algorithms/python-search-and-sorting-exercise-10.php #create a list containing only 0's, each 0 represents a value in the range of the input_array # using just 0 in an empty list multiply by the maximum value in the array to create a list of 0's count_list = [0] * (max_value + 1) sorted_list = [] #loop through the input_array, using the current item from input_array as the index of count_list, # increment by 1 for item in input_array: count_list[item] += 1 #using the enumerate function loop through count_list #index keeps track of current index of the list/array #item holds the value at that index for index, item in enumerate(count_list): if item > 0: sorted_list.append([index]*item) return sorted_list #based off insert sort from - https://realpython.com/sorting-algorithms-python/#the-insertion-sort-algorithm-in-python #left and right are necessary arguments due to this function also being used by timsort def insertion_sort(array, left=0, right=None): ''' insertion_sort - performs insertion sort to sort the input array, it works by its own but also as part of a timsort sorting algorithm the input array to sort is defined by array position in the array to start sorting at defined by optional argument left (default 0) end position in the array to sort over defined by optional argument right (default None) ''' #if no right argument supplied determine it from length of array - 1 if right is None: right = len(array) - 1 #loop through the array on indexes from the range of left to right #as we loop through we try to move the value at index i backwards to sort the array, if it has smaller values before it #it stays in place for that loop for i in range(left + 1, right + 1): #key_item is the current value we want to sort key_item = array[i] #j always starts with one index behind the key_item, #we will be checking key_item against every index before it e.g. trying to move it back through the array by comparing it #against values at index j j = i - 1 #loop through items to the left of key_item, til we find an index that has smaller value than key_item #as we loop through we move the value at index j up and for next iteration j is decrimented #this in effect makes room for key_item to replace a value as we shift the value at index j up through the array while j >= left and array[j] > key_item: #set the value at index j+1 = to value at index j #this is done to shift the values up through the array array[j + 1] = array[j] #step back through the array j -= 1 #having looped backwards through the array from the current key_item #and come across the first value smaller than key_item #set key_item as the value at the index j+1 as everything at j and below is sorted correctly compared to key_item array[j + 1] = key_item #lastly return the array, this algorithm is in-place so we don't need to assign a variable to capture the output of this function return array def merge(left, right): ''' merge - this function merges two lists/arrays together, returning a sorted merged array the first array to be merged is defined by left the second array to be merged is defined by right this function is used by the hybrid sorting algorithm function timsort as it is a hybrid algorithm, but could also be applied to a merge_sort function ''' #if either left or right is empty notghin to merge so return if len(left) == 0: return right elif len(right) == 0: return left #result will store the final merged array result = [] index_left = index_right = 0 #loop through left and right arrays until length of result array is equal to the length of the left and right while len(result) < len(left) + len(right): #this assumes the left and right arrays are already sorted #if current item from left is smaller than right append that to result array #otherwise append current item from right if left[index_left] <= right[index_right]: result.append(left[index_left]) index_left += 1 #increment index_left else: result.append(right[index_right]) index_right += 1 #increment index_right #if index_right or index_left equal the length of their array #then have finished merging in that array, so can simply add the remaining array to the #end of result array if index_right == len(right): result += left[index_left:] #result.append(left[index_left:]) break elif index_left == len(left): result += right[index_right:] break return result #based off timsort from - https://realpython.com/sorting-algorithms-python/#the-timsort-algorithm-in-python def timsort(array): ''' timsort - takes in a array to be sorted and sorts it in place takes in a single argument for the array to be sorted defined by array this is a hybrid sorting algorithm so makes use of first insertion sort on slices of the input array (32 in this case) the sorted slices of the array are then merged together using the merge logic from a merge sort algorithm ''' #min_run set to 32 here, this determines the size of slices sorted using insertion sort #also determines the size of blocks to later be merge sorted min_run = 32 #n stores the length of the array n = len(array) #loop from 0 to the size of the array in steps of 32 #this slices up the input array and allows it to perform #insertion sort on slices of the array as insertion sort handles small arrays well for i in range(0, n, min_run): insertion_sort(array, i, min((i + min_run - 1), n - 1)) #Having sorted slices of the array, merge the sorted slices #size doubles on each iteration until size exceeds length of the array #each iteration it will merge and sort each of the slices that were sorte #by insertion sort above size = min_run while size < n: #loop through slices of the input array #merging slices together as it goes for start in range(0, n, size * 2): #midpoint and end used to split current selection into #left and right arrays midpoint = start + size - 1 #end is the minimmum of next slice step or last index to the array #as we don't want to specify an index out of bounds end = min((start + size * 2 - 1), (n-1)) #using defined merge function the two arrays left and right will be merged merged_array = merge( left=list(array[start:midpoint + 1]), right=list(array[midpoint + 1:end + 1])) #replace values from array with merged values # array[start:start + len(merged_array)] = merged_array #at the end of each iteration of the while loop double size #per iteration it will be merge sorting an increasing slice of the array to be sorted # e.g. first iteration merge sort slices [0:32] and [32:64], # next loop it will merge sort slices [0:64] and [64:128] and so on size *= 2 return array if __name__ == '__main__': ''' main - the main function passes each of the sorting algorithms implemented as arguments to the timer function along with different array sizes these sorting algorithms are each tested 10 times with different random arrays with the average elapsed time measured in miliseconds the output of each being printed using formatting to present in a tabular neat layout the run time of each algorithm across different array sizes ''' bubble_avg_time_elapsed_n_100 = timer_function(bubble_sort, 100) ''' bubble_avg_time_elapsed_n_250 = timer_function(bubble_sort, 250) bubble_avg_time_elapsed_n_500 = timer_function(bubble_sort, 500) bubble_avg_time_elapsed_n_750 = timer_function(bubble_sort, 750) bubble_avg_time_elapsed_n_1000 = timer_function(bubble_sort, 1000) bubble_avg_time_elapsed_n_2000 = timer_function(bubble_sort, 2000) bubble_avg_time_elapsed_n_4000 = timer_function(bubble_sort, 4000) bubble_avg_time_elapsed_n_6000 = timer_function(bubble_sort, 6000) bubble_avg_time_elapsed_n_8000 = timer_function(bubble_sort, 8000) bubble_avg_time_elapsed_n_10000 = timer_function(bubble_sort, 10000) print(f"{'Size':<15} {'100':<12} {'250':<12} {'500':<12} {'750':<12} {'1000':<12} {'2000':<12} {'4000':<12} {'6000':<12} {'8000':<12} {'10000':<12}") print(f"{'Bubble Sort':<15} {bubble_avg_time_elapsed_n_100:<12} {bubble_avg_time_elapsed_n_250:<12} {bubble_avg_time_elapsed_n_500:<12} {bubble_avg_time_elapsed_n_750:<12} {bubble_avg_time_elapsed_n_1000:<12} {bubble_avg_time_elapsed_n_2000:<12} {bubble_avg_time_elapsed_n_4000:<12} {bubble_avg_time_elapsed_n_6000:<12} {bubble_avg_time_elapsed_n_8000:<12} {bubble_avg_time_elapsed_n_10000:<12}") ''' ''' qs_avg_time_elapsed_n_100 = timer_function(quick_sort, 100) qs_avg_time_elapsed_n_250 = timer_function(quick_sort, 250) qs_avg_time_elapsed_n_500 = timer_function(quick_sort, 500) qs_avg_time_elapsed_n_750 = timer_function(quick_sort, 750) qs_avg_time_elapsed_n_1000 = timer_function(quick_sort, 1000) qs_avg_time_elapsed_n_2000 = timer_function(quick_sort, 2000) qs_avg_time_elapsed_n_4000 = timer_function(quick_sort, 4000) qs_avg_time_elapsed_n_6000 = timer_function(quick_sort, 6000) qs_avg_time_elapsed_n_8000 = timer_function(quick_sort, 8000) qs_avg_time_elapsed_n_10000 = timer_function(quick_sort, 10000) print(f"{'Quick Sort':<15} {qs_avg_time_elapsed_n_100:<12} {qs_avg_time_elapsed_n_250:<12} {qs_avg_time_elapsed_n_500:<12} {qs_avg_time_elapsed_n_750:<12} {qs_avg_time_elapsed_n_1000:<12} {qs_avg_time_elapsed_n_2000:<12} {qs_avg_time_elapsed_n_4000:<12} {qs_avg_time_elapsed_n_6000:<12} {qs_avg_time_elapsed_n_8000:<12} {qs_avg_time_elapsed_n_10000:<12}") cs_avg_time_elapsed_n_100 = timer_function(count_sort, 100) cs_avg_time_elapsed_n_250 = timer_function(count_sort, 250) cs_avg_time_elapsed_n_500 = timer_function(count_sort, 500) cs_avg_time_elapsed_n_750 = timer_function(count_sort, 750) cs_avg_time_elapsed_n_1000 = timer_function(count_sort, 1000) cs_avg_time_elapsed_n_2000 = timer_function(count_sort, 2000) cs_avg_time_elapsed_n_4000 = timer_function(count_sort, 4000) cs_avg_time_elapsed_n_6000 = timer_function(count_sort, 6000) cs_avg_time_elapsed_n_8000 = timer_function(count_sort, 8000) cs_avg_time_elapsed_n_10000 = timer_function(count_sort, 10000) print(f"{'Count Sort':<15} {cs_avg_time_elapsed_n_100:<12} {cs_avg_time_elapsed_n_250:<12} {cs_avg_time_elapsed_n_500:<12} {cs_avg_time_elapsed_n_750:<12} {cs_avg_time_elapsed_n_1000:<12} {cs_avg_time_elapsed_n_2000:<12} {cs_avg_time_elapsed_n_4000:<12} {cs_avg_time_elapsed_n_6000:<12} {cs_avg_time_elapsed_n_8000:<12} {cs_avg_time_elapsed_n_10000:<12}") is_avg_time_elapsed_n_100 = timer_function(insertion_sort, 100) is_avg_time_elapsed_n_250 = timer_function(insertion_sort, 250) is_avg_time_elapsed_n_500 = timer_function(insertion_sort, 500) is_avg_time_elapsed_n_750 = timer_function(insertion_sort, 750) is_avg_time_elapsed_n_1000 = timer_function(insertion_sort, 1000) is_avg_time_elapsed_n_2000 = timer_function(insertion_sort, 2000) is_avg_time_elapsed_n_4000 = timer_function(insertion_sort, 4000) is_avg_time_elapsed_n_6000 = timer_function(insertion_sort, 6000) is_avg_time_elapsed_n_8000 = timer_function(insertion_sort, 8000) is_avg_time_elapsed_n_10000 = timer_function(insertion_sort, 10000) print(f"{'Insertion Sort':<15} {is_avg_time_elapsed_n_100:<12} {is_avg_time_elapsed_n_250:<12} {is_avg_time_elapsed_n_500:<12} {is_avg_time_elapsed_n_750:<12} {is_avg_time_elapsed_n_1000:<12} {is_avg_time_elapsed_n_2000:<12} {is_avg_time_elapsed_n_4000:<12} {is_avg_time_elapsed_n_6000:<12} {is_avg_time_elapsed_n_8000:<12} {is_avg_time_elapsed_n_10000:<12}") ts_avg_time_elapsed_n_100 = timer_function(timsort, 100) ts_avg_time_elapsed_n_250 = timer_function(timsort, 250) ts_avg_time_elapsed_n_500 = timer_function(timsort, 500) ts_avg_time_elapsed_n_750 = timer_function(timsort, 750) ts_avg_time_elapsed_n_1000 = timer_function(timsort, 1000) ts_avg_time_elapsed_n_2000 = timer_function(timsort, 2000) ts_avg_time_elapsed_n_4000 = timer_function(timsort, 4000) ts_avg_time_elapsed_n_6000 = timer_function(timsort, 6000) ts_avg_time_elapsed_n_8000 = timer_function(timsort, 8000) ts_avg_time_elapsed_n_10000 = timer_function(timsort, 10000) print(f"{'Timsort':<15} {ts_avg_time_elapsed_n_100:<12} {ts_avg_time_elapsed_n_250:<12} {ts_avg_time_elapsed_n_500:<12} {ts_avg_time_elapsed_n_750:<12} {ts_avg_time_elapsed_n_1000:<12} {ts_avg_time_elapsed_n_2000:<12} {ts_avg_time_elapsed_n_4000:<12} {ts_avg_time_elapsed_n_6000:<12} {ts_avg_time_elapsed_n_8000:<12} {ts_avg_time_elapsed_n_10000:<12}") ''' ''' The following section has been commented out as not part of the project brief and it includes several libraries which aren't necessary as part of the project, but it demonstrates how data was collected into dataframes (with pandas) and chart's generated using seaborn libraries lineplot ''' ''' import pandas as pd import matplotlib.pyplot as plt import seaborn as sns #ggplot style for plots plt.style.use('ggplot') df = pd.DataFrame(columns=["Average Run Time (milliseconds)", "Array Size", "Algorithm"]) df = df.append({"Average Run Time (milliseconds)":bubble_avg_time_elapsed_n_100, "Array Size":100, "Algorithm":"Bubble Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":bubble_avg_time_elapsed_n_250, "Array Size":250, "Algorithm":"Bubble Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":bubble_avg_time_elapsed_n_500, "Array Size":500, "Algorithm":"Bubble Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":bubble_avg_time_elapsed_n_750, "Array Size":750, "Algorithm":"Bubble Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":bubble_avg_time_elapsed_n_1000, "Array Size":1000, "Algorithm":"Bubble Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":bubble_avg_time_elapsed_n_2000, "Array Size":2000, "Algorithm":"Bubble Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":bubble_avg_time_elapsed_n_4000, "Array Size":4000, "Algorithm":"Bubble Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":bubble_avg_time_elapsed_n_6000, "Array Size":6000, "Algorithm":"Bubble Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":bubble_avg_time_elapsed_n_8000, "Array Size":8000, "Algorithm":"Bubble Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":bubble_avg_time_elapsed_n_10000, "Array Size":10000, "Algorithm":"Bubble Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":qs_avg_time_elapsed_n_100, "Array Size":100, "Algorithm":"Quick Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":qs_avg_time_elapsed_n_250, "Array Size":250, "Algorithm":"Quick Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":qs_avg_time_elapsed_n_500, "Array Size":500, "Algorithm":"Quick Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":qs_avg_time_elapsed_n_750, "Array Size":750, "Algorithm":"Quick Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":qs_avg_time_elapsed_n_1000, "Array Size":1000, "Algorithm":"Quick Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":qs_avg_time_elapsed_n_2000, "Array Size":2000, "Algorithm":"Quick Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":qs_avg_time_elapsed_n_4000, "Array Size":4000, "Algorithm":"Quick Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":qs_avg_time_elapsed_n_6000, "Array Size":6000, "Algorithm":"Quick Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":qs_avg_time_elapsed_n_8000, "Array Size":8000, "Algorithm":"Quick Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":qs_avg_time_elapsed_n_10000, "Array Size":10000, "Algorithm":"Quick Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":cs_avg_time_elapsed_n_100, "Array Size":100, "Algorithm":"Count Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":cs_avg_time_elapsed_n_250, "Array Size":250, "Algorithm":"Count Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":cs_avg_time_elapsed_n_500, "Array Size":500, "Algorithm":"Count Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":cs_avg_time_elapsed_n_750, "Array Size":750, "Algorithm":"Count Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":cs_avg_time_elapsed_n_1000, "Array Size":1000, "Algorithm":"Count Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":cs_avg_time_elapsed_n_2000, "Array Size":2000, "Algorithm":"Count Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":cs_avg_time_elapsed_n_4000, "Array Size":4000, "Algorithm":"Count Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":cs_avg_time_elapsed_n_6000, "Array Size":6000, "Algorithm":"Count Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":cs_avg_time_elapsed_n_8000, "Array Size":8000, "Algorithm":"Count Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":cs_avg_time_elapsed_n_10000, "Array Size":10000, "Algorithm":"Count Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":is_avg_time_elapsed_n_100, "Array Size":100, "Algorithm":"Insertion Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":is_avg_time_elapsed_n_250, "Array Size":250, "Algorithm":"Insertion Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":is_avg_time_elapsed_n_500, "Array Size":500, "Algorithm":"Insertion Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":is_avg_time_elapsed_n_750, "Array Size":750, "Algorithm":"Insertion Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":is_avg_time_elapsed_n_1000, "Array Size":1000, "Algorithm":"Insertion Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":is_avg_time_elapsed_n_2000, "Array Size":2000, "Algorithm":"Insertion Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":is_avg_time_elapsed_n_4000, "Array Size":4000, "Algorithm":"Insertion Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":is_avg_time_elapsed_n_6000, "Array Size":6000, "Algorithm":"Insertion Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":is_avg_time_elapsed_n_8000, "Array Size":8000, "Algorithm":"Insertion Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":is_avg_time_elapsed_n_10000, "Array Size":10000, "Algorithm":"Insertion Sort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":ts_avg_time_elapsed_n_100, "Array Size":100, "Algorithm":"Timsort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":ts_avg_time_elapsed_n_250, "Array Size":250, "Algorithm":"Timsort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":ts_avg_time_elapsed_n_500, "Array Size":500, "Algorithm":"Timsort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":ts_avg_time_elapsed_n_750, "Array Size":750, "Algorithm":"Timsort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":ts_avg_time_elapsed_n_1000, "Array Size":1000, "Algorithm":"Timsort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":ts_avg_time_elapsed_n_2000, "Array Size":2000, "Algorithm":"Timsort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":ts_avg_time_elapsed_n_4000, "Array Size":4000, "Algorithm":"Timsort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":ts_avg_time_elapsed_n_6000, "Array Size":6000, "Algorithm":"Timsort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":ts_avg_time_elapsed_n_8000, "Array Size":8000, "Algorithm":"Timsort"}, ignore_index=True) df = df.append({"Average Run Time (milliseconds)":ts_avg_time_elapsed_n_10000, "Array Size":10000, "Algorithm":"Timsort"}, ignore_index=True) plt.figure(figsize=(16,6)) normalplot = sns.lineplot(data=df, x="Array Size", y="Average Run Time (milliseconds)", hue="Algorithm", style="Algorithm", markers=True) plt.title('Sort Algorithm Elapsed Time v. Array Size') plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.show() plt.figure(figsize=(16,6)) logplot = sns.lineplot(data=df, x="Array Size", y="Average Run Time (milliseconds)", hue="Algorithm", style="Algorithm", markers=True) logplot.set(yscale="log") plt.title('Sort Algorithm Elapsed Time v. Array Size (Log)') plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.show() '''
87a7bf018c136bd581849c94d94150d043e70581
albertogeniola/TheThing-HostController
/src/HostController/miscellaneus/MacAddress.py
1,906
4.0625
4
import re class MacAddress: """ Wrapper for handling MacAddress. It taks a parameter in the constructor which may be an instance of MacAddress or a string. The class will parse the string/mac and will store it in a fixed format. Using this class everywhere in the code will ensure consistency in the MACAddress representation. """ _mac = None def __init__(self, mac ): # The user is expected to call this method and specify a mac address in a supported syntax. # We will try to "sanitize" those here and provide an uniform string representing that mac. if mac is None: raise Exception("Invalid or unsupported mac address specified.") m = mac if isinstance(mac, str): m = mac elif isinstance(mac, MacAddress): m = str(mac) elif isinstance(mac, unicode): m = str(mac) else: raise ValueError("Invalid mac address specified. Mac address must be either a string or an instance of MACAddress class.") m = m.lower() if re.match('^([0-9a-f]{2}[:-]){5}([0-9a-f]{2})$', m): # This mac is ok. Store it with colons self._mac = m.replace("-","").replace(":","") elif re.match('^[0-9a-f]{12}$', m): # This is a mac address with no separators self._mac = m else: raise Exception("Invalid mac address provided: %s" % m) def __hash__(self): return hash(self._mac) def __eq__(self, other): if isinstance(other, MacAddress): return self._mac == other._mac else: return self._mac == MacAddress(other)._mac def __ne__(self, other): return not self.__eq__(other) def __str__(self, separator=':'): return separator.join(map(''.join, zip(*[iter(self._mac)]*2)))
70a8687994ed41534c9074b2e86f915075f96f26
yurekliisa/BBC
/Server/ChatBot/CLI/cli.py
233
3.5
4
from Bot import ChatBot as bot ob = bot.ChatBot.getBot() i = 0 print("Print exit to leave") while True: text = input("Q : ") if text == 'exit': break print("A : "+ob.response(text)) print("Ended successfully")
dd2474245cce8d7e9dac7f0a6473ee0b1358c9a9
erikluu/Lunar-Module-Game
/src/landerFuncs.py
2,766
3.859375
4
import math def showWelcome(): print("\nWelcome aboard the Lunar Module Flight Simulator\n") print(" To begin you must specify the LM's initial altitude") print(" and fuel level. To simulate the actual LM use") print(" values of 1300 meters and 500 liters, respectively.\n") print(" Good luck and may the force be with you!\n") def getFuel(): fuel = int(input("Enter the initial amount of fuel on board the LM (in liters): ")) while(fuel <= 0): print("ERROR: Amount of fuel must be positive, please try again") fuel = int(input("Enter the initial amount of fuel on board the LM (in liters): ")) return fuel def getAltitude(): altitude = int(input("Enter the initial altitude of the LM (in meters): ")) while(altitude <= 0 or altitude > 9999): print("ERROR: Altitude must be between 1 and 9999, inclusive, please try again") altitude = int(input("Enter the initial altitude of the LM (in meters): ")) return altitude def displayLMState(elapsedTime, altitude, velocity, fuelAmount, fuelRate): #elapsedTime = elapsedTime # plus 1?? WHY DID I PUT THESE HERE?? #fuelAmount = fuelAmount - fuelRate #altitude = altitude + velocity if(elapsedTime == 0): print("\nLM state at retrorocket cutoff") print(f"Elapsed Time: {elapsedTime:4} s") print(f" Fuel: {fuelAmount:4} l") print(f" Rate: {fuelRate:4} l/s") print(f" Altitude: {altitude:7.2f} m") print(f" Velocity: {velocity:7.2f} m/s") def getFuelRate(currentFuel): fuelUsed = int(input("\nEnter fuel rate (0-9, 0=freefall, 5=constant velocity, 9=max thrust): ")) while(fuelUsed > 9 or fuelUsed < 0): print("ERROR: Fuel rate must be between 0 and 9, inclusive\n") fuelUsed = int(input("Enter fuel rate (0-9, 0=freefall, 5=constant velocity, 9=max thrust): ")) return min(fuelUsed, currentFuel) def updateAcceleration(gravity, fuelRate): return (gravity * ((fuelRate/5) - 1)) def updateAltitude(altitude, velocity, acceleration): newAlt = altitude + velocity + (acceleration/2) if(newAlt < 0): return 0 else: return newAlt def updateVelocity(velocity, acceleration): return velocity + acceleration def updateFuel(fuel, fuelRate): x = fuel - fuelRate if(x <= 0): return 0 else: return x def displayLMLandingStatus(velocity): if(velocity <= 0 and velocity >= -1): print("\nStatus at landing - The eagle has landed!") if(velocity < -1 and velocity > -10): print("\nStatus at landing - Enjoy your oxygen while it lasts!") if(velocity <= -10): print("\nStatus at landing - Ouch - that hurt!")
6c89ec5e41a42bae9abdaa042d18852391a1d39f
antcalkins/Capstone
/arguments.py
4,367
3.75
4
""" This code is designed to hash files and create a pandas dataframe that can be referenced by a graphical interface and modified by the user. Authors: L.E. Rogers and A.B. Calkins Last Edited: 16/02/2021""" import hashlib import glob import argparse import pandas as pd from datetime import datetime import platform def read_binary_file(path): """Reads a binary file specified by 'path' and print contents to console.""" file = open(path, 'rb') content = file.read() # Read entire file file.close() md5_hash = hashlib.md5(content).hexdigest() sha256_hash = hashlib.sha256(content).hexdigest() sha1_hash = hashlib.sha1(content).hexdigest() return str(md5_hash) + " " + str(sha256_hash) + " " + str(sha1_hash) def search_function(column, search_term): if dataframe_list.__contains__(column) is True: search = list(dataframe[column]) for i in dataframe.index: if search[i].__contains__(search_term) is True: if search_term == "path parts": search_list = dataframe[column][i] if search_list.__contains__(search_term) is True: print(dataframe.iloc[i]) # have this print in table print(dataframe.iloc[i]) # have this print in table i += 1 else: print("Sorry, that is an invalid column type") operating_system = platform.system() operating_system_version = platform.release() target = "/home/anthony/" # this sets the target directory slash = "" if operating_system == "Windows": if operating_system_version in (8, 8.1, 10): names = glob.glob(target + '**\\*.*', recursive=True) # this goes through every file path inside of the directory slash = "\\" elif operating_system == "Linux": names = glob.glob(target + '**/*.*', recursive=True) # this goes through every file path inside of the directory slash = "/" hashed_dict = {} """This portion of the code checks to see if the database file exists. If not, it will create the database and then allow a user to search the newly created database.""" for i in range(0, len(names)): """This creates the entries for the dictionary with the index being the full paths and the column info being hashes""" try: hashed_dict[names[i]] = read_binary_file(names[i]) except IsADirectoryError or KeyError or FileNotFoundError: pass # Database Generation and manipulation dataframe = pd.DataFrame(list(hashed_dict.items()), columns=['full file paths', 'hashes']) # creates dataframe dataframe[['md5', 'sha256', 'sha1']] = dataframe['hashes'].str.split(expand=True) # splits hashes column dataframe.drop(['hashes'], axis=1, inplace=True) # drops the unnecessary hashes column dataframe[['path parts']] = dataframe['full file paths'].str.split(slash) dataframe_list = list(dataframe.columns) now = datetime.now() file_name = "IHDB_" + now.strftime("%d-%m-%Y_%H-%M-%S") + ".csv" dataframe.to_csv(file_name) # converts dataframe to a csv file print("New database saved as " + file_name) # Argparse begins here """From here on, the following are assumed unless told otherwise via user flag: -File name is the just created file as it is the most current -No columns are specified therefore all columns will be searched for the program -The only thing the user needs to provide is the search term -If no flag is provided you just want to log and thus only a databse will be created""" parser = argparse.ArgumentParser() parser.add_argument("-d", "--database", help="Specify database", action="store_true") parser.add_argument("-l", "--list", help="List existing databases", action="store_true") parser.add_argument("-c", "--hash", help="Search by checksum", action="store_true") args = parser.parse_args() if args.database: args.database() if args.list: db_list = glob.glob("*") for i in range(0, len(db_list)): if db_list[i].__contains__("IHDB"): print(db_list[i]) i += 1 if args.hash: if args.hash().len(32) is True: search_function("md5", args.hash()) elif args.hash().len(40) is True: search_function("sha1", args.hash()) else: search_function("sha256", args.hash()) print("Thank you for using Information Hoarder")
b2b14f37ca46d7819d3585ee650c1f8f3fb03493
osamamohamedsoliman/Linked-List-2
/Problem-4.py
1,014
3.671875
4
# Time Complexity :O(n) # Space Complexity :O(1) # Did this code successfully run on Leetcode : yes # Any problem you faced while coding this : no # Your code here along with comments explaining your approach class Solution(object): def getIntersectionNode(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ lenA = 0 LenB = 0 curr = headA #get length from A while curr: curr = curr.next lenA+=1 curr = headB #get length for B while curr: curr = curr.next LenB +=1 #make the two pointers at the same length from end while lenA> LenB: headA = headA.next lenA-=1 while LenB> lenA: headB = headB.next LenB-=1 #move until reach theinterserction or None while headA != headB: headA = headA.next headB = headB.next return headA
d4594cd71821f49dcbac0068666bbdcd073f5b7d
qisaw/se370_Assignment_2
/drive.py
2,784
3.796875
4
''' Created on 27/08/2013 The underlying Drive class which actually stores all data in a real text file. USE AS IS. NO MODIFICATION WITHOUT PERMISSION. @author: robert ''' import os class Drive(object): ''' A drive. You can be sure that all drives have at least 3 blocks and less than 1000 blocks. ''' BLK_SIZE = 64 EMPTY_BLK = b' ' * BLK_SIZE SEPARATOR = b'\n** **\n' def __init__(self, name, size): ''' "name" is the real file which stores this Drive on the disk. "size" is the number of blocks. ''' self.name = name self.size = size @staticmethod def format(name, size): ''' Creates a Drive object. Associates it with underlying real file. And writes the block information, including block separators, to this file. ''' drive = Drive(name, size) drive.file = open(name, mode='w+b') for n in range(size): separator = Drive.SEPARATOR[:3] + str(n).encode().rjust(3) + Drive.SEPARATOR[6:] drive.file.write(Drive.EMPTY_BLK + separator) drive.file.flush() return drive @staticmethod def reconnect(name): ''' Reconnects an existing real file as a Drive object. ''' if not os.path.exists(name): raise IOError('file does not exist') size = os.path.getsize(name) drive = Drive(name, size // (Drive.BLK_SIZE + len(Drive.SEPARATOR))) drive.file = open(name, mode='r+b') return drive def disconnect(self): ''' Shuts the underlying real file down. ''' self.file.close() def num_blocks(self): ''' Returns the number of blocks in the drive. ''' return self.size def num_bytes(self): ''' Returns the number of "usable" bytes in the drive. ''' return self.size * Drive.BLK_SIZE def write_block(self, n, data): ''' Writes "data" to block "n" of the drive. ''' if n < 0 or n >= self.size: raise IOError('block out of range') if len(data) != Drive.BLK_SIZE: raise ValueError('data not block size') self.file.seek(n * (Drive.BLK_SIZE + len(Drive.SEPARATOR))) written = self.file.write(data) if written != Drive.BLK_SIZE: raise IOError('incomplete block written') def read_block(self, n): ''' Reads and returns block "n" from the drive. ''' if n < 0 or n >= self.size: raise IOError('block out of range') self.file.seek(n * (Drive.BLK_SIZE + len(Drive.SEPARATOR))) return self.file.read(Drive.BLK_SIZE)
a8ecbb89b15e22a9d6587c8429704f234f3cce9e
samineup0710/geneses_pythonassignment3rd
/checkingstring.py
649
3.953125
4
userinput = input("enter a input in strings:") import re """set counters""" upp=0 sc =0 num = 0 """checking and counting""" for ch in userinput: if (ch>='a'and ch<='z'): low = low+1 if(ch>='A' and ch<='Z'): upp = upp+1 if re.match("^[!@#$%^&*()_]*$", ch): #regex checking special character pattern sc = sc+1 if re.match("^[0-9]", ch): num = num+1 print("The num of lowercase char in string is {}".format(low)) print("The num of uppercase char in string is {}".format(upp)) print("The num of special char in string is {}".format(sc)) print("The num of digitnumber in string is {}".format(num))
a5b069842ace8cfab75a81333432b78ff0de0143
Gerrydh/sample-python-code
/Compartmentalisaion2(W6).py
371
3.84375
4
#different way to do compart.py def gcd(x, y): while x != 0 and y != 0: if x > y: x = x % y else: y = y % x if x == 0: return y else: return x print("GCD of 6 and 15:", gcd(6, 15)) z = gcd(221, 323) # dont have to put this in the print line, create new variable- z print("GCD of 221 and 323:", z)
55b9c9b05bcaa82321000ef230e049cab763a7f9
sovello/palindrome
/palindrome_recursive.py
632
4.28125
4
from re import * def reverseChar(word = '' ): reversed_word = '' for letter in word: if len(word) == 1: reversed_word = reversed_word + word else: reversed_word = reversed_word+word[-1] word = word[:len(word)-1] reverseChar(word) return reversed_word word = input("Write some text: ") # determine if the text is palindrome or not reversed_word = sub(r'[^A-Za-z]', "",reverseChar(word)) original_word = sub(r'[^A-Za-z]', "", word) if original_word.lower() == reversed_word.lower(): print("is a palindrome") else: print("is not a palindrome")
d67dcca89e007ebad4fcf36dcbb7736341bc5f22
jimmychen09/practicepython
/Ex25 Guessing game two.py
1,093
4.03125
4
#http://www.practicepython.org/exercise/2015/11/01/25-guessing-game-two.html ''' Game 1 with binary ''' print("Guess a number between 0 and 100") first = 0 last = 101 counter = 0 guesses = [] while True: middle = (first + last)//2 print("Is it...", middle, "?") inp = input("Is it higher, lower or correct? ") counter += 1 guesses.append(middle) if inp == "higher": first = middle elif inp == "lower": last = middle else: break print("So the number is", middle, "and I took", counter, "guesses. They were", guesses) ''' Game 2 with random ''' # import random # print("Guess a number between 0 and 100") # first = 0 # last = 100 # counter = 0 # guesses = [] # while True: # guess = random.randint(first, last) # print("Is it...", guess, "?") # inp = input("Is it higher, lower or correct? ") # counter += 1 # guesses.append(guess) # if inp == "higher": # first = guess + 1 # elif inp == "lower": # last = guess - 1 # else: # break # print("So the number is", guess, "and I took", counter, "guesses. They were", guesses)
8da2fe1e1b0e3f42a2d8e5ff1ce42c725518aa40
jimmychen09/practicepython
/Ex4 Divisors.py
253
3.8125
4
#http://www.practicepython.org/exercise/2014/02/26/04-divisors.html num = int(input("Enter a number: ")) print([i for i in range(1, num + 1) if num % i == 0]) # l = [] # for i in range(1, num + 1): # if num % i == 0: # l.append(i) # print(l)
65ce43ee9a9318d037767a3619483db61556c2ba
jimmychen09/practicepython
/Ex10 List overlap comprehensions.py
235
3.734375
4
#http://www.practicepython.org/exercise/2014/04/10/10-list-overlap-comprehensions.html a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] print([x for x in set(a) for y in set(b) if x == y])
80439cda56f781c192db39cebf41b397d392225e
jimmychen09/practicepython
/Ex3 List less than ten.py
196
3.796875
4
#http://www.practicepython.org/exercise/2014/02/15/03-list-less-than-ten.html a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] num = int(input("Choose a number: ")) print([i for i in a if i < num])
1d88cd26d0b1285ae88a60a8f15a8666a82e1c0e
amitmals/Python-Projects
/PyBanking/PyBank_akm2.py
3,483
3.75
4
#Import the classes #Keep the input file named "budget_data.csv" in the same folder as the python script #Output file name: "Output_File.csv" #Open the input file # Cycle through all the rows (remove header) #Print to terminal and output file import os import csv #open the file budget_data.csv as read only(default) and read it with csv reader csvpath = os.path.join("..", "Resources", "budget_data.csv") with open(csvpath, newline="") as csvfile: csvreader = csv.reader(csvfile, delimiter=",") #initialize my variables total_months=0 net_profit_loss=0 total_profit_loss=0 last_mon_profit_loss = 0 next_mon_profit_loss = 0 average_change = 0 great_increase_mon="" great_decrease_mon="" great_increase_amt=0 great_decrease_amt=0 #remove the header next(csvreader) #cycle thru the rest of the rows for row in csvreader: #increase the counter to count total_months total_months+=1 #for the 1st time the change is 0. so set this_mon_profit_loss and last_mon_profit_loss as the same if total_months == 1: last_mon_profit_loss = int(row[1]) #aggregate the net_profit_loss using += the current month profit loss in row[1] net_profit_loss+=int(row[1]) this_mon_profit_loss = int(row[1]) #aggregate the total_profit_loss using += the current month profit loss in row[1] total_profit_loss +=(this_mon_profit_loss - last_mon_profit_loss) #check if this is the greatest gain if (this_mon_profit_loss-last_mon_profit_loss) > great_increase_amt: great_increase_amt = this_mon_profit_loss-last_mon_profit_loss great_increase_mon = row[0] #check if this is the grestest loss if (this_mon_profit_loss-last_mon_profit_loss) < great_decrease_amt: great_decrease_amt = this_mon_profit_loss-last_mon_profit_loss great_decrease_mon = row[0] #set the value in profit loss as last_mon_profit_loss for the next iteration last_mon_profit_loss=int(row[1]) #average change is the total_profit_loss divided by the intervals (which is total_months-1) average_change = total_profit_loss/(total_months-1) #print out the output to the terminal screen print ("-------------------------------------------------------------") print ("Financial Analysis") print ("-------------------------------------------------------------") print (f'Total Months: {total_months}') print (f'Total: ${net_profit_loss}') print (f'Average Change: ${average_change:.2f}') print (f'Greatest Increase in Profits: {great_increase_mon} (${great_increase_amt})') print (f'Greatest Decrease in Profits: {great_decrease_mon} (${great_decrease_amt})') print ("-------------------------------------------------------------") #Now lets open a file and write out the data to it with open("Output_File.csv", 'w', newline='') as csvfile2: csvwriter = csv.writer(csvfile2, delimiter=',') csvwriter.writerow (['Financial Analysis']) csvwriter.writerow (['Total Months', total_months]) csvwriter.writerow (['Total',"$"+str(net_profit_loss)]) csvwriter.writerow (['Average Change', "$"+str(round(average_change,2))]) csvwriter.writerow (['Greatest Increase in Profits',great_increase_mon,"$"+str(great_increase_amt)]) csvwriter.writerow (['Greatest Decrease in Profits',great_decrease_mon,"$"+str(great_decrease_amt)])
46b26aab885b89f75b6f3f959efb714d0da00ae0
kirtykumari98/Polynomial_Regression
/Polynomial_regression.py
1,201
3.703125
4
#importing the libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt #importing the dataest df=pd.read_csv('Position_Salaries.csv') X=df.iloc[:,1:2].values y=df.iloc[:,2].values #Building the Linear Regression model from sklearn.linear_model import LinearRegression linear_regressor=LinearRegression() linear_regressor.fit(X,y) #Bulding the Polynomial Regression Model from sklearn.preprocessing import PolynomialFeatures poly_regressor=PolynomialFeatures(degree=4) poly_X=poly_regressor.fit_transform(X) poly_regressor.fit(poly_X,y) linear_regressor2=LinearRegression() linear_regressor2.fit(poly_X,y) #Visualising Linear Regression model plt.scatter(X,y,color='red') plt.plot(X,linear_regressor.predict(X),color='blue') plt.title('Linear Regressor') plt.xlabel('Level') plt.ylabel('Salary') plt.show() #Visualising Polynomial Regression Model X_grid=np.arange(min(X),max(X),0.1) X_grid=X_grid.reshape((len(X_grid),1)) plt.scatter(X,y,color='red') plt.plot(X_grid,linear_regressor2.predict(poly_regressor.fit_transform(X_grid)),color='blue') plt.title('Polynomial Regressor') plt.xlabel('Level') plt.ylabel('Salary') plt.show()
9bb6c9536c1e0b422f25163359dce6794e52e136
gnishant01/ShowRenamer
/showRenamer.py
4,307
3.5
4
#------------------------------------------------------------------------------- # Name: ShowRenamer # Purpose: To rename every episode of a TV series, fetching the title of the episode from IMDb # Author: Gaurav Nishant #------------------------------------------------------------------------------- #!/usr/bin/python import urllib, urllib2, os, re from bs4 import BeautifulSoup prefix = "http://www.imdb.com/" # Class for HTML page class Page: pageUrl = '' def __init__(self, url): self.pageUrl = url # this member function returns the soup object from the url def getHtml(self): completeUrl = prefix + self.pageUrl source = urllib2.urlopen(completeUrl) return BeautifulSoup(source, 'html.parser') # function to take tv series name as parameter & return the url of the TV series landing page def findSeriesHomeFromName(seriesName): url = prefix + "find/" data = {} data['q'] = seriesName.lower() data['ref_'] = 'nv_sr_fn' data['s'] = 'all' url_values = urllib.urlencode(data) url = url + '?' + url_values data = urllib2.urlopen(url) x = BeautifulSoup(data, 'html.parser') resultDiv = str(x.find_all("td", { "class" : "result_text" })[0].find('a').get('href')) return resultDiv # function to fetch the names from IMDb and store in the list seasonWiseEpisodes def fetchNamesFromIMDb(): for seasonNumber in range(0, numOfSeasons): print '----- Fetching season', (seasonNumber + 1), 'episode names -----' seasonPage = Page(allSeasonsList[seasonNumber].get('href')) seasonHtml = seasonPage.getHtml() episodeListDiv = seasonHtml.find_all("div", {"class" : "info"}) currentSeasonEpisode = {} for episodeNumber in range(0, len(episodeListDiv)): episodeTitle = episodeListDiv[episodeNumber].strong.get_text() episodeName = seriesName if seasonNumber < 9: episodeName = episodeName + ' ' + 'S0' + str(seasonNumber + 1) else: episodeName = episodeName + ' ' + 'S' + str(seasonNumber + 1) if episodeNumber < 9: episodeName = episodeName + 'E0' + str(episodeNumber + 1) else: episodeName = episodeName + 'E' + str(episodeNumber + 1) episodeName = episodeName + ' - ' + episodeTitle # removing the '/' & '?' characters from filename episodeName = episodeName.replace('/', '-') episodeName = episodeName.replace('?', '!') currentSeasonEpisode[episodeNumber] = episodeName print '----- Season', (seasonNumber + 1), 'episode names fetched -----' seasonWiseEpisodes[seasonNumber] = currentSeasonEpisode # get episode name stored in the seasonWiseEpisodes list def getEpisodeName(seasonNumber, episodeNumber): return seasonWiseEpisodes[seasonNumber - 1][episodeNumber - 1] seriesName = raw_input('Give the series name: ') path = raw_input('Give the series path in your PC: ') homePage = Page(findSeriesHomeFromName(seriesName)) homeHtml = homePage.getHtml() seriesName = homeHtml.find("div", {"class" : "title_wrapper"}).get_text().split('\n')[1].strip() allSeasonsDiv = str(homeHtml.find_all("div", { "class" : "seasons-and-year-nav" })[0]) seasonsListDivHtml = BeautifulSoup(allSeasonsDiv, 'html.parser') allSeasonsList = seasonsListDivHtml.find_all('a') numOfSeasons = int(allSeasonsList[0].get_text()) # reverse the seasonList list for seasonNumber in range(0, int(numOfSeasons / 2)): tempSeason = allSeasonsList[seasonNumber] allSeasonsList[seasonNumber] = allSeasonsList[numOfSeasons - seasonNumber - 1] allSeasonsList[numOfSeasons - seasonNumber - 1] = tempSeason seasonWiseEpisodes = {} fetchNamesFromIMDb() os.chdir(path) count = 0 for subdir, dirs, files in os.walk(path, topdown = False): for i in dirs: dir = os.path.join(path, i) p = re.compile(".*[sS]\D*(\d+).*") x = p.match(i) if x: seasonNum = int(x.group(1)) newDir = os.path.join(path, 'Season ' + str(seasonNum)) os.rename(dir, newDir) os.chdir(subdir) for file in files: if re.match(".*s\D*\d+\D*e\D*\d+.*\..*", file, re.I): p = re.compile(".*[sS]\D*(\d+)\D*[eE]\D*(\d+).*(\..*)") x = p.match(file) seasonNum = int(x.group(1)) episodeNum = int(x.group(2)) extension = x.group(3) try: os.rename(file, getEpisodeName(seasonNum, episodeNum) + extension) count = count + 1 except Exception: print 'Unable to rename file ' + file print 'Total ' + str(count) + ' files renamed'
571b04f2c7074d04c64206675b12b8c3bf4ecdca
lowellmower/nand_to_tetris
/projects/06/A.py
1,329
3.515625
4
import re REGX_A_COMMAND = r"^@(?P<value>\d+)$" class ACommand: """ ACommand is the class responsible for interpreting the A instructions from assembly and converting those to their respecitve binary forms. For a detailed spec see the README.md in the root of this project. Basic A instructions look like: ASSEMBLY: @9 BINARY: 0000000000001001 This binary representation then maps to the instruciton table provided along side this file at: instructions_table.md """ def __init__(self, val): if val > 2**15-1: raise ValueError("%d is too large." % val) self.val = val def __str__(self): return "ACommand: %d" % self.val def opcode(self): return bin(self.val)[2:].zfill(16) def accept(line): return True if re.match(REGX_A_COMMAND, line) else False def new(line): line = line.strip() if not accept(line): raise SyntaxError("Not an A Command", (None, -1, 0, line)) m = re.match(REGX_A_COMMAND, line) value = m.group("value") try: val = int(value) except ValueError: raise SyntaxError("Invalid A Command", (None, -1, 0, line)) try: return ACommand(val) except ValueError: raise SyntaxError("Value for A Command is Invalid.", (None, -1, 0, value))
4aa56ef1e444aa37fdb753292fd868cd6659896b
JonathanRider/calculatorgame
/calculator.py
4,810
3.6875
4
def negative(value = 0): def neg(num): return -1 * num, 1 return neg def reverse(value = 0 ): def reverse_2(num): neg = -1 if num < 0 else 1 num_rev = str(abs(num))[::-1] return int(num_rev) * neg, 1 return reverse_2 def mirror(value = 0): def mirror_2(num): num_rev = str(abs(num))[::-1] return int(str(num) + str(num_rev)), 1 return mirror_2 def sum(value = 0): def sum_2(num): total = 0 numbers = list(str(num).replace("-", "")) for i in range(0, len(numbers)): total = total + int(numbers[i]) return total, 1 return sum_2 def inverse(value = 0): def inv(num): neg = -1 if num < 0 else 1 numbers = list(str(num).replace("-", "")) final = "" for i in range(0, len(numbers)): final = final + str( 10 - int(numbers[i]) % 10 ) return int(final) * neg, 1 return inv def convert (value): def conv(num): return int( str(num).replace(str(value[0]), str(value[1]))), 1 return conv def shiftleft (value = 0): def shift(num): return int(str(num)[1:] + str(num)[:1] ), 1 return shift def shiftright (value = 0): def shift(num): return int(str(num)[-1:] + str(num)[:-1] ), 1 return shift def times(value): def timesnum(num): return value * num, 1 return timesnum def divide(value): def dividenum(num): if(num == (num / value) * value): return num / value, 1 else: return -999999999999, 999 return dividenum def plus(value): def plusnum(num): return value + num, 1 return plusnum def backspace(value = 0): def backspace_2(num): if(len(str(num))) == 1 or ( len(str(num)) == 2 and num < 0 ): return 0, 1 return int(str(num)[:-1]), 1 return backspace_2 def append(value): def appendnum(num): return int(str(num) + str(value)), 1 return appendnum def get_ops(numbers, operations): result = [] for i in range(0, len(numbers)): result.append(operations[i](numbers[i])), 1 return result def allAdd(value): def allAdd_2(num): return num, 1 return allAdd_2 def allAdd_side_effects(value, nums, flags): result = [] for i in range(0, len(nums)): if(flags[i] != 1): result.append(nums[i] + value) else: result.append(nums[i]) return result def store(value = 0): def store_func(num): return num, 0 return store_func def use_store(value = 0): def use_store_func(num, store): return int(str(num) + str(store)), 1 return use_store_func class Tree(object): def __init__(self): self.children = [] self.nums = [] self.ops = [] self.value = None self.store = None self.just_stored = False self.step = None self.parent = None root = Tree() root.step = 0 ALL_ADD_FLAG = 1 STORE_FLAG = 2 USE_STORE_FLAG = 3 ops_high = [plus, store, use_store, negative] flags = [0, STORE_FLAG, USE_STORE_FLAG , 0] root.nums = [-8,0,0,0] root.ops = get_ops(root.nums, ops_high) root.value = 12 moves = 5 end_value = 115 def calculate_children(node): for i in range(0, len(node.ops)): print node.ops[i] nums = node.nums node.children.append(Tree()) node.children[i].parent = node if(flags[i] == STORE_FLAG): if(node.just_stored): node.children[i].step = 9999 # we never want to store twice in a row node.children[i].store = node.value node.children[i].just_stored = True if(flags[i] == USE_STORE_FLAG): if(node.store is None): continue node.children[i].value, num_operations = node.ops[i](node.value, node.store) else: node.children[i].value, num_operations = node.ops[i](node.value) if(flags[i] == ALL_ADD_FLAG): node.children[i].nums = allAdd_side_effects(node.nums[i], node.nums, flags) else: node.children[i].nums = node.nums node.children[i].ops = get_ops(node.children[i].nums, ops_high) if(node.children[i].value == end_value): print("start") print_values(node.children[i]) print("end") node.children[i].step = node.step + num_operations print(node.children[i].step) if(node.children[i].step < moves and node.children[i].value % 1.0 == 0): node.children[i].children = calculate_children(node.children[i]) def print_values(node): print node.value if(node.parent is not None): print node.parent.nums print_values(node.parent) calculate_children(root)
f646e3774ac2343f9c189cb971b06601c93eefa7
himanshu81494/udacity-fsnd-p2
/tournament/tournament.py
3,615
3.828125
4
#!/usr/bin/env python # # tournament.py -- implementation of a Swiss-system tournament # import psycopg2 def connect(): """Connect to the PostgreSQL database. Returns a database connection.""" return psycopg2.connect("dbname=tournament") def deleteMatches(): """Remove all the match records from the database.""" conn = connect() C = conn.cursor() C.execute("DELETE FROM matches") conn.commit() conn.close() def deletePlayers(): """Remove all the player records from the database.""" conn = connect() C = conn.cursor() C.execute("DELETE FROM players") conn.commit() conn.close() def countPlayers(): """Returns the number of players currently registered.""" conn = connect() C = conn.cursor() C.execute("SELECT COUNT(*) AS num FROM players") Row = C.fetchone() if Row: Count = int(Row[0]) conn.close() return Count def registerPlayer(name): """Adds a player to the tournament database. The database assigns a unique serial id number for the player. (This should be handled by your SQL database schema, not in your Python code.) Args: name: the player's full name (need not be unique). """ conn = connect() C = conn.cursor() C.execute("INSERT INTO players(name) VALUES(%s)", (name,)) conn.commit() conn.close() def playerStandings(): """Returns a list of the players and their win records, sorted by wins. The first entry in the list should be the player in first place, or a player tied for first place if there is currently a tie. Returns: A list of tuples, each of which contains (id, name, wins, matches): id: the player's unique id (assigned by the database) name: the player's full name (as registered) wins: the number of matches the player has won matches: the number of matches the player has played """ conn = connect() C = conn.cursor() Query = """ SELECT P.id, P.name, W.WINS, matches_view.match_count FROM players as P LEFT JOIN wins as W ON P.id = W.ID LEFT JOIN matches_view ON P.id = matches_view.ID GROUP BY P.id, W.WINS, matches_view.match_count ORDER BY W.WINS DESC """ C.execute(Query) standings = C.fetchall() conn.close() return standings def reportMatch(Winner, Looser): """Records the outcome of a single match between two players. Args: winner: the id number of the player who won loser: the id number of the player who lost """ conn = connect() C = conn.cursor() C.execute("INSERT INTO matches(winner, looser) VALUES(%s, %s)", (int(Winner), int(Looser))) conn.commit() conn.close() def swissPairings(): """Returns a list of pairs of players for the next round of a match. Assuming that there are an even number of players registered, each player appears exactly once in the pairings. Each player is paired with another player with an equal or nearly-equal win record, that is, a player adjacent to him or her in the standings. Returns: A list of tuples, each of which contains (id1, name1, id2, name2) id1: the first player's unique id name1: the first player's name id2: the second player's unique id name2: the second player's name """ """ 0th position of standings is id 1st position of standings is name match will be in pairs that is why loop has match of i*2-1 and i*2-2 for i has value 1 to total number_of_matches/2 """ standings = playerStandings() CountOfMatches = len(standings)/2 matches_list = list() for i in range(1, CountOfMatches+1): first = i * 2 - 2 second = i * 2 - 1 matches_list.append((standings[first][0], standings[first][1], standings[second][0], standings[second][1])) return matches_list
85f6893ae854200ee989d5b43f217b37f645c7ba
truas/kccs
/python_overview/python_unit_testing/primes.py
793
3.984375
4
class Prime: def is_prime(self,number): """Return True if *number* is prime.""" if number in (0, 1): return False if number < 0: return False # can we combine these last two ? for element in range(2, number): if number % element == 0: return False return True def print_next_prime(self, number): """Print the closest prime number larger than *number*.""" index = number while True: index += 1 if self.is_prime(index): print('The next prime after {0} is {1}'.format(number, index)) return index # Reference for the code: https://jeffknupp.com/blog/2013/12/09/improve-your-python-understanding-unit-testing/
87661803c954900ef11a81ac450ffaaf76b83167
truas/kccs
/python_overview/python_database/database_03.py
1,482
4.375
4
import sqlite3 ''' The database returns the results of the query in response to the cursor.fetchall call This result is a list with one entry for each record in the result set ''' def make_connection(database_file, query): ''' Common connection function that will fetch data with a given query in a specific DB The cursor will be closed at the end of it ''' connection = sqlite3.connect(database_file) cursor = connection.cursor() cursor.execute(query) # if id is available here we can also use cursor.execute(query, [person_id]) results = cursor.fetchall() cursor.close() connection.close() return results def get_name(database_file, person_id): ''' Here we get one specific record according to an ID Different from database_01 we are using variable names to compose our query, just make sure to compose one string at the end ''' query = "SELECT personal || ' ' || family FROM Person WHERE id='" + person_id + "';" results = make_connection(database_file, query) return results[0][0] def get_allnames(database_file): ''' Here we fetch all data in our table, regardless of id ''' query = "SELECT personal || ' ' || family FROM Person;" results = make_connection(database_file, query) return results print("Full name for dyer:", get_name('survey.db', 'dyer')) # specific id partial = get_allnames("survey.db") # all results for item in partial: print(item[0])
5217a281d3ba76965d0cb53a38ae90d16e7d7640
truas/kccs
/python_overview/python_oop/abstract_animal_generic.py
2,001
4.25
4
from abc import ABC, abstractmethod #yes this is the name of the actual abstract class ''' From the documentation: "This module provides the infrastructure for defining abstract base classes (ABCs) in Python" ''' class AbstractBaseAnimal(ABC): ''' Here we have two methods that need to be implemented by any class that extends AbstractBaseAnimal ''' @abstractmethod def feed(self, other_food=None): print("All animals have to feed!") @abstractmethod def sleep(self, state=1): if state == 1: print("This animal needs to sleep") else: print("This animal does not need to sleep") # no abstract, we can implement if we want, but it is not required def exist(self): print("I am alive!") class Dolphins(AbstractBaseAnimal): ''' All the abstract methods need to be implemented otherwise we cannot instantiate any object from this class ''' def __init__(self, food="Fish"): self.food_type = food ''' Note that the abstract functions need to be implemented, even if with 'pass' (try that) We don't need to follow the same signature of the function but it has to be implemented Notice we do not implement the method 'exist()'. Why ? Try to spot the difference between this exist() and the other methods. That's right, exist() is not an abstract method, thus we do not need to implement in our class. ''' # this is an abstract method from our base class def feed(self, alternative=None): print("I like to eat ", self.food_type) print("I can also eat other things, such as ", alternative) # this is an abstract method from our base class def sleep(self, state=-1): if state == 1: print("This animal needs to sleep.") elif state == 0: print("This animal does not need to sleep.") elif state == -1: print("This animal only sleeps with half of the brain.")
a1df134da6c83c138e437c167bec3e3e6043a2c1
truas/kccs
/python_overview/python_oop/polymorphism_alternative.py
985
4.03125
4
class BadCake: def makeCake(self,): print("Making a simple cake") def makeCake(self, stuff): print("Making a simple cake, with " + stuff + " inside") class GoodCake: def makeCake(self,stuff=None): if not stuff: print("Making a simple cake") else: print("Making a simple cake, with " + stuff + " inside") if __name__ == "__main__": ''' when we run this the last function definition will be considered for badCake, so it will be expecting an argument Uncomment line 27 to see the problem Polymorphism is not allowed in python in this way. Use keyword/optional parameters instead ''' badcake = BadCake() goodcake = GoodCake() # badcake.makeCake() ''' Now for our good cake, there is only one function makeCake, and we control the optional parameters there ''' ingredient = input("Provide a special ingredient please: ") goodcake.makeCake(ingredient)
cd1da3a25cc681578afaf342b6441a8c1e98da22
abyanjan/US-Airline-Tweet-Analysis-Dashboard
/app.py
6,145
3.515625
4
import streamlit as st import pandas as pd import numpy as np import plotly.express as px from plotly.subplots import make_subplots import plotly.graph_objects as go from wordcloud import WordCloud, STOPWORDS import matplotlib.pyplot as plt import re from sklearn.feature_extraction.text import CountVectorizer from wordcloud import WordCloud st.set_option('deprecation.showPyplotGlobalUse', False) DATA_URL = ("Tweets.csv") st.title("Sentiment Analysis of Tweets about US Airlines") st.sidebar.title("Sentiment Analysis of Tweets") st.sidebar.markdown("This application is a Streamlit dashboard used " "to analyze sentiments of tweets 🐦") @st.cache(persist=True) def load_data(): data = pd.read_csv(DATA_URL) return data data = load_data() # Options for displaying the type of Analysis analysis_type = st.sidebar.radio( "Select Analysis", options=["Number of Tweets","Display Tweets", "Tweets By Sentiment", "Reasons for Negative Reviews", "Word Cloud"]) # Show the analysis results # Number of tweets if analysis_type == "Number of Tweets": tweet_counts = data.airline.value_counts().to_frame("Counts").rename_axis("Airlines").reset_index() fig = px.bar(tweet_counts, x = "Airlines", y = "Counts", title="Number of Tweets by Airlines") st.plotly_chart(fig) # Display Some Random Tweets if analysis_type == "Display Tweets": col1, col2 = st.beta_columns(2) with col1: airline = st.selectbox("Select Airlines", options = ['All',"American","Delta","Southwest","US Airways", "United","Virgin America"]) with col2: sentiment = st.radio("Select Sentiment Type", options = ["Random","Negative","Positive"]) # filter the data based on the ailrline selected if airline == "All": airline_df = data.copy() else: airline_df = data[data['airline'] == airline] # show 5 random tweets # filter the sentiment if sentiment == "Random": tweets = airline_df['text'] elif sentiment == "Negative": tweets = airline_df[airline_df['airline_sentiment']=='negative']['text'] else: tweets = airline_df[airline_df['airline_sentiment']=='positive']['text'] for tweet in np.random.choice(tweets, 5): st.markdown(tweet) # Tweets by Sentiment Type if analysis_type == "Tweets By Sentiment": col1, col2 = st.beta_columns(2) with col1: airline = st.selectbox("Select Airlines", options=['All',"American","Delta","Southwest","US Airways", "United","Virgin America"]) with col2: chart_type = st.radio("Chart Type", options = ['Bar Chart', "Pie Chart"]) if airline == "All": airline_df = data.copy() else: airline_df = data[data['airline'] == airline] tweet_by_sentiment = airline_df.airline_sentiment.value_counts().to_frame("Counts").rename_axis("Sentiment").reset_index() if chart_type == "Bar Chart": fig = px.bar(tweet_by_sentiment, x = "Sentiment", y = "Counts", title = "Tweets By sentiment") else: fig = px.pie(tweet_by_sentiment,values='Counts', names = "Sentiment") st.plotly_chart(fig) # Reasons for Negative Reviews if analysis_type == "Reasons for Negative Reviews": airline = st.selectbox("Select Airlines", options=['All',"American","Delta","Southwest","US Airways", "United","Virgin America"]) if airline == "All": airline_df = data.copy() else: airline_df = data[data['airline'] == airline] negative_reason_df = airline_df.negativereason.dropna() negative_reason_df = negative_reason_df.value_counts().to_frame(name = "Counts").rename_axis("Reason").reset_index() negative_reason_df.sort_index(axis = 0, level="Counts", ascending=False, inplace=True, ) fig = px.bar(negative_reason_df, x = "Counts", y = "Reason", orientation='h') st.plotly_chart(fig) # Wordcloud # cleant text function def clean_text(text): # remove uername and hastags text = re.sub(r'[@#]\w+', '', text) #remove urls text = re.sub(r'http\S+', '', text) # remove digits text = re.sub(r'[0-9]','', text) # remove any extra white space text = text.strip() return text if analysis_type == "Word Cloud": col1, col2 = st.beta_columns(2) with col1: sentiment_type = st.radio("Select Sentiment Type", options=["Negative", "Positive"]) with col2: ngram = st.radio("Select N-gram", options = [1, 2]) df = data.copy() df['text'] = df['text'].apply(clean_text) # filtering out data for the sentiment type if sentiment_type =="Negative": df = df[df['airline_sentiment'] == 'negative'] else: df = df[df['airline_sentiment'] == 'positive'] # creating word vectors bases on the selected n-grams if ngram == 1: vectorizer = CountVectorizer(lowercase=True, stop_words='english', min_df=2, max_features=2000) else: vectorizer = CountVectorizer(lowercase=True, stop_words='english', min_df=2, max_features=2000, ngram_range=(2,2)) vecs = vectorizer.fit_transform(df['text']) # convert the to data frame count_frame = pd.DataFrame(vecs.todense(), columns = vectorizer.get_feature_names()) # get theword counts for the words word_counts = count_frame.sum(axis = 0) cloud = WordCloud(background_color="white", max_words=100, normalize_plurals=(True)).generate_from_frequencies(word_counts) # display the word cloud if st.button("Show World Cloud"): fig = plt.imshow(cloud) plt.axis('off') st.pyplot()
c3ee005e9bac986eb8155678561dffa728a39c8f
rpalri/declare_terminal
/Declare_WIP.py
6,659
3.703125
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: import itertools import random vals = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'jack', 'queen', 'king', 'ace'] suits = ['spades', 'clubs', 'hearts', 'diamonds'] orig_deck = [list(tup) for tup in itertools.product(vals, suits)] deck = orig_deck[:] player_count = int(input("Enter the number of players: ")) game_count = int(input("Enter the number of games you want to play: ")) # In[ ]: def shuffle_deck(deck): random.shuffle(deck) return deck # In[ ]: def player_names(player_count): players = {} for i in range(player_count): players.update({input("Enter name of Player {}: ".format(str(i+1))) : []}) names = list(players.keys()) game_points = {} for i in players: game_points.update({i : int()}) return names, players, game_points # In[ ]: def deal_cards(player_count, players, deck): dead_deck = [] for p in players: players.update({p : []}) for i in range(4): for j in players: players[j].append(deck[0]) deck.pop(0) players[j].sort() return deck, players # In[ ]: def open_game(start_player, deck, players, names): open_cards = [] for i in range(2): print((i+1), "=", deck[0]) open_cards.append(deck[0]) deck.pop(0) print("\n\n{}'s turn".format(names[start_player])) joker_select = int(input("Pick a Joker from the above two cards (Press 1 or 2 to select the card): ")) joker = open_cards[joker_select-1] open_cards.pop(joker_select-1) top_card = open_cards[0] print("\n\nJoker for the game is:", joker[0]) print("Top card is:", top_card) return joker, top_card, deck #joker, top_card = open_game() # In[ ]: def calc_points(joker, players): points = {} for i in players: points.update({i : int()}) card_point = {'ace' : 1, '2' : 2, '3' : 3, '4' : 4, '5' : 5, '6' : 6, '7' : 7, '8' : 8, '9' : 9, '10' : 10, 'jack' : 10, 'queen' : 10, 'king' : 10} card_point.update({joker[0] : 0}) for i in players: for j in players[i]: points[i] += card_point[j[0]] return points # In[ ]: def same_cards(play_card, players, player, names): same = [] face = players[names[player]][play_card-1][0] for i in range(len(players[names[player]])): if players[names[player]][i][0] == str(face): same.append(players[names[player]][i]) for j in range(len(same)): players[names[player]].remove(same[j]) return same, players # In[ ]: def display_hand(players, names, player): print("Cards in {}'s hand:".format(names[player])) for card in range(len(players[names[player]])): print((card+1), "=", players[names[player]][card]) # In[ ]: def declare(points, player, names): for i in names: if points[i] < points[names[player]]: print("{} has less points than {}. You lose! BAD DECLARE!!".format(i, names[player])) input("Press Enter to continue...") return i return player # In[ ]: def round_points(result, player, points, players, game_points, names): if result == player: for i in players: if i != names[player]: game_points[i] += points[i] game_points[names[player]] += 0 print("\n\n**********\n{} won the round!\n**********\nWHAT A DECLARE!!\n**********".format(names[player])) input("Press Enter to continue...") return game_points else: for i in players: game_points[i] += 0 game_points[names[player]] += sum(points.values()) return game_points # In[ ]: def disp_game_points(game, players, game_points): print("\n\nTally after Round {}:".format(game+1)) for i in players: print("{} has {} points".format(i, game_points[i])) input("Press Enter to continue...") def rotate(lst, x=1): lst[:] = lst[-x:] + lst[:-x] return lst # In[ ]: def game_play(game_count=game_count, orig_deck=orig_deck, player_count=player_count): names, players, game_points = player_names(player_count) #start_player = -1 for game in range(game_count): deck = orig_deck[:] deck = shuffle_deck(deck) deck, players = deal_cards(player_count, players, deck) print("\n\nRound {}".format(game+1)) joker, top_card, deck = open_game(-1, deck, players, names) declare_decision = "" while declare_decision != "Y": for player in range(player_count): print("\n\n{}'s turn".format(names[player])) points = calc_points(joker, players) print("You have {} points.".format(points[names[player]])) display_hand(players, names, player) print("Top card is:", top_card) if points[names[player]] < 10: declare_decision = input("You have {} points. You are eligible to Declare. Do you want to Declare? [Y/N]\n".format(points[names[player]])).upper() if declare_decision == "Y": print("{} declared...".format(names[player])) result = declare(points, player, names) game_points = round_points(result, player, points, players, game_points, names) break play_card = int(input("Select a card to play from the cards in your hand: ")) temp_card, players = same_cards(play_card, players, player, names) pick = int(input("What would you like to pick?\n1 = A card from the deck\n2 = the top card {}\n".format(top_card))) if pick == 1: players[names[player]].append(deck[0]) deck.pop(0) elif pick == 2: players[names[player]].append(top_card) if len(temp_card) > 1: top_card = temp_card[0] else: top_card = temp_card[0] print("\n\nFinal hands:\n") for player in range(player_count): display_hand(players, names, player) input("Press Enter to continue...") disp_game_points(game, players, game_points) names = rotate(names) #start_player += 1 print("\n\nGAME OVER\n\nFinal Tally:") for i in players: print("{} has {} points".format(i, game_points[i])) print("\n\n!!!!!!!!!!\n**********\n\n{}\nWON THE GAME\n\n**********\n\n!!!!!!!!!!".format(min(game_points, key=game_points.get))) # In[ ]: game_play() # In[ ]: # In[ ]:
418aa76b306c3ddd7e502a65ac4098a93a9e352f
chris-tse/Python-Assignment-2
/assn.py
1,092
4.03125
4
# Initialize ID number for ease of testing ID = 112971666 # As written in class def is_prime(n): if n < 2: return False if n == 2: return True else: i = 2 while i*i <= n: if n % i == 0: return False i += 1 return True # Generates powers of 3 starting from 3 ^ 1 def Threes(): n = 1 while(True): yield 3 ** n n += 1 # Function to check for interesting numbers # Sequentially checks numbers after n and subtracts # powers of 3 and checks if difference is prime def interesting(n): test = n + 1 while(True): for i in Threes(): j = test - i if i >= test: break elif is_prime(j): yield test break test += 1 # Test driver for interesting function # N: Starting value # times: Number of values to print out def test_interesting(N, times): count = 0 for i in interesting(N): if count == times: break print(i) count += 1
70fc0e4e7f50a4f821780c521827e448545f37fa
AbdohDev/Pyson
/util/validations.py
1,328
3.84375
4
from user import UserManager, User def username_validation(username): if str(username).__len__() == 0: return False, "Please enter the valid username", None user = UserManager().find_user_by_username(str(username).strip()) if user is None: return False, "User does not exist", None return True, "", user def password_validation(user, password): if str(password).__len__() <= 4: return False, "Password Length should be at least 5 characters" # TODO: you can add here any other validation for password, such as containing at # least one letter or whatever you want if user.password != str(password).strip(): return False, "Enter a correct password" return True, "" def type_validation(user, password, type): if str(type).__len__() <= 4: return False, "Password Length should be at least 5 characters" if user.type != str(2).strip(): return False, "the type is wrong" return True, "" def username_signup(username): print("doing username_signup") if str(username).__len__() == 0: return False, "Please enter the valid username", None user = UserManager().find_user_by_username(str(username).strip()) if user is not None: UserManager().create_user(username) return True, "", username
9620a88aa77292cf0c882521ba2cbe7678c8d879
rjsilmaro/python-project-for-data-engineering
/extract_data_using_API.py
322
3.515625
4
import json import requests import pandas as pd from pandas import json_normalize url = "http://api.exchangeratesapi.io/v1/latest?access_key=87080aa2710f5b6f98b3386c79712e62" data = requests.get(url).text exchange_rate = pd.read_json(data) exchange_rate = exchange_rate["rates"] #print(exchange_rate) exchange_rate.to_csv("exchange_rates_1.csv")
185e34aa22d5e92c7bf133d2cd8240c641df6412
udacity/AIND-Recognizer
/asl_data.py
12,022
3.609375
4
import os import numpy as np import pandas as pd class AslDb(object): """ American Sign Language database drawn from the RWTH-BOSTON-104 frame positional data This class has been designed to provide a convenient interface for individual word data for students in the Udacity AI Nanodegree Program. For example, to instantiate and load train/test files using a feature_method definition named features, the following snippet may be used: asl = AslDb() asl.build_training(tr_file, features) asl.build_test(tst_file, features) Reference for the original ASL data: http://www-i6.informatik.rwth-aachen.de/~dreuw/database-rwth-boston-104.php The sentences provided in the data have been segmented into isolated words for this database """ def __init__(self, hands_fn=os.path.join('data', 'hands_condensed.csv'), speakers_fn=os.path.join('data', 'speaker.csv'), ): """ loads ASL database from csv files with hand position information by frame, and speaker information :param hands_fn: str filename of hand position csv data with expected format: video,frame,left-x,left-y,right-x,right-y,nose-x,nose-y :param speakers_fn: filename of video speaker csv mapping with expected format: video,speaker Instance variables: df: pandas dataframe snippit example: left-x left-y right-x right-y nose-x nose-y speaker video frame 98 0 149 181 170 175 161 62 woman-1 1 149 181 170 175 161 62 woman-1 2 149 181 170 175 161 62 woman-1 """ self.df = pd.read_csv(hands_fn).merge(pd.read_csv(speakers_fn),on='video') self.df.set_index(['video','frame'], inplace=True) def build_training(self, feature_list, csvfilename =os.path.join('data', 'train_words.csv')): """ wrapper creates sequence data objects for training words suitable for hmmlearn library :param feature_list: list of str label names :param csvfilename: str :return: WordsData object dictionary of lists of feature list sequence lists for each word {'FRANK': [[[87, 225], [87, 225], ...], [[88, 219], [88, 219], ...]]]} """ return WordsData(self, csvfilename, feature_list) def build_test(self, feature_method, csvfile=os.path.join('data', 'test_words.csv')): """ wrapper creates sequence data objects for individual test word items suitable for hmmlearn library :param feature_method: Feature function :param csvfile: str :return: SinglesData object dictionary of lists of feature list sequence lists for each indexed {3: [[[87, 225], [87, 225], ...]]]} """ return SinglesData(self, csvfile, feature_method) class WordsData(object): """ class provides loading and getters for ASL data suitable for use with hmmlearn library """ def __init__(self, asl:AslDb, csvfile:str, feature_list:list): """ loads training data sequences suitable for use with hmmlearn library based on feature_method chosen :param asl: ASLdata object :param csvfile: str filename of csv file containing word training start and end frame data with expected format: video,speaker,word,startframe,endframe :param feature_list: list of str feature labels """ self._data = self._load_data(asl, csvfile, feature_list) self._hmm_data = create_hmmlearn_data(self._data) self.num_items = len(self._data) self.words = list(self._data.keys()) def _load_data(self, asl, fn, feature_list): """ Consolidates sequenced feature data into a dictionary of words :param asl: ASLdata object :param fn: str filename of csv file containing word training data :param feature_list: list of str :return: dict """ tr_df = pd.read_csv(fn) dict = {} for i in range(len(tr_df)): word = tr_df.ix[i,'word'] video = tr_df.ix[i,'video'] new_sequence = [] # list of sample lists for a sequence for frame in range(tr_df.ix[i,'startframe'], tr_df.ix[i,'endframe']+1): vid_frame = video, frame sample = [asl.df.ix[vid_frame][f] for f in feature_list] if len(sample) > 0: # dont add if not found new_sequence.append(sample) if word in dict: dict[word].append(new_sequence) # list of sequences else: dict[word] = [new_sequence] return dict def get_all_sequences(self): """ getter for entire db of words as series of sequences of feature lists for each frame :return: dict dictionary of lists of feature list sequence lists for each word {'FRANK': [[[87, 225], [87, 225], ...], [[88, 219], [88, 219], ...]]], ...} """ return self._data def get_all_Xlengths(self): """ getter for entire db of words as (X, lengths) tuple for use with hmmlearn library :return: dict dictionary of (X, lengths) tuple, where X is a numpy array of feature lists and lengths is a list of lengths of sequences within X {'FRANK': (array([[ 87, 225],[ 87, 225], ... [ 87, 225, 62, 127], [ 87, 225, 65, 128]]), [14, 18]), ...} """ return self._hmm_data def get_word_sequences(self, word:str): """ getter for single word series of sequences of feature lists for each frame :param word: str :return: list lists of feature list sequence lists for given word [[[87, 225], [87, 225], ...], [[88, 219], [88, 219], ...]]] """ return self._data[word] def get_word_Xlengths(self, word:str): """ getter for single word (X, lengths) tuple for use with hmmlearn library :param word: :return: (list, list) (X, lengths) tuple, where X is a numpy array of feature lists and lengths is a list of lengths of sequences within X (array([[ 87, 225],[ 87, 225], ... [ 87, 225, 62, 127], [ 87, 225, 65, 128]]), [14, 18]) """ return self._hmm_data[word] class SinglesData(object): """ class provides loading and getters for ASL data suitable for use with hmmlearn library """ def __init__(self, asl:AslDb, csvfile:str, feature_list): """ loads training data sequences suitable for use with hmmlearn library based on feature_method chosen :param asl: ASLdata object :param csvfile: str filename of csv file containing word training start and end frame data with expected format: video,speaker,word,startframe,endframe :param feature_list: list str of feature labels """ self.df = pd.read_csv(csvfile) self.wordlist = list(self.df['word']) self.sentences_index = self._load_sentence_word_indices() self._data = self._load_data(asl, feature_list) self._hmm_data = create_hmmlearn_data(self._data) self.num_items = len(self._data) self.num_sentences = len(self.sentences_index) # def _load_data(self, asl, fn, feature_method): def _load_data(self, asl, feature_list): """ Consolidates sequenced feature data into a dictionary of words and creates answer list of words in order of index used for dictionary keys :param asl: ASLdata object :param fn: str filename of csv file containing word training data :param feature_method: Feature function :return: dict """ dict = {} # for each word indexed in the DataFrame for i in range(len(self.df)): video = self.df.ix[i,'video'] new_sequence = [] # list of sample dictionaries for a sequence for frame in range(self.df.ix[i,'startframe'], self.df.ix[i,'endframe']+1): vid_frame = video, frame sample = [asl.df.ix[vid_frame][f] for f in feature_list] if len(sample) > 0: # dont add if not found new_sequence.append(sample) if i in dict: dict[i].append(new_sequence) # list of sequences else: dict[i] = [new_sequence] return dict def _load_sentence_word_indices(self): """ create dict of video sentence numbers with list of word indices as values :return: dict {v0: [i0, i1, i2], v1: [i0, i1, i2], ... ,} where v# is video number and i# is index to wordlist, ordered by sentence structure """ working_df = self.df.copy() working_df['idx'] = working_df.index working_df.sort_values(by='startframe', inplace=True) p = working_df.pivot('video', 'startframe', 'idx') p.fillna(-1, inplace=True) p = p.transpose() dict = {} for v in p: dict[v] = [int(i) for i in p[v] if i>=0] return dict def get_all_sequences(self): """ getter for entire db of items as series of sequences of feature lists for each frame :return: dict dictionary of lists of feature list sequence lists for each indexed item {3: [[[87, 225], [87, 225], ...], [[88, 219], [88, 219], ...]]], ...} """ return self._data def get_all_Xlengths(self): """ getter for entire db of items as (X, lengths) tuple for use with hmmlearn library :return: dict dictionary of (X, lengths) tuple, where X is a numpy array of feature lists and lengths is a list of lengths of sequences within X; should always have only one item in lengths {3: (array([[ 87, 225],[ 87, 225], ... [ 87, 225, 62, 127], [ 87, 225, 65, 128]]), [14]), ...} """ return self._hmm_data def get_item_sequences(self, item:int): """ getter for single item series of sequences of feature lists for each frame :param word: str :return: list lists of feature list sequence lists for given word [[[87, 225], [87, 225], ...]]] """ return self._data[item] def get_item_Xlengths(self, item:int): """ getter for single item (X, lengths) tuple for use with hmmlearn library :param word: :return: (list, list) (X, lengths) tuple, where X is a numpy array of feature lists and lengths is a list of lengths of sequences within X; lengths should always contain one item (array([[ 87, 225],[ 87, 225], ... [ 87, 225, 62, 127], [ 87, 225, 65, 128]]), [14]) """ return self._hmm_data[item] def combine_sequences(sequences): ''' concatenates sequences and return tuple of the new list and lengths :param sequences: :return: (list, list) ''' sequence_cat = [] sequence_lengths = [] # print("num of sequences in {} = {}".format(key, len(sequences))) for sequence in sequences: sequence_cat += sequence num_frames = len(sequence) sequence_lengths.append(num_frames) return sequence_cat, sequence_lengths def create_hmmlearn_data(dict): seq_len_dict = {} for key in dict: sequences = dict[key] sequence_cat, sequence_lengths = combine_sequences(sequences) seq_len_dict[key] = np.array(sequence_cat), sequence_lengths return seq_len_dict if __name__ == '__main__': asl= AslDb() print(asl.df.ix[98, 1])
657a325906fecd7b706bcc9510d8d3d44ee2420f
Mutugiii/golclinics-dsa
/classwork/01/warm_up.py
676
3.953125
4
# Space complexity O(1) def reverse_helper(A, start_index, end_index): while start_index < end_index: # Python Clever # A[start_index], A[end_index] = A[end_index], A[start_index] # Generic - Using a temporary variable for switch temp = A[start_index] A[start_index] = A[end_index] A[end_index] = temp start_index += 1 end_index -= 1 return A def reverse(A): return reverse_helper(A, 0, len(A) - 1) # Space complexity O(n) def reverse_arr(A): copy_A = [None] * len(A) j = 0 for i in range(len(A) -1, -1, -1): copy_A[j] = A[i] j += 1 return copy_A
4b0e8971211845a0875bf88ba0b23d8ee16204a0
devdgit/Simple_Python_game
/game.py
1,134
4
4
import random class Game: def __init__(self, name, bal): self.name = name self.bal =bal def win(self): winning = random.randint(1,10) #self.bal += winning print "You Won The Game. Points earned: " + str(winning) def lose(self): lossing = random.randint(1,100) self.bal -= lossing print"You Lost The Game. Points lost:" + str(lossing) user_name = raw_input("What is your name?\n").lower() myname = Game(user_name, 10000) if(user_name.isalpha()): print "Welcome " + myname.name + "!!!\n" else: print("NAME SHOULD CONTAIN ONLY ALPHABETS!!") exit(); print "You are being rewarded with 10k points!!!\n" print "Let's play the game!!!" while True: value = random.randint(1,100) n = raw_input("Enter a number between 1 to 100:\n") if value == n: myname.win() print "\nNow your balance is ==>" + str(myname.bal) else: myname.lose() print "\nNow your balance is ==>" + str(myname.bal)
ba3360349707699f6dc244cda93def2efe175230
hadoopaws8/English-letters-python-coding
/prime_numbers_limit.py
243
4.03125
4
lower=int(input("enter lower element: ")) upper=int(input("enter upper element: ")) for i in range(lower,upper): if i>1: for j in range(2,i): if i%j==0: break else: print(i)
5bcf10a630df1bba2580cd255aa92255f9062269
hadoopaws8/English-letters-python-coding
/for_enumerate.py
83
3.71875
4
l=['a','b','c','d','e'] for i,j in enumerate(l): print("index",i,"value",j)
d2f0b746fed613694a66a716a7b580d7d1219414
hadoopaws8/English-letters-python-coding
/E_letter.py
175
3.734375
4
for i in range(5): for j in range(4): if (j==0 or i==0 or i==2 or i==4): print("*",end="") else: print(end=" ") print()
f0c289169c7eea7a8d4675450cda1f36b10c3baf
alexeydevederkin/Hackerrank
/src/main/python/min_avg_waiting_time.py
2,648
4.4375
4
#!/bin/python3 ''' Tieu owns a pizza restaurant and he manages it in his own way. While in a normal restaurant, a customer is served by following the first-come, first-served rule, Tieu simply minimizes the average waiting time of his customers. So he gets to decide who is served first, regardless of how sooner or later a person comes. Different kinds of pizzas take different amounts of time to cook. Also, once he starts cooking a pizza, he cannot cook another pizza until the first pizza is completely cooked. Let's say we have three customers who come at time t=0, t=1, & t=2 respectively, and the time needed to cook their pizzas is 3, 9, & 6 respectively. If Tieu applies first-come, first-served rule, then the waiting time of three customers is 3, 11, & 16 respectively. The average waiting time in this case is (3 + 11 + 16) / 3 = 10. This is not an optimized solution. After serving the first customer at time t=3, Tieu can choose to serve the third customer. In that case, the waiting time will be 3, 7, & 17 respectively. Hence the average waiting time is (3 + 7 + 17) / 3 = 9. Help Tieu achieve the minimum average waiting time. For the sake of simplicity, just find the integer part of the minimum average waiting time. input: 3 0 3 1 9 2 6 output: 9 ''' from queue import PriorityQueue def solve(): queue_arrival = PriorityQueue() queue_cook_time = PriorityQueue() end_time = 0 sum_time = 0 num = int(input()) # parse all data and push it in queue_arrival for i in range(num): arrival, cook_time = [int(x) for x in input().split()] queue_arrival.put((arrival, cook_time)) while True: next_arrival = 0 # pop all arrived by end_time from queue_arrival # push them into queue_cook_time if not queue_arrival.empty(): next_arrival = queue_arrival.queue[0][0] while not queue_arrival.empty() and end_time >= queue_arrival.queue[0][0]: arrival, cook_time = queue_arrival.get() queue_cook_time.put((cook_time, arrival)) # pop 1 item from queue_cook_time or move to next_arrival or break if queue_cook_time.empty(): if queue_arrival.empty(): break end_time = next_arrival continue else: cook_time, arrival = queue_cook_time.get() # add waiting time for it to sum_time # update end_time end_time += cook_time sum_time += end_time - arrival average_time = sum_time // num print(average_time) if __name__ == '__main__': solve()
2bca2de382e9ee902062fdfdef87862fce473ec5
LukeJVinton/pi-projects
/rpesk/morse_code.py
3,114
3.609375
4
# 02_blink_twice.py # From the code for the Electronics Starter Kit for the Raspberry Pi by MonkMakes.com import RPi.GPIO as GPIO import time def word_separation(pin): sleep_time = 7 GPIO.output(pin, False) # True means that LED turns on time.sleep(sleep_time) def pulse(pin, length = "dot"): pulse_time = 0 sleep_time = 1 if length == "dash": pulse_time = 3 elif length == "dot": pulse_time = 1 elif length == "stop": sleep_time = 3 if length != 'stop': GPIO.output(pin, True) # True means that LED turns on time.sleep(pulse_time) # delay 0.5 seconds GPIO.output(pin, False) # True means that LED turns on time.sleep(sleep_time) def get_morse_dictionary(letter): morse_dict = {'a':['dot','dash','stop'], 'b':['dash','dot','dot','dot','stop'], 'c':['dash','dot','dash','dot','stop'], 'd':['dash','dot','dot','stop'], 'e':['dot','stop'], 'f':['dot','dot','dash','dot','stop'], 'g':['dash','dash','dot','stop'], 'h':['dot','dot','dot','dot','stop'], 'i':['dot','dot','stop'], 'j':['dot','dash','dash','dash','stop'], 'k':['dash','dot','dash','stop'], 'l':['dot','dash','dot','dot','stop'], 'm':['dash','dash','stop'], 'n':['dash','dot','stop'], 'o':['dash','dash','dash','stop'], 'p':['dot','dash','dash','dot','stop'], 'q':['dash','dash','dot','dash','stop'], 'r':['dot','dash','dot','stop'], 's':['dot','dot','dot','stop'], 't':['dash','stop'], 'u':['dot','dot','dash','stop'], 'v':['dot','dot','dot','dash','stop'], 'w':['dot','dash','dash','stop'], 'x':['dash','dot','dot','dash','stop'], 'y':['dash','dot','dash','dash','stop'], 'z':['dash','dash','dot','dot','stop'], } return morse_dict[letter] def pulse_letter(letter, pin): if letter == ' ': word_separation(pin) else: pulse_list = get_morse_dictionary(letter) for beep in pulse_list: print(beep) pulse(pin, beep) # Configure the Pi to use the BCM (Broadcom) pin names, rather than the pin positions GPIO.setmode(GPIO.BCM) red_pin1 = 18 GPIO.setup(red_pin1, GPIO.OUT) try: words = input('Enter a word: ') for letter in words: pulse_letter(letter, red_pin1) finally: print("Cleaning up") GPIO.cleanup() # You could get rid of the try: finally: code and just have the while loop # and its contents. However, the try: finally: construct makes sure that # when you CTRL-c the program to end it, all the pins are set back to # being inputs. This helps protect your Pi from accidental shorts-circuits # if something metal touches the GPIO pins.
6033592ae372bada65743cdb8cad06e78b5546a4
EkataShrestha/Python-Assignment
/Assignment 1.py
2,195
4.125
4
print(" ASSIGNMENT-1 ") "-------------------------------------------------------------------------------" print("Exercise 1:---------------------------------------------------") width = 17 height = 12.0 delimiter = '.' ##1. width/2: print("answer number 1 (width/2) is:", width/2) print( type(width/2) ) ##2. width/2.0 print("answer number 2 (width/2.0) is:",width/2.0) print( type(width/2.0) ) ##3. height/3 print("answer number 3 (height/3) is:",height/3) print( type(height/3) ) ##4. 1 + 2 * 5 print("answer number 4 (1 + 2 * 5) is:",1 + 2 * 5) print( type(1 + 2 * 5) ) ##5. delimiter * 5 print("answer number 5 (delimiter * 5) is:",delimiter * 5) print( type(delimiter * 5) ) "-------------------------------------------------------------------------------" print("Exercise 2:-----------------------------------------------------------") Temperature = float(input("Enter temperature in Fahrenheit:")) Celsius = (Temperature - 32)* 5/9 print("Temperature in Celsius: ",Celsius) "-------------------------------------------------------------------------------" print("Exercise 3:-----------------------------------------------------------") SECONDS_PER_MINUTE= 60 seconds= int(input("Enter number of seconds:")) minutes= seconds / SECONDS_PER_MINUTE seconds= seconds % SECONDS_PER_MINUTE print("the duration is:", "%02d minutes and %02d seconds "% (minutes,seconds)) "-------------------------------------------------------------------------------" print("Exercise 4:-----------------------------------------------------------") list= [10,20,30,40,50,60,70,80] print("List of elements are:", list) print("length of list:", len(list)) print("first element of the list:", list[0]) print("fourth element of the list:", list[3]) "-------------------------------------------------------------------------------" print("Exercise 5:-----------------------------------------------------------") list= [10,20,30,40,50,60,70,80] print("List of elements are:", list) print("poping last element:", list.pop()) print(list) print("inserting '90' in 5th position:", list.insert(5,90)) print(list) print("removing '20' element from the list:", list.remove(20)) print(list)
cc84e0ef270f72f7acf08475e170077d7f250080
16030IT028/smartinterviewspreperation
/checksubsequence.py
734
3.703125
4
"""Given 2 strings A and B, check if A is present as a subsequence in B. Input Format First line of input contains T - number of test cases. Its followed by T lines, each line contains 2 space separated strings - A and B. Constraints 1 <= T <= 1000 1 <= len(A), len(B) <= 1000 'a' <= A[i],B[i] <= 'z' Output Format For each test case, print "Yes" if A is a subsequence of B, "No" otherwise, separated by new line. Sample Input 0 2 data gojdaoncptdhzay algo plabhagqogxt Sample Output 0 Yes No""" n=int(input()) for _ in range(n): a,b=input().split() l=len(a) m=len(b) i=j=0 while i<l and j<m: if a[i]==b[j]: i+=1 j+=1 if i==l: print("Yes") else: print("No")
146e6eebe52e4c88787f2e276ef58aa463dd6ccd
gemking/COMProj1-
/venv/Scripts/parsermodRevised1.py
33,474
3.703125
4
import sys import re with open(sys.argv[1], "r") as file: #opens file filelines = file.read().splitlines() # reads file and splits lines file.close() #closes file insideComment = 0 keywords = ["if", "else", "while", "int", "float", "void", "return"] #denotes all keywords symbols = "\/\*|\*\/|\+|-|\*|//|/|<=|<|>=|>|==|!=|=|;|,|\(|\)|\{|\}|\[|\]" #denotes symbols used comparisonSymbols = "<" or "<=" or ">" or ">=" or "==" or"!=" #holds relational operations addSubtractSymbols = "+" or "-" #holds addition and subtraction operations multiplyDivideSymbols = "*" or "/" #holds multiplication and division operations characters = "[a-zA-Z]+" #obtains all words for the IDs digits = "[0-9]+(\.[0-9]+)?([eE][-+]?[0-9]+)?" #gets all decimal values, including integer values 0-9 errors = "\S" #reports errors token = [] # creates a list that holds all of the tokens x = 0 #value that holds the token counter for the parser for importantLines in filelines: #receiving importantlines from filelines importantLine = importantLines #sets importantLine to importantLines if not importantLine: continue # if not an important line, it continues through the file list = "(%s)|(%s)|(%s)|(%s)" % (characters, digits, symbols, errors) # puts entire library into a list of strings for word in re.findall(list, importantLine): #finds list if re.match(characters, word[0]) and insideComment == 0: #matches characters and makes sure insideComment is 0 if word[0] in keywords: token.append(word[0]) #keyword is constructed out of characters a-zA-Z else: token.append(word[0]) #appends character values that are not keywords elif re.match(digits,word[1]) and insideComment == 0: #matches digits and makes sure inside comment is 0 if "." in word[1]: token.append(word[1]) #checks if value is a decimal value and appends elif "E" in word[1]: token.append(word[1]) #checks if value is an expontential value and appends else: token.append(word[1]) #appends integer value elif re.match(symbols, word[4]): #matches symbols if "/*" in word[4]: #Checks when word approaches /* insideComment = insideComment + 1 #increments insideComment if inside elif "*/" in word[4] and insideComment > 0: #Checks when word approaches */ insideComment = insideComment - 1 #decrements insideComment if outside elif "//" in word[4] and insideComment == 0: #If neither break elif insideComment == 0: #when inside counter is 0 if "*/" in word[4]: #when it reaches terminal */ if "*/*" in importantLine: #when it's still sorting through comments token.append("*") insideComment += 1 continue #skips comments and continue through the program else: token.append("*") #appends multiplication symbol token.append("/") #appends division symbol else: # print t[5] token.append(word[4]) #appends rest of symbols elif word[3] and insideComment == 0: #matches errors and makes sure insideComment is 0 # print "ERROR:", t[6] token.append(word[3]) #appends error # ----- end of lexer ----- # token.append("$") #appended to determine when the program is done programming checkMain = 0 #checks if there is 1 main function checkLastMain = 0 #check if the last function is main finished = 0 exception0 = 0 exception1 = 0 exceptionReturn = 0 parameterMatch = 0 parameter = 0 variableDeclaration = [] #list which holds declared scope, type, and variables variableType = [] #list that holds the type of variables variableOperation = [] #checks for operator and operand agreement vars = [] #list to hold all of the declared variables varsScope = [] #list of all variable scopes varsScopeBlock = [] #list of all variable scopes in bllock number functionDeclaration =[] #list to hold declared functions with parms/arguments functionIndex = 0 #index to keep track of apramters/arguments functionCall = [] #functions called functionCallArguments = [] #list of argument types in a function's paramters functionNames = [] #list of all function names functionTypes = [] #list of all function types functionName = 0 #function name for scope functionType = 0 #function type and sees if ti needs return currentScope = 0 #current scope functionReturn = 0 # does function have a return? functionReturnIntFloat = 0 #check if int/float function has return # ----- beginning of parser ----- # def hasnum(inputstring): return any(char.isdigit() for char in inputstring) def programDeclaration(): #runs program(Rule 1) global completed declarationList() if "$" in token[x]: finished = 1 #continues outside else: print ("REJECT") #if not, Reject def declarationList(): #Rule 2 declaration() declarationListPrime() def declarationListPrime(): #Rule 3 if "int" in token[x] or "void" in token[x] or "float" in token[x]: declaration() declarationListPrime() elif "$" in token[x]: return else: return def declaration(): #Rule 4 global x global checkMain global checkLastMain global currentScope global functionName global functionType global functionReturn typeSpecifier() w = token[x].isalpha() if token[x] not in keywords and w is True: if "main" in token[x]: #if main is in the file checkMain += 1 checkLastMain += 1 if token[x-1] != "void": #if void is not in the file print("REJECT") exit(0) else: checkLastMain = 0 x += 1 # Accepts ID if ";" in token[x]: x += 1 # Accepts ; m = 0 for duplicates in vars: #checking for duplicates of declared variables if duplicates in token[x-2]: if variableType in token[x-3]: print("REJECT") exit(0) m += 1 variableDeclaration.append(token[x-3] + " " + token[x-2] + " global 0") vars.append(token[x-2]) variableType.append(token[x-3]) varsScope.append("global") varsScopeBlock.append(0) if "void" in token[x-3]: print("REJECT") exit(0) elif "[" in token[x]: x += 1 # Accepts [ m = 0 for duplicates in vars: #checking for duplicates of declared variables if duplicates in token[x-2]: if variableType in token[x-3]: print("REJECT") exit(0) m += 1 variableDeclaration.append(token[x - 3] + " " + token[x - 2] + " global 0") vars.append(token[x - 2]) variableType.append(token[x - 3]) varsScope.append("global") varsScopeBlock.append(0) if "void" in token[x-3]: print("REJECT") exit(0) z = hasnum(token[x]) if z is True: x += 1 # Accepts NUM/FLOAT declarationPrime() if "]" in token[x]: x += 1 # Accepts ] if ";" in token[x]: x += 1 # Accepts ; else: print("REJECT") exit(0) else: print("REJECT") exit(0) else: print("REJECT") exit(0) def declarationPrime(): #Rule 5 global x typeSpecifier() #variableDeclaration() w = token[x].isalpha() if token[x] not in keywords and w is True: x += 1 # Accepts ID else: return if "(" in token[x]: x += 1 # Accepts ( for duplicates in functionDeclaration: # check if there is duplicates of declared functions if duplicates in token[x - 2]: print("REJECT") exit(0) functionDeclaration.append(token[x - 3] + " " + token[x - 2]) functionName = token[x - 2] functionNames.append(token[x - 2]) functionTypes.append(token[x - 3]) functionType = token[x - 3] functionReturn = 0 currentScope = 0 parameters() if ")" in token[x]: x += 1 #Accepts ) compoundStatement() if 0 in functionReturn and "int" in functionType: print ("REJECT") exit(0) elif 0 in functionReturn and "float" in functionType: print("REJECT") exit(0) else: functionReturn = 0 else: print("REJECT") exit(0) else: print("REJECT") exit(0) def variableDeclaration(): #Rule 6 global x typeSpecifier() w = token[x].isalpha() if token[x] not in keywords and w is True: x += 1 # Accepts ID m = 0 for duplicates in vars: #check for duplicated declared variables if duplicates in token[x-1]: if functionName in varsScope[m]: if currentScope <= varsScopeBlock[m]: print ("REJECT") exit(0) m += 1 variableDeclaration.append(token[x-2] + " " + token[x-1] + " " + str(functionName) + " " + str(currentScope)) vars.append(token[x-1]) variableType.append(token[x-2]) varsScope.append(functionName) varsScopeBlock.append(currentScope) if "void" in token[i-2]: # check if ID is type void print("REJECT") exit(0) else: print("REJECT") exit(0) variableDeclarationPrime() def variableDeclarationPrime(): #Rule 7 global x if ";" in token[x]: x += 1 # Accepts ; elif "[" in token[x]: x += 1 # Accepts [ w = hasnum(token[x]) if w is True: x += 1 # Accepts NUM/FLOAT if "." in token[x-1]: # check for float in the array declaration print("REJECT") exit(0) if "E" in token[x-1]: #check for float in the array declaration print("REJECT") exit(0) if "]" in token[x]: x += 1 # Accepts ] if ";" in token[x]: x += 1 # Accepts ; return else: print("REJECT") exit(0) else: print("REJECT") exit(0) else: print("REJECT") exit(0) else: print("REJECT") exit(0) # checking to see if in keyword throws an error during the execution of the program def typeSpecifier(): #Rule 8 global x if "int" in token[x] or "void" in token[x] or "float" in token[x]: x += 1 # Accepts int/void/float else: return def parameter(): #Rule 9 global x typeSpecifier() w = token[x].isalpha() if token[x] not in keywords and w is True: x += 1 # Accepts ID else: return parameterPrime() def parameterPrime(): #Rule 10 global x global currentScope global functionName typeSpecifier() functionDeclaration[functionIndex] - functionDeclaration[functionIndex] + " " + token[x-1] functionCallArguments.append("") functionCallArguments[functionIndex] = functionCallArguments[functionIndex] + " " + token[x-1] w = token[x].isalpha() if token[x] not in keywords and w is True: x += 1 #Accepts ID functionDeclaration[functionIndex] = functionDeclaration[functionIndex] + " " + token[x-1] m = 0 g = 0 gh = 0 cz = 0 for duplicates in vars: #check for duplicate declared variables and with scope if duplicates in token[x-1]: if "global" not in varsScope[m] and functionName not in varsScope[m]: #may not work cz = 1 continue if "global" in varsScope[m]: m = g gh = 1 break m += 1 currentScope = 1 if not varsScope: cz = 1 if 0 in cz and "global" in varsScope[m] and 1 in gh: #may not work variableDeclaration.append(token[x-2] + " " + token[x-1] + " global 0") vars.append(token[x-1]) vartype.append(token[x-2]) varsScope.append("global") varsScopeBlock.append(0) else: variableDeclaration.append(token[i-2] + " " + token[i-1] + " " + str(functionName) + " " + str(currentScope)) vars.append(token[i-1]) variableType.append(token[i-2]) varsScope.append(functionName) varsScopeBlock.append(currentScope) currentScope = 0 if "[" in token[x]: x += 1 # Accepts [ if "]" in token[x]: x += 1 # Accepts ] return else: print("REJECT") exit(0) else: return else: if "void" in token[x-1]: return else: print("REJECT") exit(0) def parameters(): #Rule 11 global x global functionIndex if "int" in token[x] or "float" in token[x]: parametersList() elif "void" in token[x]: x += 1 # Accepts void parametersPrime() functionIndex += 1 else: print("REJECT") exit(0) def parametersPrime(): #Rule 12 global x typeSpecifier() w = token[x].isalpha() if token[x] not in keywords and w is True: x += 1 # Accepts ID parameterPrime() parametersListPrime() else: return def parametersList(): #Rule 13 parameter() parametersListPrime() def parametersListPrime(): #Rule 14 global x if "," in token[x]: x += 1 # Accepts , parameter() parametersListPrime() elif ")" in token[x]: return else: return def compoundStatement(): #Rule 15 global x if "{" in token[x]: x += 1 # Accepts { currentScope += 1 else: return localDeclarations() statementList() if "}" in token[x]: x += 1 # Accepts } else: print("REJECT") exit(0) def localDeclarations(): #Rule 16 localDeclarationsPrime() def localDeclarationsPrime(): #Rule 17 if token[x] == "void" or token[x] == "float" or token[x] == "int": variableDeclaration() localDeclarationsPrime() else: return def statementList(): #Rule 18 statementListPrime() def statementListPrime(): #Rule 19 w = token[x].isalpha() z = hasnum(token[x]) if token[x] not in keywords and w is True: statement() statementListPrime() elif z is True: statement() statementListPrime() elif "(" in token[x] or ";" in token[x] or "{" in token[x] or "if" in token[x] or "while" in token[x] or "return" in token[x]: statement() statementListPrime() elif "}" in token[x]: return else: return def statement(): #Rule 20 w = token[x].isalpha() z = hasnum(token[x]) if token[x] not in keywords and w is True: expressionStatement() elif z is True: expressionStatement() elif "(" in token[x] or ";" in token[x]: expressionStatement() elif "{" in token[x]: compoundStatement() elif "if" in token[x]: selectionStatement() elif "while" in token[x]: iterationStatement() elif "return" in token[x]: returnStatement() else: print("REJECT") exit(0) def expressionStatement(): #Rule 21 global x w = token[x].isalpha() z = hasnum(token[x]) if token[x] not in keywords and w is True: expressionPrime() if ";" in token[x]: x += 1 # Accepts ; else: print("REJECT") exit(0) elif z is True: expressionPrime() if ";" in token[x]: x += 1 # Accepts ; else: print("REJECT") exit(0) elif "(" in token[x]: expressionPrime() if ";" in token[x]: x += 1 # Accepts ; else: print("REJECT") exit(0) elif ";" in token[x]: x += 1 # Accepts ; else: print("REJECT") exit(0) def selectionStatement(): #Rule 22 global x if "if" in token[x]: x += 1 # Accepts if else: return if "(" in token[x]: x += 1 # Accepts ( else: print("REJECT") exit(0) expressionPrime() if ")" in token[x]: x += 1 # Accepts ) else: print("REJECT") exit(0) statement() selectionStatementPrime() def selectionStatementPrime(): #Rule 23 global x if "else" in token[x]: x += 1 # Accepts else statement() else: return def iterationStatement(): #Rule 24 global x if "while" in token[x]: x += 1 # Accepts while else: return if "(" in token[x]: x += 1 # Accepts ( else: print("REJECT") exit(0) expressionPrime() if ")" in token[x]: x += 1 # Accepts ) else: print("REJECT") exit(0) statement() def returnStatement(): #Rule 25 global x global functionReturn if "return" in token[x]: x += 1 # Accepts return if "int" in functionType: functionReturn = 1 else: functionReturn = 1 else: return returnStatementPrime() def returnStatementPrime(): #Rule 26 global x global functionReturn global exceptionReturn global expressionType w = token[x].isalpha() z = hasnum(token[x]) if ";" in token[x]: x += 1 # Accepts ; if "void" not in functionType: #may not work; check if int or float function does not return value print("REJECT") exit(0) return elif token[x] not in keywords and w is True: if "void" in functionType: #Check if void has return with value print("REJECT") exit(0) if "int" in functionType: expressionType = "int" else: expressionType = "float" exceptionReturn = 1 expressionPrime() exceptionReturn = 0 if ";" in token[x]: x += 1 # Accepts ; return else: print("REJECT") exit(0) elif z is True: if "void" in functionType: # check if void has return with value print("REJECT") exit(0) if "int" in functionType: expressionType = "int" else: expressionType = "float" exceptionReturn = 1 expressionPrime() exceptionReturn = 0 if ";" in token[x]: x += 1 # Accepts ; return else: print("REJECT") exit(0) elif "(" in token[x]: expressionPrime() if ";" in token[x]: x += 1 # Accepts ; return else: print("REJECT") exit(0) else: print("REJECT") exit(0) def expression(): #Rule 27 global x global exception0 global exception1 global expressionType global parameter global parameterMatch if "=" in token[x]: x += 1 # Accepts = m = 0 for duplicates in vars: #find the type of the first ID for the expression if v in token[x-2]: expressionType = variableType[m] exception0 = 1 k += 1 expressionPrime() exception0 = 0 elif "[" in token[x]: x += 1 # Accepts [ expressionType = "int" exception1 = 1 expressionPrime() exception1 = 0 if "[" in token[x-1]: print("REJECT") exit(0) if "]" in token[x]: x += 1 # Accepts ] if "=" in token[x]: x += 1 # Accepts = expressionPrime() elif multiplyDivideSymbols in token[x]: termPrime() addExpressionPrime() simpleExpressionPrime() elif addSubtractSymbols in token[x]: addExpressionPrime() if comparisonSymbols in token[x]: comparisonOperation() addExpression() elif comparisonSymbols in token[x]: comparisonOperation() addExpression() else: return else: print("REJECT") exit(0) elif "(" in token[x]: x += 1 # Accepts ( m = 0 for duplicates in functionNames: if token[i-2] in v: break m += 1 arguments() parameter = 0 r = 0 if not parameterMatch: r = 1 if 0 in r and parameterMatch not in functionCallArguments[m]: print("REJECT") exit(0) if ")" in token[x]: x += 1 # Accepts ) if multiplyDivideSymbols in token[x]: termPrime() addExpressionPrime() simpleExpressionPrime() elif addSubtractSymbols in token[x]: addExpressionPrime() if comparisonSymbols in token[x]: comparisonOperation() addExpression() elif comparisonSymbols in token[x]: comparisonOperation() addExpression() else: return else: print("REJECT") exit(0) elif multiplyDivideSymbols in token[x]: termPrime() addExpressionPrime() simpleExpressionPrime() # error begins elif addSubtractSymbols in token[x]: addExpressionPrime() simpleExpressionPrime() elif comparisonSymbols in token[x]: comparisonOperation() addExpression() else: return def expressionPrime(): #Rule 28 global x global expressionType global exception0 global exception1 global exceptionReturn global parameterMatch global parameter w = token[x].isalpha() z = hasnum(token[x]) if token[x] not in keywords and w is True: x += 1 # Accepts ID if 1 in parameter: q = 0 for duplicates in vars: #get the type of the var for operand/operator checking if token[x-1] in duplicates: check = variableType[q] q += 1 parameterMatch = parameterMatch + " " + check if 1 in exception0 and 0 in parameter: if "(" in token[x]: q = 0 check = 0 for duplicates in functionNames: #get the type of the function for operand/operator checking if token[x-1] in v: check = functionTypes[q] q += 1 if check not in expressionType: print("REJECT") exit(0) if 1 in exceptionReturn: q = 0 check = 0 for duplicates in vars: #get the type of the var for operand/operator checking if token[x-1] in duplicates: check = variableType[q] q += 1 if check not in expressionType: print("REJECT") exit(0) if "(" in token[x] and 0 in exceptionReturn and 0 in parameter: if token[x-1] not in functionNames: print("REJECT") exit(0) cz = 0 m = 0 for duplicates in vars: #check for duplicate declared variables if v in token[x-1]: if functioName not in varsScope[m] and "global" not in varsScope[m]: cz = 1 if functionName in varsScope[m]: cz = 0 m += 1 if token[x-1] not in vars and "(" not in token[x]: print("REJECT") exit(0) if 1 in cz: print("REJECT") exit(0) expression() elif "(" in token[x]: x += 1 # Accepts ( expressionPrime() if ")" in token[x]: x += 1 # Accepts ) termPrime() addExpressionPrime() if "==" in token[x] or "<=" in token[x] or ">=" in token[x] or "!=" in token[x] or "<" in token[x] or ">" in token[x]: simpleExpressionPrime() elif addSubtractSymbols in token[x]: addExpressionPrime() if "==" in token[x] or "<=" in token[x] or ">=" in token[x] or "!=" in token[x] or "<" in token[x] or ">" in token[x]: simpleExpressionPrime() elif "==" in token[x] or "<=" in token[x] or ">=" in token[x] or "!=" in token[x] or "<" in token[x] or ">" in token[x]: simpleExpressionPrime() else: return else: print("REJECT") exit(0) elif z is True: x += 1 # Accepts NUM/FLOAT if 1 in parameter: if "." in token[x-1]: parameterMatch = parameterMatch + " float" elif "E" in token[x-1]: parameterMatch = parameterMatch + "float" else: parameterMatch = parameterMatch + " int" cz = 0 if "." in token[x-1]: cz = 1 if "E" in token[x-1]: cz = 1 if 1 in exceptionReturn and 1 in cz: if "float" not in expressionType: print("REJECT") exit(0) if 1 in exceptionReturn and 0 in cz: if "int" not in expressionType: print("REJECT") exit(0) if 1 in exception1 and "E" in token[x-1]: print("REJECT") exit(0) if 1 in exception1 and "." in token[x-1]: print("REJECT") exit(0) if leftExpression == 1: if 1 is not cz and "float" in expressionType: if "." not in token[x-1] and "E" not in token[x+1]: print("REJECT") exit(0) termPrime() addExpressionPrime() if "==" in token[x] or "<=" in token[x] or ">=" in token[x] or "!=" in token[x] or "<" in token[x] or ">" in token[x]: simpleExpressionPrime() elif addSubtractSymbols in token[x]: addExpressionPrime() if "==" in token[x] or "<=" in token[x] or ">=" in token[x] or "!=" in token[x] or "<" in token[x] or ">" in token[x]: simpleExpressionPrime() elif "==" in token[x] or "<=" in token[x] or ">=" in token[x] or "!=" in token[x] or "<" in token[x] or ">" in token[x]: simpleExpressionPrime() else: return else: print("REJECT") exit(0) def variable(): #Rule 29 global x w = token[x].isalpha() if token[x] not in keywords and w is True: x += 1 # Accepts ID else: return variablePrime() def variablePrime(): #Rule 30 if "[" in token[x]: x += 1 # Accepts [ expressionPrime() if "]" in token[x]: x += 1 # Accepts ] else: print("REJECT") exit(0) else: return def simpleExpression(): #Rule 31 addExpression() simpleExpressionPrime() def simpleExpressionPrime(): #Rule 32 if "==" in token[x] or "<=" in token[x] or ">=" in token[x] or "!=" in token[x] or "<" in token[x] or ">" in token[x]: comparisonOperation() addExpression() else: return def comparisonOperation(): #Rule 33 global x if "==" in token[x] or "<=" in token[x] or ">=" in token[x] or "!=" in token[x] or "<" in token[x] or ">" in token[x]: x += 1 # Accepts <=, <, >, >=, ==, or != else: return def addExpression(): #Rule 34 term() addExpressionPrime() def addExpressionPrime(): #Rule 35 if "-" in token[x] or "+" in token[x]: addOperation() term() addExpressionPrime() else: return def addOperation(): #Rule 36 global x if "-" in token[x] or "+" in token[x]: x += 1 # Accepts +, - else: return def term(): #Rule 37 factor() termPrime() def termPrime(): #Rule 38 if "/" in token[x] or "*" in token[x]: multiplyOperation() factor() termPrime() else: return def multiplyOperation(): #Rule 39 global x if "/" in token[x] or "*" in token[x]: x += 1 # Accepts *, / else: return def factor(): #Rule 40 global x global exceptionReturn global exception0 w = token[x].isalpha() z = hasnum(token[x]) if token[x] not in keywords and w is True: x += 1 # Accepts ID if expressionReturn == 0: q = 0 cz = 0 for duplicates in vars: #get the type of the var for operand/operator checking if token[x-1] in v: if "global" not in varsScope[q] and functionName not in varsScope[q]: cz = 1 if functionName in varsScope[q]: cz = 0 check = variableType[q] break check = variableType[q] q += 1 if check not in expressionType: print("REJECT") exit(0) if 1 in cz: print("REJECT") exit(0) if expressionReturn == 1: q = 0 for duplicates in vars: #get the type of the var for operand/operator checking if token[i-1] in duplicates: check = variableType[q] q += 1 if check not in expressionType: print("REJECT") exit(0) if "[" in token[x]: x += 1 # Accepts [ expressionPrime() if "]" in token[x]: x += 1 # Accepts ] else: return elif "(" in token[x]: x += 1 # Accepts ( arguments() if ")" in token[x]: x += 1 # Accepts ) else: return else: return elif z is True: x += 1 # Accepts NUM/FLOAT elif "(" in token[x]: x += 1 # Accepts ( expressionPrime() if ")" in token[x]: x += 1 # Accepts ) else: return else: print("REJECT") exit(0) def factorPrime(): #Rule 41 global x w = token[x].isalpha() if token[x] not in keywords and w is True: x += 1 # Accepts ID if "(" in token[x]: x += 1 # Accepts ( arguments() if ")" in token[x]: x += 1 # Accepts ) else: print("REJECT") exit(0) else: print("REJECT") exit(0) else: return variablePrime() def arguments(): #Rule 42 global x w = token[x].isalpha() z = hasnum(token[x]) if token[x] not in keywords and w is True: argumentsList() elif z is True: argumentsList() elif "(" in token[x]: argumentsList() elif ")" in token[x]: return else: return def argumentsList(): #Rule 43 global parameter global parameterMatch parameterMatch = "" parmeter = 1 expressionPrime() argumentslistPrime() def argumentslistPrime(): #Rule 44 global x if "," in token[x]: x += 1 # Accepts , expressionPrime() argumentslistPrime() elif ")" in token[x]: return else: return # ----- end of parser ------ # programDeclaration() #Starts parsing the print(variableDeclaration) print(functionDeclaration) if checkMain == 1 and checkLastMain == 1: #check if contains 1 main function print("ACCEPT") else: print("REJECT")
2b1ca91c21fffbb99c3dc411fd9d507df9923096
vccabral/crashncompile
/parse_inputs.py
730
3.515625
4
#!/Users/bracero/code/crashncompile/venv/bin/python from sys import stdin remove_new_lines = True split_by_char = True special_character = "#" remove_empty_last_cell = True remove_all_empty = True def get_rid_of_newlines(str1): return str1[0:-1] def split_by_special_char(str_arr): accum = [[]] for str1 in str_arr: if str1 == special_character: accum.append([]) else: if remove_all_empty and str1=="": pass else: accum[len(accum)-1].append(str1) if remove_empty_last_cell and accum[-1] == []: accum.pop() return accum data = stdin.readlines() if remove_new_lines: data = map(get_rid_of_newlines,data) if split_by_char: data = split_by_special_char(data) print(data)
90b380c2f84d1b9d56d68224aaae9d58e31ae7ba
Sammyuel/LeetcodeSolutions
/islands2.py
1,558
3.921875
4
from collections import deque class Solution(object): def append_if(self, queue, x, y): """Append to the queue only if in bounds of the grid and the cell value is 1.""" if 0 <= x < len(self.grid) and 0 <= y < len(self.grid[0]): if self.grid[x][y] == '1': queue.append((x, y)) def mark_neighbors(self, row, col): """Mark all the cells in the current island with value = 2. Breadth-first search.""" queue = deque() queue.append((row, col)) while queue: x, y = queue.pop() self.grid[x][y] = '2' self.append_if(queue, x - 1, y) self.append_if(queue, x, y - 1) self.append_if(queue, x + 1, y) self.append_if(queue, x, y + 1) def numIslands(self, grid): """ :type grid: List[List[str]] :rtype: int """ if not grid or len(grid) == 0 or len(grid[0]) == 0: return 0 self.grid = grid row_length = len(grid) col_length = len(grid[0]) island_counter = 0 for row in range(row_length): for col in range(col_length): if self.grid[row][col] == '1': # found an island island_counter += 1 self.mark_neighbors(row, col) return island_counter if __name__ == '__main__': grid = """11000 11000 00100 00011""" grid = [list(line) for line in grid.splitlines()] print(Solution().numIslands(grid))
7f39eac47889ee3645f3f99610784fb3d1ccbb6b
Sammyuel/LeetcodeSolutions
/reorderlist.py
983
3.78125
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reorderList(self, head): if not head or not head.next: return slow = head fast = head.next previoous = None while fast and fast.next: previous = slow slow = slow.next fast = fast.next.next new_head = slow.next slow.next = None nextNode = new_head.next new_head.next = None while nextNode: old_head = new_head new_head = nextNode nextNode = nextNode.next new_head.next = old_head ptr = head ptr2 = new_head while ptr and ptr2: next_ptr = ptr.next next_ptr2 = ptr2.next ptr.next = ptr2 ptr2.next = next_ptr ptr2 = next_ptr2 ptr = next_ptr
e3064817ccf6b20632485a1c1cd52864d3dfc6fe
felipesavaris/pythonstuds
/s3.3-coleçoes-python/a26-listas.py
3,162
4.34375
4
""" listas -> são como vertores/matrizes; são dinâmicas e podem armazenar qualquer tipo de dados listas aceitam repetição ex: lista = [] """ # funções interessantes: """ # verificar se valor está contido na lista num = 8 if num in lista_4: print(f'{num} -> Número encontrado.') else: print(f'{num} -> Não encontrado.') # função de ordenação de lista -> sort lista_1.sort() print(lista_1) # função para contar número de ocorrências -> count print(lista_1.count(1)) # função para adiconar elemento -> append lista_1.append(6) print(lista_1) # função para adicionar mais de um elemento a lista -> extend lista_1.extend([7, 8, 9]) print(lista_1) # função para adicionar elemento informando a posição da lista (não substiui o valor original) lista_1.insert(0, 0) print(lista_1) # função para imprimir inversa lista_1.reverse() print(lista_1) # função para copiar elementos da lista -> copy lista_6 = lista_2.copy() print(lista_6) # função para contar elementos da lista -> len print(len(lista_6)) # função remover último elemento -> pop lista_6.pop() # obs: retorna o elemento excluído print(lista_6) # também é possível remover pelo índice -> pop(2) lista_6.pop(0) print(lista_6) # função remover toda a lista -> clear lista_6.clear() print(lista_6) # função para transformar string em lista string = 'Felipe Savaris: Desenvolvedor Python' lista_dev = string.split() print(lista_dev) string = string.split(':') print(string) # função para transformar lista em string lista_7 = ['Felipe', 'Savaris:', 'Desenvolvedor', 'Python'] string_dev = ' '.join(lista_7) print(string_dev) # alterar caracter de um string string = 'Felipe.Savaris:.Desenvolvedor.Python' string_dev = string.replace('.', ' ') print(string_dev) # ---------------------------------------------------------------- # iterando entre lista soma = 0 for i in lista_1: print(i) soma = soma + i print(f'Total: {soma}') soma = '' for i in lista_2: soma = soma + i print(f'Total: {soma}') # ---------------------------------------------------------------- carrinho = [] produto = '' while produto != 'sair': print("Informe o produto a ser adicionado ou digite 'sair' para encerrar.") produto = input("Digite aqui: ") if produto != 'sair': carrinho.append(produto) for produto in carrinho: print(produto) # em listas faz acesso de forma indexada cores = ['verde', 'azul', 'preto', 'branco'] print(cores[1]) print(cores[-2]) print('----------------------') indice = 0 while indice < len(cores): print(cores[indice]) indice = indice + 1 # gerar indice em um for for indice, cor in enumerate(cores): print(indice, cor) # função para descobrir qual é o indice de um determinado elemento da lista -> index print(cores.index('azul')) print(cores.index('azul, 1) # começa a buscar o indice a partir da posição 1 da lista """ lista_1 = [1, 2, 3, 4, 5, 1, 2] lista_2 = ['F', 'e', 'l', 'i', 'p', 'e', ' ', 'S', 'a', 'v', 'a'] lista_3 = [] lista_4 = list(range(11)) lista_5 = list("Felipe Savaris") cores = ['verde', 'azul', 'preto', 'branco'] # parei o vídeo em: 1h 51min 28s
767125d9ac4d1bee62d953f2f20bc49740d7a4fa
xlii0064/algorithms
/year2/dijkstra/roadPath.py
23,454
4.0625
4
class Vertex: def __init__(self,u): """ Functionality of the function is to make instance of vertex Time complexity:O(1) Space complexity:O(1) Error handle:None Precondition:u must be a number :param u: the index number of the vertex to be made """ self.u=u self.adj=[] self.hasCamera=False self.hasService=False def addEdge(self,edge): """ Functionality of the function is to add an edge into this vertex's list Time complexity:O(1) Space complexity:O(1) Error handle:None Precondition: a vertex instance has been made :param edge: the edge to be inserted in the list :return: None """ self.adj.append(edge) def __str__(self): """ Functionality of the function is to generate all the information in this vertex to a string Time complexity:O(len(adj)) Space complexity:O(1) Error handle:None Precondition:a vertex instance has been made :return: a string that contains all the edges and attributes in this vertex """ string=str(self.u)+"->"+str(self.hasCamera)+"->" if len(self.adj)==0: return string+"[]" for i in range (len(self.adj)-1): string+=str(self.adj[i])+"," string+=str(self.adj[len(self.adj)-1]) return string class Edge: def __init__(self,u,v,w): """ Functionality of the function is to create an instance of the class Edge Time complexity:O(1) Space complexity:O(1) Error handle:None Precondition:u,v,w must be numbers :param u: the vertex index which is the starting point :param v: the end vertex :param w: the weight of this edge """ self.u=u self.v = v self.w=w self.hasToll=False def __str__(self): """ Functionality of the function is to generate all the information in this edge to a string Time complexity:O(1) Space complexity:O(1) Error handle:None Precondition:an edge instance has been made :return: the string that contains all the attributes in this edge """ return "("+str(self.v)+","+str(self.w)+","+str(self.hasToll)+")" class Graph: def __init__(self): self.graph=[] self.largest=0 self.serviceList=[] self.reverseGraph=[] self.reverseGraphLargest=0 def buildGraph(self,filename_roads): """ Functionality of the function is to generate the graph using the information from the file Time complexity:O(E) since all the edges in the file should be inserted in this graph Space complexity:O(E) since all the edges in the file should be inserted in this graph Error handle: If the file is invalid, print the error message and return Precondition:a graph instance has been created :param filename_roads: the file that contains all the possible roads :return:None """ try: open(filename_roads, "r") except: print("Invalid file") return file = open(filename_roads, "r") lines = file.read().split("\n") for i in range(len(lines)): lines[i] = lines[i].split(" ") lines[i][0] = int(lines[i][0]) lines[i][1] = int(lines[i][1]) lines[i][2] = float(lines[i][2]) u=Vertex(lines[i][0]) edge=Edge(lines[i][0],lines[i][1],lines[i][2]) self.largest=self.insert(u, edge,self.largest,self.graph) def insert(self,vertex,edge,largest,graph): """ Functionality of the function is to insert the new edge into this graph Time complexity:O(1) in best case where the vertex to be inserted in already existed.O(v) in the worst case where the edge contains the largest vertex in the file and there's nothing in the graph yet Space complexity:O(1) in best case where the vertex to be inserted in already existed.O(v) in the worst case where the edge contains the largest vertex in the file and there's nothing in the graph yet Error handle: None Precondition: an instance of the graph has already been created :param vertex: where the edge should be inserted in :param edge: the edge to be inserted :param largest: the largest index of the vertex in the graph :param graph: the graph to be inserted in :return: the new index of the largest vertex """ if edge.v>=largest: for i in range (largest,edge.v+1,1): graph.append(Vertex(i)) largest=edge.v+1 if vertex.u>=largest: for i in range (largest,vertex.u+1,1): graph.append(Vertex(i)) largest=vertex.u+1 graph[vertex.u].addEdge(edge) return largest def dijkstra(self,source,target,graph,largest,whole): """ Functionality of the function is to find the shortest path to some the target using dijkstra algorithm Time complexity:O(ElogV) since inserting takes O(logV) and for E edges the algorithm would loop through E times Space complexity:O(E+V) since the input graph would be O(E+V) Error handle:print error message and return if the target and source are not int Precondition:the graph instance has been created :param source: the start node of the path :param target: the end node of the path :param graph: the graph to be explored :param largest: the largest vertex in the graph :param whole: whether the function needs to return a whole finalized list or it can stop as soon as it has finalized the target :return: a list contains the finalized list, the list contains the index of the vertices in the heap and if it is possible to reach the target from source or not """ try: source = int(source) target = int(target) except: print("source and target must be numbers") return possible = False discovered = [[source, 0]] finalized = [] vertices = [-2 for _ in range(largest + 1)] vertices[source] = 0 while len(discovered) > 0: if vertices[target] == -1: possible = True if not whole: break u = discovered[0][0] for edgeIndex in range(len(graph[u].adj)): edge = graph[u].adj[edgeIndex] vPos = vertices[edge.v] uPos = vertices[edge.u] if vPos == -2: item = [edge.v, discovered[uPos][1] + edge.w, edge.u] discovered = self.heapInsert(discovered, item, vertices) else: if discovered[vPos][1] > discovered[uPos][1] + edge.w: if vPos != -1: discovered[vPos][1] = discovered[uPos][1] + edge.w discovered[vPos][2] = edge.u finalized.append(discovered[0]) self.heapRemoveSmallest(discovered, vertices) return [finalized,vertices,possible] def quickestPath(self,source,target): """ Functionality of the function is to find the shortest path from the source to the target Time complexity:O(ElogV) since inserting takes O(logV) and for E edges the algorithm would loop through E times Space complexity:O(E+V) since the input graph would be O(E+V) Error handle:print error message and return if the target and source are not int Precondition:the graph instance has been created :param source:the start node of the path :param target: the end node of the path :return: return [[],-1] if it is impossible to reach target from source. Else return (path,time) """ try: source = int(source) target = int(target) except: print("source and target must be numbers") result=self.dijkstra(source,target,self.graph,self.largest,False) finalized=result[0] vertices=result[1] possible=result[2] if vertices[target] == -1: possible = True if possible: quickest=self.findPath(finalized,source) else: return [[],-1] time=finalized[len(finalized)-1][1] return (quickest,time) def heapInsert(self,heap,item,vertices): """ Functionality of the function is to insert the item into the heap Time complexity:O(logv) for worst case and O(1) for best case where the item is the largest one in the heap Space complexity:O(v) for the list vertices Error handle:None Precondition:the heap must be a valid min heap :param heap: where the item should be inserted in :param item: the item to insert :param vertices: the vertices' list that contains all indexes of the vertices in the heap :return: return a heap that contains the newly added item """ heap.append(item) if (len(heap))==1: vertices[item[0]]=0 return heap vertices[item[0]]=len(heap)-1 index=len(heap)-1 parent=(index-1)//2 while parent>=0: if heap[index][1]<heap[parent][1]: heap[index],heap[parent]=heap[parent],heap[index] vertices[heap[index][0]],vertices[heap[parent][0]]=vertices[heap[parent][0]],vertices[heap[index][0]] index=parent parent=(index-1)//2 else: break vertices[item[0]]=index return heap def heapRemoveSmallest(self,heap,vertices): """ Functionality of the function is to remove the smallest one in the heap Time complexity:O(logv) for worst case and O(1) for best case where the all the values in the heap are all the same Space complexity:O(v) for the list vertices Error handle: None Precondition: the heap is a min heap :param heap: the heap to be removed the smallest :param vertices: the vertices' list that contains all indexes of the vertices in the heap :return: None """ vertices[heap[0][0]]=-1 if len(heap)==1: heap.pop() return vertices[heap[len(heap)-1][0]] =0 heap[0]=heap[len(heap)-1] heap.pop() if len(heap)>0: self.down(heap,0,vertices) def down(self, heap, index, vertices): """ Functionality of the function is to move down the node until it is a valid heap Time complexity:O(logv) for worst case and O(1) for best case where the all the values in the heap are all the same Space complexity:O(v) for the list vertices Error handle: None Precondition: the list vertices contains all the correct indexes of the vertices in the heap :param heap: the heap to be modified :param index: the index of the node to be adjusted :param vertices:the vertices' list that contains all indexes of the vertices in the heap :return: None """ left=index*2+1 right=index*2+2 if right>=len(heap): if left>=len(heap): return heap else: minIdex=left else: if heap[left][1]<=heap[right][1]: minIdex=left else: minIdex=right if heap[index][1]>heap[minIdex][1]: heap[index],heap[minIdex]=heap[minIdex],heap[index] vertices[heap[index][0]], vertices[heap[minIdex][0]]= vertices[heap[minIdex][0]], vertices[heap[index][0]] self.down(heap, minIdex, vertices) def findPath(self,final,source): """ Functionality of the function is to find all the vertices that made the shortest path Time complexity:O(V) in the worst case and O(1) in the best case where the target directly connects with the source node Space complexity:O(V) same as the input final list Error handle:None Precondition: the source node is in the final list :param final: the list that contains all the possible nodes in the shortest path :param source: the source node that starts the path :return: a list that contains all the nodes of the shortest path """ index=len(final)-1 result = [final[index][0]] if index==0: return result prev=final[index][2] while final[index][0]!=source: #O(V) if final[index][0]==prev: result.append(prev) prev=final[index][2] index-=1 result.append(source) result.reverse() return result def augmentGraph(self,filename_camera,filename_toll): """ Functionality of the function is to generate the graph so it can indicate if a vertex has cameras or an edge has tolls Time complexity: O(E) since it needs to go through every edge to generate the graph Space complexity: O(E+V) same as the input graph Error handle:print error message and return if the file is invalid Precondition: a graph that contains all the nodes in the file has been created :param filename_camera: the file that contains all the nodes that has cameras :param filename_toll: the file that contains all the edges that has tolls :return: None """ try: open(filename_toll, "r") open(filename_camera,"r") except: print("Invalid file") return camera_file = open(filename_camera, "r") cameras = camera_file.read().split("\n") toll_file = open(filename_toll, "r") tolls = toll_file.read().split("\n") for index in range(len(cameras)): cameras[index]=int(cameras[index]) vertexIndex=cameras[index] self.graph[vertexIndex].hasCamera=True for index in range (len(tolls)): tolls[index]=tolls[index].split(" ") tolls[index][0]=int(tolls[index][0]) tolls[index][1] = int(tolls[index][1]) uIndex=tolls[index][0] vIndex=tolls[index][1] for edge in range (len(self.graph[uIndex].adj)): if self.graph[uIndex].adj[edge].v ==vIndex: self.graph[uIndex].adj[edge].hasToll=True def quickestSafePath(self,source,target): """ Functionality of the function is to find the shortest from the source to the target that doesn't contain any cameras or tolls Time complexity:O(ElogV) since dijkstra using min heap will use O(ElogV) time Space complexity: O(E+V) same as the input graph print error message and return if the target and source are not int Precondition:the graph instance has been created :param source:the start node of the path :param target: the end node of the path :return: return [[],-1] if it is impossible to reach target from source. Else return (path,time) """ try: source = int(source) target = int(target) except: print("source and target must be numbers") possible=False discovered=[[source,0]] finalized=[] vertices=[-2 for i in range (self.largest+1)] vertices[source]=0 while len(discovered)>0: if vertices[target]==-1: possible=True break u=discovered[0][0] for edgeIndex in range (len(self.graph[u].adj)): edge=self.graph[u].adj[edgeIndex] vPos = vertices[edge.v] uPos = vertices[edge.u] #if u and v don't have cameras and this edge doesn't have a toll valid=self.graph[u].hasCamera==False and edge.hasToll==False and self.graph[edge.v].hasCamera==False if vPos==-2 and valid: item=[edge.v,discovered[uPos][1]+edge.w,edge.u] discovered=self.heapInsert(discovered,item,vertices) else: if valid: if discovered[vPos][1]>discovered[uPos][1]+edge.w: if vPos!=-1: discovered[vPos][1]=discovered[uPos][1]+edge.w discovered[vPos][2]=edge.u finalized.append(discovered[0]) self.heapRemoveSmallest(discovered,vertices) if vertices[target] == -1: possible = True if possible: quickest=self.findPath(finalized,source) else: return [[],-1] time=finalized[len(finalized)-1][1] return (quickest,time) def addService(self, filename_service): """ Functionality of the function is to add the service to the graph according to the file and generate a reverse graph Time complexity:O(E) for generating a reverse graph Space complexity:O(V+E) same as the input graph Error handle: print error message and return if the file is invalid Precondition: a graph that contains all the nodes in the file has been created :param filename_service: the file that contains all the service points :return: None """ try: open(filename_service, "r") except: print("Invalid file") return service_file = open(filename_service, "r") services = service_file.read().split("\n") self.serviceList=services for index in range (len(services)): services[index]=int(services[index]) servicePos=services[index] self.graph[servicePos].hasService=True for vertexIndex in range(len(self.graph)): for edge in self.graph[vertexIndex].adj: u = Vertex(edge.v) e=Edge(edge.v,edge.u,edge.w) self.reverseGraphLargest= self.insert(u,e,self.reverseGraphLargest,self.reverseGraph) def quickestDetourPath(self, source, target): """ Functionality of the function is to find the shortest path that contains at least one node that has services Time complexity:O(Elogv) since the dijkstra would take ElogV time and other loops take V time which is less than ElogV Space complexity:O(E+V) since the input graph would be O(E+V) Error handle: print error message and return if one of the source and target is not a number Precondition: a graph that contains source and target has been made :param source: the source node to start the path :param target: the end node of the path :return: return [[],-1] if it is impossible to reach target from source. Else return (path,time) """ try: source = int(source) target = int(target) except: print("source and target must be numbers") #O(ElogV) result=self.dijkstra(source,target,self.graph,self.largest,True) finalized=result[0] result2=self.dijkstra(target,source,self.reverseGraph,self.reverseGraphLargest,True) reverseFinalized=result2[0] newFinalized=[0 for _ in range(len(self.graph))] for index in range (len(finalized)): #O(V) vertexID=finalized[index][0] newFinalized[vertexID]=finalized[index] newReverseFinalized=[0 for _ in range(len(self.graph))] for index in range (len(reverseFinalized)): #O(V) vertexID=reverseFinalized[index][0] newReverseFinalized[vertexID]=reverseFinalized[index] path=[0 for _ in range (len(self.graph))] for item in range (len(newFinalized)): #O(V) if newFinalized[item]!=0 and newReverseFinalized[item]!=0: newFinalized[item][1]+=newReverseFinalized[item][1] path[item]=newFinalized[item] minTime=0 minTimeServicePoint=0 found=False for vertices in range (len(path)): #O(V) if path[vertices]==0: continue vertexId=path[vertices][0] if self.graph[vertexId].hasService and not found: minTime=path[vertices][1] minTimeServicePoint=vertexId found=True if self.graph[vertexId].hasService and path[vertices][1]<minTime: minTime=path[vertices][1] minTimeServicePoint=vertexId for num in range (len(finalized)): #O(V) if finalized[num][0]==minTimeServicePoint: finalized=finalized[:num+1] break for num in range (len(reverseFinalized)): #O(V) if reverseFinalized[num][0]==minTimeServicePoint: reverseFinalized=reverseFinalized[:num+1] break if not found: return [[],-1] else: #O(V) front=self.findPath(finalized,source) end=self.findPath(reverseFinalized,target) end.pop() end.reverse() whole=front+end return (whole,minTime) def __str__(self): string="" for i in self.graph: string+=str(i)+"\n" return string def printByRequirments(self,result): output="" if result==[[],-1]: return "No path exists\nTime: 0 minute(s)" path=result[0] time=result[1] for i in range (len(path)-1): output+=str(path[i])+"-->" output+=str(path[len(path)-1])+"\nTime: "+str(time)+" minute(s)" return output if __name__=="__main__": g=Graph() file_road=input("Enter the file name for the graph: ") g.buildGraph(file_road) file_camera=input("Enter the file name for camera nodes:") file_toll=input("Enter the file name for the toll roads:") file_service=input("Enter the file name for the service nodes:") source=input("Source node:") target=input("Sink node:") quickest=g.quickestPath(source,target) g.augmentGraph(file_camera,file_toll) safest=g.quickestSafePath(source,target) g.addService(file_service) detour=g.quickestDetourPath(source,target) print("Quickest path:") print(g.printByRequirments(quickest)) print("Safe quickest path:") print(g.printByRequirments(safest)) print("Quickest detour path:") print(g.printByRequirments(detour))
ff9f8aa35da14934dc7976be668bda7c6e757374
leandrohl/python-image-processing
/6-suavizacao/suavizacao_pela_media.py
1,993
3.84375
4
''' A suavisação da imagem (do inglês Smoothing), também chamada de „blur‟ ou „blurring‟ que podemos traduzir para “borrão”, é um efeito que podemos notar nas fotografias fora de foco ou desfocadas onde tudo fica embasado. Esse efeito é muito útil quando utilizamos algoritmos de identificação de objetos em imagens pois os processos de detecção de bordas por exemplo, funcionam melhor depois de aplicar uma suavização na imagem. ''' ''' SUAVIZACAO PELA MEDIA Neste caso é criada uma “caixa de pixels” para envolver o pixel em questão e calcular seu novo valor. O novo valor do pixel será a média simples dos valores dos pixels dentro da caixa, ou seja, dos pixels da vizinhança. Alguns autores chamam esta caixa de janela de cálculo ou kernel (do inglês núcleo) OS PARAMETROS Os parâmetros são a imagem a ser suavizada e a janela de suavização. Colocarmos números impars para gerar as caixas de cálculo pois dessa forma não existe dúvida sobre onde estará o pixel central que terá seu valor atualizado ''' import cv2 import numpy as np img = cv2.imread("..\entrada.jpg") img = img[::3, ::3] #diminui a imagem horizontal = np.hstack([img, cv2.blur(img, (3,3))]); vertical = np.vstack([img, cv2.blur(img, (5,5))]); cv2.imshow("testando hstack", horizontal) cv2.imshow("testando vstack", vertical) cv2.waitKey(0) ''' vstack (pilha vertical) e hstack (pilha horizontal) para juntar as imagens em uma única imagem final mostrando desde a imagem original e seguinte com caixas de calculo de 3x3, 5x5, 7x7, 9x9 e 11x11. ''' suave = np.vstack([ np.hstack([img, cv2.blur(img, (3, 3))]), np.hstack([cv2.blur(img, (5,5)), cv2.blur(img, ( 7, 7))]), np.hstack([cv2.blur(img, (9,9)), cv2.blur(img, (11, 11))]), ]) cv2.imshow("Imagens suavisadas (Blur)", suave) cv2.waitKey(0) ''' Perceba que conforme aumenta a caixa maior é o efeito de borrão (blur) na imagem. '''
c2f0c31e5223eaec9db32e80a267e942ae66710e
mousexjc/basicGrammer
/org/teamsun/mookee/faceObject/011staticMethod.py
410
3.5625
4
""" 静态方法:类和对象都可以调用静态方法 和普通的函数没什么区别 """ class StudentB: param1 = "param1" def __init__(self): pass # 加 @staticmethod 装饰器即可 @staticmethod def testStaticMethod(stra): print("This is a static method:" + stra) stu = StudentB() stu.testStaticMethod("object") StudentB.testStaticMethod("class")
ee92f82c3045780e90ec02a533f0f3d86921b3cb
mousexjc/basicGrammer
/org/teamsun/mookee/basic/006dict.py
667
4.09375
4
""" 字典是另一种可变容器模型,且可存储任意类型对象。 字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 ,格式如下所示: d = {key1 : value1, key2 : value2 } 键必须是唯一的,但值则不必。 值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。 """ dictVar = {"a": "av", "b": "bv", 3: "cv"} print(dictVar[3]) var1 = {"a": 1, 2: 2, 3: "c", "4": dictVar} print(var1["4"]) var2 = {1: "a", 2: "b", 3: "c", 4: "d"} print(var2) del var2[2] print("After Del :", var2) # var2.clear() # print("After Del :", var2)
2b82cd1ea8697747b28486a7987f99dceea7775a
mousexjc/basicGrammer
/org/teamsun/mookee/senior/c012_1funcType.py
452
4.53125
5
""" Chapter 12 函数式编程 匿名函数 格式:lambda param_list: expression lambda:关键字 expression * :只能是【表达式】 """ # 正常函数 def add(x, y): return x + y f = lambda x, y: x + y print(f(2, 3)) print("=====================") # 三元表达式 # 其他语言:表达式 ?true结果 : false结果 # Python : true结果 if 表达式 else false结果 x = 1 y = 2 a = x if x > y else y print(a)
ab23dfabe747fc2f15041233ef96da9b1f830f84
hiyouga/cryptography-experiment
/MyCrypto/utils/galois_field.py
5,015
3.625
4
class GF: # A python implementation of Galois Field GF(2^n) def __init__(self, data, order): assert isinstance(data, int) self.data = data self.order = order if order == 1: self.modulo = 0b10 # x elif order == 2: self.modulo = 0b111 # x^2+x+1 elif order == 3: self.modulo = 0b1011 # x^3+x+1 elif order == 4: self.modulo = 0b10011 # x^4+x+1 elif order == 8: self.modulo = 0b100011011 # x^8+x^4+x^3+x+1 elif order == 16: self.modulo = 0b10001000000001011 # x^16+x^12+x^3+x+1 elif order == 0: self.modulo = 0 # cannot do multiply else: raise Exception def __call__(self, data=None): if data is None: data = self.data return self.__class__(data=data, order=self.order) def __repr__(self): if self.order == 0: return format(self.data, 'b') return format(self.data, '0{:d}b'.format(self.order)) def __eq__(self, obj): if isinstance(obj, int): return self.data == obj elif isinstance(obj, self.__class__): return self.data == obj.data else: raise Exception def __lshift__(self, obj): assert isinstance(obj, int) return self(self.data << obj) def __rshift__(self, obj): assert isinstance(obj, int) return self(self.data >> obj) def __add__(self, obj): assert isinstance(obj, self.__class__) return self(self.data ^ obj.data) def __sub__(self, obj): assert isinstance(obj, self.__class__) return self(self.data ^ obj.data) def __mul__(self, obj): assert isinstance(obj, self.__class__) and self.modulo != 0 temp = self.data multi = (obj.data & 1) * temp for i in range(1, self.order): temp = self._xtimes(temp) multi ^= (((obj.data >> i) & 1) * temp) return self(multi) def __pow__(self, obj): assert isinstance(obj, int) and obj >= -1 if obj == -1: return self.inv res, temp = self(1), self() while obj: if obj & 1: res = res * temp temp = temp * temp obj >>= 1 return res def __truediv__(self, obj): assert isinstance(obj, self.__class__) return self.__mul__(obj.inv) def __floordiv__(self, obj): assert isinstance(obj, self.__class__) diff = self.deg - obj.deg pos = self.deg res = 0 if diff < 0: return self(res) temp, div = self.data, obj.data while diff >= 0: res <<= 1 if temp & (1 << pos): temp ^= (div << diff) res ^= 1 pos, diff = pos - 1, diff - 1 return self(res) def __mod__(self, obj): assert isinstance(obj, self.__class__) diff = self.deg - obj.deg pos = self.deg if diff < 0: return self() res, div = self.data, obj.data while diff >= 0: if res & (1 << pos): res ^= (div << diff) pos, diff = pos - 1, diff - 1 return self(res) def _xtimes(self, x): assert isinstance(x, int) if x & (1 << (self.order-1)): return (x << 1) ^ self.modulo else: return x << 1 @property def inv(self): if self.data == 0: raise Exception x1, x0 = self(1), self(0) y1, y0 = self(0), self(1) a, b = self(self.modulo), self() q = a//b r1, r0 = b, a%b while not r0 == 0: x1, x0 = x0, x1-q*x0 y1, y0 = y0, y1-q*y0 q = r1//r0 r1, r0 = r0, r1%r0 return y0 @property def deg(self): if self.data == 0: return -1 else: return self.data.bit_length() - 1 @staticmethod def gcd(a, b): if b == 0: return a return GF.gcd(b, a%b) @staticmethod def exgcd(a, b): x1, x0 = a(1), a(0) y1, y0 = a(0), a(1) q = a//b r1, r0 = b, a%b while not r0 == 0: x1, x0 = x0, x1-q*x0 y1, y0 = y0, y1-q*y0 q = r1//r0 r1, r0 = r0, r1%r0 return r1, x0, y0 if __name__ == '__main__': a = GF(0b0010001, order=8) b = GF(0b1101001, order=8) print('a\t', a) print('b\t', b) print('a.deg\t', a.deg) print('a^-1\t', a**-1) print('a+b\t', a+b) print('a-b\t', a-b) print('a*b\t', a*b) print('a//b\t', a//b) print('a%b\t', a%b) print('a/b\t', a/b) print('a/a\t', a/a) print('gcd(a,b)\t', GF.gcd(a, b)) print('exgcd(a,b)\t', GF.exgcd(a, b)) d, x, y = GF.exgcd(a, b) print('x*a+y*b\t', x*a+y*b)
3aec5f005f09c98d7645a691961960a1f75b6cc7
pite2019/pite2019s-t1-g1-davidegualandris
/task.py
1,720
4.03125
4
class Matrix: """" Defining the constructor ul = upper left ur = upper right bl = below left br = below right """ def __init__(self, ul, ur, bl, br): self.__ul = ul self.__ur = ur self.__bl = bl self.__br = br # Getters and setters def get_ul(self): return self.__ul def set_ul(self, ul): self.__ul = ul def get_ur(self): return self.__ur def set_ur(self, ur): self.__ur = ur def get_bl(self): return self.__bl def set_bl(self, bl): self.__bl = bl def get_br(self): return self.__br def set_br(self, br): self.__br = br # define the 2 methods def add(self, matrix): ul = self.__ul + matrix.get_ul() ur = self.__ur + matrix.get_ur() bl = self.__bl + matrix.get_bl() br = self.__br + matrix.get_br() return Matrix(ul, ur, bl, br) # to do def mul(self, matrix): ul = (self.__ul * matrix.get_ul()) + (self.__ur * matrix.get_bl()) ur = (self.__ul * matrix.get_ur()) + (self.__ur * matrix.get_br()) bl = (self.__bl * matrix.get_ur()) + (self.__br * matrix.get_bl()) br = (self.__bl * matrix.get_ur()) + (self.__br * matrix.get_bl()) return Matrix(ul, ur, bl, br) # define the toString() method def __str__(self): return str(self.__ul) + " " + str(self.__ur) + " " + str(self.__bl) + " " + str(self.__br) if __name__ == '__main__': matrix_1 = Matrix(4,5,6,7) print(matrix_1) matrix_2 = Matrix(2,2,2,1) print(matrix_2) matrix_3 = matrix_2.add(matrix_1) print(matrix_3) matrix_4 = matrix_2.mul(matrix_1) print(matrix_4)
dc7d915b87aeed1779e5a0095074238868701201
avisek-3524/Python-
/gcd.py
245
3.96875
4
''' write a program to print the gcd of the two numbers''' a = int(input('enter the first number ')) b = int(input('enter the second number ')) i = 1 while(a >= i and b >= i): if(a%i==0 and b%i==0): gcd = i i = i+1 print( gcd )
2e86e6d499de5d51f19051728db135aac6b36044
avisek-3524/Python-
/oddeven.py
260
4.1875
4
'''write a program to print all the numbers from m-n thereby classifying them as even or odd''' m=int(input('upper case')) n=int(input('lower case')) for i in range(m,n+1): if(i%2==0): print(str(i)+'--even') else: print(str(i)+'--odd')
3d3513f1520a98a06f7047699c4bee78d6e4a00f
carolinesekel/caesar-cipher
/caesar.py
361
4.34375
4
alphabet = "abcdefghijklmnopqrstuvwxyz" #shift by 5 cipher = "fghijklmnopqrstuvwxyzabcde" input_string = input("What would you like to encrypt? ") print("Now encrypting ", input_string, "...") encrypted = "" for letter in input_string: position = alphabet.index(letter) new_char = cipher[position] encrypted += new_char print("Encrypted string: ", encrypted)
d52653878c95ab7502a7f1a7a97e3d38040951aa
Athul8raj/Main-Repo
/Deep Learning/Tensorflow tutorials/Tensorflow with mnist data.py
2,354
3.609375
4
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('/tmp/data/',one_hot=True) n_nodes_hl1 = 512 n_nodes_hl2 = 1024 n_nodes_hl3 = 512 n_classes = 10 batch_size = 100 x = tf.placeholder('float',[None,784]) def neural_network(data): hidden_layer_1 = {'weights':tf.Variable(tf.random_normal([784,n_nodes_hl1])),'biases':tf.Variable(tf.random_normal([n_nodes_hl1]))} hidden_layer_2 = {'weights':tf.Variable(tf.random_normal([n_nodes_hl1,n_nodes_hl2])),'biases':tf.Variable(tf.random_normal([n_nodes_hl2]))} hidden_layer_3 = {'weights':tf.Variable(tf.random_normal([n_nodes_hl2,n_nodes_hl3])),'biases':tf.Variable(tf.random_normal([n_nodes_hl3]))} output_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl3,n_classes])),'biases':tf.Variable(tf.random_normal([n_classes]))} l1 = tf.add(tf.matmul(data,hidden_layer_1['weights']),hidden_layer_1['biases']) l1 = tf.nn.relu(l1) l2 = tf.add(tf.matmul(l1,hidden_layer_2['weights']),hidden_layer_2['biases']) l2 = tf.nn.relu(l2) l3 = tf.add(tf.matmul(l2,hidden_layer_3['weights']),hidden_layer_3['biases']) l3 = tf.nn.relu(l3) output = tf.matmul(l3,output_layer['weights'])+output_layer['biases'] return output def train_nn(x): prediction = neural_network(x) y = tf.placeholder('float') cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction,labels=y)) optimizer = tf.train.AdamOptimizer().minimize(cost) hm_epochs = 20 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for epoch in range(hm_epochs): epoch_loss = 0 for _ in range(int(mnist.train.num_examples/batch_size)): epoch_x,epoch_y = mnist.train.next_batch(batch_size) _,c = sess.run([optimizer,cost],feed_dict={x:epoch_x,y:epoch_y}) epoch_loss+=c print(f'Epoch: {epoch+1} completed out of {hm_epochs},loss: {epoch_loss}') correct = tf.equal(tf.argmax(prediction,1),tf.argmax(y,1)) accuracy = tf.reduce_mean(tf.cast(correct,'float')) print('Accuracy', accuracy.eval({x:mnist.test.images,y:mnist.test.labels})) train_nn(x)
b39dc36b9df1aba9fed2f1958c4f73e79c152ac9
geforcexfx/arrayDub
/exercise1.py
903
3.671875
4
def eliminate( numbers,n ): endLoop = False num = 0 new_number = [] #dictionary to store the time of a number appears in the array dictionary = dict([]) for i in range(0,len(numbers)): #if the number found in dictionary, increase the count if numbers[i] in dictionary.keys(): count = dictionary[numbers[i]] count = count + 1 dictionary[numbers[i]] = count if count != n: new_number.append(numbers[i]) #if the number is not in the dictionary, add this number to dictionary with the value is 1 else: count = 1 dictionary[numbers[i]] = count new_number.append(numbers[i]) print dictionary print new_number numlist = [1, 2, 2, 3, 5, 2, 4, 5, 5, 2] eliminate( numlist,3 ) numlist2 = [1,1,2,2,1,2,3,3,4,4,5,5] eliminate(numlist2,2)
8c6e920238d869d8a98aee888acec584a95dc6d9
tomduhourq/p4e-coursera
/src/Week05/min.py
159
3.75
4
from src.Week05.list_helper import create_list min = None for elem in create_list('min'): if min is None or elem < min: min = elem print 'smallest is ',min
1286812346feeb6a75e2ff7ecd5f265c851690af
tomduhourq/p4e-coursera
/src/DictPractice/examples.py
807
3.578125
4
__author__ = 'tomasduhourq' import string from src.FilePractice.file_helper import choose_file # Sorting the keys of a dict counts = {'chuck': 1, 'annie': 42, 'jan': 100} # Create a list of the keys in the dict def sort_keys(d): keys = d.keys() keys.sort() for key in keys: print key, d[key] sort_keys(counts) # Using string.translate to get rid of punctuation characters counts = dict() for line in open('../ListPractice/romeo.txt'): line = line.translate(None, string.punctuation).lower() for word in line.split(): counts[word] = counts.get(word, 0) + 1 # Integrating everything counts = dict() for line in choose_file(): for word in line.translate(None, string.punctuation).lower().split(): counts[word] = counts.get(word, 0) + 1 sort_keys(counts)
b06ea463ef5033368b8f97c0097b09a16a76adef
saloni2805/Assignment-Submission
/ASS1/Ass1Q2.py
66
3.515625
4
x=5 y=((x^2+5*x+6)/(2*x+5)) print('Result= ',y) #Result= 2.4
b1dd62f0e1927d1fb553f3426eac22a79ad655d1
voidbeast6/voidbeast6
/comps209fproject/comps209fprojectV1.1/comps209fproject/MC.py
9,939
3.515625
4
# #created by Lewis #finished on 3rd May 2021 # import tkinter as tk import random, string class MultipleChoice(tk.Tk): def __init__(self, *args, file = "words.txt"): tk.Tk.__init__(self, *args) self.width=800 self.height=600 self.geometry(str(self.width)+"x"+str(self.height)) #create the variables self.score = tk.IntVar(self) self.pos = tk.StringVar(self) self.definition = tk.StringVar(self) self.answer = tk.StringVar(self) self.wrongChoice1 = tk.StringVar(self) self.wrongChoice2 = tk.StringVar(self) self.wrongChoice3 = tk.StringVar(self) #create the top container which contains menu, score and hint informations topWindow = tk.Frame(master = self, relief = tk.RAISED) topWindow.pack(side = "top", fill = "x", expand = True) self.menuButton = tk.Button(master = topWindow, text = "Menu", font = 50, pady=5, state = "disabled", command = self.gameMenu) self.menuButton.pack(side = "right") scoreBoard = tk.Label(master = topWindow, text = " Your score: ", font = 50) scoreBoard.pack(side = "left", fill = "y") scoreText = tk.Label(master = topWindow, textvariable = self.score, font = 50) scoreText.pack(side = "left", fill = "y") self.posText = tk.Label(master = topWindow, textvariable = self.pos, font = 50) self.posText.pack_forget() #Buttons area bottomWindow = tk.Frame(master = self, relief = tk.RAISED, borderwidth = 1) bottomWindow.pack(side = "bottom", fill = "x", expand = True) buttonLeft = tk.Frame(master = bottomWindow, relief = tk.RAISED, borderwidth = 1) buttonRight = tk.Frame(master = bottomWindow, relief = tk.RAISED, borderwidth = 1) buttonLeft.pack(side = "left", fill = 'y', expand = True) buttonRight.pack(side = "right", fill = 'y', expand = True) self.button1 = tk.Frame(master = buttonLeft, relief = tk.RAISED, borderwidth = 1) self.button1.pack(fill = 'both', expand = True) self.button2 = tk.Frame(master = buttonLeft, relief = tk.RAISED, borderwidth = 1) self.button2.pack(fill = 'both', expand = True) self.button3 = tk.Frame(master = buttonRight, relief = tk.RAISED, borderwidth = 1) self.button3.pack(fill = 'both', expand = True) self.button4 = tk.Frame(master = buttonRight, relief = tk.RAISED, borderwidth = 1) self.button4.pack(fill = 'both', expand = True) self.message = tk.Label(master = bottomWindow, text = "3 out of 4 buttons are wrong answers", font = 30) self.message.pack(side = "top", fill = 'both', expand = True) #create the center window to contain the word self.wordWindow = tk.Frame(master = self) self.wordWindow.pack(fill='both', expand = True) self.definitionText = tk.Label(master = self.wordWindow, textvariable = self.definition, font = 100) self.definitionText.pack_forget() self.starting = tk.Button(master = self.wordWindow, text = "click to start", font = 50, command = self.start) self.starting.pack(fill='both', expand = True) #pick the word list words=list() with open(file, "r") as infile: count=0 for line in infile: count +=1 #skip the first line if count == 1: continue #create a list whose elements are [word,category,meaning] words.append(line.strip().split(';')) self.wordList = list() self.category = dict() self.meaning = dict() for x in words: word=x[0] self.wordList.append(word.lstrip().casefold()) self.category[word]=x[1].lstrip().casefold() self.meaning[word]=x[2].lstrip().casefold() #start game and show the buttons and hints def start(self): self.message.destroy() self.starting.destroy() self.definitionText.pack(fill='both', expand = True) self.posText.pack(fill = "y", expand = True) self.menuButton.config(state = "normal") self.next() #switch to next word def next(self): #Random position for the buttons positions=[self.button1, self.button2, self.button3, self.button4] position1=random.choice(positions) positions.remove(position1) position2=random.choice(positions) positions.remove(position2) position3=random.choice(positions) positions.remove(position3) position4=positions[0] self.right = tk.Button(master = position1, textvariable = self.answer, font = 30, padx=self.width/6, pady=5, command = self.getScore) self.wrong1 = tk.Button(master = position2, textvariable = self.wrongChoice1, font = 30, padx=self.width/6, pady=5, command = self.wrongAnswer) self.wrong2 = tk.Button(master = position3, textvariable = self.wrongChoice2, font = 30, padx=self.width/6, pady=5, command = self.wrongAnswer) self.wrong3 = tk.Button(master = position4, textvariable = self.wrongChoice3, font = 30, padx=self.width/6, pady=5, command = self.wrongAnswer) self.right.pack(fill='both', expand = True) self.wrong1.pack(fill='both', expand = True) self.wrong2.pack(fill='both', expand = True) self.wrong3.pack(fill='both', expand = True) #pick the word randomly and set the hints to the boxes word = random.choice(self.wordList) self.pos.set(self.category[word]) #set that 40 is the maximum length of a line self.definition.set(self.cutByLength(self.meaning[word], 40)) self.answer.set(word) #change the word random times while True: for n1 in range(random.randint(1, len(word)*4)): word1 = self.changeIndex(word, random.randint(0,len(word)-1)) word1 = self.changeAlphabet(word, word[random.randint(0,len(word)-1)]) if word1 != word: break while True: for n2 in range(random.randint(1, len(word)*4)): word2 = self.changeIndex(word, random.randint(0,len(word)-1)) word2 = self.changeAlphabet(word, word[random.randint(0,len(word)-1)]) if word2 != word and word2 != word1: break while True: for n3 in range(random.randint(1, len(word)*4)): word3 = self.changeIndex(word, random.randint(0,len(word)-1)) word3 = self.changeAlphabet(word, word[random.randint(0,len(word)-1)]) if word3 != word and word3 != word1 and word3 != word2: break self.wrongChoice1.set(word1) self.wrongChoice2.set(word2) self.wrongChoice3.set(word3) #cut the sentence by max length def cutByLength(self, sentence, maxLength): list = sentence.split() l = 0 sentence = "" for n in list: l += len(n) if l <maxLength: sentence = sentence + n + " " else: sentence = sentence + "\n" + n + " " l=0 return sentence #change the word by replace specific index def changeIndex(self, word, index): alphabets=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] newWord = list(word) newWord[index] = random.choice(alphabets) newWord = "".join(newWord) return newWord #change the word by replace specific alphabet def changeAlphabet(self, word, alphabet): alphabets=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] alphabets.remove(alphabet) wrong = random.choice(alphabets) newWord = word.replace(alphabet,wrong) return newWord def wrongAnswer(self): self.score.set(self.score.get()-1) self.right.destroy() self.wrong1.destroy() self.wrong2.destroy() self.wrong3.destroy() self.next() def getScore(self): self.score.set(self.score.get()+1) self.right.destroy() self.wrong1.destroy() self.wrong2.destroy() self.wrong3.destroy() self.next() #create menu to show quit button and resume button, hints and guess buttons would be hidden def gameMenu(self): self.menuButton.config(state = "disabled") self.posText.pack_forget() self.definitionText.pack_forget() self.right.pack_forget() self.wrong1.pack_forget() self.wrong2.pack_forget() self.wrong3.pack_forget() self.buttonResume = tk.Button(self.wordWindow, text = "Resume", font = 50, padx=self.width/5, pady=self.height/50, command=self.resume) self.buttonQuit = tk.Button(self.wordWindow, text = "Exit", font = 50, padx=self.width/5, pady=self.height/50,command=self.destruct) self.buttonResume.pack() self.buttonQuit.pack() #destroy the menu and show the hints and guess buttons again def resume(self): self.menuButton.config(state = "normal") self.buttonResume.destroy() self.buttonQuit.destroy() self.definitionText.pack() self.posText.pack(fill = "y", expand = True) self.right.pack(fill='both', expand = True) self.wrong1.pack(fill='both', expand = True) self.wrong2.pack(fill='both', expand = True) self.wrong3.pack(fill='both', expand = True) def destruct(self): self.destroy() def MCgame(): game = MultipleChoice() game.mainloop() if __name__ == '__main__': game = MultipleChoice() game.mainloop()
8ffef9d61aeb24f3348195bc09b765ed61262f67
AyseErdanisman/PythonProgramlamaKursu
/6.8_uygulama-sayi-tahmin.py
1,006
3.765625
4
""" 1 - 100 arasında üretilecek bir sayıyı aşağı yukarı ifadeleri ile bulmaya çalışınız: * 'random' modülü için rangom araştırması yapınız. ** 100 üzerinden puanlama yapınız. Her sor 20 puan olacaktır. *** Hak bilgisini kullanıcıdan alın ve her soru belirtilen can sayısı üzerinden hesaplansın. """ import random sayi = random.randint(1, 10) can = int(input('1 den 100 e kadar tutlan sayıyı tahmin etmek için kaç hak istersiniz? ')) hak = can # can ı haka atamamızın sebebi puan hesaplamasında can değişkenini sabit tutumak ve kalan kısmı can üzerinden halletmek sayac = 0 while hak > 0: hak -= 1 sayac += 1 tahmin = int(input('Tahmin: ')) if(sayi == tahmin): print(f'Tebrikler {sayac}. hakkınızda bildiniz. Puanınız {100 - (100/can) * (sayac - 1)}') break elif(sayi > tahmin): print('Yukarı') else: print('Aşağı') if (hak == 0): print(f'Hakkınız bitti. Doğru cevap: {sayi}')
b4bcc71a567588ce3a87f18f75846f2cc3631c40
AyseErdanisman/PythonProgramlamaKursu
/3.18_uygulama-dictionary-demo.py
1,871
3.5
4
""" ogrenciler ={ "120": { "ad": "Ali", "soyad": "Yılmaz", "telefon": "1231 231 23 12" }, "125": { "ad": "Can", "soyad": "Korkmaz", "telefon": "1231 123 12 12" }, "128": { "ad": "Volkan", "soyad": "Yükselen", "telefon": "1231 123 12 12" } } 1- Bilgileri verilen öğrencileri kullanıcıdan aldığınız bilgilerle dictionary içinde saklayınız. 2- öğrenci numarasını kullanıcıdan alıp ilgili öğrenci bilgisini görseriniz """ ogrenciler = { } number = input("ogrenci no: ") name = input("ogrenci ad: ") surname = input("ogrenci soyad: ") phone = input("ogrenci telefon no: ") """ ogrenciler[number] = { "ad": name, "soyad": surname, "telefon": phone } burada yapılanlar update metoduyla da yapılabilir """ ogrenciler.update({ number: { "ad": name, "soyad": surname, "telefon": phone } }) number = input("ogrenci no: ") name = input("ogrenci ad: ") surname = input("ogrenci soyad: ") phone = input("ogrenci telefon no: ") ogrenciler.update({ number: { "ad": name, "soyad": surname, "telefon": phone } }) number = input("ogrenci no: ") name = input("ogrenci ad: ") surname = input("ogrenci soyad: ") phone = input("ogrenci telefon no: ") ogrenciler.update({ number: { "ad": name, "soyad": surname, "telefon": phone } }) print("*"*50) # 2- öğrenci numarasını kullanıcıdan alıp ilgili öğrenci bilgisini görseriniz ogrNo = input("ogrenci no: ") ogrenci = ogrenciler[ogrNo] print(f'Aradığınız {ogrNo} numaralı öğrencinin adı: {ogrenci["ad"]} soyadı: {ogrenci["soyad"]} ve telefonu ise {ogrenci["telefon"]} dir')
1fdb39656d8df970aab30707d5dfcfc08bbb1486
AyseErdanisman/PythonProgramlamaKursu
/4.5_matiksal-operatorler.py
536
3.828125
4
x = 6 hak = 5 devam = 'e' result = 5 < x < 6 # and result2 = (x > 5) and (x < 10) # koşulun her iki durumu da doğru olursa ture değerini döndürür print(result2) result3 = (hak > 0) and (devam == 'e') print(result3) # or result4 = (x > 0) or (x % 2 == 0) # true deger için ifadelerden sadece birinin true olması yeterli print(result4) # not result5 = not(x > 0) # sourlan sorunun cevabının tam tersini üretir # x, 5-10 arasında olan bir çift sayı mı?? result5 = ((x > 5) and (x < 10) and (x % 2 == 0)) print(result5)
5b05a8ac8d51f8e784eda8064088dfcf5cf877dc
AyseErdanisman/PythonProgramlamaKursu
/3.11_uygulama-string-metotlari.py
3,167
4.0625
4
website = "http://www.sadikturan.com" course = "Python Kursu: Baştan Sona Python Programlama Rehberiniz (40 Saat)" # 1- " Hello word " karakter dizisinin baştaki ve sondaki boşluk karakterlerini silin # result = " Hello word " # result = result.strip() # result = result.lstrip() --> left stript # result = result.rstrip() --> right stript # print(result) #--------------------------------------------------------------------------------------------------- # 2- "www.sadikturan.com" ifadesi içerisindeki sadikturan bilgisi dışındaki her karakteri silin # website = website.split(".") # website[0] = "" # website[2] = "" # website = "".join(website) # print(website) # ya da # result = website.lstript(":/pth") da denebilir :) #---------------------------------------------------------------------------------------------------- # 3- "course" karakter dizisinin tüm karakterini küçük harf yapın # course = course.lower() # print(course) #---------------------------------------------------------------------------------------------------- # 4- "website" içerisinde kaç tane a karakteri vardır # website = website.count('a') # print(website) # website = website.count('www', 0, 10) --> 0 ile 10. indis arasında www karaketrini arar #---------------------------------------------------------------------------------------------------- # 5- "website" www ile başlayıp com ile bitiyor mu? # isFound = website.startswith("www") # isFounnd = website.endswith("com") # print(isFound) # print(isFounnd) #----------------------------------------------------------------------------------------------------- # 6- "website içerisinde ".com" ifadesi var mı? # result = website.find(".com") # print(result) # result = website.rfind("Python") --> sağdan saymaya başlar #----------------------------------------------------------------------------------------------------- # 7- "course" içerisindeki karakterlerin hepsi alfabetik karakter mi? (isalpha, isdigit) result = course.isalpha() print(result) #------------------------------------------------------------------------------------------------------ # 8- "Contents" ifadesini satırda 50 karakter içine yerleştirip sağ ve soluna * kaarakteri ekleyin # result = "Contents" # result = result.center(50, "*") # result = result.ljust(50, "*") --> dersek ifadeyi sağa yaslayarak gerçekleştirir # result = result.rjust(50, "*") # print(result) #------------------------------------------------------------------------------------------------------- # 9- "course" karaker dizisindeki tüm boşluk karakterleini - karakteri ile değiştirin # course = course.replace(" ", "-") # print(course) #------------------------------------------------------------------------------------------------------- # 10- "Hello World" karakter dizisinin "Word" ifadesini "There" olarak değiştirin # result = "Hello World" # result = result.replace("World", "There") # print(result) #------------------------------------------------------------------------------------------------------- # 11- "course" karakter dizisini boşluk karakterlerinden ayırın course = course.split(" ") print(course)
a0ac1bd7ae21e0cc2bbe1cb66425903ec03fea6d
AyseErdanisman/PythonProgramlamaKursu
/4.2_uygulama-atama-operatoleri.py
785
3.875
4
x, y, z = 2, 5, 107 numbers = 1, 5, 7, 10, 6 # 1- kullanıcıdan aldığınız 2 sayının çarpımı ile x,y,z nin toplamı kaçtır? a = input("ilk degeri giriniz: ") b = input("ikinci degeri giriniz: ") c = int(a) * int(b) + (x+y+z) print(c) # 2- y'nin x'e kalansız bölümünü hesaplayınız print(y // x) # 3- (x,y,z) toplamının mod 3 ü nedir print((x + y + z) % 3) # 4- y'nin x. kuvvetini hesaplayınız print(y**x) # 5- x, *y, z = numbers işlemine göre z nin küpü kaçtır? x, *y, z = numbers #burada x 1. elemanı alır, z sonuncu elemanı alır, y ise ortada kalan tüm elemanları alır print(y) #[5, 7, 10] print(z ** 3) # 6- x, *y, z = numbers işlemine göre y'nin degerleri toplamı kaçtır? x, *y, z = numbers result = y[0] + y[1] + y[2] print(result)
f9a87ecc31ca17ed6bbeda260a84ea5a60e59937
Thyrvald/MinimaxAlgorithm
/main.py
3,772
3.609375
4
from functions import * import timeit def main(): tic_tac_toe_tree = make_tree() minimax_search_depth1 = 2 minimax_search_depth2 = 4 minimax_search_depth3 = 6 minimax_search_depth4 = 10 x = [] o = [] d = [] for i in range(6): x.append(0) o.append(0) d.append(0) for i in range(1000): games = [] print("Random game result:\n") games.append(random_game(tic_tac_toe_tree)) print(games[0]) print("MinimaxFull game result:\n") games.append(minimax_full_game(tic_tac_toe_tree)) print(games[1]) print(f"Minimax with search depth = {minimax_search_depth1} game result:\n") games.append(minimax_game(tic_tac_toe_tree, minimax_search_depth1)) print(games[2]) print(f"Minimax with search depth = {minimax_search_depth2} game result:\n") games.append(minimax_game(tic_tac_toe_tree, minimax_search_depth2)) print(games[3]) print(f"Minimax with search depth = {minimax_search_depth3} game result:\n") games.append(minimax_game(tic_tac_toe_tree, minimax_search_depth3)) print(games[4]) print(f"Minimax with search depth = {minimax_search_depth4} game result:\n") games.append(minimax_game(tic_tac_toe_tree, minimax_search_depth4)) print(games[5]) for j in range(len(games)): if games[j] == 1: x[j] += 1 elif games[j] == -1: o[j] += 1 elif games[j] == 0: d[j] += 1 print(24 * '-') print("Random games: x wins: " + str(x[0]) + ", o wins: " + str(o[0]) + ", draws: " + str(d[0])) print("MinimaxFull games: x wins: " + str(x[1]) + ", o wins: " + str(o[1]) + ", draws: " + str(d[1])) print(f"Minimax with search depth = {minimax_search_depth1} games: x wins: " + str(x[2]) + ", o wins: " + str( o[2]) + ", draws: " + str(d[2])) print(f"Minimax with search depth = {minimax_search_depth2} games: x wins: " + str(x[3]) + ", o wins: " + str( o[3]) + ", draws: " + str(d[3])) print(f"Minimax with search depth = {minimax_search_depth3} games: x wins: " + str(x[4]) + ", o wins: " + str( o[4]) + ", draws: " + str(d[4])) print(f"Minimax with search depth = {minimax_search_depth4} games: x wins: " + str(x[5]) + ", o wins: " + str( o[5]) + ", draws: " + str(d[5])) random = 0 min_full = 0 min_d2 = 0 min_d4 = 0 min_d6 = 0 min_d10 = 0 for i in range(10): random += timeit.timeit(lambda: random_game(tic_tac_toe_tree), number=1) min_full += timeit.timeit(lambda: minimax_full_game(tic_tac_toe_tree), number=1) min_d2 += timeit.timeit(lambda: minimax_game(tic_tac_toe_tree, minimax_search_depth1), number=1) min_d4 += timeit.timeit(lambda: minimax_game(tic_tac_toe_tree, minimax_search_depth2), number=1) min_d6 += timeit.timeit(lambda: minimax_game(tic_tac_toe_tree, minimax_search_depth3), number=1) min_d10 += timeit.timeit(lambda: minimax_game(tic_tac_toe_tree, minimax_search_depth4), number=1) print(f"Execution time for random game: {random/10:.2f} seconds") print(f"Execution time for MinimaxFull game: {min_full/10:.2f} seconds") print(f"Execution time for Minimax with search depth = {minimax_search_depth1} game: {min_d2/10:.2f} seconds") print(f"Execution time for Minimax with search depth = {minimax_search_depth2} game: {min_d4/10:.2f} seconds") print(f"Execution time for Minimax with search depth = {minimax_search_depth3} game: {min_d6/10:.2f} seconds") print(f"Execution time for Minimax with search depth = {minimax_search_depth4} game: {min_d10/10:.2f} seconds") if __name__ == '__main__': main()