blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
c77f712d6f3884cf359c38910c9fbf7f6fe4d05c
AugustoDipNiloy/Uri-Solution
/Python3/uri1017.py
232
3.59375
4
class Main: def __init__(self): self.a = int(input()) self.b = int(input()) def output(self): print("%0.3f" % ((self.a * self.b) / 12)) if __name__ == '__main__': obj = Main() obj.output()
59461ccc175dee4e08e714548d4e4f129ba23239
bheki-maenetja/small-projects-py
/courses/python_data_structures_queues/Exercise Files/Ch02/02_03/End/stacks.py
515
4.1875
4
class Stack: def __init__(self): self.items = [] def push(self, item): """Accepts an item as a parameter and appends it to the end of the list. Returns nothing. The runtime for this method is O(1), or constant time, because appending to the end of a list happens in constant time. """ self.items.append(item) def pop(self): pass def peek(self): pass def size(self): pass def is_empty(self): pass
37e4139ffdc1d85f026e44e48c05a60b2babc642
caspd3v/Python-Calculator
/main.py
940
4.21875
4
import sys #Print the help menu print(''' Calculator App --------------- a -> Add/+ s -> Subtract/- m -> Multiply/* d -> Devide// --------------- By CaspD3V ''') #Number Variable int1 = int(input("Number 1: ")) #Choose Addition, Subtraction, Multiplication, or Devision choice = input("a, s, m, or d: ") #Number Variable int2 = int(input("Number 2: ")) #Making sure that the "choice" variable is always uppercase if choice.upper() == "A": #Adding the 2 numbers together answer = int1 + int2 #Printing out the math problem print(int1, "+", int2, "=", answer) #Or subtracting elif choice.upper() == "S": answer = int1 - int2 print(int1, "-", int2, "=", answer) #Or multiplying elif choice.upper() == "M": answer = int1 * int2 print(int1, "*", int2, "=", answer) #Or deviding elif choice.upper() == "D": answer = int1 / int2 print(int1, "/", int2, "=", answer) print("End") #Exit the script sys.exit()
f8ad168010da0b1ccd8d2013d45139cc2968eb62
Lolita88/BioinformaticsAlgorithms
/Python/Bioinformatics/BeginningBioinformatics/ApproximatePatternMatching.py
782
3.640625
4
def ApproximatePatternMatching(Pattern, Text, d): positions = [] # initializing list of positions #for every i in the range of 0 to length of text: if (call function) Hamming Distance with parameters (slice Text from i to length of pattern, pattern) is less than or equal to d: postions.append[i] for i in range(0, len(Text)-len(Pattern)+1): #print Text[i:i+8] #print HammingDistance(Pattern, Text[i:i+8] if(HammingDistance(Pattern, Text[i:i+len(Pattern)]) <= d): positions.append(i) return positions def HammingDistance(genome1, genome2): distance = 0 for x,y in zip(genome1, genome2): if x != y : distance += 1 return distance print (ApproximatePatternMatching("CCA", "CCACCT", 0))
de17b0f171a03809acd6ad7ddf4fc7b0d15d4244
eduardoramirez/adventofcode
/2019/day3/day3.py
1,943
3.59375
4
import math INPUT = open('input.txt', 'r').read().split() wire_directions = list(map(lambda l: l.split(','), INPUT)) def create_points(directions): all_points = [(0, 0)] for d in directions: steps = int(d[1:]) (x, y) = all_points[-1] if d.startswith('R'): points = [(step_x, y) for step_x in range(x+1, x+steps+1)] all_points += points elif d.startswith('U'): points = [(x, step_y) for step_y in range(y+1, y+steps+1)] all_points += points elif d.startswith('L'): points = [(step_x, y) for step_x in range(x-1, x-(steps+1), -1)] all_points += points elif d.startswith('D'): points = [(x, step_y) for step_y in range(y-1, y-(steps+1), -1)] all_points += points else: raise Exception('Unknown direction {}'.format(d)) return all_points[1:] def manhattan_dist(a, b): (x1, y1) = a (x2, y2) = b return abs(x1 - x2) + abs(y1 - y2) def part1(): root = (0, 0) wire_1 = set(create_points(wire_directions[0])) wire_2 = set(create_points(wire_directions[1])) intersections = list(wire_1.intersection(wire_2)) return min([manhattan_dist(root, p) for p in intersections]) def part2(): wire_1_points = create_points(wire_directions[0]) wire_2_points = create_points(wire_directions[1]) # Create the mapping in reverse so we keep the shortest path wire_1_idx = {wire_1_points[i]:i for i in range(len(wire_1_points)-1, -1, -1)} wire_2_idx = {wire_2_points[i]:i for i in range(len(wire_2_points)-1, -1, -1)} intersections = list(set(wire_1_points).intersection(set(wire_2_points))) # 2 is to account for omitted roots return min([2 + wire_1_idx[itx] + wire_2_idx[itx] for itx in intersections]) if __name__ == '__main__': print('Part 1: {}'.format(part1())) print('Part 2: {}'.format(part2()))
eca5db6ebf6e92768a8a89d86857a12a5537dbed
AnansiCoding/Macchanger
/mac.py
13,116
3.796875
4
#!/usr/bin/env python3 # This Program has almost all the features of mac changer in terminal # Christopher Valdez # August 23, 2018 # mac.py version 1.0 #To do list #[1] find a way to internally find computer's wifi and ethernet names to get rid of user input import sys import os import time import dialogue from addressBin import * if __name__ == '__main__': os.system('clear') def main(): dialogue.main() user_input = input("Make your choice ==> ") os.system('clear') if user_input == ('1'): showMac() if user_input == ('2'): randomMac() if user_input == ('3'): customMac() if user_input == ('4'): resetMac() if user_input == ('5'): closeProgram() if user_input == ('5150'): findRef() else: main() def showMac(): #Start of show Mac option dialogue.connectionType() connectionType = input("Enter your connection type ==> ") os.system('clear') if connectionType == ('1'): showWifi() if connectionType == ('2'): showEth() if connectionType == ('3'): os.system('clear') main() else: dialogue.inputError() os.system('clear') showMac() def showWifi(): print("The following is your Mac-Address for "+(wifi)+"\n") showWifiAddress() continueInput = input("\n\nPress any key to continue, or B to go back. ") if continueInput.lower() == ('b'): os.system('clear') showMac() else: os.system('clear') main() def showEth(): print("The following is your Mac-Address for "+(eth)+"\n") showEthAddress() continueInput = input("\n\nPress any key to continue, or B to go back. ") if continueInput.lower() == ('b'): os.system('clear') showMac() else: os.system('clear') main() def randomMac(): #Start of random mac option dialogue.connectionType() connectionType = input("Enter your connection type ==> ") os.system('clear') if connectionType == ('1'): randomWifi() if connectionType == ('2'): randomEth() if connectionType == ('3'): os.system('clear') main() else: dialogue.inputError() os.system('clear') randomMac() def randomWifi(): dialogue.randomMac() randomType = input("Make your choice ==> ") os.system('clear') if randomType == ('1'): print("Your Mac-Address has been randomly set.\n") wifiDown() os.system('sudo macchanger -r '+(wifi)) wifiUp() networkManagerRestart() continueInput = input("\n\nPress any key to continue, or B to go back. ") if continueInput.lower() == ('b'): os.system('clear') randomWifi() else: os.system('clear') main() if randomType == ('2'): print("Everything but vendor bytes have been randomly set.\n") wifiDown() os.system('sudo macchanger -e '+(wifi)) wifiUp() networkManagerRestart() continueInput = input("\n\nPress any key to continue, or B to go back. ") if continueInput.lower() == ('b'): os.system('clear') randomWifi() else: os.system('clear') main() if randomType == ('3'): print("Random vendor Mac-Address of the same kind has been set.\n") wifiDown() os.system('sudo macchanger -a '+(wifi)) wifiUp() networkManagerRestart() continueInput = input("\n\nPress any key to continue, or B to go back. ") if continueInput.lower() == ('b'): os.system('clear') randomWifi() else: os.system('clear') main() if randomType == ('4'): print("Completly random vendor Mac-Address has been set.\n") wifiDown() os.system('sudo macchanger -A '+(wifi)) wifiUp() networkManagerRestart() continueInput = input("\n\nPress any key to continue, or B to go back. ") if continueInput.lower() == ('b'): os.system('clear') randomWifi() else: os.system('clear') main() if randomType == ('5'): print("Here is a list of known vendors.\n") print("When finished press Q to quit.\n") continueInput = input("Press any key to show list.") os.system('macchanger -l | less') os.system('clear') continueInput = input("\n\nPress any key to continue, or B to go back. ") if continueInput.lower() == ('b'): os.system('clear') randomWifi() else: os.system('clear') main() if randomType == ('6'): os.system('clear') randomMac() else: dialogue.inputError() os.system('clear') randomWifi() def randomEth(): dialogue.randomMac() randomType = input("Make your choice ==> ") os.system('clear') if randomType == ('1'): print("Your Mac-Address has been randomly set.\n") ethDown() os.system('sudo macchanger -r '+(eth)) ethUp() networkManagerRestart() continueInput = input("\n\nPress any key to continue, or B to go back. ") if continueInput.lower() == ('b'): os.system('clear') randomEth() else: os.system('clear') main() if randomType == ('2'): print("Everything but vendor bytes have been randomly set.\n") ethDown() os.system('sudo macchanger -e '+(eth)) ethUp() networkManagerRestart() continueInput = input("\n\nPress any key to continue, or B to go back. ") if continueInput.lower() == ('b'): os.system('clear') randomEth() else: os.system('clear') main() if randomType == ('3'): print("Random vendor Mac-Address of the same kind has been set.\n") ethDown() os.system('sudo macchanger -a '+(eth)) ethUp() networkManagerRestart() continueInput = input("\n\nPress any key to continue, or B to go back. ") if continueInput.lower() == ('b'): os.system('clear') randomEth() else: os.system('clear') main() if randomType == ('4'): print("Completly random vendor Mac-Address has been set.\n") ethDown() os.system('sudo macchanger -A '+(eth)) ethUp() networkManagerRestart() continueInput = input("\n\nPress any key to continue, or B to go back. ") if continueInput.lower() == ('b'): os.system('clear') randomEth() else: os.system('clear') main() if randomType == ('5'): print("Here is a list of known vendors.\n") print("When finished press Q to quit.\n") continueInput = input("Press any key to show list.") os.system('macchanger -l | less') os.system('clear') continueInput = input("\n\nPress any key to continue, or B to go back. ") if continueInput.lower() == ('b'): os.system('clear') randomEth() else: os.system('clear') main() if randomType == ('6'): os.system('clear') randomMac() else: dialogue.inputError() os.system('clear') randomEth() def customMac(): #Start of custom mac option dialogue.connectionType() connectionType=input("Enter your connection type ==> ") os.system('clear') if connectionType == ('1'): customWifi() if connectionType == ('2'): customEth() if connectionType == ('3'): os.system('clear') main() else: dialogue.inputError() os.system('clear') customMac() def customWifi(): customWifiMac = input("\nEnter a new Mac-Address or B to go Back ==> ") if customWifiMac.lower() == ('b'): os.system('clear') customMac() else: wifiDown() time.sleep(1) os.system('sudo macchanger -m '+(customWifiMac)+' '+(wifi)) time.sleep(1) wifiUp() networkManagerRestart() print("\nMac-Address has been change to "+(customWifiMac)) continueInput=input("\n\nPress any key to continue, or B to go back. ") if continueInput.lower() == ('b'): os.system('clear') customWifi() else: os.system('clear') main() def customEth(): customEthMac = input("\nEnter a new Mac-Address or B to go Back ==> ") if customEthMac.lower() == ('b'): os.system('clear') customMac() else: ethDown() time.sleep(1) os.system('sudo macchanger -m '+(customEthMac)+' '+(eth)) time.sleep(1) ethUp() networkManagerRestart() print("\nMac-Address has been change to "+(customEthMac)) continueInput = input("\n\nPress any key to continue, or B to go back. ") if continueInput.lower() == ('b'): os.system('clear') customEth() else: os.system('clear') main() def resetMac(): #Start of reset mac option dialogue.connectionType() connectionType = input("Enter your connection type ==> ") os.system('clear') if connectionType == ('1'): resetWifi() if connectionType == ('2'): resetEth() if connectionType == ('3'): os.system('clear') main() else: dialogue.inputError() os.system('clear') resetMac() def resetWifi(): resetQuestion = input("You would like to reset your Mac-Address Y/n ==> ") if resetQuestion.lower() == ('y'): print("Your Mac-Address is being reset\n") wifiDown() os.system('sudo macchanger -p '+(wifi)) wifiUp() networkManagerRestart() print("\nMac-Address has been reset") continueInput=input("\n\nPress any key to continue, or B to go back. ") if continueInput.lower()==('b'): os.system('clear') resetMac() else: os.system('clear') main() if resetQuestion.lower() == ('n'): os.system('clear') resetMac() else: dialogue.inputError() os.system('clear') resetWifi() def resetEth(): resetQuestion = input("You would like to reset your Mac-Address Y/n ==> ") if resetQuestion.lower() == ('y'): print("Your Mac-Address is being reset\n") ethDown() os.system('sudo macchanger -p '+(eth)) ethUp() networkManagerRestart() print("\nMac-Address has been reset") continueInput = input("\n\nPress any key to continue, or B to go back. ") if continueInput.lower() == ('b'): os.system('clear') resetMac() else: os.system('clear') main() if resetQuestion.lower() == ('n'): os.system('clear') resetMac() else: dialogue.inputError() os.system('clear') resetEth() def closeProgram(): #start of close program exit_answer = input("Are you sure? Y/n ==> ") if exit_answer.lower() == ('y'): os.system('clear') sys.exit(0) if exit_answer.lower() == ('n'): os.system('clear') main() else : dialogue.inputError() os.system('clear') closeProgram() def findRef(): dialogue.findRef() time.sleep(5) os.system('clear') main() main() #Run main program
051ea04aaa0f1eeb520645c2eef1560241dd1386
odgiedev/python-cev
/PythonCeV/ex102.py
534
3.71875
4
def fatorial(num=0, show=False): """ ver o fatorial de um numero. parametro 'num': o numero que vc quer o fatorial; parametro 'show': se vc quer ver a conta; return: o valor do fatorial do num(que foi passado). """ f = 1 for c in range(num, 0, -1): f = f * c if show: print(c, end='') if c <= 1: print(' = ', end='') if c > 1: print(' x ', end='') return f print(fatorial(5)) help(fatorial)
ad930443e80c01089e720230f04de34a58d3dec4
Astony/Homeworks
/homework2/task01/text_func/fill_weight_list.py
598
4.125
4
def fill_word_weight_list(list_of_words, dict_of_chars_count): """Since we counted the number of repetitions of chars, and we have a list of all words, we will replace each char in the word with its number of repetitions, which represented its uniqueness, and then add these values and get the weight of the word, the less it is, the more unique the word""" words_weight = [] summ = 0 for i in list_of_words: for j in i: summ += dict_of_chars_count[j] words_weight.append((summ, i)) summ = 0 return sorted(words_weight)
e66f0915f85642425415ef7e41854ac782e78e26
MaroderKo/Labs
/Lab10/1.4 Iterable.py
778
3.640625
4
""" 1. Сформувати функцію для введення з клавіатури послідовності чисел і виведення її на екран у зворотному порядку (завершаючий символ послідовності – крапка) Виконав: Перепелиця А.С. """ from datetime import datetime a = list() j = input() # ввод начальных значений значений start_time = datetime.now() # Начало записи аремени while (j!="."): a.append(j) j = input() # ввод начальных значений значений for n in range(len(a)-1,-1,-1): print(a[n]) # вывод результата print(datetime.now() - start_time) #Вывод времени
f112f8b14f10ebec36ff6a241e16856da277524c
AlelksandrGeneralov/ThinkPythonHomework
/tuples_sort.py
532
3.5
4
import cProfile import pstats def sort_by_length(): """sort a words by len1""" t = [] words = open('words.txt') for word in words: line = word.strip() t.append((len(line), line)) t.sort(reverse=False) res = [] for length, line in t: res.append(line) return(res) pr = cProfile.Profile() pr.enable() print(sort_by_length.__doc__) print(sort_by_length()) pr.disable() pr.dump_stats('prof_data') ps = pstats.Stats('prof_data') ps.sort_stats('cumulative') ps.print_stats()
b6f986bd31f92954abfcba100f6871213879a9a3
MrHamdulay/csc3-capstone
/examples/data/Assignment_2/dngmon002/question3.py
240
3.9375
4
import math p=0 prox=2 nxt=0 while nxt!=1: p=math.sqrt(2+p) prox*=2/p nxt=2/p print("Approximation of pi:",round(prox,3)) radius=eval(input("Enter the radius:\n")) area= prox*(radius**2) print("Area:",round(area,3))
1da3970bd09e1f08d9288d99c9930f32c9322f52
FReeshabh/sarraf-machine-learning-class
/project_5/Project5.py
4,882
3.796875
4
import numpy as np import matplotlib.pyplot as plt np.random.seed(137) # # PART 1 - 2 layered Neural Network with 2 hidden Units # -1, as inputs, gave funky results so switched it out for 0's def PART_1(): INPUT_UNITS = 2 HIDDEN_UNITS = 2 OUTPUT_UNITS = 1 C_INPUT = np.array([[0, 0], [0, 1], [1, 0], [1,1]]) # C_OUTPUT = np.array([[0], [1], [1], [0]]) # Hyperparameters EPOCHS = 10000 RHO_LEARNING_RATE = 0.1 random_initializer = lambda size1, size2: np.random.uniform(size=(size1, size2)) # Found this was the best for initializing weights and biases weight_hidden = random_initializer(INPUT_UNITS, HIDDEN_UNITS) # 2, 2 weight_prediction = random_initializer(HIDDEN_UNITS, OUTPUT_UNITS) # 2, 1 bias_hidden = random_initializer(1, HIDDEN_UNITS) # 1, 2 bias_prediction = random_initializer(1, OUTPUT_UNITS) # 1, 1 # Activation Funcs sigmoid_activation = lambda z: (1 / (1 + np.exp(-z))) sigmoid_backpropagation = lambda z: (z * (1 - z)) # Calculating loss def loss(target, prediction): """Calculates the loss""" return (1/2) * (np.linalg.norm((np.square(target - prediction)), ord=2)) def grad_loss(target, prediction): """Derivative of (1/2) * LSE""" return (target-prediction) costs = [] for i in range(EPOCHS): """Perform forward propagation""" hidden_layer = sigmoid_activation(np.dot(C_INPUT, weight_hidden) + bias_hidden) prediction_layer = sigmoid_activation(np.dot(hidden_layer, weight_prediction) + bias_prediction) costs.append(loss(C_OUTPUT, prediction_layer)) # if((costs[i] - costs[i-1]) < 0.00000001): # EPOCHS = i # break """Backpropagation""" error_prediction_layer = grad_loss(C_OUTPUT, prediction_layer) error_hidden_layer = np.dot((error_prediction_layer * sigmoid_backpropagation(prediction_layer)), weight_prediction.T) # Calculating gradients for the update grad_prediction_weight = np.dot(hidden_layer.T, (error_prediction_layer * sigmoid_backpropagation(prediction_layer))) grad_prediction_bias = np.sum(error_prediction_layer * sigmoid_backpropagation(prediction_layer), keepdims=True) grad_hidden_weight = np.dot(C_INPUT.T, (error_hidden_layer * sigmoid_backpropagation(hidden_layer))) grad_hidden_bias = np.sum((error_hidden_layer * sigmoid_backpropagation(hidden_layer)), keepdims=True) #Updating Weights and Biases weight_prediction -= (-RHO_LEARNING_RATE * grad_prediction_weight) bias_prediction -= (-RHO_LEARNING_RATE * grad_prediction_bias) weight_hidden -= (-RHO_LEARNING_RATE * grad_hidden_weight) bias_hidden -= (-RHO_LEARNING_RATE * grad_hidden_bias) def graph_loss_part_1(loss): # plt.plot(loss, label="error", color = 'red') # plt.xlabel('Iterations (EPOCHS)') # plt.ylabel('Loss') # plt.title('Cost graph Rishabh Tewari') # plt.legend() plt.plot(C_INPUT, prediction_layer, label="prediction", linestyle = None) plt.plot(C_INPUT, C_OUTPUT, label = "Target value", linestyle = None) plt.show() # graph_loss_part_1(costs) # print(*prediction_layer) plt.plot(costs) # Error Cost plt.show() PART_1() def PART_2(): X = np.random.rand(1, 50) - 1 T = np.sin(2 * np.pi * X) + (0.3 * np.random.randn(1, 50)) activation_tanh = lambda z: np.tanh(z) backprop_tanh = lambda z: 1.0 - np.square(np.tanh(z)) INPUT_UNITS = 1 HIDDEN_UNITS = 3 OUTPUT_UNITS = 1 random_initializer = lambda size1, size2: np.random.uniform(size=(size1, size2)) # Found this was the best for initializing weights and biases weight_hidden = random_initializer(INPUT_UNITS, HIDDEN_UNITS) # 2, 2 weight_prediction = random_initializer(HIDDEN_UNITS, OUTPUT_UNITS) # 2, 1 bias_hidden = random_initializer(1, HIDDEN_UNITS) # 1, 2 bias_prediction = random_initializer(1, OUTPUT_UNITS) # 1, 1 # Hyperparameters EPOCHS = 10000 RHO_LEARNING_RATE = 0.1 # Calculating loss def loss(target, prediction): """Calculates the loss""" return (1/2) * (np.linalg.norm((np.square(target - prediction)), ord=2)) def grad_loss(target, prediction): """Derivative of (1/2) * LSE""" return (target-prediction) costs = [] for i in range(EPOCHS): hidden_layer = activation_tanh(np.dot(X.T , weight_hidden) + bias_hidden) prediction_layer = backprop_tanh(np.dot(hidden_layer, weight_prediction) + bias_prediction) costs.append(loss(T, prediction_layer)) """Backpropagation""" error_prediction_layer = grad_loss(T, prediction_layer) # PART_2()
bc96a2a4c9b837f689864113810e71413a136bf2
zhulijuan1128/1128
/私有属性.py
466
3.640625
4
# -*- coding: utf-8 -*- """ Created on Wed Sep 9 16:10:43 2020 @author: tute """ #class_student.py class Student: def __init__(self,name,age): self.name=name self.__age=age def say(self): return self.name def getage(self): return self.__age su=Student('易烊千玺',20) print(su.say()) print(su.getage()) print("大家好,我是",su.say(),"年龄:",su.getage())
2d7ef57ce631879d49c000dc239eead5faf0566b
Naateri/JustForFun
/DataStructures/R-Tree.py
3,882
3.546875
4
class Coord: #coordinates def __init__(self, x, y): self.x = x self.y = y class Objct: def __init__(self, data, lower, upper): self.data = data self.ll = lower self.ur = upper self.type = 1 class BBox: #bounding box def __init__(self, lower, upper): self.ll = lower self.ur = upper self.data = list() def add_data(self, data): self.data.append(data) def print_data(self): print ('Bounding box') for dat in self.data: print('nombre del dato: ' + str(dat.data) + '\nLower left corner (' + str(dat.ll.x) + ',' + str(dat.ll.y) + ')\nUpper right corner (' + str(dat.ur.x) + ',' + str(dat.ur.y) + ')') print() class RNode: #type 0 = internal node, type 1 = leaf node def __init__(self, obj_bb, n_type = 1): self.type = n_type self.ll = [None] * 4 self.ur = [None] * 4 self.obj_ptr = [None] * 4 self.boundbox = [None] * 4 self.ll[0] = obj_bb.ll self.ur[0] = obj_bb.ur self.obj_ptr[0] = obj_bb """if (n_type == 1): self.obj_ptr[0] = obj_bb #Object pointer else: #type = 0, pointer to child self.boundbox[0] = obj_bb #bounding box""" #4 minimum bounding boxes (mbb) per leaf node class RTree: def __init__(self): #self.root = [None] * 4 self.root = None def real_lookup(self, x, y, n, result): if n.type == 0: return else: obj = n if (obj.ll.x <= x and x <= obj.ur.x and obj.ll.y <= y and y <= obj.ur.y): #if the object is in the point result.append(obj) """for obj in n.obj_ptr: if obj is None: continue if (obj.ll.x <= x and x <= obj.ur.x and obj.ll.y <= y and y <= obj.ur.y): #if the object is in the point result.append(obj)""" return result def lookup(self, x, y, n, result = list()): for node in n.obj_ptr: #print('node data: ' + node.data) if node is not None: print ('n: ' + str(n)) self.real_lookup(x,y,node,result) return result def insert(self, obj, n): if self.root is None: self.root = RNode(obj, 1) else: if n.type == 0: for i in range(4): if (n[i].ll.x <= obj.ll.x and obj.ur.x <= n[i].ur.x and n[i].ll.y <= obj.ll.y and obj.ur.y <= n[i].ur.y): self.insert(obj, n[i].obj_ptr) return else: return """ #split leaf node into 2 nodes #find bounding box for new nodes #and the stuff found at #http://www.mathcs.emory.edu/~cheung/Courses/554/Syllabus/3-index/R-tree.html """ bb1 = BBox(Coord(0,0),Coord(60,50)) house1 = Objct('house1',Coord(25,25), Coord(50,40)) bb1.add_data(Objct('house1',Coord(25,25), Coord(50,40))) bb1.add_data(Objct('road1', Coord(0,45), Coord(60,50))) bb1.add_data(Objct('road2', Coord(55,0), Coord(60,50))) bb2 = BBox(Coord(20,20),Coord(100,80)) bb2.add_data(Objct('school', Coord(20,60), Coord(50,80))) bb2.add_data(Objct('pop', Coord(70,60), Coord(80,75))) bb2.add_data(Objct('house2', Coord(70,40), Coord(90,60))) bb2.add_data(Objct('pipeline', Coord(50,35), Coord(100,40))) bb1.print_data() bb2.print_data() #print ('Upper corner y: ' + str(bb1.ur.y) ) gg = RTree() gg.insert(house1, gg.root) temp = gg.lookup(35,40,gg.root) print ('Value found: ' + str(temp[0].data))
280abf36cef0ba80bf0a238498b8676299c52764
ConnorLeeJones/cons_coding_challenge
/main/flag.py
1,125
4.625
5
# Jump The Flag # A Kangaroo, is trying to reach a flag that's flagHeight units above the ground. # In his attempt to reach the flag, the kangaroo can make any number of jumps up the rock wall where it's mounted; # however, he can only move up the wall (meaning he cannot overshoot the flag and move down to reach it). # There are 2 types of jumps: # 1.) A jump of height 1. # 2.) A jump of height jumpHeight. # the kangaroo wants your help determining the minimum number of jumps it will take him to collect the flag. # Complete the jumps function. It has 2 parameters: # An integer, flagHeight, the height of the flag. # An integer, jumpHeight, the number of units he ascends in a jump of type 2. # It must return an integer denoting the minimum number of times the kangaroo must jump to collect the flag. # Example: # flagHeight = 3, jumpHeight = 1 # Should return 3 # As the kangaroo can only jump 1 unit or jumpHeight units and jumpHeight = 1, the kangaroo can only ever make 1-unit jumps. # This means that it will take him 3 steps to reach the flag, so we return 3. def jumps(flagHeight, jumpHeight): pass
4c933228c8e655bc7ec70f48ae821c6e6288c37c
RomanAdriel/AlgoUnoDemo
/Bili/UTN_Unidad_2/ejercicio_3.py
1,082
4.46875
4
# Ejercicio 3 # Cree un diccionario con las claves: #· identificador #· nombre #· apellido #· telefono #Nota: al utilizar claves no utilice acentos u # otros caracteres en español, por ejemplo no # ponga “teléfono” sino “telefono”. #Realice un programa que a partir del # diccionario creado retorne en una oración: #1) El número de elementos del diccionario #2) Las claves del diccionario #Pregunta: ¿Cree que para guardar y recuperar # información es mejor un diccionario o una # lista? Justifique su respuesta. claves = ['identificador', 'nombre', 'apellido', 'telefono'] valores = ['00', 'Juan', 'Perez', '0810 000 111'] d = dict(zip(claves,valores)) print('El diccionario creado tiene ' + str(len(d)) + ' elementos y sus claves son ' + ', '.join(d.keys())) print('\n') print("""¿Cree que para guardar y recuperar información es mejor un diccionario o una lista?""") print('\n') print(""" Respuesta: no hay uno mejor que el otro. La lista trabaja con elementos ordenados mientras que a los elementos del diccionario se accede por las llaves. """)
22ef4070e49acd4e3ce95e4821047e5548b6b9f9
pharaon1815/math_functions
/division.py
633
3.984375
4
# Error handling practice def quotient(): # define quotient function response = input('Do you need help with division? (y/n): ') while response == 'y': # loop to continue asking try: n = input('numerator: ') # input numerator d = input('denominator: ') # input denominator print(str(n) + '/' + str(d) + ' =', end=' ') print(int(n)/int(d)) response = input('Do you need help with division? (y/n): ') except ZeroDivisionError: print('Error: I can\'t divide by 0') quotient() # calls the quotient function
3f5a55ea2f7bccf348d3257c9c668063b68d43c4
rafaelperazzo/programacao-web
/moodledata/vpl_data/40/usersdata/106/24720/submittedfiles/funcoes.py
1,338
3.734375
4
#ARQUIVO COM SUAS FUNCOES # -*- coding: utf-8 -*- from __future__ import division #Estabelecer a função valor_absoluto para comparar o valor do cosseno com o epislon def valorabsoluto(x): if x>=0: valorabsoluto = x else: valorabsoluto = x*(-1) return valorabsoluto #calculo do valor de pi def calculapi(m): pi = 3.00 a=2.00 variavel =1 i=1 while i<= m: pi = pi + ((variavel*4)/(a*(a+1)*(a+2))) a = a+2 variavel = variavel*(-1) i=i+1 return pi #Para calcular a função cosseno, é necessário definir a função fatorial para os denominadores def fatorial(a): fatorial = 1 while a>=1: fatorial = fatorial*a a = a-1 return fatorial #Iniciarei o cosseno com cosz=1 para facilitar os cálculos, já que é a parte fixa para o cálculo de todos os cossenos #criei uma variável p para facilitar no fator de correção do sinal def calculacosseno(x,epislon): cosz = 1.00 p = 1.00 while True: cosz = cosz+((((x**2)**p)/fatorial(2*p))*((-1)**p)) if valorabsoluto ((((x**2)**p)/fatorial(2*p))*((-1)**p)) > epislon: p = p+1 else: break return cosz def razaoaurea(m,epislon): z = (calculapi(m)/5) RA = 2*calculacosseno(z,epislon) return RA
1dfb76eb98c50de8b7511d53219a856ce6d8d5da
ConstanceBeguier/tensorflow-examples
/2_manage_overfitting.py
3,606
3.875
4
#!/usr/bin/env python3 """ TensorFlow code to learn the following network on the MNIST database [28, 28, 1] -> Conv2D(30, (5, 5), relu) -> MaxPooling(2, 2) -> Conv2D(15, (3, 3), relu) -> MaxPooling(2, 2) -> Flatten -> Dense(128, relu) -> Dense(50, relu) -> Dense(10, softmax) Early stopping and regularizers are used to limit the overfitting. Copyright (c) 2020 ConstanceMorel Licensed under the MIT License Written by Constance Beguier """ # Third-party library imports import tensorflow as tf from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt def main(): """ Learning the following network on the MNIST database [28, 28, 1] -> Conv2D(30, (5, 5), relu) -> MaxPooling(2, 2) -> Conv2D(15, (3, 3), relu) -> MaxPooling(2, 2) -> Flatten -> Dense(128, relu) -> Dense(50, relu) -> Dense(10, softmax) """ # Load database (images_train, targets_train), (images_test, targets_test) = tf.keras.datasets.mnist.load_data() # Normalization images_train = images_train.reshape(-1, 784).astype(float) scaler = StandardScaler() images_train = scaler.fit_transform(images_train) images_test = images_test.reshape(-1, 784).astype(float) images_test = scaler.transform(images_test) images_train = images_train.reshape(-1, 28, 28, 1).astype(float) images_test = images_test.reshape(-1, 28, 28, 1).astype(float) # Create validation database from training_database images_train, images_validation, targets_train, targets_validation = train_test_split( images_train, targets_train, test_size=0.2, random_state=42) # Network architecture model = tf.keras.models.Sequential() model.add(tf.keras.layers.Conv2D(30, (5, 5), input_shape=(28, 28, 1), \ activation="relu", padding='same')) model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2))) model.add(tf.keras.layers.Conv2D(15, (3, 3), activation="relu", padding='same')) model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2))) model.add(tf.keras.layers.Dropout(0.2)) model.add(tf.keras.layers.Flatten()) model.add(tf.keras.layers.Dense(128, activation="relu", \ kernel_regularizer=tf.keras.regularizers.l1_l2(l1=0.01, l2=0.01))) model.add(tf.keras.layers.Dense(50, activation="relu", \ kernel_regularizer=tf.keras.regularizers.l1_l2(l1=0.01, l2=0.01))) model.add(tf.keras.layers.Dense(10, activation="softmax")) # Optimizer model.compile( loss="sparse_categorical_crossentropy", optimizer="sgd", metrics=["accuracy"]) # Early stopping early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', mode='min', patience=5) # Learn history = model.fit(images_train, targets_train, \ validation_data=(images_validation, targets_validation), \ epochs=4000, callbacks=[early_stopping]) loss_curve = history.history["loss"] acc_curve = history.history["accuracy"] loss_val_curve = history.history["val_loss"] acc_val_curve = history.history["val_accuracy"] plt.figure() plt.subplot(1, 2, 1) plt.plot(loss_curve, label="Train") plt.plot(loss_val_curve, label="Test") plt.legend() plt.title("Loss") plt.subplot(1, 2, 2) plt.plot(acc_curve, label="Train") plt.plot(acc_val_curve, label="Test") plt.legend() plt.title("Accuracy") plt.savefig("loss_acc_1.png") # Evaluate on the test database scores = model.evaluate(images_test, targets_test, verbose=0) print(scores) if __name__ == '__main__': main()
8827a7b1690357f40922e0b77574b0d16489351e
GabrielCB1/StructuredProgramming2A
/unit1/Codes/one.py
385
3.875
4
num = int (input("Join your number:... ")) def evaluar_primo(num): contador=0 resultado=True for i in range (1, num+1): if (num%i==0): contador +=1 if (contador>2): resultado=False break return resultado if (evaluar_primo(num)==True): print("This number is prime") else: print ("This number isn't prime")
85bbc85f0cb8dea5a52e02beae92303b113cbec1
karleypetracca/week-1-python-exercises
/dict-name-to-number.py
615
4.46875
4
# Series of basic dictionary exercises with given dictionary # Print Elizabeth's phone number. # Add an entry to the dictionary: Kareem's number is 938-489-1234. # Delete Alice's phone entry. # Change Bob's phone number to '968-345-2345'. # Print all the phone entries. phonebook_dict = { 'Alice': '703-493-1834', 'Bob': '857-384-1234', 'Elizabeth': '484-584-2923' } print(phonebook_dict["Elizabeth"]) phonebook_dict["Kareem"] = "938-489-1234" phonebook_dict.pop("Alice") phonebook_dict["Bob"] = "968-345-2345" for i in phonebook_dict: print(phonebook_dict[i]) # OR #print(phonebook_dict.values())
957559b306fe090effe9d4cb7d5dc5471a7445ab
mycho2003/TIY
/6/6-6.py
353
3.671875
4
favorite_languages = {"jen": "python", "sarah": "c", "phil": "python", "edward": "ruby"} pollers = ["michael", "phil", "josh", "ben", "jen"] for poller in pollers: if poller in favorite_languages: print("Thank you for responding to the poll, " + poller.title() + "!") else: print(poller.title() + ", you should take the poll!")
6c384deeebd011fb078c897832aea41747f9adb3
season101/PasswordEncrpyter
/test.py
717
4.03125
4
print("Welcome to the program where we will encrpypt your passowrd in image for you.") print() print("Press any key to continue...") input() print() print() masterKey = input("Enter a key that you want to use throughout your lifetime: ") imageName = input("Enter the image name you want to put password to: ") outputName = input("Enter the name for your output image: ") print() imageName+= ".jpg" outputName+= ".png" from cryptosteganography import CryptoSteganography crypto_steganography = CryptoSteganography(masterKey) # Save the encrypted file inside the image passcode = input("Enter your secret passcode: ") crypto_steganography.hide(imageName,outputName,passcode) print("Successfully Encrypted...")
bbcba63fc120e7d6e237804e5a64e4a1ef7ff41c
JoeMaurice88/testayed2021
/Unidad 3/ejercicio6.py
306
3.875
4
""" Determinar si una persona tiene fiebre. (fiebre : 37.5 grados) o tiene menos de 30° y sino esta sano """ temperatura= float(input("Ingrese su temperatura: ")) if temperatura>= 37.5: print("tiene fiebre") elif temperatura<= 30: print("tiene baja temperatura") else: print("Estas sano")
95e025f9c688a41e505e037bd4c7e188b82e8655
RoxanaTesileanu/Py_for_kids
/py_for_kids_ch5.py
5,038
4
4
Python 2.7.12 (default, Jul 1 2016, 15:12:24) [GCC 5.4.0 20160609] on linux2 Type "copyright", "credits" or "license()" for more information. >>> # questions = conditions >>> # we combine these conditions and the responses into if statements >>> >>> age= 13 >>> if age> 20 : print ('You\'r too old') >>> age=23 >>> if age> 20 : print ('You\'r too old') You'r too old >>> # if the answer is true the commands in the block will be run >>> # a block is a group of programming statements >>> age=25 >>> if age > 20 : print('You are too old!') print ('Why are you here?') print ('Why aren\'t you mowing a lawn or sorting papers') You are too old! Why are you here? Why aren't you mowing a lawn or sorting papers >>> if age > 20 : print('You are too old!') print ('Why are you here?') print ('Why aren\'t you mowing a lawn or sorting papers') You are too old! Why are you here? Why aren't you mowing a lawn or sorting papers >>> if age > 20 : print('You are too old!') print ('Why are you here?') print ('Why aren\'t you mowing a lawn or sorting papers') File "<pyshell#20>", line 4 print ('Why aren\'t you mowing a lawn or sorting papers') ^ IndentationError: unexpected indent >>> >>> age=10 >>> if age>10 : print('you are too old for my jokes') >>> age =1- SyntaxError: invalid syntax >>> age =10 >>> if age >= 10 : print ('you are too old for my jokes') you are too old for my jokes >>> age=10 >>> if age == 10 : print ('What\'s brown and sticky? A stick!!') What's brown and sticky? A stick!! >>> print ('want to hear a dirty joke?') want to hear a dirty joke? >>> age =12 >>> if age == 12 : print ('a pig fell in the mud') else : print ("shh. it's a secret") a pig fell in the mud >>> age=8 >>> if ager ==12 : print ('a pig fell in the mud') else : print ('shh. it\'s a secret') Traceback (most recent call last): File "<pyshell#47>", line 1, in <module> if ager ==12 : NameError: name 'ager' is not defined >>> if age ==12 : print ('a pig fell in the mud') else : print ('shh. it\'s a secret') shh. it's a secret >>> age=12 >>> if age ==10 : print ('what do you call an unhappy cranberry?) SyntaxError: EOL while scanning string literal >>> if age ==10 : print ('what do you call an unhappy cranberry?') print('a blueberry!') elif age==11 : print ('what did the green grape say tp the blue grape?') print('breathe! breath!') elif age ==12 : print ('what did 0 say to 8?') print ('hi guys!') elif age ==13 : print ('why wasn\'t 10 afraid of 7?') print ('because rather than eating 9, 78 pi') else : print ('huh?') what did 0 say to 8? hi guys! >>> if age ==10 or age==11 or age==12 or age==13 : print('what is 10 + 11+12+13? A mess!') else : print ('huh?') what is 10 + 11+12+13? A mess! >>> if age >=10 and age<=13 : print ('what is 10+13? A mess!') else : print ('huh?') what is 10+13? A mess! >>> age 12 >>> myval=None >>> print(myval) None >>> # empty value >>> if myval==None : print ('the variable myval doesn\'t have a value') the variable myval doesn't have a value >>> >>> age 12 >>> if age ==10 : print ('what\'s the best way to speak to a monster?') print ('from as far away as possible!') >>> age=10 >>> if age ==10 : print ('what\'s the best way to speak to a monster?') print ('from as far away as possible!') what's the best way to speak to a monster? from as far away as possible! >>> age='10' >>> converted_age=int(age) >>> age=10 >>> converted_age=str(age) >>> print age 10 >>> age 10 >>> age='10' >>> converted_age=int(age) >>> if converted_age==10 : print ('what\'s the best way to speak to a monster?') print ('from as far away as possible!') what's the best way to speak to a monster? from as far away as possible! >>> age='10.5' >>> converted_age=int(age) Traceback (most recent call last): File "<pyshell#105>", line 1, in <module> converted_age=int(age) ValueError: invalid literal for int() with base 10: '10.5' >>> converted_age=float(age) >>> converted_age 10.5 >>> age='ten' >>> converted_age=int(age) Traceback (most recent call last): File "<pyshell#109>", line 1, in <module> converted_age=int(age) ValueError: invalid literal for int() with base 10: 'ten' >>> cakes=250 >>> if cakes <=100 or cakes>=500 : print ('too few or too many') else : print ('just right') just right >>> cakes = 600 >>> if cakes <=100 or cakes >=500 : print ('too few or too many') else : print ('just right') too few or too many >>> cakes =600 >>> if cakes <=1000 or cakes >= 5000 : print ('too few or too many') else : print ('just right') too few or too many >>> ninjas=5 >>> if ninjas < 10 : print ('I can fight those ninjas') elif ninjas <30 : print ('It will be a struggle') elif ninjas < 50 : print ('That\'s too many!') I can fight those ninjas >>> ninjas=15 >>> if ninjas < 10 : print ('I can fight those ninjas') elif ninjas <30 : print ('It will be a struggle') elif ninjas < 50 : print ('That\'s too many!') It will be a struggle >>>
1cf1b29b66e158ece7739ca5c9bc31c39f35deff
asethi-ds/Algorithm-Toolbox
/binary_search/first_occurence.py
814
3.9375
4
def findFirst(arr, a): """ Unlike binary search, cannot return in the loop. The purpose of while loop is to narrow down the search range. Can combine two conditions: `arr[m] >= a` """ if not arr: return -1 l, r = 0, len(arr) - 1 # exit loop when l + 1 == r, i.e. consecutive while l + 1 < r: # avoid integer overflow m = (r - l) // 2 + l if arr[m] == a: # cannot do r = m - 1, because # m could be the first occurrence # out-of-bound error also possible r = m elif arr[m] > a: # can do r = m - 1 r = m else: # can do l = m + 1 l = m # three possible result: XXOO if arr[l] == a: # XXOO # ^^ return l elif arr[r] == a: # XXOO # ^^ return r # XXYY, X < O < Y # ^^ return -1 # not found
6ddd82dfe0eacffb84221bf3d1c5d0d25c90e949
rabi-siddique/LeetCode
/Arrays/MedianOfTwoSortedArrays.py
779
4.15625
4
''' Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. Follow up: The overall run time complexity should be O(log (m+n)). Example 1: Input: nums1 = [1,3], nums2 = [2] Output: 2.00000 Explanation: merged array = [1,2,3] and median is 2. Example 2: Input: nums1 = [1,2], nums2 = [3,4] Output: 2.50000 Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. Example 3: Input: nums1 = [0,0], nums2 = [0,0] Output: 0.00000 ''' import math class Solution(object): def findMedianSortedArrays(self,nums1, nums2): l = sorted(nums1 + nums2) if len(l)%2 == 0: n = len(l)//2 return float((l[n]+l[n-1])/float(2)) else: return l[len(l)//2]
72df9cd5936d7bd80abd4316ffd3a1c9d7515e08
avinsrid/Hangman
/hangman.py
1,898
3.890625
4
#!/usr/bin/env python # blitzavi89 # ---------------------------------------------------------------- # SIMPLE HANGMAN GAME WITH GUI (Python 3.x) # ---------------------------------------------------------------- from Hangman_GUI import * import random import json import tkinter # Begin the Game Here def Begin_Game() : global hangman hangman.Tile_Create() hangman.Main_Display() Show_Puzzle() # Main game logic, that includes reading from JSON file def Show_Puzzle() : global hangman country_file = open("countries.json" , "r+") json_Obj = json.loads(country_file.read()) country_file.close() country_list = [] for country in json_Obj : country_list.append(country["name"]) country_question = random.choice(country_list) print ("Show_Puzzle(): Random Generated Country is " + country_question) testfunc = Check_Game_Status hangman.Generate_Puzzle_Blank(country_question, testfunc) hangman.Quit_Button() # Check if we need to continue the game or not based on 'replay' value def Check_Game_Status() : global hangman if hangman.replay == True : Game_Replay() else : Destroy_Game() # Destroy game. I think this never gets called. However :P just to be safe def Destroy_Game() : global hangman hangman.destroy() # If 'replay' from Check_Game_Status = True, we will reset game environment variables and proceed to play game again def Game_Replay() : global hangman for every_element in hangman.blank_buttons : if every_element != " " : every_element.destroy() else : every_element = None hangman.tiles_button = [] hangman.blank_buttons = [] hangman.display_buttons = [] hangman.question = None hangman.callbackfunc = None hangman.chance = 0 hangman.Initialize_Hanger() hangman.play_again_button1 = None hangman.play_again_button2 = None Begin_Game() # Initiate the game process here hangman = Hangman_GUI(None) Begin_Game() hangman.mainloop()
d5ff4d04602f58c0dc5a539d5a1abb759e2f365c
rlyyah/2nd-self-instructed-week
/code/trying-out/strings.py
240
3.65625
4
word = 'tomek' for i in range(-1,-len(word)-1,-1): print(word[i]) print(word[1:4]) print(word[-4:-1]) print(word[::-1]) print(word[0:len(word):2]) print(word[1:len(word):2]) print('format-=====') print(word+ '{}'.format('kappa'))
fca0f9ad72989f88ec599b65b84b1046b63dd55a
zhlthunder/python-study
/python框架/flask/补充:对象的内置方法.py
1,017
4.03125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- #author:zhl class Foo(object): def __add__(self, other): return 123 obj1=Foo() #当执行: obj1+2 #就会自动执行obj1的__add__方法,就和 ‘对象()’ 会自动执行对象的__call__方法一样,也是一个语法糖 #上面的2可以看成是int类的一个对象,所以 两个对象相加时也一样会调用这个方法 obj2=Foo() v=obj1+obj2 print(v) #输出 123 class Foo(object): def __init__(self,num): self.num=num def __add__(self, other): data=self.num+other.num return Foo(data) obj1=Foo(11) obj2=Foo(22) v=obj1+obj2 print(v) ##其它对于加减乘除都可以使用 #可以查看下flask的源码中支持的 __方法__ #在local.py中查看 from flask import Flask print("----------------------------------") class Foo(): def __str__(self): print("aaaa") return '123' obj=Foo() print(obj) ##语法糖: print(obj) 会自动执行对象的__str__方法
6908e6bd68cc725f00502d017f6f0fece2e2b069
DanThePutzer/tars
/2-12-Linear_Regression/6-Pickling_And_Scaling.py
627
3.53125
4
import pandas as pd import numpy as np import pickle from sklearn import preprocessing, model_selection from sklearn.linear_model import LinearRegression from matplotlib import pyplot as plt # Importing model from pickle pickle_in = open('Data/GoogleStockClassifier.pickle', 'rb') clf = pickle.load(pickle_in) # Importing data google = pd.read_pickle('Data/GoogleFeatures&Label.pickle') predictionSet = np.array(google.drop(['Label'], axis=1)) predictionSet = preprocessing.scale(predictionSet) predictionSet = predictionSet[-35:] # Predict results = clf.predict(predictionSet) print(results) plt.plot(results) plt.show()
83a22251f0766fd285a337548eaf486f334f59bc
gautambp/codeforces
/509-A/509-A-46916805.py
157
3.671875
4
n = int(input()) def getMatrixVal(i, j): if i == 1 or j == 1: return 1 return getMatrixVal(i-1, j) + getMatrixVal(i, j-1) print(getMatrixVal(n, n))
0149a9129fb64d7bc2ceb246956ab2d036dc0e7f
Yfke/AoC2020
/15/15a2.py
848
3.5
4
import time test1 = [0, 3, 6] input = [15, 12, 0, 14, 3, 1] def main(): start_time = time.time() start = input history = [-1] * 30000000 # initialize fixed input (but skip the last one) # -1 signifies "this value hasn't occurred yet" for i in range(len(start) - 1): history[start[i]] = i # store last fixed input into separate variable prev = start[-1] for i in range(len(start), 30000000): # at which index did this number occur last? (-1 = none) occurs = history[prev] # store the index for future reference history[prev] = i-1 if occurs == -1: # say zero prev = 0 else: # say difference prev = i - 1 - occurs print(prev) print(time.time() - start_time) if __name__ == "__main__": main()
f026cea4a1e8284b8228b54e26e531ac339cc6b5
Ichbini-bot/python-labs
/13_list_comprehensions/13_06_SLT.py
281
3.765625
4
letters = [i for i in "codingnomads"] print(letters) letter = [] for char in 'CodingNomads': letter.append(char.lower()) print(letter) class MyCustomException(Exception): pass try: raise MyCustomException("There was a problem") except Exception as e: print(e)
74b439f7675086d2c0b70a8bcdecde4acd17d6a5
xandrd/CourseraPhython
/week4/module4/solution_summa.py
109
3.671875
4
def summa(a): if a != 0: a += summa(int(input())) return a a = int(input()) print(summa(a))
5d83dc0f354d12718b5ae1c879c8b4b169c508e5
alexwei316/SortPractice
/SortPractice/bruteForceSort.py
317
3.578125
4
__author__ = 'WEI' def brute_force_sort(A): for p in range(len(A)): brute_force_sublist_sort(A, p) return A def brute_force_sublist_sort(A, p): for i in range(p + 1, len(A)): if A[i] < A[p]: swap(A, i, p) def swap(A, i, j): temp = A[i] A[i] = A[j] A[j] = temp
a0d23de90fdab5aa7e3ecaf0cd0eee4ad024d7dc
pns845/Selenium
/listof.py
854
3.640625
4
#to find all the tags are present or all buttons are present #finding multiple elements from selenium import webdriver from selenium.webdriver.common.by import By class FindList(): def test(self): baseURL="https://learn.letskodeit.com/p/practice" driver=webdriver.Chrome(executable_path="C:\\Users\\M524891\\PycharmProjects\\workspace_python\\drivers\\chromedriver.exe") driver.get(baseURL) elements_id=driver.find_elements_by_id("name") list1=len(elements_id) print("the number of webelements with same id are"+str(list1)) elements_tag=driver.find_elements(By.TAG_NAME,"a") list2=len(elements_tag) print("the number of webelements with same tag are" +str(list2)) # for i in range(list2): # print(i.__getattribute__()) c=FindList() c.test()
91fe273774cdf2abc109f852d2ce6cce19639260
yzl232/code_training
/mianJing111111/Google/Given N dices.Each dice has A faces.That means each dice has numbers from 1 to A.Given Sum S,Find the number of ways to make the sum S if dices are rolled together..py
2,192
3.921875
4
# encoding=utf-8 ''' Given N dices.Each dice has A faces.That means each dice has numbers from 1 to A.Given Sum S,Find the number of ways to make the sum S if dices are rolled together. ''' #http://www.geeksforgeeks.org/dice-throw-problem/ ''' Given n dice each with m faces, numbered from 1 to m, find the number of ways to get sum X. X is the summation of values on each face when all the dice are thrown. The Naive approach is to find all the possible combinations of values from n dice and keep on counting the results that sum to X. ''' pass ''' Let the function to find X from n dice is: Sum(m, n, X) The function can be represented as: Sum(m, n, X) = Finding Sum (X - 1) from (n - 1) dice plus 1 from nth dice + Finding Sum (X - 2) from (n - 1) dice plus 2 from nth dice + Finding Sum (X - 3) from (n - 1) dice plus 3 from nth dice ................................................... ................................................... ................................................... + Finding Sum (X - m) from (n - 1) dice plus m from nth dice So we can recursively write Sum(m, n, x) as following Sum(m, n, X) = Sum(m, n - 1, X - 1) + Sum(m, n - 1, X - 2) + .................... + Sum(m, n - 1, X - m) ''' class Solution: d = {} def findWays(self, m, n, x): #m算是固定值. 比如6。 主要是x, n if n<1 or x<=0: return 0 if n==1 and 1<=x<=m: return 1 if (n, x) not in self.d: self.d[n, x] = sum(self.findWays(m, n-1, x-i) for i in range(1, m+1)) return self.d[n, x] s = Solution() print s.findWays(4, 2, 1) print s.findWays(2, 2, 3) ''' class Solution: def findWays(self, m, n, x): #m算是固定值. 比如6。 主要是x, n dp = [[0]*(x+1) for i in range(n+1)] for j in range(1, m+1): if j>x: break #防止越界 dp[1][j] = 1 for i in range(2, n+1): for j in range(1, x+1): dp[i][j]= sum(dp[i-1][j-k] for k in range(1, m+1) if j-k>=0) #防止越界 return dp[-1][-1] '''
4c6f96f009bd105216be5f59051f491c63976588
ishchow/alexa_chess
/flasks/classdef.py
7,652
3.859375
4
from itertools import product class Board: """The game board. Contains information about: locations of chess pieces number of active pieces x-axis: a-h y-axis: 1-8 """ def __init__(self): self.board = {(x,y):None for x in range(8) for y in range(8)} self.pieceCount = 32 self.whitePieces = 16 self.blackPieces = 16 self.SpawnAll() self.DisplayBoard() def SpawnAll(self): for x in range(8): self.board[(x, 1)] = pawn('pawn', 'white') self.board[(1, 0)] = knight('knight', 'white') self.board[(6,0)] = knight('knight', 'white') self.board[(0,0)] = rook('rook', 'white') self.board[(7,0)] = rook('rook', 'white') self.board[(2,0)] = bishop('bishop', 'white') self.board[(5,0)] = bishop('bishop', 'white') self.board[(4,0)] = king('king', 'white') self.board[(3,0)] = queen('king', 'white') #spawn black pieces for x in range(8): self.board[(x, 6)] = pawn('pawn', 'black') self.board[(1, 7)] = knight('knight', 'black') self.board[(6,7)] = knight('knight', 'black') self.board[(0,7)] = rook('rook', 'black') self.board[(7,7)] = rook('rook' , 'black') self.board[(2,7)] = bishop('bishop', 'black') self.board[(5,7)] = bishop('bishop', 'black') self.board[(4,7)] = king('king', 'black') self.board[(3,7)] = queen('queen', 'black') def DisplayBoard(self): print(self.board) def GetPieceCount(self): print(self.pieceCount) """ Moves a piece from one location to another Parameters: piece: the chess piece to move loc: the current location of the chess piece dest: the destination to move to game: the game """ def Move(self, loc, dest, game): piece = self.board[loc] # the piece object to move if piece == None: print("There's nobody there, ya dingus!") return None if piece.color != game.currentPlayer: print("he ain't your guy ya dingus!") return None if (dest[0] not in range(8) or dest[1] not in range(8)): print("That destination ain't on the board, ya dingus!") return None legalMoves = piece.legalmoves() # a list of all possible movement vectors attemptedMove = (dest[0]-loc[0],dest[1]-loc[1]) if attemptedMove not in legalMoves: # If the destination is not possible to move to print("Not a legal move") return None #leftright if attemptedMove[0] != 0 and attemptedMove[1] == 0 and piece.piecetype == 'rook' or 'queen': left = min(loc[0],dest[0]) right = max(loc[0],dest[0]) checkblock = [(a,loc[1]) for a in range(left,right)] for i in range(len(checkblock)): if self.board[checkblock[i]] != None: print('blocked') return None #ada #updown if attemptedMove[0] == 0 and attemptedMove[1] != 0 and piece.piecetype == 'rook' or 'queen': bot = min(loc[1],dest[1]) top = max(loc[1],dest[1]) checkblock = [(loc[0],a) for a in range(bot,top)] for i in range(len(checkblock)): if self.board[checkblock[i]] != None: print('blocked') return None #diagonal if attemptedMove[0] == attemptedMove[1] and piece.piecetype == 'bishop' or 'queen': botleftx = min(loc[0],dest[0]) botlefty = min(loc[1],dest[1]) toprightx = max(loc[0],dest[0]) toprighty = max(loc[1],dest[1]) for j in range(abs(attemptedMove[0])): checkblock += [(botleftx+j,botlefty+j)] for i in range(len(checkblock)): if self.board[checkblock[i]] != None: print('blocked') return None if attemptedMove[0] == -(attemptedMove[1]) and piece.piecetype == 'bishop' or 'queen': topleftx = min(loc[0],dest[0]) toplefty = max(loc[1],dest[1]) botrightx = max(loc[0],dest[0]) botrighty = min(loc[1],dest[1]) for j in range(abs(attemptedMove[0])): checkblock += [(topleftx+j,toplefty-j)] for i in range(len(checkblock)): if self.board[checkblock[i]] != None: print('blocked') return None if self.board[dest] != None: if self.board[dest].color == game.currentPlayer: # If you are moving to a space with your own unit print("You already have a guy there") return None else: print("You killed a guy!") print(piece) self.board[dest] = piece self.pieceCount -= 1 if game.currentPlayer == "white": self.blackPieces -= 1 print(self.blackPieces) game.CurrentPlayer = "black" else: self.whitePieces -= 1 print(self.whitePieces) game.CurrentPlayer = "white" self.board[loc] = None print("Its now %s turn" % (game.CurrentPlayer)) else: print(piece) self.board[dest] = piece self.board[loc] = None print("Its now %s turn" % (game.CurrentPlayer)) class chesspiece(object): horizontal = [(a,0) for a in range(-7,8)] horizontal.remove((0,0)) vertical = [(0,b) for b in range(-7,8)] vertical.remove((0,0)) diagonal1 = [(a,a) for a in range(-7,8)] diagonal1.remove((0,0)) diagonal2 = [(a,-a) for a in range(-7,8)] diagonal2.remove((0,0)) def __init__(self,piecetype,color): self.piecetype = piecetype self.color = color class king(chesspiece): #king.piecetype = 'king' def legalmoves(): kingmoves = [(a,b) for a,b in product(range(-1,2),repeat = 2)] kingmoves.remove((0,0)) castlemove = [(-2,0),(2,0)] return kingmoves+castlemove class queen(chesspiece): #queen.piecetype = 'queen' def legalmoves(self): return horizontal+vertical+diagonal1+diagonal2 class bishop(chesspiece): #bishop.piecetype = 'bishop' def legalmoves(self): return diagonal1+diagonal2 class knight(chesspiece): #knight.piecetype = 'knight' def legalmoves(self): return [(-1,2), (1,2), (2,1), (2,-1), (-2,1), (-2,1), (1,-2), (-1,-2)] class rook(chesspiece): #rook.piecetype = 'rook' def legalmoves(self): return self.horizontal+self.vertical class pawn(chesspiece): #pawn.piecetype = 'pawn' def legalmoves(self): if self.color == "white": return [(0,1),(0,2),(-1,1),(1,1)] elif self.color == "black": return [(0,-1),(0,-2),(-1,-1),(1,-1)] class rungame(): def __init__(self): self.gameBoard = Board() self.currentPlayer = "white" def GetCurrentPlayer(self): return self.currentPlayer def ChangePlayer(self): if self.currentPlayer == "white": self.currentPlayer = "black" elif self.currentPlayer == "black": self.currentPlayer = "white" else: print("I don't know who's turn it is") def getinput(self): print('enter a location and destination as tuples:') playermove = input()
2c4b4b25d19e504d43c5c623a9ddabcbaf394131
gits00/MachineLearning
/Homework/HW12/KMeans.py
1,356
3.671875
4
# -*- coding: utf-8 -*- """ Created on Wed Apr 15 15:18:38 2020 @author: digo """ import matplotlib.pyplot as plt import numpy as np # import KMeans from sklearn.cluster import KMeans #Reading File ##Train data f_train = open('training_set.txt', 'r') data = f_train.read() f_train.close() data_train = data.split() data_train = map(float, data_train) data_train_m = np.array(data_train) x = len(data_train_m)/3 y = 3 data_train_m = data_train_m.reshape(x,y) data_train_t = data_train_m.transpose() points = data_train_m[:,1:] #Implementing clustering using K-means # create kmeans object kmeans = KMeans(n_clusters=2) # fit kmeans object to data kmeans.fit(points) # print location of clusters learned by kmeans object print(kmeans.cluster_centers_) clusters = kmeans.cluster_centers_ # save new clusters for chart y_km = kmeans.fit_predict(points) #Calculate Error Rate error = 0 for i in range(len(y_km)): if(y_km[i] != data_train_t[0][i]): error += 1 error_rate = float(error)/len(data_train_m) print('K-Mean Error:') print(error_rate*100.00) #Plot Results plt.scatter(points[y_km ==0,0], points[y_km == 0,1], s=10, c='red') plt.scatter(clusters[0][0], clusters[0][1], c= 'black', s = 50) plt.scatter(points[y_km ==1,0], points[y_km == 1,1], s=10, c='blue') plt.scatter(clusters[1][0], clusters[1][1], c= 'black', s = 50) plt.show()
5efd98152a534c3aaab472cf094c5d0499ad403e
juank27/Python
/intermedio/f_orden_superior.py
497
3.875
4
#funciones de orden superior def saludo(func): func() def hola(): print("Hola!!") def adios(): print("Adios!!") saludo(hola) saludo(adios) # uso con filter my_list = [1,4,5,6,9,13,19,21] odd = list(filter(lambda x: x%2 !=0, my_list)) print(odd) #uso con map my_list2 = [1,2,3,4,5,6] squares = list(map(lambda x: x **2,my_list2)) print(squares) #uso con reduce from functools import reduce my_list3 = [2,2,2,2,2] all_miltiplied = reduce(lambda a, b : a * b, my_list3) print(my_list3)
e01712481aae9f2c4b78f9989ceb374fa12d7fde
jaroslaw-wieczorek/SI-Numbrix-Game-and-SAT-Problem
/board/cell.py
766
3.53125
4
import sys from os import path class Cell(): """ ID is the value representing the cell |1||2||3| |4||5||6| |7||8||9| """ def __init__(self, ID, value): if type(ID) != int: raise TypeError("TypeError: ID") elif ID < 0: raise ValueError("ValueError: ID") elif type(value) == int and value < 0: raise ValueError("ValueError: ID") else: self.ID = ID self.value = value def __str__(self): return "({:};{:})".format(self.ID , self.value) def __repr__(self): return "({:};{:})".format(self.ID , self.value)
0dd0e7ddba42d63680229c3b64bdeafcfeda48b5
meznak/advent-of-code-2020
/aoc2020/day08/__init__.py
2,652
3.75
4
''' Advent of Code Day 08 Handheld Halting ''' SAMPLE_SOLUTIONS = [5, 8] class Instruction(object): '''A single instruction nop - No operation acc - Add value to accumulator jmp - jump to instruction at offset ''' def __init__(self, code: str, value: int): self.code = code self.value = value self.run_count = 0 self.was_tried = False def interpret(self): '''Determine the result of an instruction''' instr_ptr = 1 accumulator = 0 if self.code == 'nop': pass elif self.code == 'acc': accumulator = self.value elif self.code == 'jmp': instr_ptr = self.value return instr_ptr, accumulator def flip(self): '''Swap a nop for jmp or vice versa''' if self.code == 'nop': self.was_tried = True self.code = 'jmp' elif self.code == 'jmp': self.was_tried = True self.code = 'nop' def parse_data(dataset: list) -> list: '''Interpret string data''' output = [] for item in dataset: if len(item) != 0: code, value = tuple(item.split(' ')) instruction = Instruction(code, int(value)) output.append(instruction) return output def solve_1(program: list) -> int: '''Solve part 1''' instr_ptr = 0 accumulator = 0 while program[instr_ptr].run_count == 0: instruction = program[instr_ptr] instruction.run_count += 1 ip_delta, acc_delta = instruction.interpret() instr_ptr += ip_delta accumulator += acc_delta return accumulator def solve_2(program: list) -> int: '''Solve part 2''' program_end = len(program) found = False while not found: changed_index = -1 instr_ptr = 0 accumulator = 0 # Run the program while program[instr_ptr].run_count == 0: instruction = program[instr_ptr] instruction.run_count += 1 if changed_index == -1 \ and instruction.code in ['nop', 'jmp'] \ and not instruction.was_tried: changed_index = instr_ptr instruction.flip() ip_delta, acc_delta = instruction.interpret() instr_ptr += ip_delta accumulator += acc_delta if instr_ptr >= program_end: found = True break if not found: program[changed_index].flip() for instruction in program: instruction.run_count = 0 return accumulator
6cd6051345f5604a830415b808f4756eb941728f
jzhangfob/jzhangfob.csfiles
/CS313e/Blackjack.py
8,205
3.78125
4
# File: Blackjack.py # Description: Create a program that will stimulate one round of blackjack between the player and the dealer # Student's Name: Jonathan Zhang # Student's UT EID: jz5246 # Course Name: CS 313E # Unique Number: 50940 # # Date Created: 9/21/2016 # Date Last Modified: 9/23/2016 import random #Class for card class Card: #Initialize the default method of the class that runs every time an object is created def __init__(self, suit, pip): #A suit will be either Heart, Clover, Spade, or Diamond (H, C, S, D) self.suit = suit #A pip will be either a number 2-10 or J, Q, K, A self.pip = pip #Initialize the value self.value = 0 if self.pip == "A": self.value = 11 elif pip.isalpha(): self.value = 10 else: number = int(pip) self.value = number def __str__(self): return (self.pip + self.suit) #Class for deck class Deck: suits = ['C', 'D', 'H', 'S'] pips = ['2','3','4','5','6','7','8','9','10','J','Q','K','A'] #Constructor method def __init__(self): #Initialize the instance variable cardList self.cardList = [] for i in range(len(Deck.suits)): for j in range(len(Deck.pips)): aCard = Card(Deck.suits[i], Deck.pips[j]) self.cardList.append(aCard) #Method to shuffle the deck def shuffle(self): random.shuffle(self.cardList) #Deal card method def dealOne(self, player): #Add the top card to the player's hand and simultaneously delete the card firstCard = self.cardList[0] player.hand.append(firstCard) player.handTotal += firstCard.value self.cardList.remove(firstCard) #Print method def __str__(self): return_string = '' for i in range(len(self.cardList)) : return_string += str(self.cardList[i]).rjust(4) if (i == 12 or i == 25 or i == 38 or i == 51): return_string += "\n" return return_string #Class for players class Player: def __init__(self): self.hand = [] self.handTotal = 0 self.blackJack = False def __str__(self): return_string = '' for i in range(len(self.hand)): return_string += str(self.hand[i]).ljust(4) return return_string #Function for show hands def showHands(dealer, player): print ("Dealer shows" + " " + str(dealer.hand[1]) + " faceup") print ("You show" + " " + str(player.hand[1]) + " faceup") print () #Function for the player's turn def playerTurn(cardDeck, player, dealer): print ("You go first") totalValue = player.handTotal dealtAce = False blackJack = False flag = False #print (totalValue) -- worked for obj in player.hand: if "A" in str(obj): print ("Assuming 11 points for an ace you were dealt for now") dealtAce = True print ("You hold " + str(player.hand[0]) + " " + str(player.hand[1]) + \ " for a total of " + str(totalValue)) if totalValue == 21: player.blackJack = True print ("Blackjack!") print ("Dealer's turn") return choice = int(input("1 (hit) or 2 (stay)? ")) print () #Input validation while choice != 1 and choice != 2: choice = int(input("1 (hit) or 2 (stay)? ")) print() if choice == 1: while choice != 2: nextCard = cardDeck.cardList[0] if "A" in str(nextCard): dealtAce = True player.hand.append(nextCard) print ("Card dealt: " + str(nextCard)) totalValue += nextCard.value player.handTotal += nextCard.value #If player busts with an ace if totalValue > 21 and dealtAce: print ("Over 21. Switching an ace from 11 points to 1") totalValue -= 10 player.handTotal -= 10 print ("New total: " + str(totalValue)) print() #If player busts without an ace elif totalValue > 21 and dealtAce == False: print ("You bust!") print ("Dealer wins!") print() return #If player gets 21 elif totalValue == 21: print ("21!") cardDeck.cardList.remove(nextCard) print() break #If everything is normal and still under 21 else: print ("New total: " + str(totalValue)) print() print ("You hold ", end = '') for obj in player.hand: print (str(obj), end = ' ') print ("for a total of " + str(totalValue)) cardDeck.cardList.remove(nextCard) choice = int(input("1 (hit) or 2 (stay)? ")) dealtAce = False print() #If player chooses to stay after the first deal if choice == 2: print ("You choose to stay. Now it's the dealer's turn") flag = True #If player chooses to stay after the initial hand if choice == 2 and flag == False : print ("You choose to stay. Now it's the dealer's turn") print ("Dealer's turn") print ("Your hand: ", end = '') for obj in player.hand: print (str(obj), end = ' ') print ("for a total of " + str(totalValue)) #Function for the dealer's turn def dealerTurn(cardDeck, player, dealer): totalValue = dealer.handTotal dealtAce = False if player.handTotal > 21: return print ("\nDealer's hand: ", end = '') for obj in dealer.hand: print (str(obj), end = ' ') print ("for a total of " + str(totalValue)) #If player got a blackjack if player.blackJack == True: if totalValue != 21: print ("Dealer didn't get a blackjack. Dealer loses!") print ("You win!") print () return elif totalValue == 21: print ("Dealer also got a blackjack") print ("Dealer wins!") print () return #If not 21, dealer hits until ties or beats player's value if player.blackJack == False: #If dealer dealt an ace to himself for obj in dealer.hand: if "A" in str(obj): print ("Assuming 11 points for an ace you were dealt for now") dealtAce = True #If dealer surpasses the player if totalValue > player.handTotal: print ("Dealer's hand beats yours") print ("Dealer wins!") print () return #If tied with player elif totalValue == player.handTotal: print ("Dealer ties with you") print ("Dealer wins!") print () return while totalValue < player.handTotal: #Deal the next card nextCard = cardDeck.cardList[0] #If ace in the next card that's dealt if "A" in str(nextCard): dealtAce = True dealer.hand.append(nextCard) #print ("Card dealt: " + str(nextCard)) totalValue += nextCard.value dealer.handTotal += nextCard.value print ("Dealer hits: ", end = '') print (str(nextCard)) print ("New total: " + str(totalValue)) print() #If dealer busts with an ace, change the ace to 1 if totalValue > 21 and dealtAce == True: print ("Over 21. Switching an ace from 11 points to 1") totalValue -= 10 dealer.handTotal -= 10 print ("New total: " + str(totalValue)) print() #If dealer busts if totalValue > 21 and dealtAce == False: print ("Dealer busts!") print ("You win!") print () return #If dealer surpasses the player elif totalValue > player.handTotal: print ("Dealer's hand beats yours") print ("Dealer wins!") print () return #If tied with player elif totalValue == player.handTotal: print ("Dealer ties with you") print ("Dealer wins!") print () return cardDeck.cardList.remove(nextCard) dealtAce = False def main(): testCard = Card("H", "A") testDeck = Deck() print ("Initial deck:\n") print (testDeck) random.seed(24) testDeck.shuffle() print ("Shuffled deck: \n") print (testDeck) player = Player() dealer = Player() testDeck.dealOne(player) testDeck.dealOne(dealer) testDeck.dealOne(player) testDeck.dealOne(dealer) print ("Deck after dealing two cards each:\n") print (testDeck) print () showHands(dealer, player) playerTurn(testDeck, player, dealer) dealerTurn(testDeck, player, dealer) print ("Game over.") print ("Final hands: ") print (" Dealer: ", end = '') print (dealer) print (" Opponent: ", end = '') print (player) main()
879db25fc729b0e70249046bc094dec30c3ff804
lawieXhoiger/PythonNotes
/MultiThreading/Global_Interpreter_Lock.py
725
3.515625
4
import threading from queue import Queue import copy import time # test gil def job(l,q): res = sum(l) q.put(res) def multithreading(l): q = Queue() threads = [] for i in range(4): t = threading.Thread(target=job,args=(copy.copy(l),q),name='T%i'%i) t.start() threads.append(t) [t.join() for t in threads] total = 0 for _ in range(4): total += q.get() print(total) def normal(l): total = sum(l) print(total) if __name__ == "__main__": l = list(range(100)) st = time.time() normal(l*4) print("normal cost time:",time.time()-st) st_1 = time.time() multithreading(l) print("multithreading cost times:",time.time()-st_1)
0f823b49bdfbf438e55d90e6ba23003e4e8b2569
local80forlife/CollegeClasses
/Barton_wk8_homework - Copy.py
2,761
3.734375
4
#Characters: 65 #Letters: 32 #Consonants: 21 #Digits: 22 #spaces: 2 #Word Characters: 4 #Punctuation: 5 def main(): try: userInput = "C:/Users/v-bartan/OneDrive/College/data.txt" except: print("ERROR: Unable to load file, please try again") userFile = open(userInput, 'r') divide_file(userFile, userInput) #logic for dividing and function control def divide_file(file, userInput): totalCount = {"vowels":0, "consonants": 0, "punctuation":0, "characters":0, "spaces":0, "digits":0, "total" : 0} totalChar = 0 fileLine = file.readline() while fileLine != "": fileLine = fileLine.rstrip("\n") totalChar += len(fileLine) count = count_char(fileLine) totalCount["vowels"] += count["vowels"] totalCount["consonants"] += count["consonants"] totalCount["punctuation"] += count["punctuation"] totalCount["characters"] += count["characters"] totalCount["spaces"] += count["spaces"] totalCount["digits"] += count["digits"] totalCount["total"] += count["total"] fileLine = file.readline() print_stats(totalCount, userInput) #count spaces and return a string with no spaces def count_char(fileLine): fileLine = fileLine.lower() counts = {"vowels":0, "consonants": 0, "punctuation":0, "characters":0, "spaces":0, "digits":0, "total": 0} vowels = 'aeiou' punctuation = '!~`^()_{}[]|\\;:\"\',.?' characters = '@#$%&+-=<>*/' #count spaces for char in fileLine: counts["total"] = len(fileLine) if char == vowels[vowels.find(char)]: counts["vowels"] += 1 elif char == punctuation[punctuation.find(char)]: counts["punctuation"] += 1 elif char == characters[characters.find(char)]: counts["characters"] += 1 elif char == " ": counts["spaces"] += 1 elif char.isdigit(): counts["digits"] += 1 else: counts["consonants"] += 1 return counts def print_stats(stats, userInput): nameIndex = userInput.rfind('/') print("Breakdown for user file: " + userInput[nameIndex+1:]) print("Total file Length: " + str(stats["total"])) print("Spaces: " + str(stats["spaces"])) print("Word Characters: " + str(stats["characters"])) print("Punctuation: " + str(stats["punctuation"])) print("Digits: " + str(stats["digits"])) print("Consonants: " + str(stats["consonants"])) main() ''' One problem I had, i didn't strip the new line '\n' off the fileLine so the .isdigit() would return false '''
a1d4fc6ba7f6ecb980a8555a76cc84465ce0f689
Automedon/Codewars
/8-kyu/Merging sorted integer arrays (without duplicates).py
267
3.984375
4
""" Description: Write a function that merges two sorted arrays into a single one. The arrays only contain integers. Also, the final outcome must be sorted and not have any duplicate. """ def merge_arrays(first, second): return sorted(list(set(first + second)))
5805d9b9b0e997562965ad87f76c953ab82a8c41
PBiret/AdventOfcode2019
/day6/puzzle1.py
1,776
3.625
4
import numpy file = open("C:/Users/Pierre/Documents/AdventCode2019/inputs/day6.txt","r") input = file.read().splitlines() def list_planets(input): planets_list=[] for orbit in input: planets=orbit.split(")") for planet in planets: if not(planet in planets_list): planets_list += [planet] return planets_list def list_orbits(input): planets_list = list_planets(input) orbits_list = [[] for _ in range(len(planets_list))] for orbit in input: planets=orbit.split(")") orbits_list[planets_list.index(planets[0])] += [planets[1]] # print(planets) return planets_list,orbits_list def count_orbits(input): planets_list,orbits_list = list_orbits(input) orbits_count = [0]*len(planets_list) for k,orbiters in enumerate(orbits_list): orbits_count[k] = len(orbiters) return planets_list, orbits_list, orbits_count def terminal_recursive(planets_list, orbits_list, planet, result): if orbits_list[planets_list.index(planet)]==[]: return result else: current_orbits = orbits_list[planets_list.index(planet)] new_result = result for k in range(len(current_orbits)): subplanet = current_orbits[k] # print(subplanet) new_result = 1 + terminal_recursive(planets_list, orbits_list, subplanet, new_result) return(new_result) def count_all_orbits(input, planet): planets_list, orbits_list, _ = count_orbits(input) result = terminal_recursive(planets_list, orbits_list, planet, 0) return result # print(list_orbits(input)[1]) # print(count_all_orbits(input, "C")) result = 0 for planet in list_planets(input): result += count_all_orbits(input, planet) print(result)
d944d1cea2d5c0b82e87db6a7704f37fadd3dc8f
EssamEmad/Middle-In
/huffman/main.py
4,859
3.5625
4
from huffman_node import HuffmanNode from heapq import heappop, heappush from binary_io import BinaryWriter import binascii import struct import argparse def build_freq_dict(filename, is_binary): """ calculates freq of each character in a file and store the result in a dictionary :param filename: input filename :return: freq dictionary (character: freq) """ freq = {} with open(filename, "rb" if is_binary else "r") as f: for line in f: for c in line: freq[c] = freq[c] + 1 if c in freq else 1 return freq def build_min_heap(freq): """ Build a min queue heap structure from the freq dictionary :param freq: dictionary :return: heap (list) """ heap = [] for char, freq in freq.items(): node = HuffmanNode(char, freq) heappush(heap, node) return heap def get_code_map(root): """ returns the variable length code for each character in huffman binary tree :param root: of huffman binary tree :return: dictionary (character: code) """ code_map = {} _calc_code(root, code_map) return code_map def _calc_code(root, code_map, code=''): if not root.is_internal(): code_map[root.character] = code else: if root.left is not None: _calc_code(root.left, code_map, code=code + '0') if root.right is not None: _calc_code(root.right, code_map, code=code + '1') def build_huffman_tree(heap, freq): """ build huffman code binary tree using huffman algorithm :param heap: heap of nodes :param freq: freq of characters :return: root of the tree """ for i in range(len(freq.keys())): x = heappop(heap) y = heappop(heap) if len(heap) else None z = HuffmanNode(None, x.freq + y.freq, x, y) if y else x heappush(heap, z) return heappop(heap) def ascii_binary(self, character): return "{0:b}".format(ord(character)) def str_from_ascii_binary_str(self, ascii): return chr(int(ascii, '2')) def tree_height(node): if node is None or not(node.is_internal()): return 0 return 1 + max(tree_height(node.left), tree_height(node.right)) def print_compressed(input_file, code_map, is_binary=False): # if not is_binary: for line in input_file: for c in line: for digit in code_map[c]: bw.append(digit != '0') if __name__ == '__main__': # Program Arguments setup parser = argparse.ArgumentParser() parser.add_argument('-f', '--file', help="File Name to be compressed", required=True) parser.add_argument('-o', '--output', help="Compressed Filename (Default: same as the file name)") parser.add_argument('-b', '--binary', action="store_true", help="Is Binary File?") args = parser.parse_args() file_name = args.file output_file_name = args.output if args.output else file_name is_binary = args.binary # to keep freq of each character in the input file # read input file and calculate freq freq = build_freq_dict(file_name,is_binary) # print("FREQUENCYDYYY dIIICT MATHAAR RUFU: {}".format(freq)) # for each character build a huffman node and insert it # into the min queue heap = build_min_heap(freq) # build huffman tree and get root root = build_huffman_tree(heap, freq) # get variable length code for each character code_map = get_code_map(root) # Format of header: # 12 binary bits for length of header, 16 bits for length of each entry then # length of header entries each of length length of entry headerlength = len(freq) # number of leaves assert headerlength < 1024 # header_entry_length = 8 + treeHeight(root) #8 bits for ascii char, then max length of tree # not handling the case where length is greater than 4 bytes # print the code representation for each character to the compressed file file_mode = "rb" if is_binary else "r" with open(output_file_name + ".em", "wb") as output_file, open(file_name, file_mode) as input_file: bw = BinaryWriter(output_file) header_length_bin = "{0:012b}".format(headerlength) print("COMPRESSIon HEADER LENGTH: {}, binary:{}".format(headerlength,header_length_bin)) for char in header_length_bin: bw.append(char != '0') # print header itself for key,value in code_map.items(): for char in "{0:04b}".format(len(value)) + "{0:08b}".format(key if is_binary else ord(key)) +value: bw.append(char != '0') # for line in input_file: # for c in line: # for digit in code_map[c]: # bw.append(digit != '0') print_compressed(input_file, code_map, is_binary) bw.write() bw.close()
32dfcbe151af9a677d321800a6d72775fff03665
AlexisDongMariano/miniProjects
/email_phone_extractor.py
3,513
3.765625
4
''' Date: Jun-26-2020 Platform: Windows Description: Copy text from any source and this script will extract the phone numbers (000-000-0000) and email (username@domain.com) then place in the clipboard to be pasted in text editor or same form. Sections: A-D (Working code located in Section C) ''' #################################################################### # SECTION A ''' Solution Creation High-level Steps: 1. Extract the text from the clipboard 1.a. Use module 'pyperclip' 2. Use regex to extract phone number and email 2.a. Create regex for phone number and email separately 2.b. Match both regex in the text from the clipboard 3. Format the extracted values 3.a. Maybe place the values in a string separated by new lines 4. Replace the clipboard with the formatted values 4.a Use module 'pyperclip' ''' #################################################################### # SECTION B # Sample string to extract the phone numbers and email: ''' This is just a sample text from admin@company.com with number 123-456-7890 to be used in this program to extract emails like name1.surname1@company.com and number like 098-765-4321 with examples below: email: name2.surname2@company.com cp no: 420-881-8261 email: peter_cetera@singers.com cp no: 444-9999 (postal optional) invalid samples: email: user@user@company.com cp no: 420,881,8261 ''' # Output of the program # *following will be copied to clipboard to use: ''' 123-456-7890 098-765-4321 420-881-8261 444-9999 admin@company.com name1.surname1@company.com name2.surname2@company.com peter_cetera@singers.com user@company.com ''' #################################################################### # SECTION C import pyperclip import re text = pyperclip.paste() #place the clipboard contents in a variable #define the regex num_pattern = re.compile(r'((\d{3}-)?\d{3}-\d{4})') email_pattern = re.compile(r'(([a-z0-9]+[._-]?[a-z0-9]+)@[a-z0-9-]+\.[a-z]{2,3})', re.I) #find the regex matches num_items = num_pattern.findall(text) email_items = email_pattern.findall(text) num_items_str = "" email_items_str = "" for item in num_items: num_items_str += item[0] + '\n' for item in email_items: email_items_str += item[0] + '\n' print('Copied to clipboard:') print(num_items_str) print(email_items_str) #copy the resulting string to the clipboard pyperclip.copy(num_items_str + email_items_str) #################################################################### # SECTION D # *Another Solution # import pyperclip, re # # # phoneRegex = re.compile(r'''( # (\d{3}|\(\d{3}\))? # area code # (\s|-|\.)? # separator # (\d{3}) # first 3 digits # (\s|-|\.) # separator # (\d{4}) # last 4 digits # (\s*(ext|x|ext.)\s*(\d{2,5}))? # extension # )''', re.VERBOSE) # # # Create email regex. # emailRegex = re.compile(r'''( # u [a-zA-Z0-9._%+-]+ # username # v @ # @ symbol # w [a-zA-Z0-9.-]+ # domain name # (\.[a-zA-Z]{2,4}) # dot-something # )''', re.VERBOSE) # # # Find matches in clipboard text. # text = str(pyperclip.paste()) # # matches = [] # for groups in phoneRegex.findall(text): # phoneNum = '-'.join([groups[1], groups[3], groups[5]]) # if groups[8] != '': # phoneNum += ' x' + groups[8] # matches.append(phoneNum) # # for groups in emailRegex.findall(text): # matches.append(groups[0]) # # # Copy results to the clipboard. # if len(matches) > 0: # pyperclip.copy('\n'.join(matches)) # print('Copied to clipboard:') # print('\n'.join(matches)) # else: # print('No phone numbers or email addresses found.')
61c836185b3855af1bc678dec6bcfb8061818444
nabeel-m/python_hardway
/ch01/ex2.py
523
3.828125
4
cars=100 space_in_car=4.0 drivers=30 passengers=90 car_not_driven=cars - drivers cars_driven=drivers carpool_capacity=cars_driven * space_in_car average_passengers_per_car=passengers / cars_driven print("there are",cars,"available") print("there are only ",drivers,"available") print("there will be ",car_not_driven,"empty cars today") print("we can transport ",carpool_capacity,"people") print("we have", passengers,"to carpool today") print("we need to put about",average_passengers_per_car,"in each cars")
6ebff97a8c43ab708731a33561a74c7173b9782e
malanb5/srt_parser
/srt_parser.py
14,050
3.640625
4
#!/usr/bin/python """ quick parsing script for parsing srt subtitle files to a full transcript Author: Matthew Bladek """ import pysrt, argparse, sys, logging, subprocess, os, yaml import Utils.Quiet_Run # init logger logging.basicConfig() logger = logging.getLogger('logger') def is_language_file(file, language): """ selects file based upon a language parameter :param file: the subtitle file :param language: the language as abbreviated in the subtitle file :return: boolean as to whether the file is in the right language or not """ logger.info("File: %s, Langugage: %s" %(file, language)) # parse the file name to check to see if english is in the header file_name_list = file.split('-') logger.info("File Language Piece: %s" %(file_name_list[1])) return file_name_list[1].find(language) != -1 def key_extract(tup, delim, first_index, second_index): """ key extractor function to sort based upon the second element, select the first element split on "-" :param tup: the tuple to extract the key from :param delim: the delimiter to split the word up on :param first_index: the index of the tuple :param second_index: the index of the substring :return: the number extracted as the key """ try: return int(tup[first_index].split(delim)[second_index]) except: return 9999 def get_full_paths(root_dir, fn_l): """ returns the full path of a file for a root directory and a list of files :param root_dir the root directory where the files are located :param fn_l the list of file names :return: a list of the full path file list """ if(type(fn_l) is not list): raise Exception("the file name's list must be a list") fp_fn_l = list() for each_fn in fn_l: fp_fn_l.append("/".join([root_dir, each_fn])) return fp_fn_l def extractor(word, index, delim): """ splits a word based on a delimiter and then selects the substring based upon an index if the index is outside of the word list, then the index will be the last substring in the broken up word :param word: the word to be split up and a substring extracted from :param index: the index of the substring to be extracted from the word :param delim: the delimiter on which to split the word into pieces :return: the substring of word, given by the split on delim and the index """ word_list = word.split(delim) if(len(word_list)<= index): index = len(word_list) - 1 return word_list[index] def is_correct_language(file_name, args): """ selector function which determines if the file name is in the correct language :param file_name: the file name to determine if the correct language is selected :param args: a list of arguments [0]: the function to extract just the word to see if the language is in [1]: the language abbreviation to select :return: whether the file_name has selected the correct language """ extract_fxn = globals()[args[0]] lang_abbr = args[1] index = args[2] delim = args[3] extracted_fn = extract_fxn(file_name, index, delim) return extracted_fn.find(lang_abbr) is not -1 def select_file(file_name, criteria_fns, critera_fns_args): """ selects a file based upon a set of criteria :param file_name: the file name to be selected or not :param criteria_fn: a list of boolean functions that takes the file name as an argument and determines whether or not the criteria has been meet for each function :param critera_fns_args: the list of args that will be feed into each criteria function :return: whether the file is to be selected or not """ for i in range(0, len(criteria_fns)): if not criteria_fns[i](file_name, critera_fns_args[i]): return False return True def select_append(selector_fxn, dir, fn, criteria_fxns, criteria_args, build_list): """ if the given function is true then append the selection to the list :param selector_fxn: the selector function :param dir: the directory where the file resides :param fn: the name of the file :param criteria_fxns: the criteria functions are a set of functions which will determine if the fn is to be selected or not :param criteria_args: the criteria args are additional arguments to each criteria function :param build_list: the list to append the """ if (selector_fxn(fn, criteria_fxns, criteria_args)): build_list.append((dir, fn)) def get_files_recursive(root_dir, dir_list, critiera_fxns, criteria_args, root_fn_l): """ recursively gets all of the files from the directories and appends it to a list of files is called recursively until all files have been obtained from all all levels of nested directories select files based upon a certain criteria function and args :param root_dir the root directory of where the directories are located :param dir_list a list of directories to get files from :param criteria_fxns: the criteria functions are a set of functions which will determine if the fn is to be selected or not :param criteria_args: the criteria args are additional arguments to each criteria function :param root_fn_l a list of path and file names :return: a list of all of the files in a list of directories """ for each_dir in dir_list: fp_fn_l = get_full_paths(root_dir, [each_dir]) for root, dirs, files in os.walk(fp_fn_l[0], topdown=True): if(len(dirs) != 0): get_files_recursive(dirs, root_fn_l) for each_file in files: select_append(select_file, root, each_file, critiera_fxns, criteria_args, root_fn_l) def get_fxns_from_symbol_table(fxns_names): """ gets the requested functions from the symbol table :param fxns_names: strings of the function names :return: a list of the functions """ fxn_list = list() for each_fxn in fxns_names: fxn_list.append(globals()[each_fxn]) return fxn_list def get_sub_files(config_yaml): """ :param config_yaml: the configuration dictionary :param config_yaml: temp_dir: the root directory where the file to parse are located :param delim (optional): splits the file based upon a delimiter, the default is '-' """ root_dir = config_yaml["temp_dir"] root_fn_l = list() # a list of file names of the files to be parsed critiera_fxns = get_fxns_from_symbol_table(config_yaml["criteria_fxns"]) criteria_args = config_yaml["criteria_args"] for root, dirs, files in os.walk(root_dir, topdown=True): get_files_recursive(root, dirs, critiera_fxns, criteria_args, root_fn_l) for each_file in files: select_append(select_file, root, each_file, critiera_fxns, criteria_args, root_fn_l) print_root_fn_l(root_fn_l) return root_fn_l def get_args_in_sub(): """ subroutine to get the command line args :return: the command line args object """ parser = init_parse_cl_args() args_in = parser.parse_args() return args_in def merge_settings(args_in, config_yaml): """ merge the command line arguments and yaml file configurations if a command line argument is present it will take precedence over the same yaml config setting. a single yaml dictionary will be returned with the merged settings. :param config_yaml: a dictionary of the configuration from the yaml file :param args_in: a Namespace object containing the CL args :return: a dictionary of the merged settings from the CL and the yaml file """ if (args_in.file_in != None): config_yaml["file_in"] = args_in.file_in logger.info("CL FOUND: UPDATING IN THE CONFIG DICTIONARY: %s", config_yaml["file_in"]) if (args_in.file_to_write_to != None): config_yaml["file_to_write_to"] = args_in.file_to_write_to logger.info("CL FOUND: UPDATING IN THE CONFIG DICTIONARY: %s", config_yaml["file_to_write_to"]) if (args_in.lang != None): config_yaml["lang_abbr"] = args_in.lang logger.info("CL FOUND: UPDATING IN THE CONFIG DICTIONARY: %s", config_yaml["lang_abbr"]) def print_root_fn_l(root_fn_l): """ prints out the list of tuples of the root and file name :param root_fn_l: list of tuples of the root and file name """ for each_r, each_f in root_fn_l: logger.info("Root: %s, File: %s", each_r, each_f) def write_subheader(root, file_to_write, fn, folder_format): """ writes subheaders to the output file, each file name is the subheading a folder that contains the files will be the major heading there are two modes: subfolder: indicate that the zip has subfolders where the subtitles are broken down by module regular: indicates that the zip has no subfolders, the subtitles are directly in the folder :param root: the location of the files :param file_to_write: the output file to write to :param fn: the file name :param folder_format: subfolder - if the directory structure is broken down by subfolders, regular - if the directory contains regular subtitle files """ seen_dirs = [] if(folder_format == "subfolder"): if root not in seen_dirs: sub_root = root[(root.rfind('/')) + 1:] + " : " + fn[:-4] file_to_write.write("\n\n" + sub_root + "\n\n") file_lines = get_text_from_subs(root + "/" + fn) else: seen_dirs.append(root) elif (folder_format == "regular"): logger.debug("regular file formatting") file_list = fn.split("-") counter = 1 # always add the first part of the header header = "\n\n" header += file_list[0] while(counter < len(file_list)): if(file_list[counter].find("lang") != -1): break else: header += " - " header += file_list[counter] counter += 1 header += "\n\n" file_to_write.write(header) else: raise Exception("Invalid option must be subfolder or regular.") def get_text_from_subs(file_path): """ opens a subtitle srt file, returns a string of all of the text in the subtitle file :param file_path: the path to the file :return: a string of the subtitles """"" subs = pysrt.open(file_path) text = str() for line in subs: curr_line = line.text curr_line_len = len(curr_line) if curr_line_len == 0: continue else: text += curr_line text+= " " return text def write_transcript(root_fn_l, config_yaml): """ writes out the transcript from the list of files :param root_fn_l the sorted list of tuples of the file path and the file name """ with open(config_yaml["file_to_write_to"], "w+") as file_to_write: for each in root_fn_l: root = each[0] file = each[1] write_subheader(root, file_to_write, file, "regular") file_lines = get_text_from_subs(root + "/" + file) file_to_write.writelines(file_lines) def parse_srt(config_yaml): """ parses the zipped srt archive into a single transcript file :param config_yaml: a dictionary of settings to parse the srt archive :return: a string of the srt contents concatenated together, selected by the language, and ordered in ascending numerical order """ # the temp dir is where the subtitle files will be unzipped to temp_dir = config_yaml["temp_dir"] # unzips the files to the temporary directory subprocess.call(["unzip", config_yaml["zipped_sub_file"], "-d", temp_dir]) root_fn_l = get_sub_files(config_yaml) return root_fn_l def main(config_yaml): args_in = get_args_in_sub() logger.setLevel(logging.DEBUG) logger.info('Starting the Subtitle Parser Script') merge_settings(args_in, config_yaml) root_fn_l = parse_srt(config_yaml) root_fn_l.sort(key=lambda key: key_extract(key, "-", 1, 0)) write_transcript(root_fn_l, config_yaml) # delete the temporary files subprocess.call(["rm", "-rf", config_yaml["temp_dir"]]) logger.info('success: output written to: %s' %(config_yaml["file_to_write_to"])) if __name__ == '__main__': with open("config.yaml") as config_file: config_yaml = yaml.safe_load(config_file) logger.setLevel(logging.DEBUG) logger.info(config_yaml) prereqs = config_yaml["preqs"] # set the encoding and python version Python3 = sys.version_info[0] == config_yaml["python_version"] Encoding= config_yaml["Encoding"] Utils.Quiet_Run.check_prereqs(prereqs) main(config_yaml) def init_parse_cl_args(): """ creates an object parser to process the command line args :return: an object to parse the command line args """ parser = argparse.ArgumentParser(description="Subtitle to Transcript Parser") parser.add_argument('--fileout', '-fo', dest="file_to_write_to", type=str, help="the file to write the subtitles to.") parser.add_argument('--filein', '-fin', dest="file_in", type=str, required=True, help="the zipped subtitle archive containing the subtitles.") parser.add_argument('--language', '-l', dest="lang", type=str, help="the language to parse, abbreviated (eg. English would be en), \n" "if the subtitles do not specify a language then do not include \n" "this argument. Language cannot be ^&null, which is the default\n" "language to indicate that no language has been selected") return parser
33071d645521e331b3125c6947913c3646b03299
bry012/DataStructures
/Lab8/Lab 8/sorts/selectionSort.py
754
3.8125
4
def selectionSort(alist): # Loop for the total number of passes (n-1) # Each pass will generate a decreasing passnum for the next loop for fillslot in range(len(alist)-1,0,-1): # Create variable to hold where the position is positionOfMax=0 # Loop through the correct items for the pass for location in range(1,fillslot+1): # If this item is greater than the max for this pass if alist[location]>alist[positionOfMax]: # Store the position of this item positionOfMax = location # Swap the max item encountered to proper position temp = alist[fillslot] alist[fillslot] = alist[positionOfMax] alist[positionOfMax] = temp
2e29e38bbcbcc07dd628bbb1332d0dae7ca0b2d5
scar86/python_scripts
/examples/testGetKeys.py
1,075
4.5
4
'''Test the function to extract keys from a format string for a dictionary.''' def getKeys(formatString): '''formatString is a format string with embedded dictionary keys. Return a list containing all the keys from the format string.''' keyList = list() end = 0 repetitions = formatString.count('{') for i in range(repetitions): start = formatString.find('{', end) + 1 end = formatString.find('}', start) key = formatString[start : end] keyList.append(key) return keyList originalStory = """ Once upon a time, deep in an ancient jungle, there lived a {animal}. This {animal} liked to eat {food}, but the jungle had very little {food} to offer. One day, an explorer found the {animal} and discovered it liked {food}. The explorer took the {animal} back to {city}, where it could eat as much {food} as it wanted. However, the {animal} became homesick, so the explorer brought it back to the jungle, leaving a large supply of {food}. The End """ print(getKeys(originalStory))
d2003fb7ab532464c94928cf64bc6ab863f66dc6
Noronha1612/wiki_python-brasil
/Estruturas de repetição/ex41.py
952
3.8125
4
from functions.validação import lerFloat, lerInt from functions.visual import formatDinheiro from time import sleep divida = lerFloat('Valor da dívida: R$', pos=True, erro='Digite uma quantia válida') if divida == 0: print('Nenhuma dívida registrada') print('Programa encerrado') exit() while True: parcelas = lerInt('Quantas parcelas deseja pagar? ', pos=True, erro='Digite uma quantidade válida') if parcelas > 0: break print('Digite uma quantidade válida') if parcelas < 3: juros = 0 else: juros = 5 + 5 * (parcelas // 3) total = divida + (divida * (juros / 100)) print('Analisando...') sleep(1.5) print(f'{"Valor da dívida":<30}{"Valor do juros":<30}{"Quantidade de parcelas":<30}{"Valor da parcela":<30}{"Valor total"}') print('-='*76) print(f'{formatDinheiro(divida):<30}{formatDinheiro(divida * (juros / 100)):<30}{parcelas:<30}{formatDinheiro(total / parcelas):<30}{formatDinheiro(total)}')
8e40aafccc4500bb7743087fc95331db8bd22067
dingwengit/Code_practice
/Python/string/sentence_break.py
966
3.671875
4
# given a string, print out all possible words that make up the entire string # e.g., s = "onpinsandneedles" # result: # ['on", "pin", "sand", "needles"], # ['on", "pins", "and", "needles"] dictionary = ["on", "pin", "pins", "and", "sand", "needles"] def sentence_break(s, res): if s == '': print(res) return for i in range(1, len(s) + 1): if s[:i] in dictionary: # print s[:i] + " -- " + s[i:] res.append(s[:i]) sentence_break(s[i:], res) del res[len(res) -1] def sentence_break2(s, idx=0, res=[]): if idx >= len(s): print(res) return for i in range(idx+1, len(s)+1): if s[idx:i] in dictionary: res.append(s[idx:i]) sentence_break2(s, i, res) del res[len(res) -1] # sentence_break("onpinsandneedles",[]) # sentence_break("onpinsan",[]) sentence_break2("onpinsandneedles") # sentence_break2("onpinsan", 0, [])
dc5fbca4672b4fcf6d216e48d2e4781fbe1540c4
Knniff/python-vorkurs
/Uebung08/Aufgabe2.py
1,039
4.1875
4
def chiffre(input: str, key: int, direction: str) -> str: input = input.lower() output = "" if direction == "encrypt": for letter in input: if letter.isalpha(): temp = ord(letter) temp = temp + key if temp > 122: temp_key = temp - 123 temp = 97 + temp_key output += chr(temp) else: output += letter return output else: for letter in input: if letter.isalpha(): temp = ord(letter) temp = temp - key if temp < 97: temp_key = 97 - temp temp = 123 - temp_key output += chr(temp) else: output += letter return output print( chiffre( "fakt ist, dass alles im universum entweder eine kartoffel ist oder nicht.", 13, "encrypt", ) ) # print(chiffre("Test Test.",3,"encrypt",))
be3ff677381a2d6b3706f179d96b9d4000c94c26
noveljava/study_leetcode
/completed/137_single_number_2.py
447
3.515625
4
from typing import List class Solution: def singleNumber(self, nums: List[int]) -> int: from collections import defaultdict result = [] count = defaultdict(int) for i in nums: count[i] += 1 if count[i] == 1: result.append(i) elif count[i] == 2: result.remove(i) return result[0] nums = [2,2,4,2] print(Solution().singleNumber(nums))
602fc18177762b632c2613e49078b22ab9ba981c
mathans1695/Python-Practice
/Own Python Module/gameoflife.py
911
3.625
4
from life import LifeGrid INIT_CONFIG = [(0,0), (0,1), (1,0), (1,2), (3,2), (3,4), (5,4), (5,6), (7,6), (7,8), (9,8), (9,10), (11,10), (11, 12), (12, 11), (12,12)] GRID_WIDTH = int(input("Enter grid width: ")) GRID_HEIGHT = int(input("Enter grid height: ")) NUM_GENS = int(input("Enter the num of generations: ")) def main(): grid = LifeGrid(GRID_WIDTH, GRID_HEIGHT) grid.configure(INIT_CONFIG) draw(grid) for i in range(NUM_GENS): evolve(grid) draw(grid) def evolve(grid): liveCells = list() for i in range(grid.numRows()): for j in range(grid.numCols()): neighbors = grid.numLiveNeighbors(i, j) if (neighbors == 2 and grid.isLiveCell(i, j)) or \ (neighbors == 3): liveCells.append((i, j)) grid.configure(liveCells) def draw(grid): for i in range(GRID_WIDTH): for j in range(GRID_HEIGHT): print(grid._grid[i, j], end = "") print() print() main()
5850dc6375d0bc9deb12bc2601b6c0d19f76db1f
JMW0503/CSCI_4
/Lotto.py
586
3.6875
4
""" Lotto Number Gen Author: Justin Wilson Date Created: 9/12/2019 Description: Outputs five (5) numbers, each number ranging from 1-47 """ import sys import random randomNumber = random.randint(1,47) randomNumber2 = random.randint(1,47) randomNumber3 = random.randint(1,47) randomNumber4 = random.randint(1,47) randomNumber5 = random.randint(1,47) print("Lucky Lotto Numbers:\n", randomNumber, randomNumber2, randomNumber3, randomNumber4, randomNumber5) import sys def main(): #Your code here return 0 if __name__ == '__main__': sys.exit(main())
aefdf57f94b3b671dd431ed3d9571a975ec2a335
SakuraGo/leetcodepython3
/PythonLearning/fourteen/c5.py
1,437
4.09375
4
##可迭代对象 ## 列表、元组、集合 ## for in # for in iterable # 对象 class class Book: pass ##把一个类变成可迭代的.. ##迭代器 # Iterator ##一组书 class BookCollection: def __init__(self): self._data = ["《往事》","zhineng","huiwei"] self.cur = 0 def __iter__(self):##需要实现这两个函数,就能把这个类变成可迭代的。 return self def __next__(self):##需要实现这两个函数,就能把这个类变成可迭代的。 if self.cur>= len(self._data): raise StopIteration() r = self._data[self.cur] self.cur += 1 return r pass asdff = {3,5,6} for i in asdff: print(i) asd = (3,5,6) for a in asd: print(a) import copy # books_copy = books.copy() #'BookCollection' object has no attribute 'copy' books = BookCollection() books_copy = copy.copy(books) for book in books: ## for in 循环的实质就是一直在调用可迭代类的 __next__,取得下一个 print("book:",book) ## 直到遍历完了,返回异常。 books = BookCollection() print(next(books)) print(next(books)) print(next(books)) # 《往事》 # zhineng # huiwei print("~~~~~~") for book in books_copy: ##第一次把迭代器用完了,不会再有打印输出 print("book:",book) lis = [1,3,5,6] for n in lis: print(n) for n in lis: ##list可以再打印 print(n)
d4d714b783a8d8ed3762798b6dedcd6e58465977
MrAlekzAedrix/MetodosNumericos
/data.py
122
4
4
name = input('Whats your name? ') age = int(input('Whats your age? ')) print('Hi!', name, 'you are', age, 'years old')
dc23022392afad671741b7df896a7a3e793c4947
yeasy/code_snippet
/python/regex.py
171
3.515625
4
#!/usr/bin/python #-*- coding: utf-8 -*- import re regex = re.compile('[a-z]{10}') t1 = re.match(regex,'1234567890') t2 = re.match(regex,'abcdefghij') print t1 print t2
cf3d5e9ae92e0692a4395e048c489fc93c0e14f0
bwoodru87/SQLAlchemy_Homework
/hawaii_bw.py
4,636
3.625
4
# Import my dependencies import numpy as np import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func from flask import Flask, jsonify # Create our engine, connecting it to the assigned sqlite database engine = create_engine("sqlite:///hawaii.sqlite") # reflect an existing database into a new model Base = automap_base() # Reflect the tables Base.prepare(engine, reflect=True) # Save references to each table Measurement = Base.classes.measurement Station = Base.classes.station # Setup Flask app = Flask(__name__) # Establish routes # Provide in-line HTML formatting to make the page look prettier @app.route("/") def welcome(): return ( f"<h3>Hawaii Climate Info <br>" f"Below are the available routes:</h3> <br>" # Precipitation f"<b>Precipitation by day for the last year:</b><br>" f"/api/v1.0/precipitation<br>" # Weather Station f"<b>All Hawaii weather stations:</b><br>" f"/api/v1.0/stations<br>" # Temperature page f"<b>Temperature by day for the last year:</b><br>" f"/api/v1.0/tobs<br><br>" # Min, max, avg temp page - by start date f"<b>The below route will give you the min, max and average temperature values for all dates greater than the date provided: </b><br>" f"<b>Please provide a start date after the backslash using .../api/v1.0/YYYY-MM-DD/ </b><br>" f"/api/v1.0/<start_date><br><br>" # Min, max, avg temp page - by start and end date f"<b>The below route will give you the min, max and average temperature values for the provided date range. </b><br>" f"<b>Please provide a start date and an end date after the backslash using .../api/v1.0/YYYY-MM-DD/YYYY-MM-DD </b><br>" f"/api/v1.0/<start_date>/<end_date>" ) # Precipitation route @app.route("/api/v1.0/precipitation") def precips(): # Start the session for the page session = Session(engine) precip = session.query(Measurement.date, Measurement.prcp).filter(Measurement.date > '2016-08-22').all() # Convert list of tuples into normal list precip_lastyear = list(np.ravel(precip)) # JSONIFY the object return jsonify(precip_lastyear) # Stations route @app.route("/api/v1.0/stations") def stations(): # Start the session for the page session = Session(engine) # Query Station sqlite and get all station names station_names = session.query(Station.name).all() # Convert list of tuples into normal list all_stations = list(np.ravel(station_names)) # JSONIFY the list of tuples return jsonify(all_stations) # Temperature route @app.route("/api/v1.0/tobs") def temps(): # Start the session for the page session = Session(engine) # Query Measurement sqlite to get the date and temperature temps = session.query(Measurement.date, Measurement.tobs).filter(Measurement.date > '2016-08-22').order_by(Measurement.date).all() # Create a list of a collection of dictionaries that extracts the data we want from the object temps_lastyear = [] for date, tobs in temps: temp_dict = {} temp_dict["date"] = date temp_dict["tobs"] = tobs temps_lastyear.append(temp_dict) # JSONIFY the list return jsonify(temps_lastyear) # Start date only route @app.route("/api/v1.0/<start_date>") def startDate(start_date): # Start the session for the page session = Session(engine) # Query Measurement sqlite to get the min, max and avg result for the selected date ranges start_date = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\ filter(Measurement.date >= start_date).all() # JSONIFY the object return jsonify(start_date) # Start and end date route @app.route("/api/v1.0/<start_date>/<end_date>") def startAndEndDate(start_date, end_date): # Start the session for the page session = Session(engine) # Query Measurement sqlite to get the min, max and avg result for the selected date ranges start_and_end_date = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\ filter(Measurement.date >= start_date).filter(Measurement.date <= end_date).all() # JSONIFY the object return jsonify(start_and_end_date) # Allow for page debugging / log if __name__ == '__main__': app.run(debug=True)
cccb78c3947720bbc99661ab20ac2d5e3f434cdc
burakbayramli/books
/Introduction_to_Python_for_Econometrics/Python_introduction_solutions/logical_operators_and_find_solutions.py
1,724
3.953125
4
"""Solutions for 'Logical Operators and Find' chapter. Solutions file used IPython demo mode. To play, run from IPython.lib.demo import Demo demo = Demo('logical_operators_and_find.py') and then call demo() to play through the code in steps. """ # <demo> auto from __future__ import print_function import numpy as np from numpy import mean, std # <demo> --- stop --- # Exercise 1 data = np.load('exercise3_compressed.npz') dates = data['dates'] SP500 = data['SP500'] XOM = data['XOM'] print("sum(SP500<0):") print(sum(SP500<0)) print("sum(XOM<0):") print(sum(XOM<0)) # <demo> --- stop --- # Exercise 2 SP500big = SP500>(2*SP500.std()) SP500small = SP500<(-2*SP500.std()) print("mean(SP500[SP500big]):") print(mean(SP500[SP500big])) print("mean(SP500[SP500small]):") print(mean(SP500[SP500small])) XOMbig = XOM>(2*std(XOM)) XOMsmall = XOM<(-2*std(XOM)) print("mean(XOM[XOMbig]):") print(mean(XOM[XOMbig])) print("mean(XOM[XOMsmall]):") print(mean(XOM[XOMsmall])) # <demo> --- stop --- # Exercise 3 bothNeg = np.logical_and(SP500<0,XOM<0) data = np.vstack((SP500,XOM)).T corr = np.corrcoef(data.T) negCorr = np.corrcoef(data[bothNeg,:].T) print("corr:") print(corr) print("negCorr:") print(negCorr) # <demo> --- stop --- # Exercise 4 oneNeg = np.logical_or(SP500<0,XOM<0) oneNegCorr = np.corrcoef(data[oneNeg,:].T) print("oneNegCorr:") print(oneNegCorr) # <demo> --- stop --- # Exercise 5 def myany(x): """Returns True if any value in the input is True """ return not np.all(np.logical_not(x)) def myall(x): """Returns True if all values in the input is True """ return not np.any(np.logical_not(x))
b195259246424078508425061224a3d2283a4ae5
OldTruckDriver/Chexer
/ChexerBattle/Chexers-master/random_player/utils.py
1,705
3.640625
4
# The minimum and maximum coordinates on the q and r axes MIN_COORDINATE = -3 MAX_COORDINATE = 3 # Delta values which give the corresponding cells by adding them to the current # cell MOVE_DELTA = [(0, 1), (1, 0), (-1, 1), (0, -1), (-1, 0), (1, -1)] JUMP_DELTA = [(delta_q * 2, delta_r * 2) for delta_q, delta_r in MOVE_DELTA] def all_cells(): """ generate the coordinates of all cells on the board. """ ran = range(MIN_COORDINATE, MAX_COORDINATE + 1) return [(q, r) for q in ran for r in ran if -q-r in ran] ALL_CELLS = all_cells() def generate_cells(cell, delta_pairs): """ generate a list of cells by adding delta values """ return [(cell[0] + delta_q, cell[1] + delta_r) for delta_q, delta_r in delta_pairs] def moveable_cells(curr_cell, occupied): """ moveable_cells are cells next to the current_cell with nothing occupied """ neighbours = generate_cells(curr_cell, MOVE_DELTA) return [cell for cell in neighbours if cell in ALL_CELLS and cell not in occupied] def jumpable_cells(curr_cell, occupied): """ jumpable_cells are cells that are one cell apart from the current cell and cells in the middle must be occupied by either a block or a piece """ generated_cells = generate_cells(curr_cell, JUMP_DELTA) jumpable = [] for cell in generated_cells: if cell in ALL_CELLS and cell not in occupied: middle_cell = tuple(map(lambda x, y: (x + y) // 2, curr_cell, cell)) if middle_cell in ALL_CELLS and middle_cell in occupied: jumpable.append(cell) return jumpable
abd686c671e269973e862b7ff6382b2924aeb10c
nikisix/classes
/examples/python/groups_of_lists-naive.py
428
3.84375
4
''' i have a list a = [1, 2, 3, 5, 2] i need to group these list elements to where they are in groups that their sum `<= 5` ie; this would produce myNewList = [[1,2,2], [3], [5]] ''' a = [1, 1, 2, 3, 5, 2] a = sorted(a, reverse=True) target = 5 #"target val" result = [] f=lambda x: x<=target t = [] for i in a: if f(sum(t+[i])): t += [i] else: result.append(t) t = [i] result.append(t print result
38b51be998f199f8f47f44a181eed6c32a143b48
mcxu/code-sandbox
/PythonSandbox/src/misc/powerset_subsets.py
3,619
4.25
4
''' Powerset Function that takes array of unique integers, and returns powerset. Powerset of set X, P(X), is set of all subsets of X. Sample input: [1, 2, 3] Sample output: [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]] ''' class PS: """ Time complexity: O(n!*n): get permutations O(n*n!): nested for loop O(2^n): turn each subset into list, done once at end Total: 2*O(n!*n) + O(2^n) = O(n!*n) Space complexity: O(n!*n): get permutations O(2^n): number of subsets Total: O(n!*n) + O(2^n) = O(n!*n) """ @staticmethod def powerset(array): pwrset = [] # space: O(2^n) subsets for a set of n values #handle null set pwrset.append(set([])) #handle subsets where 1 < subset.length < len(array) # get permutations perms = PS.getPermutations(array) # Time: O(n!*n), Space: O(n!*n) print("perms: ", perms) for count in range(len(array)): # time: O(n) for perm in perms: # time: O(n!) permset = set(perm[0:count+1]) print("permset: ", permset) if permset not in pwrset: pwrset.append(permset) # space: O(2^n) subsets return [list(subset) for subset in pwrset] # time: O(2^n) once """ Return list of all permutations """ @staticmethod def getPermutations(array): return PS.permHelper(array, []) @staticmethod def permHelper(array, perms): if array not in perms: perms.append(array.copy()) else: return perms for i in range(len(array)-1): array[i], array[i+1] = array[i+1], array[i] PS.permHelper(array, perms) array[i], array[i+1] = array[i+1], array[i] return perms @staticmethod def test1(): array = [1,2,3] ps = PS.powerset(array) print("test1: powerset: ", ps) """ Time complexity: O(n * 2^n) Space complexity: There are 2^n subsets, each subset has on average len(n)/2 elements. O(n * 2^n) """ @staticmethod def powersetIterative(array): pwrset = [[]] # pre append the empty set for val in array: # time O(n) print("== val: ", val) for i in range(len(pwrset)): # time O(2^n) b/c at the final iteration of powerset for each val, there are twice as many subsets as previously print("i: ", i) currentSubset = pwrset[i] print("currentSubset: ", currentSubset) pwrset.append(currentSubset + [val]) print("pwrset after append: ", pwrset) return pwrset @staticmethod def test2(): array = [1,2,3,4] ps = PS.powersetIterative(array) print("test2: powersetIterative: ", ps) """ Return all subsets that add up to a given sum. """ @staticmethod def subsetSum(array, targetSum): pwrset = [[]] for val in array: for i in range(len(pwrset)): pwrset.append(pwrset[i] + [val]) print("pwrset after: ", pwrset) valids = [] for ss in pwrset: if sum(ss) == targetSum: valids.append(ss) return valids @staticmethod def test3(): array = [2,3,4,5,6] ans = PS.subsetSum(array, int(sum(array)/2)) print("test3: subsetSum: ", ans) #PS.test1() #PS.test2() PS.test3()
6518ae0ce6d8e6dbc5287af9c15aa31035b3a884
WilliamQLiu/python-examples
/algorithms/insertion_sort.py
785
4.40625
4
""" Insertion Sort """ def insertionSort(mylist): for index in range(1, len(mylist)): print("Index is ", index) # 1, 2, 3, 4, 5, 6, 7, 8; this is the outer loop # setup first case (only one item) currentvalue = mylist[index] position = index # this is the inner loop, loops through the sorted list backwards and compares values while position > 0 and mylist[position-1] > currentvalue: mylist[position] = mylist[position-1] position = position - 1 mylist[position] = currentvalue # found spot in inner sorted loop to place item if __name__ == '__main__': mylist = [54,26,93,17,77,31,44,55,20] print("Original: ", mylist) insertionSort(mylist) print("Insertion Sorted: ", mylist)
0386db2baac8bdec271f15928ba0a5c699ed1a0a
bitfun-eu/ARLM-mpy-tinybit
/voice_control.py
1,478
3.703125
4
# Add your Python code here. E.g. from microbit import pin1, sleep from tinybit import run def listen(level=100, duration_ms=1000, speed=70, wait=300): noise = pin1.read_analog() if noise > level: run(speed, speed) sleep(duration_ms) run(0, 0) sleep(wait) while True: listen() # Questions # 1. Why do we sleep(wait) at line 11? what could happen if we don't do that? # 2. Can we use two microphone, such that tinybit can run towards the voice source? # e.g. if voice comes from left, then it turns left, if voice comes from right, it turns right? # There is a mic sensor in the hardware pack, please use microbit v1 if your tinybit is not fixed for v2. # running only when voice KEEPS high from microbit import pin1, sleep from tinybit import run def listen(level=100, duration_ms=1000, speed=70, wait=300): noise = pin1.read_analog() if noise > level: run(speed, speed) else: run(0, 0) #sleep(duration_ms) #run(0, 0) #sleep(wait) while True: listen(level=150) # Below is another version which is more sensitive, think about why this is the case? from microbit import pin1, sleep from tinybit import run def listen(level=100, duration_ms=1000, speed=70, wait=300): while True: noise = pin1.read_analog() if noise < level: continue else: run(speed, speed) sleep(duration_ms) run(0, 0) sleep(wait) listen()
f196cdc37d85d6030ebd2f5c05822e12a1f52cbd
johnkmur/Battleship
/main.py
15,682
3.671875
4
#! /usr/bin/python # John Murphy # Coatue Coding Challenge # Types of ships with their abbreviations as well as their length. ship_list = {"carrier":['5', 'C'], "battleship":['4', 'b'], "submarine":['3', 's'], "cruiser":['2', 'c'], "destroyer":['2', 'd']} # Player A's ships my_ships_A = {} # The coordinates of all of Player A's ships ship_coordinates_A = [] # Player B's ships my_ships_B = {} # The coordinates of all of Player B's ships ship_coordinates_B = [] # Player A's gameboard, this represents Player A's ship positions and where # Player B has attacked. board_A = [] # Player B's gameboard, this represents Player B's ship positions and where # Player A has attacked. board_B = [] # Player A's target record, this is a record of where A has attacked and whether # is was a hit ('H') or a miss ('M'). board_A_targets = [] # Player B's target record, this is a record of where A has attacked and whether # is was a hit ('H') or a miss ('M'). board_B_targets = [] # Create the boards used for gameplay def create_boards(board_size): for i in range( int(board_size) ): board_row = [] for j in range( int(board_size) ): board_row.append('.') board_A.append(board_row) for i in range( int(board_size) ): board_row = [] for j in range( int(board_size) ): board_row.append('.') board_B.append(board_row) for i in range( int(board_size) ): board_row = [] for j in range( int(board_size) ): board_row.append('.') board_A_targets.append(board_row) for i in range( int(board_size) ): board_row = [] for j in range( int(board_size) ): board_row.append('.') board_B_targets.append(board_row) return board_A, board_B, board_A_targets, board_B_targets # This function is used to roughly determine the minimum board size to allow for # the placement of the ships that the user selected. def determine_min_size(ships): max_length = -1 total_area = 0 for ship in ships: if (ships[ship] > 0): total_area = total_area + (ships[ship] * int(ship_list[ship][0]) ) if (int(ship_list[ship][0]) > max_length): max_length = int(ship_list[ship][0]) return max_length, total_area # Returns true if the sink was sunk. def is_ship_sunk(coordinates, destination, my_ships): x_coor, y_coor = coordinates.split(",") x_coor = int(x_coor) y_coor = int(y_coor) type_of_ship = destination[x_coor][y_coor] for i in range( len(my_ships[type_of_ship] )): if coordinates in my_ships[type_of_ship][i]: my_ships[type_of_ship][i].remove(coordinates) if (len(my_ships[type_of_ship][i]) == 0): return True; return False # Determines if missile hit or missed. def fire_at_target(coordinates, source, destination, player_ships, my_ships): x_coor, y_coor = coordinates.split(",") x_coor = int(x_coor) y_coor = int(y_coor) if (destination[x_coor][y_coor] is '.'): # Miss destination[x_coor][y_coor] = 'M' source[x_coor][y_coor] = 'M' print "MISS" return player_ships else: # Hit, check if last missile sunk the ship sunk = is_ship_sunk(coordinates, destination, my_ships) destination[x_coor][y_coor] = 'H' source[x_coor][y_coor] = 'H' if (sunk == True): player_ships = player_ships - 1 print "HIT and sunk a ship!" else: print "Target HIT!" return player_ships # Checks that target is within battlefield dimensions and not visited before. def is_valid_target(board_in, coordinates): x_coor, y_coor = coordinates.split(",") if (int(x_coor) < 0 or int(x_coor) > len(board_in)-1): print "Sorry, the coordinate you have entered is not valid, try again." return False if (int(y_coor) < 0 or int(y_coor) > len(board_in)-1): print "Sorry, the coordinate you have entered is not valid, try again." return False if (board_in[int(x_coor)][int(y_coor)] == 'H' or board_in[int(x_coor)][int(y_coor)] == 'M'): print "Sorry, you have already fired at this location, try again." return False return True # Places a Player A's ships onto their board. def place_ship_A(start, end, ship): x_start, y_start = start.split(",") x_end, y_end = end.split(",") x_min = min( int(x_start), int(x_end)) x_max = max( int(x_start), int(x_end)) y_min = min( int(y_start), int(y_end)) y_max = max( int(y_start), int(y_end)) move_vertical = False if (x_min == x_max): # We are moving vertically move_vertical = True all_coors = [] while (x_min != x_max or y_min != y_max): board_A[x_min][y_min] = ship_list[ship][1] all_coors.append(str(x_min) + "," + str(y_min)) if (move_vertical == True): y_min = y_min + 1 else: x_min = x_min + 1 board_A[x_min][y_min] = ship_list[ship][1] all_coors.append(str(x_min) + "," + str(y_min)) ship_coordinates_A.append(all_coors) my_ships_A[ship_list[ship][1]] = ship_coordinates_A # Places a Player B's ships onto their board. def place_ship_B(start, end, ship): x_start, y_start = start.split(",") x_end, y_end = end.split(",") x_min = min( int(x_start), int(x_end)) x_max = max( int(x_start), int(x_end)) y_min = min( int(y_start), int(y_end)) y_max = max( int(y_start), int(y_end)) move_vertical = False if (x_min == x_max): # We are moving vertically move_vertical = True all_coors = [] while (x_min != x_max or y_min != y_max): board_B[x_min][y_min] = ship_list[ship][1] all_coors.append(str(x_min) + "," + str(y_min)) if (move_vertical == True): y_min = y_min + 1 else: x_min = x_min + 1 board_B[x_min][y_min] = ship_list[ship][1] all_coors.append(str(x_min) + "," + str(y_min)) ship_coordinates_B.append(all_coors) my_ships_B[ship_list[ship][1]] = ship_coordinates_B # Returns True is a ship can be placed in the given location, False otherwise. def is_valid_placement(board_in, ship, start, end): x_start, y_start = start.split(",") x_end, y_end = end.split(",") x_min = min( int(x_start), int(x_end)) x_max = max( int(x_start), int(x_end)) y_min = min( int(y_start), int(y_end)) y_max = max( int(y_start), int(y_end)) if (x_min < 0 or y_min < 0 or x_max > len(board_in) - 1 or y_max > len(board_in) - 1): print "\nSorry, please choose coordinates within the battlefield\n" return False vertical_diff = y_max - y_min horizontal_diff = x_max - x_min min_diff = min(vertical_diff, horizontal_diff) max_diff = max(vertical_diff, horizontal_diff) if ( not (min_diff == 0 and max_diff == int(ship_list[ship][0]) - 1) ): # Size of ship doesn't match print "\nSorry, that is not the correct dimension of the ship, try again.\n" return False move_vertical = False if (x_min == x_max): # We are moving vertically move_vertical = True while (x_min != x_max or y_min != y_max): if (board_in[x_min][y_min] == '.'): if (move_vertical == True): y_min = y_min + 1 else: x_min = x_min + 1 else: print "\nSorry, this spot is already taken, try again.\n" return False return True # Game board print function def board_print(board_in): board_size_in = len(board_in) line = " " for i in range(board_size_in): line = line + str(i) + ' ' print line line = '' j = 0 for row in board_in: line = line + str(j) + ' ' for col in row: line = line + col + ' ' print line line = "" j = j + 1 def main(): ships = {} print "Which ships would you like to play with and how many?" print "The ships available are:\nCarrier (5x1)\nBattleship (4x1)\nSubmarine (3x1)\nCruiser (2x1)\nDestroyer (2x1)\n" num_ships = 0 while (num_ships == 0): ship_number = input("Would you like to play with a Carrier? If so, how many? (Enter 0 if you don't want to use a carrier: ") ships["carrier"] = int(ship_number) num_ships = num_ships + int(ship_number) ship_number = input("Would you like to play with a Battleship? If so, how many? (Enter 0 if you don't want to use a carrier: ") ships["battleship"] = int(ship_number) num_ships = num_ships + int(ship_number) ship_number = input("Would you like to play with a Submarine? If so, how many? (Enter 0 if you don't want to use a carrier: ") ships["submarine"] = int(ship_number) num_ships = num_ships + int(ship_number) ship_number = input("Would you like to play with a Cruiser? If so, how many? (Enter 0 if you don't want to use a carrier: ") ships["cruiser"] = int(ship_number) num_ships = num_ships + int(ship_number) ship_number = input("Would you like to play with a Destroyer? If so, how many? (Enter 0 if you don't want to use a carrier: ") ships["destroyer"] = int(ship_number) num_ships = num_ships + int(ship_number) if (num_ships == 0): print "You must select at least one ship." # Determine the minimum size board given the ships selected. max_length, total_area = determine_min_size(ships) print "\n" board_size = input("Enter the dimensions (Ex. type '10' if you want a 10x10 board) that you would like to play on: ") while ( int(board_size) < 1): print "Error, dimensions must be greater than one" board_size = input("Enter dimensions again: ") good_board_size = False while (not good_board_size): if ( (int(board_size) * int(board_size)) < total_area or int(board_size) < max_length): print "Given the number of ships and type of ships that you entered, the battlefield needs to be larger" board_size = input("Enter dimensions again: ") else: good_board_size = True print "\nA battlefield of size " + str(board_size) + "x" + str(board_size) + " will be created." # Create the gameboards board_A, board_B, board_A_targets, board_B_targets = create_boards(int(board_size)) # Switch to Player A so that they can place their ships. print "Player A will now select where to place their ships, Player B, look away.\n\n" for ship in ships: for num in range(ships[ship]): # Print board_A board_print(board_A) print "Where would you like to place this ship: " + ship + " (" + ship_list[ship][0] + "x" + ship_list[ship][0] + ")" coor_start = raw_input("Please enter the coordinates (x,y) of the front of the ship: ") coor_end = raw_input("Please enter the coordinates (x,y) of the back of the ship: ") # Check if it is a valid spot to place the ship. valid = is_valid_placement(board_A, ship, str(coor_start), str(coor_end)) while (not valid): print "Where would you like to place this ship: " + ship + " (" + ship_list[ship][0] + "x" + ship_list[ship][0] + ")" coor_start = raw_input("Please enter the coordinates (x,y) of the front of the ship: ") coor_end = raw_input("Please enter the coordinates (x,y) of the back of the ship: ") valid = is_valid_placement(board_A, ship, str(coor_start), str(coor_end)) place_ship_A(str(coor_start), str(coor_end), ship) print "Successfully added the ship\n\n" print "Board A complete, Player A, this is the positioning of your ships." board_print(board_A) # Now switch to Player A so that they can place their ships. print "Now Player B will now select where to place their ships, Player A, look away.\n\n" for ship in ships: for num in range(ships[ship]): # Print board_A board_print(board_B) print "Where would you like to place this ship: " + ship + " (" + ship_list[ship][0] + "x" + ship_list[ship][0] + ")" coor_start = raw_input("Please enter the coordinates (x,y) of the front of the ship: ") coor_end = raw_input("Please enter the coordinates (x,y) of the back of the ship: ") # Check if it is a valid spot to place the ship. valid = is_valid_placement(board_B, ship, str(coor_start), str(coor_end)) while (not valid): print "Where would you like to place this ship: " + ship + " (" + ship_list[ship][0] + "x" + ship_list[ship][0] + ")" coor_start = raw_input("Please enter the coordinates (x,y) of the front of the ship: ") coor_end = raw_input("Please enter the coordinates (x,y) of the back of the ship: ") place_ship_B(str(coor_start), str(coor_end), ship) print "Successfully added the ship\n\n" print "Board B complete, Player B, this is the positioning of your ships." board_print(board_B) # Now we get into the game play portion. # Set up players player_A_ships = num_ships player_B_ships = num_ships game_over = False turn = "A" winner = "" while (not game_over): # Display the Player's board so that they know how they are doing. if (turn == "A"): print "\n\nPLAYER A" print "This is your board: \n" board_print(board_A) print "\nNow select the coordinate that you want to target on Player B's board.\n" board_print(board_A_targets) target = raw_input("\nWhat coordinate (x,y) would you like to fire at?: ") valid = is_valid_target(board_A_targets, str(target)) while (not valid): target = raw_input("\nWhat coordinate (x,y) would you like to fire at?: ") valid = is_valid_target(board_A_targets, str(target)) player_B_ships = fire_at_target(str(target), board_A_targets, board_B, player_B_ships, my_ships_B) if (player_B_ships == 0): game_over = True winner = turn else: turn = "B" else: print "\n\nPLAYER B" print "This is your board \n" board_print(board_B) print "\nNow select the coordinate that you want to target on Player A's board.\n" board_print(board_B_targets) target = raw_input("\nWhat coordinate (x,y) would you like to fire at?: ") valid = is_valid_target(board_B_targets, str(target)) while (not valid): target = raw_input("\nWhat coordinate (x,y) would you like to fire at?: ") valid = is_valid_target(board_B_targets, str(target)) player_A_ships = fire_at_target(str(target), board_B_targets, board_A, player_A_ships, my_ships_A) if (player_A_ships == 0): game_over = True winner = turn else: turn = "A" print "\n\n\n\nGAME OVER, Player " + winner + " has won!" print "\nFINAL BATTLEFIELDS\n" print "Player A's final battlefield:" board_print(board_A) print "\n\nPlayer B's final battlefield:" board_print(board_B) print "\n\nThank you for playing!" if __name__=="__main__": main()
0d4c91a22a4e4f9822d773ac2d701ee7f1d6b0e9
mynameischokan/python
/Strings and Text/1_13.py
865
4.03125
4
""" ************************************************************ **** 1.13. Aligning Text Strings ************************************************************ ######### # Problem ######### # You need to format text with some sort of alignment applied. ######### # Solution ######### # For basic alignment of strings, the `ljust()`, `rjust()`, # and `center()` methods of strings can be used. """ text = 'Hello World' # TODO # Adjust `text` to left by 20 total width of chars # Adjust `text` to right by 20 total width of chars # Adjust `text` to center by 20 total width of chars # TODO # Do the same thing done above with `format()` function x = 1.2345 # TODO # By using the benefit of `format()` function, # which is applicable to numbers. Center text by width of 20 chars. # Cut float do hundredth. if __name__ == '__main__': format(x, '=^20.2f')
f56b7728d9dd9677b8bb498a9c679e1961da4bdc
Adomkay/sql-intro-to-join-statements-lab-nyc-career-ds-062518
/sql_queries.py
933
3.515625
4
# Write your SQL queries inside the strings below. If you choose to write your queries on multiple lines, make sure to wrap your query inside """triple quotes""". Use "single quotes" if your query fits on one line. def select_hero_names_and_squad_names_of_heroes_belonging_to_a_team(): return "SELECT superheroes.name, squads.name FROM superheroes JOIN squads ON superheroes.squad_id = squads.id;" def reformatted_query(): return "SELECT superheroes.name, squads.name AS team FROM superheroes JOIN squads ON superheroes.squad_id = squads.id ORDER BY team" def all_superheroes(): return "SELECT superheroes.name, superheroes.superpower, squads.name AS team FROM superheroes LEFT JOIN squads ON superheroes.squad_id = squads.id ORDER BY team;" def all_squads(): return "SELECT squads.name AS team, COUNT(superheroes.id) FROM squads LEFT JOIN superheroes ON superheroes.squad_id = squads.id GROUP BY squads.name;"
bfb87251e8500338aa182edcdf96940323f10770
DevinTyler26/learningPython
/mvaIntroToPython/if-else.py
315
4.125
4
g = 9 h = 8 if g < h: print('g < h') else: if g == h: print('g == h') else: print('g > h') name = 'Devin' height = 2 weight = 110 bmi = weight / (height ** 2) print('bmi: ') print(bmi) if bmi < 25: print(name) print('is not overweight') else: print(name) print('is overweight')
afeb98a626530d7aa205909b49df3c9cc32104db
JunyoungChoi/programmers
/K번째수.py
231
3.53125
4
def solution(array, commands): answer = [] arr = [] for i in range(0,len(commands)): arr=array[commands[i][0]-1 :commands[i][1]] arr.sort() answer.append(arr[commands[i][-1]-1]) return answer
4e811e34951024d6ad626c7e5b8091d1e5ac6ba0
srvasquez/TareaBuda
/dijkstra.py
1,636
3.640625
4
def insert_open(open_queque, visited, station): distance_new_station = visited[station]['distance'] for i in range(len(open_queque)): compared_station = open_queque[i] distance_station = visited[compared_station]['distance'] if distance_station and distance_new_station <= distance_station: open_queque.insert(i, station) return open_queque open_queque.append(station) return open_queque def solve_path(start_station, goal_station, vagon_color, visited): open_queque = [start_station] visited[start_station]['distance'] = 0 while open_queque: actual_station = open_queque.pop(0) visited[actual_station]['visited'] = True if str(actual_station) == goal_station: return actual_station for station in actual_station.get_conections(): if visited[station]['visited']: continue color_station = station.get_color() if vagon_color != 'white' and color_station != 'white' and vagon_color != color_station: distance = 0 else: distance = 1 total_distance = visited[actual_station]['distance'] + distance if visited[station]['distance'] and total_distance >= visited[station]['distance']: continue visited[station]['distance'] = total_distance visited[station]['parent'] = actual_station open_queque = insert_open(open_queque, visited, station) return False
6267db4390d60165430bf4ea2d3c8043534ae8e3
timkao/Tim-Python-Codes
/findNextPerfectSquare.py
377
3.59375
4
# identify if the given number is a perfect square number # if not, return -1 # if yes, return next perfect square def findpsquare(num): A = 1 B = [] while num/A >= A: if num % A == 0: B.append(num/A) B.append(A) A += 1 for i in B: if B.count(i) == 2: return (i + 1)**2 if num == 0: return 1 return -1 print findpsquare(int(raw_input("> ")))
4589a9e5ff5a5dbcecc4160960318be0ad16dc34
ferreirads/uri
/uri1097.py
196
3.515625
4
i = 1 somador = 0 for I in range(1, 6): print(f'I={i} J={7 + somador}') print(f'I={i} J={6 + somador}') print(f'I={i} J={5 + somador}') i = i + 2 somador = somador + 2
7b9a2718f812762c1e3ba3bdae22a9f92abdbfda
asafepy/desafio-zoox
/questoes/q8.py
226
3.59375
4
def escrevaSort(alist): tempLista = [] for i, num in enumerate(alist): tempLista.append(num) print(sorted(tempLista)) if __name__ == '__main__': alist = [7, 5, 81, 3, 99] escrevaSort(alist)
b0039a55b1b3f690c4f7ea5d42c4b5d1b2308afd
Zahidsqldba07/python_course_exercises
/TEMA 2_CONDICIONALES/Iteraciones_3/Ej2.28.py
751
4.25
4
#!/usr/bin/env python # -*- coding: utf-8 -*- #Solicitar por teclado un número en hexadecimal y calcular su valor en decimal. hexadecimal = str(input("Introduce un numero hexadecimal para convertirlo a decimal: ")) exponente = len(hexadecimal) decimal = 0 for digito in hexadecimal: if digito == 'A': digito = 10 elif digito == 'B': digito = 11 #segun los valores de ABCDEF voy dandoles el valor en decimal elif digito == 'C': digito = 12 elif digito == 'D': digito = 13 elif digito == 'E': digito = 14 elif digito == 'F': digito = 15 exponente -= 1 base = int(digito) * (16**exponente) decimal = decimal + base print("El numero en decimal es " + str(decimal))
cbac5138b1e78127eaea686089bda03edf111389
ruddyadam/prometheus
/project_euler/002_sum_of_even_fibbonaccis.py
394
3.59375
4
fiblist = [1] def fib(fiblist): while fiblist[-1] < 4000000: if len(fiblist) == 1: fiblist.append(1) else: fiblist.append(fiblist[-1] + fiblist[-2]) print fiblist sumlist = [] for n in fiblist: if n%2 == 0: sumlist.append(n) print "sum of even fibbonacci numbers below 4000000 is:", sum(sumlist) fib(fiblist)
60e148a5d3ddfc1140be103dfb5dcefbc708f609
haojian/python_learning
/31. nextPermutation.py
729
3.671875
4
class Solution: # @param num, a list of integer # @return nothing (void), do not return anything, modify num in-place instead. #pseudo code #find the increasing pair and swap it #which pair? the swap should happen at the lower digit, the lower the better #happen means the left digit def nextPermutation(self, num): for li in range(len(num)-2, -1, -1): for ri in range(len(num)-1, li, -1): if num[ri] > num[li]: #swap ri and li print num[ri], num[li] tmp = num[ri] num[ri] = num[li] num[li] = tmp num[li+1:] = sorted(num[li+1:]) return else: num.reverse() if __name__ == "__main__": sol = Solution() num = [4,2,0,2,3,2,0] sol.nextPermutation(num) print num
6047ef64e86dc2ca1eee87546496466674c4469e
songjiyang/Mypython
/myPractice/List_util.py
1,188
3.859375
4
# -*- coding:utf-8 -*- """ 写一个列表工具类,可以对列表进行去重,合并,求差,初始化的时候打印hello world,销毁的时候打印Good bye """ class List_util(object): """列表工具类,可以对列表进行去重,合并,求差操作""" def __init__(self): super(List_util, self).__init__() print 'hello world' @classmethod def remove_repeat(cls, inlist): rsp_list = [] for item in inlist: if item not in rsp_list: rsp_list.append(item) return rsp_list @classmethod def merge(cls, inlist1, inlist2): rsp_list = [] for item in inlist1: rsp_list.append(item) for item in inlist2: rsp_list.append(item) rsp_list = cls.remove_repeat(rsp_list) return rsp_list @classmethod def sub(cls, inlist1, inlist2): rsp_list = [] if len(inlist1)>len(inlist2): max = inlist1 min = inlist2 else: max = inlist2 min = inlist1 for item in max: if item not in min: rsp_list.append(item) return rsp_list if __name__ == '__main__': list1 = [2,56,52,34,5,2,4,5] list2 = [2,3,4,5,6] print List_util.remove_repeat(list1) print List_util.merge(list1,list2) print List_util.sub(list1,list2)
8fa50331c168a0edcb00befe30b51dca21f5d2c7
darraes/coding_questions
/v2/_cracking_code_/10_Completed/10.7_tower_routine.py
855
3.6875
4
from collections import namedtuple Person = namedtuple("Person", ["height", "weight"]) def max_possible_tower(artists): ''' Longest Increasing Subsequence ''' artists.sort(key=lambda p: p.height) gmax = 0 dp = [0] * len(artists) dp[0] = 1 for i in range(1, len(dp)): for j in range(i): cur_max = 1 if artists[i].weight > artists[j].weight: cur_max = 1 + dp[j] dp[i] = max(dp[i], cur_max) gmax = max(gmax, dp[i]) return gmax ############################################################### import unittest class TestFunctions(unittest.TestCase): def test_1(self): self.assertEqual( 2, max_possible_tower([Person(80, 60), Person(70, 120), Person(65, 100)]) ) if __name__ == "__main__": unittest.main()
057ea667098f74b6602a9bb4a264a1bdfffade47
kmouse/Game_1
/Game/Data/Code/mouse.py
399
3.65625
4
import pygame TRANSPARENT = (0, 0, 0, 0) BLACK = (0, 0, 0) SIZE = (10, 10) class Mouse: def __init__(self, color=(47, 204, 222)): self.image = pygame.Surface(SIZE, pygame.SRCALPHA) self.image.fill(TRANSPARENT) # Draw a circle with a black outline pygame.draw.circle(self.image, BLACK, (5, 5), 5) pygame.draw.circle(self.image, color, (5, 5), 4)
c0a57d90fd86692d489bb6fa51a9af9b2b0069c1
nayakrujul/python-scripts
/Old Programs/BMI Calculator.py
1,056
4.3125
4
print("") testlist = [1, 2, 3] def test(): testlist.append(4) print(testlist) test() print("") print("-------------------------------------") print("") name = input('What is your name? ') print("Welcome " + name + ". This is your Python world.") age = int(input('How old are you? ')) if age < 12: print("You are still at primary school.") elif age < 18: print("You are still in secondary school.") elif age < 23: print("You are in college / university.") elif age < 50: print("You've still got over half your life remaining.") else: print("You are an old man / woman.") height = float(input('What is your height in metres? ')) weight = float(input('What is your weight in kilograms? ')) bmi = 0 bmi = float(weight) / (float(height) * float(height)) print("Your BMI is " + str(bmi)) if bmi < 18: print("You are underweight.") elif bmi < 25: print("You are healthy.") elif bmi < 30: print("You are overweight.") else: print("You are obese") # Go to https://repl.it/repls/VividLittleOutlier (Command + Click) ## Thank you
d83115460437362de99d1d1f34b566c6cbaacf69
zettran/PRACTICE-PYTHON
/webpage.py
964
3.9375
4
""" Use the BeautifulSoup and requests Python packages to print out a list of all the article titles on the New York Times homepage. """ import requests from bs4 import BeautifulSoup # the URL of the NY Times website we want to parse base_url = 'http://www.nytimes.com' # http://docs.python-requests.org/en/master/ r = requests.get(base_url) soup = BeautifulSoup(r.text) # soup = BeautifulSoup(r.text, 'lxml') # Use Chrome inspect to find out which HTML tags contain all the titles # https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all for story_heading in soup.find_all(class_="story-heading"): # this is class_ not class # if story_heading.contents is a tag if story_heading.a: # print a tag's text strip white space and '\n' print(story_heading.a.text.replace("\n", " ").strip()) else: # try to print story_heading.contents first to understand print(story_heading.contents[0].strip()) view raw
a49dff3215ac533fd89824cc3c0b583b5b07c2ba
Ackermannn/PythonBase
/PythonCode/my_roulette.py
454
3.515625
4
# -*- coding: utf-8 -*- """ Created on Wed Oct 30 22:53:09 2019 @author: Administrator """ ## my常用函数库 ## 轮盘赌函数 import numpy as np from numpy import cumsum from numpy.random import rand def roulette(p): cum = cumsum(p) pr = rand() for i,item in enumerate(cum): if pr < item: return i if __name__ == '__main__': p = np.array([0.3, 0.3, 0.4]) print(roulette(p)) # 输出 在 0 1 2范围
e57cd1b2a183be160f0f8f5b56fab83b535e274e
adalbertobrant/cursoPythonModerno
/decToBin.py
152
3.921875
4
def decBin(num): if num > 1: decBin(num // 2) print(num % 2, end='') num = int(input("Entre o número inteiro decimal")) decBin(num)
85c5a349050b7290dd3b9e059fc74ee8cf5a10bd
gabrielavirna/interactive_python
/problem_solving_with_algs_and_data_struct/chp2_analysis/dictionaries.py
1,731
4.1875
4
""" Dictionaries ============ - dictionaries differ from lists in that you can access items in a dictionary by a key rather than a position. - Operations: the get item and set item operations on a dictionary are O(1). - Another operation: the contains operation - Checking to see whether a key is in the dictionary or not is also O(1). In some rare cases the contains, get item, and set item operations can degenerate into O(n) operation Big-O Efficiency copy O(n) get item O(1) set item O(1) delete item O(1) contains (in) O(1) iteration O(n) Dictionaries vs lists: compare the performance of the contains operation. The time it takes for the contains operator on the list grows linearly with the size of the list O(n). The contains operator on a dictionary is constant even as the dictionary size grows: O(1) Implementation -> List: Make a list with a range of numbers in it. Then pick numbers at random and check to see if the numbers are in the list. If our performance tables are correct the bigger the list the longer it should take to determine if any one number is contained in the list. -> Dictionary: Repeat for a dictionary that contains numbers as the keys. Determining whether or not a number is in the dictionary is not only much faster, but the time it takes to check should remain constant even as the dictionary grows larger. """ import timeit import random for i in range(10000, 1000001, 20000): t = timeit.Timer("random.randrange(%d) in x" % i, "from __main__ import random, x") x = list(range(i)) lst_time = t.timeit(number=1000) x = {j: None for j in range(i)} dict_time = t.timeit(number=1000) print("%d, %10.3f, %10.3f" %(i, lst_time, dict_time))
23a47e9b99ee03b9c0ab8216d194fc94a8a3e794
gitJaesik/algorithm_archive
/acmicpc/1110.py
526
3.78125
4
def getStrNum(num): newValue = "" if num < 10: newValue = "0" + str(num) else: newValue = str(num) return newValue def getNextPlusCicle(num): num2 = getStrNum(num) sum = int(num2[0]) + int(num2[1]) sum2 = getStrNum(sum) return int(num2[1] + sum2[1]) def main(): a = int(input()) origin = a cnt = 1 while True: a = getNextPlusCicle(a) if origin == a: break cnt += 1 print(cnt) if __name__ == "__main__": main()
23e7836aee72d0f0cb9fae9cd975cc21f18646b7
Codechef-SRM-NCR-Chapter/30-DaysOfCode-March-2021
/answers/Drish-xD/Day-16/Question-1.py
714
3.984375
4
# Program to count the number of 1's in a binary array :) def count_1(array, x, y): while y >= x: z = (x + y) // 2 # Finding mid term if array[y] == 0: # If last term of array is 0, so count of 1 = 0 return 0 elif array[x] == 1: # If first term of array is 1, so count of 1 = len of array return y - x + 1 else: return count_1(array, z + 1, y) + count_1(array, x, z) # Using recursion return False arr = map(int, input("Enter the elements of binary array *With spaces b/w number* :").split()) arr = sorted(arr) # Sorting the list in increasing order x = 0 y = len(arr) - 1 print(count_1(arr, x, y))
447dae5a34f62bf47dc7fa2c1ef5c2f9991bb36c
mechanicalgirl/young-coders-tutorial
/games/number_guessing/guess_one.py
161
3.8125
4
secret_number = 7 guess = input("What number am I thinking of? ") if secret_number == guess: print "Yay! You got it." else: print "No, that's not it."
e1a2a6c55edba7a76c9fd5e7b7db80387b8a271f
RiteshBhola/literate-octo-train
/fibonacci.py
210
3.71875
4
""" FIbonacci program: This program prints first n fibonacci numbersG 02/09/2019 Ritesh Kr, Bhola """ def fibonacci(k): f0=0 f1=1 print(f0) for i in range(1,k): print(f1) temp=f0 f0=f1 f1=temp+f1
5b9e00a7f9c8a6bed1a8c3ae24f45dfdb2d5df61
richard-yap/Lets_learn_Python3
/module_2_data_types.py
6,043
3.90625
4
# ---------------------MODULE 2 Data Types---------------------- # . # . # . # . # . # . # . # . # . # . # number/ int, float # string # list # tuple # dictionary # set # you can also write a variable like this in atom, but not in jupyter notebook: a, b = 1, 2 c = a + b a b # .format nicely puts them into the pcurly brackets #.format only works with curly brackets {} # new indexing method, the values in () function like a list print("{} + {} = {}".format(a, b ,c)) # for hydrogen you don't have to write print all the time will return with a quotation mark #to change the positions of a, b, c: "{1} + {0} = {2}".format(a, b, c) #to change the number of decimal places: "{:.1f} + {:.2f} = {:.5f}".format(a, b, c) #to specify how many spaces you want the character/value to occupy: # but unable to put them in the middle "{0:5.1f} + {1:5.2f} = {2:5.5f}".format(a, b, c) #-----------------------------PRACTICE 1---------------------------------- a = 4.444 b = 5.555 c= 6.666 d = a + b + c print("{1:.2f} + {2:.2f} + {0:.1f} = {3:.0f}".format(a, b, c, d)) #------------------------------------------------------------------------- # string concatenation adding the string "-" * 50 a = 'hello ' b = 'world!' c = a + b # apparantly you can multiply strings here, not sure if can in jupyter notebook though c #functions for variables that are strings #but the result is a derivative, unless you link it to a variable c.upper() c.lower() c.capitalize() # replaces the string with a new string specified after the comma c.replace("world", "Richard") # -------------------------PRACTICE 2----------------------------------- country = "france" capital = "paris" print("The capital of {} is {}".format(country.upper(), capital.capitalize())) # ----------------------------------------------------------------------- # \n gives new line # \t gives new tab #.strip() gets rid of all the white spaces print("\n\t Hello ".strip()) print(" g ha wi ".strip()) #.split() function splits the strings into a list a = 'Today is a sunny day' a.split() b = 'The answer = 5' c = b.split(' = ') # the '' you specify becomes the spliting point print(c) #joining list if strings d = ['hello', 'world', '1234'] ",".join(d) #--------------------------------PRACTICE 3---------------------------------- practice_3 = "abc@def.com" list1 = practice_3.split("@") print(list1[0], "is from", list1[1] ) # doing it the .format way "{} is from {}".format(list1[0], list1[1]) # doing it the .join() way " is from ".join(list1) # the * unpacks the list into individual variables # syntactic sugar :)) "{} is from {}".format(*list1) # may be gone in python 4, but used in python2 when .format was not available, seen in javascript and c f"{list1[0]} is from {list1[1]}" #--------------------------------------------------------------------------- # .find() function a = 'Today is a nice day' a.find('nice') a.find('z') # .count() function b = "aiwnecouebeo" b.count('b') #--------------------------------LISTS------------------------------------- # the [] notation also applies to a string # you can think of strings as an ordered collection b = 'hello2' b[0] lista = [7, 8, 9, 10, 11] # cloning the list: new_list = lista[:] print(new_list) lista[1:] lista[::-1] lista[:2] #cloning list method 2 v = lista.copy() print(v) # finding number of items in the list/ string len(lista) len(b) # to obtain the index position in the list: lista = [7, 8, 9, 10, 11] lista.index(9) #mutative/transformative/mutable functions #extending the list: lista.append(10) print(lista) #specific location: # lista.insert(position, value) lista.insert(2, 99) print(lista) #deleting #don't use del lista[2] <- may be removed in python 4 # use with parenthesis del(lista[2]) print(lista) #getting back the value lista.pop(2) #--------------------------------------------------------------------------- #mutative sort listb = [3, 6, 1, 0, 5] listb.sort() listb #derivative sort sorted(listb) #reverse the list listb.reverse() listb listb[::-1] #---------------------------PRACTICE 4---------------------------------- letters = list("ACCATTGACA") letters # 1. letters.count("A") # 2. letters.index("T") # 3. letters2 = letters[:] letters2.remove("G") # 4. letters2 letters2.insert(2, "A") letters2 # 5. reverse_letters2 = letters2[::-1] print(reverse_letters2) #----------------------------------TUPLES--------------------------------- # if you don't put parenthesis, it will become a TUPLE a = 1, 2, 3, 4, 5 a n,m = 3,4 n m #----------------------------------DICTIONARIES------------------------------- # the keys you use must be immutable (tuple, strings or numbers) new_dict = {} new_dict[(1,4)] = 'happy' new_dict # dictionary are not ordered # You can also insert an item to a dictionary by using the update() method, e.g.: dict = {"cat" : "chat", "dog" : "chien", "horse" : "cheval"} dict.update({"duck" : "canard"}) print(dict) # To remove the last item in a dictionary, you can use the popitem() method: dict = {"cat" : "chat", "dog" : "chien", "horse" : "cheval"} dict.popitem() print(dict) # outputs: {'cat' : 'chat', 'dog' : 'chien'} # This is done with the del instruction. # # Here's the example: dict = {"cat" : "chat", "dog" : "chien", "horse" : "cheval"} del dict['dog'] print(dict) #------------------------------------SETS-------------------------------------- s = {1,2,3,1,2,3} s #the set will take out duplicates, values will be unique #--------------------------------PRACTICE 4----------------------------------- sent = "Peter reads a book on a table" list_sent = sent.split() set_sent = set(list_sent) print(list_sent) print(set_sent) len(set_sent) #-----------------------------------------------------------------------------
bdb37d4b31d2be06a8e320d63f92eee4d1d2f380
fyrtoes/project_01_Stage_Reader
/colconverter.py
3,647
4.375
4
# GCAV Information # 1/22/2015 FINISHED on 1/25/2015 # The purpose of this program is to convert the column index from Meyer's into a number. A = 1, B = 2, etc. ''' print "\n" # Here is where I will ask the user to provide the column, from where I will store it. column = raw_input('Enter the column index (a, b, ac, etc.):') # I will print back what the user selected print 'Hello, the column you entered is: ', column, "\n" ''' # In function form def columnconverter(column): #Here I take the size of the column entered for good coding. length = len(column) #Here I have the map that I will be working off of. a = 0 due to the array organization. map = 'abcdefghijklmnopqrstuvwxyz' map2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' ## variables for 1st for-loop # initialize 'i' and 'j' just in case. i = 0 # Index of column[i]. Goes through each letter in the column j = 0 # Compares column[i] to each letter to all alphabet flag_success = False j_var = [] ## variables for 2nd for-loop i2 = 0 # needed for the second for-loop iteration counter j2 = 0 # maybe wont need it sum = 0 # Final sum of the index b = len(map) # how many elements does 'map' contain? 26 n = len(column) # how many elements does 'column' contain? User-dependent ############## 1st for-loop ############ # This version of the for loop will convert each letter in the of the 'column' variable into an number in an array. # i is the iteration # len(map) is the size of the character array above called "map" # range(len(map)) crates an array out of the integer value that is "len(map)" # This will permit the for-loop to operate, since it requires an array of numbers ######################################### for i in range(len(column)): # run the for-loop as many times as there are characters in the 'column' variable while ((j < len(map)) and (flag_success == False)): # run while-loop as many times as there are characters in our 'map' no need for more, #.....because there are no more letters in the alphabet. # The other condition is our exit flag. We exit when we succeed. Must reset in the for-loop. if (map[j] == column[i]): # If these do match. j_var.append( j + 1 ) # Include the numerical value (1-26) in the array called j_var flag_success = True # trigger flag to exit while-loop, or else we are stuck succeeding forever elif (map2[j] == column[i]): # If these do match. j_var.append( j + 1 ) # Include the numerical value (1-26) in the array called j_var flag_success = True # trigger flag to exit while-loop, or else we are stuck succeeding forever else: j = j + 1 # counter to accomplish two things: 1) increase the index, comparing the next letter in 'map' # 2) Counter to exit a perpetually failing while-loop if (j >= len(map) ): # if statement in case goober enters a non-alphabetical symbol print "***********", column[i], "is not a letter ***********" # error message to goober j = 0 # must restart j for the re-enabling of the next while-loop flag_success = False # must reset for the re-enabling of the next while-loop ############## 2nd for-loop ############ # This loop will take j_var array and use each as the coefficient of the base conversion polynomial: # SIGMASUM (n, itersum = 0), L(_itersum) * (b**(n-itersum)), # where L is the j_var index for that particular itersum iteration, b and n can be found on lines 29-30 ######################################## for i2 in range(len(j_var)): sum = sum + ( j_var[i2] * ( b ** ( n - i2 - 1 ) ) ) return sum print columnconverter(column)
d4faa91c74c189a892ac7441e18a2eef59354a17
12Me21/markup
/parse1.py
3,808
3.65625
4
def highlight(code, language): return code def escape_html(code): return code.replace("&","&amp;").replace("<","&lt;").replace("\n","<br>") def escape_html_char(char): if char=="<": return "&lt;" if char=="&": return "&amp;" if char=="\n": return "<br>" if char=="\r": return "" return char def parse(code): i = -1 c = None output = "" def next(): nonlocal i nonlocal c i += 1 if i < len(code): c = code[i] else: c = "" def nextb(): next() while c=="{": parse() def skip_linebreak(): nonlocal i nonlocal c if c=="\n" or c=="\r": next() def is_start_of_line(): return i==0 or code[i-1]=="\n" def parse(): nonlocal i nonlocal c nonlocal output nextb() while c: ## code block if c=="`": next() if c=="`": next() # multiline code block if c=="`": output += "<code>" language = "" while 1: nextb() if c=="\n": break elif c: language += c else: raise Exception("Reached end of input while reading ``` start") start = i+1 while 1: next() if c=="`": next() if c=="`": next() if c=="`": break; if not c: raise Exception("Reached end of input while reading code inside ```") output += highlight(code[start:i-2], language.strip()) output += "</code>" nextb() skip_linebreak() # bad else: output += "``" next() # inline code block else: output += "<code>" while 1: if c=="`": output += "</code>" break elif c: output += escape_html_char(c) else: raise Exception("Unclosed ` block") next() nextb() ## heading elif c=="*" and is_start_of_line(): heading_level = 1 nextb() while c=="*": heading_level += 1 nextb() if heading_level > 6: raise Exception("Heading too deep") output += "<h%d>" % heading_level while 1: if not c or c=="\n": break output += escape_html_char(c) nextb() output += "</h%d>" % heading_level nextb() ## escaped char elif c=="\\": nextb() if c: output += escape_html_char(c) nextb() ## tables elif c=="|": nextb() # table start if c=="=": nextb() while c=="=": nextb() if c=="|": nextb() else: raise Exception("missing | in table start") while c=="\n" or c=="\r": nextb() if c=="|": nextb() else: raise Exception("missing | in table start") output += "<table><tbody><tr><td>" skip_linebreak() # table start (with header) elif c=="*": nextb() if c=="*": nextb() if c=="|": nextb() else: raise Exception("missing | in table start") if c=="\n" or c=="\r": nextb() if c=="|": nextb() else: raise Exception("missing | in table start") output += "<table class='header_table'><tbody><tr><td>" skip_linebreak() # other else: skip_linebreak() # this is used for the linebreak after | as well as the linebreak between || # table end or next row if c=="|": nextb() #table end if c=="=": nextb() if c=="=": nextb() if c=="|": nextb() else: raise Exception("missing | in table end") output += "</td></tr></tbody></table>" skip_linebreak() #next row else: output += "</td></tr><tr><td>" skip_linebreak() # next cell else: output += "</td><td>" ## return elif c=="}": nextb() return ## other symbol else: output += escape_html_char(c) nextb() parse() return output
4a62e8e097e7433ae8266ffd517fc88927acbb81
waveletus/yang
/wordhunt.py
5,601
3.5625
4
################################# #Basic idea: # word is inserted into table by sequence of horizon and vertical # line or column is selected by probability of left space number # The first step is to select line or column and put into the free space (more space more probability) # The second step is to try to compact the word letter (share the letter as most as possible) # line 1 # line 2 ################################# import sys import numpy as np import random horizonNumber = 14 vertialNumber = 14 def words_input(): words = ['habit', 'review', 'frequently', 'talent', 'productivity', 'constant', 'something', 'guess', 'experience', 'experiment', 'simplicity', 'letter', 'most', 'compact'] words.sort(key = lambda s:len(s), reverse = True) words_arrange(words) def obtain_index(num, option): if option == 'h': temp = int(num / vertialNumber) elif option == 'v': temp = num % vertialNumber else: print('mistake') temp = -1 return(temp) def words_arrange(words): candidate = [] for i in range(horizonNumber * vertialNumber): candidate.append(i) letterMatrix = [] for i in range(horizonNumber): temp = [] for j in range(vertialNumber): temp.append('*') letterMatrix.append(temp) missed = [] flag = -1 for word in words: flag = flag * (-1) sign = 1 count = 0 while sign: count += 1 if flag == 1 and count > 14: missed.append(word) break else: if flag == -1 and count > 9: missed.append(word) break selected = random.choice(candidate) hor = obtain_index(selected, 'h') ver = obtain_index(selected, 'v') coe = -1 if flag == 1: coe = hor else: coe = ver if letterMatrix[hor][ver] == '*': if put(word, letterMatrix, candidate, flag, hor, ver): sign = 0 else: if putfromzero(word, letterMatrix, candidate,flag, coe): sign = 0 else: continue else: if putfromzero(word, letterMatrix, candidate, flag, coe): sign = 0 else: continue if len(missed) > 0: for word in missed: found = 0 for i in range(0, horizonNumber): if putfromzero(word, letterMatrix, candidate, 1, i): found = 1 missed.remove(word) break if found == 0: for j in range(0, vertialNumber): if putfromzero(word, letterMatrix, candidate, -1, j): found = 1 missed.remove(word) break for word in missed: words.remove(word) words_output(letterMatrix, words) print(missed) def put(word, letterMatrix, candidate, flag, hor, ver): if flag == 1: for i in range(0, len(word)): if (ver + i < vertialNumber and letterMatrix[hor][ver + i] != '*' and letterMatrix[hor][ver + i] != word[i]) or (ver+i >=vertialNumber): return(False) for i in range(0, len(word)): if letterMatrix[hor][ver + i] == '*': letterMatrix[hor][ver + i] = word[i] temp = hor * vertialNumber + ver + i candidate.remove(temp) return(True) else: for i in range(0, len(word)): if (hor+i < horizonNumber and letterMatrix[hor + i][ver] != '*' and letterMatrix[hor + i][ver] != word[i]) or (hor + i >= horizonNumber): return(False) for i in range(0, len(word)): if letterMatrix[hor + i][ver] == '*': letterMatrix[hor + i][ver] = word[i] temp = (hor + i) * vertialNumber + ver candidate.remove(temp) return(True) # check if there are shared letter and then from 0-1 check put indpendently def putfromzero(word, letterMatrix, candidate, flag, coe): if flag == 1: for i in range(0, vertialNumber): if letterMatrix[coe][i] != '*': index = word.find(str(letterMatrix[coe][i])) if index >= 0 and i > index and put(word, letterMatrix, candidate, flag,coe, i - index): return(True) for i in range(vertialNumber-1, len(word)-1, -1): if letterMatrix[coe][i] == '*': if put(word, letterMatrix, candidate, flag, coe, i - len(word)): return(True) else: for i in range(0,horizonNumber): if letterMatrix[i][coe] != '*': index = word.find(str(letterMatrix[i][coe])) if index >= 0 and i > index and put(word, letterMatrix, candidate, flag, i - index, coe): return(True) for i in range(horizonNumber-1, len(word)-1, -1): if letterMatrix[i][coe] == '*': if put(word, letterMatrix, candidate,flag, i - len(word), coe): return(True) return(False) def words_output(letterMatrix, words): all_letters = 'abcdefghijklmnopqrstuvwxyz' alpha = [] for char in all_letters: alpha.append(char) with open('wordhunt.txt', 'w+') as f: f.write('\\begin{tikzpicture}\n') #f.write('\\textblockorigin{0cm}{0cm}' + '\n') f.write('\draw(7,17) node{WORDHUNT};\n') f.write('\\node(fig2) at(9,17){\includegraphics[width=1cm]{/Users/lxb/Documents/yyc/latex/gmbrothers.png}};') f.write('\\node(fig1) at(15,17){\includegraphics[width=4cm]{/Users/lxb/Documents/yyc/pokemonpics/wordhunt/mickymouse.png}};\n') dis = 2 #move the table below for i in range(0, horizonNumber): for j in range(0, vertialNumber): f.write('\draw(' + str(i) + ',' + str(j+dis) + ')+(-.5, -.5) rectangle++(.5, .5);' + '\n') f.write('\draw(' + str(i) + ',' + str(j+dis) + ') node{') if letterMatrix[i][j] == '*': f.write(random.choice(alpha).upper() + '};\n') else: f.write(str(letterMatrix[i][j]).upper() + '};\n') f.write('\n') x = vertialNumber + 0.5 y = dis + 1 for word in words: f.write('\draw(' + str(x)+','+str(y) + ')[text width = 2cm, anchor = west] node{' + word.upper() + '};\n') y += 0.8 f.write('\end{tikzpicture}') def main(): words_input() if __name__ == '__main__': main()
67950b8dbc12adbba0f7ed69fa3d2cb37830ab62
ash-xyz/Galaxy-Zoo
/src/model.py
805
3.5
4
import tensorflow as tf from data import CLASSES, IMAGE_SHAPE def create_model(): """Creates a keras model for training Returns: model: keras model """ # Densenet Model conv_net = tf.keras.applications.MobileNetV2( include_top=False, input_shape=IMAGE_SHAPE) neural_net = tf.keras.layers.Flatten()(conv_net.output) neural_net = tf.keras.layers.Dropout(rate=0.5)(neural_net) neural_net = tf.keras.layers.Dense(300, activation='relu')(neural_net) neural_net = tf.keras.layers.Dropout(rate=0.5)(neural_net) neural_net = tf.keras.layers.Dense( len(CLASSES), activation='sigmoid')(neural_net) model = tf.keras.Model(inputs=conv_net.inputs, outputs=neural_net) for layer in model.layers: layer.trainable = True return model
20f11235ad844ba085625e2f870295da07dbb596
kvp250688/assignment8
/assignment8.py
1,038
3.578125
4
# coding: utf-8 # In[2]: import numpy as np import pandas as pd # In[3]: from pandasql import sqldf # In[ ]: import sqlite3 import pandas as pd from pandas import DataFrame, Series from pandasql import sqldf pysqldf = lambda q: sqldf(q, globals()) sqladb = pd.read_csv("https://archive.ics.uci.edu//ml//machine-learning-databases//adult//") #sqladb = pd.read_csv('adult.csv') pysqldf("""sqlite3.connect('sqladb')""") pysqldf("""CREATE TABLE adult ( age int, workclass varchar(40), fnlwgt int, education varchar(40), education_num int, marital_status varchar(40), occupation varchar(20), relationship varchar(40), race varchar(20), sex varchar(10), capital_gain int, capital_loss int, hours_per_week int, native_country varchar(50), label varchar(10))""") #question 1 pysqldf("SELECT * FROM adult LIMIT 10;")