blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
ab4a89539958603ec6a8b0586b1218ca6602b60c
marcimarc1/Pydoku
/Interface/classes.py
3,525
3.6875
4
import pygame import time pygame.font.init() class Sudoku: def __init__(self, board, width, height): self.board = board self.rows = 9 self.cols = 9 self.cubes = [[Cube(self.board[i][j], width, height) for j in range(self.cols)] for i in range(self.rows)] self.width = width self.height = height self.model = None self.selected = None def update_model(self): self.model = [[self.cubes[i][j].value for j in range(self.cols)] for i in range(self.rows)] def place(self, val): row, col = self.selected if self.cubes[row][col].value == 0: self.cubes[row][col].set(val) self.update_model() if valid(self.model, val, (row, col)) and solve(self.model): return True else: self.cubes[row][col].set(0) self.cubes[row][col].set_temp(0) self.update_model() return False def sketch(self, val): row, col = self.selected self.cubes[row][col].set_temp(val) def draw(self, win): # Draw Grid Lines gap = self.width / 9 for i in range(self.rows + 1): if i % 3 == 0 and i != 0: thick = 4 else: thick = 1 pygame.draw.line(win, (0, 0, 0), (0, i * gap), (self.width, i * gap), thick) pygame.draw.line(win, (0, 0, 0), (i * gap, 0), (i * gap, self.height), thick) # Draw Cubes for i in range(self.rows): for j in range(self.cols): self.cubes[i][j].draw(win) def select(self, row, col): # Reset all other for i in range(self.rows): for j in range(self.cols): self.cubes[i][j].selected = False self.cubes[row][col].selected = True self.selected = (row, col) def clear(self): row, col = self.selected if self.cubes[row][col].value == 0: self.cubes[row][col].set_temp(0) def click(self, pos): """ :param: pos :return: (row, col) """ if pos[0] < self.width and pos[1] < self.height: gap = self.width / 9 x = pos[0] // gap y = pos[1] // gap return (int(y), int(x)) else: return None def is_finished(self): for i in range(self.rows): for j in range(self.cols): if self.cubes[i][j].value == 0: return False return True class Cube: def __init__(self,value, width, height): self.value = value self.temp = 0 self.row = 9 self.col = 9 self.width = width self.height = height self.selected = False def draw(self, win): fnt = pygame.font.SysFont("ubuntu", 40) gap = self.width / 9 x = self.col * gap y = self.row * gap if self.temp != 0 and self.value == 0: text = fnt.render(str(self.temp), 1, (128, 128, 128)) win.blit(text, (x + 5, y + 5)) elif not (self.value == 0): text = fnt.render(str(self.value), 1, (0, 0, 0)) win.blit(text, (x + (gap / 2 - text.get_width() / 2), y + (gap / 2 - text.get_height() / 2))) if self.selected: pygame.draw.rect(win, (255, 0, 0), (x, y, gap, gap), 3) def set(self, val): self.value = val def set_temp(self, val): self.temp = val
3aa2076bc76d17d5cb2c903e5089f9dc6c913a13
acemourya/D_S
/C_1/Chatper-01 DataScience Modules-stats-Example/Module-numpy-example.py
1,100
4.15625
4
#numpy: numerical python which provides function to manage multiple dimenssion array #array : collection of similar type data or values import numpy as np #create array from given range x = np.arange(1,10) print(x) y = x*2 print(y) #show data type print(type(x)) print(type(y)) #convert list to array d = [11,22,4,45,3,3,555,44] n = np.array(d) print(n) print(type(n)) print(n*2) ##change data type n = np.array(d,dtype=float) print(n) #show shpae print(n.shape) #change demenssion n = np.array(d).reshape(-1,2) #read from 1st element , 2 two dimenssion print(n) d = [11,22,4,45,3,3,555,44,3] n = np.array(d).reshape(-1,3) #read from 1st element , 3 dimenssion print(n) #generate the array of zeors print(np.zeros(10)) #generate the array of ones print(np.ones(10)) #matrix or two dimession array and operation x = [[1,2,3],[5,6,7],[66,77,88]] #list y = [[11,20,3],[15,26,70],[166,707,88]] #list #convert to array x = np.array(x) y = np.array(y) print(x) print(y) #addition print(np.add(x,y)) print(np.subtract(x,y)) print(np.divide(x,y)) print(np.multiply(x,y))
803761ecc916ed783192a842385ff34d1fffce5c
vibhor-vibhav-au6/CVRaman-solutions
/week04/day03.py
1,153
4.09375
4
# Q1. # Write a Python program to round the numbers of a given list, print the minimum # and maximum numbers and multiply the numbers by 5. Print the unique numbers # in ascending order separated by space. # Original list: [22.4, 4.0, 16.22, 9.1, 11.0, 12.22, 14.2, 5.2, 17.5] # Minimum value: 4 # Maximum value: 22 # Result: # 20 25 45 55 60 70 80 90 110 def multiTasks(array): array.sort() temp = list(map(round, array)) print ('max is: '+ str(max(temp)) + '\n' + 'min is: '+ str(min(temp))) # def f(a): # return a*5 # this is equivalant to the lambda function below return(list(map(lambda a : a*5,temp))) # driver l = [22.4, 4.0, 16.22, 9.1, 11.0, 12.22, 14.2, 5.2, 17.5] print(multiTasks(l)) # Q2. Write a Python program to create a list by concatenating a given list which # range goes from 1 to n. # Sample list : ['p', 'q'] # n =5 # Sample Output : ['p1', 'q1', 'p2', 'q2', 'p3', 'q3', 'p4', 'q4', 'p5', 'q5' def concatList(n, string): # return [c+str(i) for i in range(1,n+1) for c in string] # or return ['{}{}'.format(i, j) for j in range(1, n+1) for i in string] # driver n = 5 s = ['p', 'q'] print(concatList(n,s))
bfa28ab12a8a5da15f46ea7daf625b9d26d75757
sam98na/consolidatedCollegeWork
/cs188/python_basics/listcomp.py
229
3.75
4
nums = [1, 2, 3, 4, 5, 6] oddNums = [x for x in nums if x % 2 == 1] print(oddNums) oddNumsPlusOne = [x + 1 for x in nums if x % 2 == 1] print(oddNumsPlusOne) def listcomp(lst): return [i.lower() for i in lst if len(i) >= 5]
ae0009a76b00c9000d4cf023b55461676b6706b8
cakmakaf/Project_Euler_Challenges
/sum_of_multiplies_3_or_5.py
140
3.75
4
total_sum = 0 for i in range(1000): if (i % 3 == 0 or i % 5 ==0): total_sum = total_sum + i print(total_sum)
b9b836dffee50eea89374a9978eeb48a86431187
vladosed/PY_LABS_1
/3-4/3-4.py
730
4.3125
4
#create random string with lower and upper case and with numbers str_var = "asdjhJVYGHV42315gvghvHGV214HVhjjJK" print(str_var) #find first symbol of string first_symbol = str_var[0] print(first_symbol) #find the last symbol of string last_symbol = str_var[-1] print(last_symbol) #slice first 8 symbols print(str_var[slice(8)]) #print only symbols with index which divides on 3 without remaining list_of_str_var = list(str_var.strip(" ")) every_third_elem = list_of_str_var[::3] list_to_str = ''.join(str(x) for x in every_third_elem) print(list_to_str) #print the symbol of the middle of the string text middle = str_var[int(len(str_var) / 2)] #len(str_var) / 2 print(middle) #reverse text using slice print(str_var [::-1])
46710e021657795e54522f6820ae99429b93b0bb
DinoSubbu/SmartEnergyManagementSystem
/backend/gasBoiler/hot_water_demand_api.py
3,911
3.65625
4
from datetime import datetime import config import csv import os ############################################### Formula Explanation ############################################## # Formula to calculate Heat Energy required : # Heat Energy (Joule) = Density_Water (kg/l) * Specific_Heat_water (J/Kg/degree Celsius) * Water_Demand (l) * # Temp_Desired - Temp_Current (deg Celsius) # Formula to convert from Heat energy to Power : # Power (Watt) = Heat Energy (Joule) / Time (s) # Example : # Heat Energy required to achieve hot water demand in a hour = 3600 Joule # Power required = No of Joules per second # Assuming time frame of 1 hour = 3600 s # Power = 3600/3600 = 1 J/s = 1 W # (i.e) 1 Joule of energy has to be supplied per second for a duration of 1 hr to meet the demand ################################################################################################################## ############################# Mathematical Constants ################################### DENSITY_WATER = 1 # 1 kg/l SPECIFIC_HEAT_CAPACITY_WATER = 4200 # 4.2KJ/Kg/degree Celsius --> 4200 J/Kg/deg Celsius ######################################################################################## class HotWaterAPI: """ API to calculate power required for meeting hot water demand. Requires hot water demand profile in the form of csv. Attributes ---------- buildingName : string name of the building where gas boiler is installed and hot water has to be supplied noOfOccupants : int number of occupants in a building desiredTempWater : float desired temperature of hot water. Reads from global config file currentTempWater : float current temperature of tap water. Reads from global config file demandProfile : dictionary hourly demand profile for a building hotWaterDemand : float amount of hot water (in litres) needed at the current hour of the day ThermalPowerDHW : float power (in Watts) needed to meet the hot water demand at the current hour of the day Methods ------- getHotWaterProfile() based on the building name and no of occupants, selects the hot water demand profile for the entire day getCurrentHotWaterDemand() returns the hot water demand (in litres) for the current hour getThermalPowerDHW(buildingName) returns power required (in Watt) for hot water demand """ def __init__(self, noOfOccupants = 4): self.noOfOccupants = noOfOccupants self.desiredTempWater = config.DESIRED_TEMPERATURE_WATER self.currentTempWater = config.CURRENT_TEMPERATURE_WATER self.hotWaterDemand = 0 def getHotWaterProfile(self): currentDirectory = os.path.abspath(os.path.dirname(__file__)) pathCsv = os.path.join(currentDirectory, "dhw_demand_profiles/" + self.buildingName + ".csv") with open(pathCsv) as hotWaterProfilecsv: hotWaterCsvReader = csv.reader(hotWaterProfilecsv) demandProfile = [row for idx, row in enumerate(hotWaterCsvReader) if idx==self.noOfOccupants-1] demandProfile = demandProfile[0] demandProfile = {i:float(demandProfile[i]) for i in range(24)} return demandProfile def getCurrentHotWaterDemand(self): currentHour = datetime.now().hour return(self.demandProfile[currentHour]) def getThermalPowerDHW(self, buildingName): self.buildingName = buildingName self.demandProfile = self.getHotWaterProfile() self.hotWaterDemand = self.getCurrentHotWaterDemand() heatEnergy = DENSITY_WATER * SPECIFIC_HEAT_CAPACITY_WATER * self.hotWaterDemand * \ (self.desiredTempWater - self.currentTempWater) self.ThermalPowerDHW = heatEnergy / 3600 return(self.ThermalPowerDHW)
4b96b2b9227aa69affad957b559437872e1ed3ff
SpencerOfwiti/machine-learning-algorithms
/Neural Networks/image_classifier.py
1,850
3.796875
4
# import libraries import tensorflow as tf from tensorflow import keras import numpy as np import matplotlib.pyplot as plt # load dataset data = keras.datasets.fashion_mnist # splitting data into training and testing data (train_images, train_labels), (test_images, test_labels) = data.load_data() # defining a list of class names class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] # pre-processing images # scaling the pixel values down to make computations easier train_images = train_images/255.0 test_images = test_images/255.0 # creating our model # a sequential model with 3 layers from input to output layer # input layer of 784 neurons representing the 28*28 pixels in a picture # hidden layer of 128 neurons # output layer of 10 neurons for each of the 10 classes model = keras.Sequential([ keras.layers.Flatten(input_shape=(28, 28)), keras.layers.Dense(128, activation='relu'), keras.layers.Dense(10, activation='softmax') ]) # compiling and training the model # compiling is picking the optimizer, loss function and metrics to keep track of model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(train_images, train_labels, epochs=5) # testing the accuracy of our model test_loss, test_acc = model.evaluate(test_images, test_labels) print('\nTest accuracy:', test_acc) # using the model to make predictions predictions = model.predict(test_images) # displaying first 5 images and their predictions plt.figure(figsize=(5, 5)) for i in range(5): plt.grid(False) # plotting an image plt.imshow(test_images[i], cmap=plt.cm.binary) plt.xlabel('Actual: ' + class_names[test_labels[i]]) plt.title('Prediction: ' + class_names[np.argmax(predictions[i])]) plt.show()
092484419e6ca5d7ea8c70c89c183c74cfffa743
jisheng1997/pythontest
/main/list.py
2,549
3.890625
4
#!/usr/bin/python3 # -*- encoding: utf-8 -*- """ @File : list.py @Time : 2020/8/6 22:53 @Author : jisheng """ #列表索引从0开始。列表可以进行截取、组合 #列表是最常用的Python数据类型,它可以作为一个方括号内的逗号分隔值出现。 #列表的数据项不需要具有相同的类型 #变量表 list1 = ['Google', 'python', 1997, 2000] list2 = [1, 2, 3, 4, 5 ] list3 = ["a", "b", "c", "d"] list5 = ['b','a','h','d','y'] tuple1 = ('I','love','python') print('------------以下是列表的获取,修改,删除-------------') print ("list1[0]: ", list1[0]) print ("list1[-2]: ", list1[-2]) print ("list2[1:5]: ", list2[1:5]) print ("list3[1:]: ", list3[1:]) #你可以对列表的数据项进行修改或更新,你也可以使用append()方法来添加列表项 print ("第三个元素为 : ", list1[2]) list1[2] = 2001 print ("更新后的第三个元素为 : ", list1[2]) print ("原始列表 : ", list1) del list1[3] print ("删除第三个元素 : ", list1) print('-----------------以下是列表脚本操作符-------------------') #1.长度 2.组合 3.重复 4.元素是否存在于列表中 print(len(list2),list2+list3,list1*4,3 in list2) #5.迭代 for x in list1: print(x,end=' ') print('') print('-------------------以下是嵌套列表--------------------') list4 = [list1,list2,list3] print("list4: ",list4) print("list4[1]: ",list4[1]) print("list4[2][3]: ",list4[2][3]) print('-------------------以下是列表函数&方法---------------------') #列表元素个数/返回列表元素最大值/返回列表元素最小值 print(len(list2),max(list2),min(list2)) #将元组转换为列表 print(list(tuple1)) #在列表末尾添加新的对象 list1.append('baidu') print(list1) #统计某个元素在列表中出现的次数 print(list1.count('Google')) #在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表) list1.extend(list2) print(list1) #从列表中找出某个值第一个匹配项的索引位置 print(list1.index("Google")) #将对象插入列表 list1.insert(len(list1),'nihao') print(list1) #移除列表中的一个元素(默认最后一个元素),并且返回该元素的值 print(list1.pop()) #移除列表中某个值的第一个匹配项 list1.remove("Google") print(list1) #反向列表中元素 list1.reverse() print(list1) #对原列表进行排序 True升序 list5.sort(reverse=True) print(list5) #复制列表 listlist = list1.copy() print(listlist) #清空列表 list1.clear() print(list1)
5af8ab9e91bc331bd64ac43aaaf6be59ac95c949
divij-pherwani/Algorithms
/Corona Tracking App/Code.py
1,189
3.5625
4
import sys def trackerApp(n, d, event): ret = [""] * n position = dict() pairs = 0 for k, i in enumerate(event): if i[0] == 1: # Adding element position[i[1]] = "Value" # Adding number of pairs formed using the element pairs = pairs + int((i[1] + d) in position) + int((i[1] - d) in position) elif i[0] == -1: # Removing element del position[i[1]] # Removing number of pairs formed using the element pairs = pairs - int((i[1] + d) in position) - int((i[1] - d) in position) # Final events if pairs >= 1: ret[k] = "red" else: ret[k] = "yellow" del position del pairs return ret # Reads the input astr = sys.stdin.readline().split() n = int(astr[0]) d = int(astr[1]) event = [[0 for _ in range(2)] for _ in range(n)] # Read event for i in range(0, n): astr = sys.stdin.readline().split() event[i] = [int(s) for s in astr[0:2]] # Calls your function ret = trackerApp(n, d, event) # Writes the output for i in range(0, n): print(ret[i])
078677cc461c3047153af9b95bf1f94280fa2855
wayhive/python_course
/python_course/demo1.py
553
3.859375
4
def print_name(): print("My name is Sey") print_name()#calling a function def print_country(country_name): print("My country is " + country_name) print_country("Kenya") developer = "William and Sey" def get_dev(The_string): for x in The_string: print(x) get_dev(developer) stuff = ["hospitals","schools","offices","houses","cars"] def get_dev(a_list): for x in a_list: print(x) get_dev(stuff) def say_name(name = "Developer"): return "My name is " + name say_name("Sey") get_tosh = say_name("Sey") print(get_tosh)
b07283832e229a7e1b45f59784c7abc499dd8fce
davidwrpayne/PythonScripting
/postmasscustomers.py
1,521
3.515625
4
import urllib2 import json import sys import random import base64 def main(): if len(sys.argv) == 1 : print "Usage:" print "Please provide an api host, for example 'https://s1409077295.bcapp.dev'" print "create a legacy api user and token" print sys.argv[0] + " <API_Host> <API_UserName> <APIToken>" sys.exit(0) url = str(sys.argv[1]) url = url + '/api/v2/customers' user = str(sys.argv[2]) token = str(sys.argv[3]) count = 30 if len(sys.argv) == 3 : count = int(sys.argv[2]) for i in range(count): randomint = random.randint(0, sys.maxint) jsondata = createRandomCustomer() createConnection(url, user, token, jsondata) def createRandomCustomer() : firstName = randomString() lastName = randomString() customer = { "first_name":firstName, "last_name":lastName, "email": firstName + "." + lastName + "@example.com" } jsondata = json.dumps(customer) return jsondata def createConnection(url , user, token, data) : request = urllib2.Request(url) # You need the replace to handle encodestring adding a trailing newline # (https://docs.python.org/2/library/base64.html#base64.encodestring) base64string = base64.encodestring('%s:%s' % (user, token)).replace('\n', '') request.add_header("Authorization", "Basic %s" % base64string) request.add_header("Content-Type","application/json") result = urllib2.urlopen(request,data) def randomString() : return ''.join(random.choice('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz') for i in range(8)) main()
06368e81ea8b2e85b99fba1d001d6509eeec6a2c
cohn-julian/algorithms
/insertionSort.py
372
3.515625
4
#Insertion Sort. Best O(n) (nearly sorted) - worts/avg O(n^2) import random def sort(arr): for i in range(1, len(arr) ): val = arr[i] j = i - 1 while (j >= 0) and (arr[j] > val): arr[j+1] = arr[j] j = j - 1 arr[j+1] = val a = [] for i in range(50): a.append(random.randint(1,100)) print a sort(a) print a
39c9a51126bf6a3a8fe5d69b7ab180d279c647b3
willyii/CS235-New-York-Airbnb
/Util/FillNa.py
1,509
3.671875
4
import pandas as pd class FillNa: def __init__(self): self.fill_value = 0 def fit(self, data: pd.DataFrame, column_name: str, method ="mean" ): """ Fill the missing value, default use mean to fill :param data: Dataset with missing value. Dataframe format :param column_name: The name of column. String format :param method: filling method, default "mean", also has [mean, median, mode, max, min] or specific value :return the dataframe column with filled value """ filling_name = ["mean", "median", "mode", "max", "min"] if method in filling_name: if method == "mean": self.fill_value = data[column_name].mean() elif method == "median": self.fill_value = data[column_name].median() elif method == "mode": self.fill_value = data[column_name].mode() elif method == "max": self.fill_value = data[column_name].max() elif method == "min": self.fill_value = data[column_name].min() else: self.fill_value = method def transform(self, data: pd.DataFrame, column_name: str): return data[[column_name]].fillna(self.fill_value).to_numpy() if __name__ == '__main__': test = pd.read_csv("AB_NYC_2019.csv") print(test.columns) test_encoder = FillNa() test["reviews_per_month"] = test_encoder.fill(test, "reviews_per_month") print(test)
dcc1cb77098649757c8bc62c5820b002cde8a3b0
Celia-xy/AIPathPlaning
/A_star.py
11,435
4.25
4
# The A* algorithm is for shortest path from start to goal in a grid maze # The algorithm has many different choices: # choose large or small g when f values are equal; forward or backward; adaptive or not from GridWorlds import create_maze_dfs, set_state, get_grid_size, draw_grid from classes import Heap, State import Tkinter # ------------------------------ initialization ------------------------------ # # create original grid of state of size (col, row) def create_state(col=100, row=100): # create grid state_grid = [[State() for i in range(col)] for i in range(row)] # change values in state for i in range(col): for j in range(row): # correct position state_grid[j][i].position = (i, j) # correct movement # if the first column, remove left if i == 0: state_grid[j][i].actions[0] = 0 # if the first row, remove up if j == 0: state_grid[j][i].actions[2] = 0 # if the last column, remove right if i == col-1: state_grid[j][i].actions[1] = 0 # if the last row, remove down if j == col-1: state_grid[j][i].actions[3] = 0 return state_grid # ------------------------------- start A* ------------------------------------ # # global movement [[0, 0, up, down], [left, right, 0, 0]] move = [[0, 0, -1, 1], [-1, 1, 0, 0]] # action is int from 0 to 3, represents left, right, up, down; position is (c, r); state is the state grid def get_succ(states, position, action): # movement [[0, 0, up, down], [left, right, 0, 0]] global move (c, r) = position if states[r][c].action_exist(action): # get next position r_new = r + move[0][action] c_new = c + move[1][action] succ = states[r_new][c_new] return succ # if action is available, cost is 1, otherwise cost is 0 def cost(state, position, action): # movement [[0, 0, up, down], [left, right, 0, 0]] global move (c, r) = position # if the action is available if state[r][c].action_exist(action): cost = 1 else: cost = 1000 # --------------------------------------------- # # search for a new path when original one blocked def compute_path(states, goal, open_list, close_list, counter, expanded, large_g, adaptive): global move (cg, rg) = goal while states[rg][cg].g > open_list.heap[-1][1].f: # open_list is binary heap while each item contains two value: f, state # remove the smallest f value item from open_list heap last_item = open_list.pop() # add the state with smallest f value into close_list close_list.append(last_item[1]) (c, r) = last_item[1].position for i in range(4): if states[r][c].action_exist(i): # get the successor of last item when action is i pos = (c, r) successor = get_succ(states, pos, i) # the position of successor r_succ = r + move[0][i] c_succ = c + move[1][i] try: close_list.index((c_succ, r_succ)) except ValueError: if successor.search < counter: # the successor state in state_grid states[r_succ][c_succ].g = 10000 states[r_succ][c_succ].renew_hf(goal) states[r_succ][c_succ].search = counter if successor.g > states[r][c].g + states[r][c].cost(i): states[r_succ][c_succ].g = states[r][c].g + states[r][c].cost(i) states[r_succ][c_succ].renew_hf(goal) states[r_succ][c_succ].tree = states[r][c] succ_state = states[r_succ][c_succ] # choose favor of large g or small g when f is equal if large_g == "large": succ_favor = states[r_succ][c_succ].f * 10000 - states[r_succ][c_succ].g else: succ_favor = states[r_succ][c_succ].f * 10000 + states[r_succ][c_succ].g i = 0 while i < len(open_list.heap) and len(open_list.heap) > 0: # if successor is in open list if succ_state.position == open_list.heap[i][1].position: # renew the g value in the corresponding open list item and renew heap open_list.remove(i) i += 1 # insert the successor into open list open_list.insert([succ_favor, succ_state]) expanded += 1 else: continue if len(open_list.heap) == 0: break return states, open_list, close_list, expanded # --------------------------------------- A* search ---------------------------------------- # # (path, exist) = A_star_forward(start, goal, maze_grid, large_g="large", forward="forward", adaptive="adaptive" # # input: start, goal: the coordinates (x, y) of start and goal # maze_grid: a grid maze created by create_maze_dfs() function in GridWorlds # large_g: "large" to choose large g when f are same, otherwise choose small g # forward: "forward" to choose forward A*, otherwise choose backward A* # adaptive: "adaptive" to choose adaptive A*, otherwise choose A* # # output: path: array of coordinates (x, y) of path nodes from start to goal # exist: boolean, "True" if path exists, "False" otherwise def A_star_forward(start, goal, maze_grid, large_g="large", adaptive="adaptive"): # initial state grid states = create_state(len(maze_grid), len(maze_grid[0])) # decide if goal is reached reach_goal = False counter = 0 expanded = 0 current = start (cg, rg) = goal path = [] path2 = [] # the current position while reach_goal == False: counter += 1 (cs, rs) = current states[rs][cs].g = 0 states[rs][cs].renew_hf(goal) states[rs][cs].search = counter states[rg][cg].g = 10000 states[rg][cg].renew_hf(goal) states[rg][cg].search = counter # open_list is binary heap while each item contains two value: f, state open_list = Heap() # close_list only store state close_list = [] open_state = states[rs][cs] # choose favor of large g or small g when f is equal if large_g == "large": open_favor = states[rs][cs].f * 1000 - states[rs][cs].g else: open_favor = states[rs][cs].f * 1000 + states[rs][cs].g # insert s_start into open list open_list.insert([open_favor, open_state]) # compute path (states, open_list, close_list, expanded) = compute_path(states, goal, open_list, close_list, counter, expanded, large_g, adaptive) if len(open_list.heap) == 0: print "I cannot reach the target." break # get the path from goal to start by tree-pointer (cc, rc) = goal path = [(cc, rc)] while (cc, rc) != (cs, rs): (cc, rc) = states[rc][cc].tree.position path.append((cc, rc)) # follow the path (c_0, r_0) = path[-1] while states[r_0][c_0].position != (cg, rg): # (c, r) = successor.position (c, r) = path.pop() try: index = path2.index((c, r)) except ValueError: path2.append((c, r)) else: for i in range(index+1, len(path2)): path2.pop() try: index = path2.index((c, r)) except ValueError: path2.append((c, r)) else: for i in range(index+1, len(path2)): path2.pop() if len(path2) > 4: (c1, r1) = path2[-4] (c2, r2) = path2[-1] if abs(c1-c2) + abs(r1-r2) == 1: path2.pop(-3) path2.pop(-2) # if blocked, stop and renew cost of all successors if maze_grid[r][c] == 1: states[r][c].g = 10000 states[r][c].renew_hf(goal) # set action cost if c - c_0 == 0: # cannot move down if r - r_0 == 1: states[r_0][c_0].actions[3] = 0 # cannot move up else: states[r_0][c_0].actions[2] = 0 else: # cannot move right if c - c_0 == 1: states[r_0][c_0].actions[1] = 0 # cannot move left else: states[r_0][c_0].actions[0] = 0 break (c_0, r_0) = (c, r) # set start to current position current = (c_0, r_0) if states[r_0][c_0].position == (cg, rg): reach_goal = True # if path from start to goal exists if reach_goal: # (cc, rc) = start # path = [] # # while (cc, rc) != (cs, rs): # # path.append((cc, rc)) # (cc, rc) = states[rc][cc].tree.position # # while len(path2) > 0: # path.append(path2.pop()) print "I reached the target" print path2 return path2, reach_goal, expanded # draw the path from start to goal def draw_path(maze_grid, path): # get size (col, row) = get_grid_size(maze_grid) screen = Tkinter.Tk() canvas = Tkinter.Canvas(screen, width=(col+2)*5, height=(row+2)*5) canvas.pack() # create initial grid world for c in range(1, col+2): canvas.create_line(c*5, 5, c*5, (row+1)*5, width=1) for r in range(1, row+2): canvas.create_line(5, r*5, (col+1)*5, r*5+1, width=1) # mark blocked grid as black, start state as red, goal as green for c in range(0, col): for r in range(0, row): # if blocked if maze_grid[r][c] == 1: canvas.create_rectangle((c+1)*5+1, (r+1)*5+1, (c+2)*5, (r+2)*5, fill="black") # if the path if (c, r) in path: # mark path as blue canvas.create_rectangle((c+1)*5+1, (r+1)*5+1, (c+2)*5, (r+2)*5, fill="blue") # if start if maze_grid[r][c] == "A": canvas.create_rectangle((c+1)*5+1, (r+1)*5+1, (c+2)*5, (r+2)*5, fill="red") # if goal if maze_grid[r][c] == "T": canvas.create_rectangle((c+1)*5+1, (r+1)*5+1, (c+2)*5, (r+2)*5, fill="green") screen.mainloop() # test my_maze = create_maze_dfs(101, 101) (start, goal, my_maze) = set_state(my_maze) draw_grid(my_maze) # get path by A* search (PATH, reach_goal, expanded) = A_star_forward(start, goal, my_maze, "large", "forward") # if path exist, draw maze and path if reach_goal: draw_path(my_maze, PATH) print expanded else: print "Path doesn't exist"
1cab18caa6822e5a164a198ec77b243086b6a840
phoenix1796/algorithms-practice
/mergeSort.py
783
4.03125
4
def merge(l1,l2): ind1 = ind2 = 0 list = [] while ind1<len(l1) and ind2<len(l2): if l1[ind1]<l2[ind2]: list.append(l1[ind1]) ind1+=1 else: list.append(l2[ind2]) ind2+=1 while ind1<len(l1): list.append(l1[ind1]) ind1+=1 while ind2<len(l2): list.append(l2[ind2]) ind2+=1 # print(list) # lists when bubbling up return list def mergeSort(list): # print(list) # lists when dividing if len(list) <= 1: return list pivot = int((len(list))/2) l1=mergeSort(list[:pivot]) l2=mergeSort(list[pivot:]) return merge(l1,l2) test_list = [21,4,1,3,9,20,25] print(mergeSort(test_list)) # test_list = [0,1,2,3,4] # print(mergeSort(test_list))
1874acb1d4c7dc6c1d0e3e90df8f303698e6bb20
ssong319/Dicts-word-count
/wordcount.py
924
3.765625
4
# put your code here. import sys def count_words(filename): the_file = open(filename) word_counts = {} for line in the_file: #line = line.rstrip('?') list_per_line = line.rstrip().lower().split(" ") # out = [c for c in list_per_line if c not in ('!','.',':', '?')] # print out for word in list_per_line: word = word.rstrip('?') word = word.rstrip('!') word = word.rstrip('.') word = word.rstrip(',') word_counts[word] = word_counts.get(word, 0) + 1 the_file.close() word_counts = word_counts.items() count = 0 for tpl in word_counts: word_counts[count] = list(tpl) word_counts[count].reverse() count += 1 word_counts.sort() word_counts.reverse() for count, word in word_counts: print "{}: {}".format(word, count) count_words(sys.argv[1])
8e668075fd8ddc7f0209e8fcb24689eb2c3af0da
Noahprog/DataProcessing
/Homework/Week_3/convertCSV2JSON.py
557
3.578125
4
# Noah van Grinsven # 10501916 # week 3 # convert csv to json format import csv import json # specific values def csv2json(filename): csvfilename = filename jsonfilename = csvfilename.split('.')[0] + '.json' delimiter = "," # open and read csv file with open(filename, 'r') as csvfile: reader = csv.DictReader(csvfile, delimiter = delimiter) data = list(reader) # open and write to json with open(jsonfilename, 'w') as jsonfile: json.dump(data, jsonfile) # convert csv file csv2json('MaandregenDeBilt2015.csv')
bc21452d6fe5e22f5580c172737d2cecea07dee5
DimaLevchenko/intro_python
/homework_5/task_7.py
739
4.15625
4
# Написать функцию `is_date`, принимающую 3 аргумента — день, месяц и год. # Вернуть `True`, если дата корректная (надо учитывать число месяца. Например 30.02 - дата не корректная, # так же 31.06 или 32.07 и т.д.), и `False` иначе. # (можно использовать модуль calendar или datetime) from datetime import datetime d = int(input('Enter day: ')) m = int(input('Enter month: ')) y = int(input('Enter year: ')) def is_date(a, b, c): try: datetime(day=a, month=b, year=c) return True except ValueError: return False print(is_date(d, m, y))
09a6e8d8e627becba4124c4fe37bbcc94020da82
DimaLevchenko/intro_python
/homework_5/task_4.py
763
3.875
4
# Дан список случайных целых чисел. Замените все нечетные числа списка нулями. И выведете их количество. import random def randomspis(): list = [] c = 0 while c < 10: i = random.randint(0, 100) list.append(i) c += 1 print('Список случайных чисел: ', list) return list spis = randomspis() def newspis(lis): lis2 = [] c = 0 for i in lis: if i % 2 != 0: lis2.append(0) c += 1 else: lis2.append(i) return lis2, c spis2 = newspis(spis) print('Новый список: ', spis2[0]) print('Количество нечетных чисел: ', spis2[1])
0e68170f1d26748450f78365d974c7d052f67d52
DimaLevchenko/intro_python
/homework_15/task_3.py
1,288
4.0625
4
# Вводимый пользователем пароль должен соответсвовать требованиям, # 1. Как минимум 1 символ от a-z # 2. Как минимум 1 символ от A-Z # 3. Как минимум 1 символ от 0-9 # 4. Как минимум 1 символ из $#@-+= # 5. Минимальная длина пароля 8 символов. # Программа принимает на ввод строку, в случае если пароль не верный - # пишет какому требованию не соответствует и спрашивает снова, # в случае если верный - пишет 'Password is correct'. import re password = input('Enter your password - ') def check(pw): if not re.search(r'[a-z]', pw): return 'At least 1 symbol from a-z is required' if not re.search(r'[A-Z]', pw): return 'At least 1 symbol from A-Z is required' if not re.search(r'\d', pw): return 'At least 1 symbol from 0-9 is required' if not re.search(r'[$#@+=\-]', pw): return 'At least 1 symbol of $#@-+= is required' if len(pw) < 8: return 'At least 8 symbol is required' return 'Password is correct' print(check(password))
46c58187e7ad3f322958c60ba51f4332cb0eaea9
DimaLevchenko/intro_python
/homework_4/task_4.py
353
4.03125
4
# По данному натуральному `n ≤ 9` выведите лесенку из `n` ступенек, # `i`-я ступенька состоит из чисел от 1 до `i` без пробелов. n = int(input('Введите число: ')) for i in range(1, n+1): for x in range(1, i+1): print(x, end='') print()
50b6fdeb9324f95234d1d15d3345e728f0c2d5d5
goldiekapur/algorithm-snacks
/leetcode_python/22.Generate_Parentheses.py
1,683
3.546875
4
# https://leetcode.com/problems/generate-parentheses/ # 回溯. 逐个字符添加, 生成每一种组合. # 一个状态需要记录的有: 当前字符串本身, 左括号数量, 右括号数量. # 递归过程中解决: # 如果当前右括号数量等于括号对数 n, 那么当前字符串即是一种组合, 放入解中. # 如果当前左括号数量等于括号对数 n, 那么当前字符串后续填充满右括号, 即是一种组合. # 如果当前左括号数量未超过 n: # 如果左括号多于右括号, 那么此时可以添加一个左括号或右括号, 递归进入下一层 # 如果左括号不多于右括号, 那么此时只能添加一个左括号, 递归进入下一层 class Solution: def generateParenthesis(self, n: int): if n == 0: return '' res = [] self.helper(n, n, '', res) return res def helper(self, l, r, string, res): if l > r: return if l == 0 and r == 0: res.append(string) if l > 0: self.helper(l - 1, r, string + '(', res) if r > 0: self.helper(l, r - 1, string + ')', res) # https://www.youtube.com/watch?v=PCb1Ca_j6OU class Solution: def generateParenthesis(self, n: int) -> List[str]: res = [] if n == 0: return res self.helper(n, 0, 0, res, '') return res def helper(self, k, left, right, res, temp): if right == k: res.append(temp) return if left < k: self.helper(k, left + 1, right, res, temp + '(') if right < left: self.helper(k, left, right + 1, res, temp + ')')
5e39352eeb9519b9b17408456592cd4fc585473f
goldiekapur/algorithm-snacks
/leetcode_python/528.RandomPick_with_Weight.py
792
3.65625
4
#!/usr/bin/env python3 # coding: utf-8 # Time complexity: O() # Space complexity: O() # https://leetcode.com/problems/random-pick-with-weight/ class Solution: # 1 8 9 3 6 # 1 9 18 21 27 # 20 def __init__(self, w: List[int]): for i in range(1, len(w)): w[i] += w[i - 1] self.s = w[-1] self.w = w def pickIndex(self) -> int: seed = random.randint(1, self.s) l = 0 r = len(self.w) - 1 while l < r: # 注意边界 mid = (l + r) // 2 if self.w[mid] < seed: l = mid + 1 # 注意边界 else: r = mid return l # Your Solution object will be instantiated and called as such: # obj = Solution(w) # param_1 = obj.pickIndex()
1d7e96d1abce1a5f23c20b18890761cabd363df0
goldiekapur/algorithm-snacks
/leetcode_python/480.Sliding_Window_Median.py
743
3.625
4
#!/usr/bin/env python3 # coding: utf-8 # https://leetcode.com/problems/sliding-window-median/ import bisect class Solution: def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]: heap = nums[:k] heap.sort() mid = k // 2 if k % 2 == 0: res = [(heap[mid] + heap[mid - 1]) / 2] else: res = [heap[mid]] for i, n in enumerate(nums[k:]): # print(heap) idx = bisect.bisect(heap, nums[i]) # print(idx) heap[idx - 1] = n heap.sort() if k % 2 == 0: res.append((heap[mid] + heap[mid - 1]) / 2) else: res.append(heap[mid]) return res
1e03ddfbc1e14e81606b805b55234686b2ccadd1
goldiekapur/algorithm-snacks
/leetcode_python/417.Pacific_Atlantic_Water_Flow.py
3,364
3.765625
4
#!/usr/bin/env python3 # coding: utf-8 # https://leetcode.com/problems/pacific-atlantic-water-flow/ # 这道题的意思是说让找到所有点既可以走到左面,上面(pacific)又可以走到右面,下面(atlantic) # dfs的思路就是,逆向思维,找到从左边,上面(就是第一列&第一排,已经是pacific的点)出发,能到的地方都记录下来. # 同时右面,下面(就是最后一列,最后一排,已经是Atlantic的点)出发,能到的地方记录下来。 # 综合两个visited矩阵,两个True,证明反过来这个点可以到两个海洋。 # Time complexity: O(MN) # Space complexity: O(MN) class Solution: def pacificAtlantic(self, matrix: List[List[int]]) -> List[List[int]]: if not matrix: return [] m = len(matrix) n = len(matrix[0]) pacific_m = [[False for _ in range(n)] for _ in range(m)] atlantic_m = [[False for _ in range(n)] for _ in range(m)] for i in range(m): # 从第一列(pacific)到对面atlantic self.dfs(matrix, i, 0, pacific_m) # 从最后一列(atlantic)到对面pacific self.dfs(matrix, i, n - 1, atlantic_m) for i in range(n): # 从第一行(pacific)到最后一行atlantic self.dfs(matrix, 0, i, pacific_m) # 从最后一行(atlantic)到第一行pacific self.dfs(matrix, m - 1, i, atlantic_m) res = [] for i in range(m): for j in range(n): if pacific_m[i][j] and atlantic_m[i][j]: res.append([i, j]) return res def dfs(self, matrix, x, y, visited): visited[x][y] = True # 存放一个四个方位的var方便计算左右上下 for i, j in [(0, -1), (0, 1), (-1, 0), (1, 0)]: nx, ny = x + i, y + j if 0 <= nx < len(matrix) and 0 <= ny < len(matrix[0]) and not visited[nx][ny] and matrix[nx][ny] >= \ matrix[x][y]: self.dfs(matrix, nx, ny, visited) # 第二种方法是bfs,使用一个queue去记录可以到达的点,最后同样是合并来给你个能到达的列表的重合返回。 class Solution2: def pacificAtlantic(self, matrix: List[List[int]]) -> List[List[int]]: if not matrix: return [] # 存放一个四个方位的var方便计算左右上下 self.direction = [(0, -1), (0, 1), (-1, 0), (1, 0)] m = len(matrix) n = len(matrix[0]) pacific_set = set([(i, 0) for i in range(m)] + [(0, j) for j in range(n)]) atlantic_set = set([(m - 1, i) for i in range(n)] + [(j, n - 1) for j in range(m)]) def bfs(reachable_point): queue = collections.deque(reachable_point) while queue: x, y = queue.popleft() for i, j in [(0, -1), (0, 1), (-1, 0), (1, 0)]: nx, ny = x + i, y + j if 0 <= nx < len(matrix) and 0 <= ny < len(matrix[0]) and (nx, ny) not in reachable_point and \ matrix[nx][ny] >= matrix[x][y]: reachable_point.add((nx, ny)) queue.append((nx, ny)) return reachable_point return list(bfs(pacific_set) & bfs(atlantic_set))
b9bd0caf3cb168ad51c9f36ab8390890ad50d9d4
goldiekapur/algorithm-snacks
/leetcode_python/410.Split_Array_Largest_Sum.py
940
3.625
4
#!/usr/bin/env python3 # coding: utf-8 # Time complexity: O() # Space complexity: O() class Solution: def splitArray(self, nums: List[int], m: int) -> int: def valid(mid): count = 1 total = 0 for num in nums: total += num if total > mid: total = num count += 1 if count > m: return False return True low = max(nums) high = sum(nums) while low <= high: mid = (low + high) // 2 if valid(mid): high = mid - 1 else: low = mid + 1 return low # https://leetcode.com/problems/split-array-largest-sum/discuss/141497/AC-Java-DFS-%2B-memorization # dp 做法 # https://leetcode.com/problems/split-array-largest-sum/discuss/89821/Python-solution-dp-and-binary-search
74cb46e1099bbcd6f6c8a5c2be93829e6207fa14
vnikhila/PythonClass
/operators.py
606
4.0625
4
a = int(input('Enter value for a\n')) b = int(input('Enter value for b\n')) print('\n') print('Arithmetic Operators') print('Sum: ',a+b) print('Diff: ',a-b) print('Prod: ',a*b) print('Quot: ',b/a) print('Remnder: ',b%a) print('Floor Divisn: ',b//a) print('Exponent: ',a**b) print('\n') print('Relational Operators') print('a == b:', a == b) print('a != b:', a != b) print('a >= b:', a >= b) print('a <= b:', a <= b) print('a > b:', a > b) print('a < b:', a < b) print('\n') print('Logical Operators') print('a or b:', a or b) print('a and b:', a and b) print('\n') print('Assignment Operators') print()
3d773a08b8a163465cc06cfccb597a47e809a17d
vnikhila/PythonClass
/listexamples.py
1,797
4.1875
4
# --------Basic Addition of two matrices------- a = [[1,2],[3,4]] b = [[5,6],[7,8]] c= [[0,0],[0,0]] for i in range(len(a)): for j in range(len(a[0])): c[i][j] = a[i][j]+b[i][j] print(c) # -------Taking values of nested lists from user-------- n = int(input('Enter no of row and column: ')) a = [[0 for i in range(n)] for j in range(n)] #to create a nested list of desired size b = [[0 for i in range(n)] for j in range(n)] c = [[0 for i in range(n)] for j in range(n)] print('Enter the elements: ') for i in range(n): for j in range(n): a[i][j] = int(input('Enter val for list a: ')) b[i][j] = int(input('Enter val for list b: ')) for i in range(n): for j in range(n): c[i][j] = a[i][j] + b[i][j] print('List a: ',a) print('List b: ',b) print('a + b:',c) # -------Values from user method2 (Using While loop)-------- n = int(input('Enter no of rows and col: ')) a,b,rowa,rowb = [],[],[],[] c = [[0 for i in range(n)] for j in range(n)] j = 0 print('Enter values for a') while(j < n): for i in range(n): rowa.append(int(input('Enter value for a: '))) rowb.append(int(input('Enter value for b: '))) a.append(rowa) b.append(rowb) rowa,rowb = [],[] j += 1 for i in range(n): for j in range(n): c[i][j] = a[i][j] + b[i][j] print('a: ',a) print('b: ',b) print('a + b: ',c) # -------Matrix Multiplication---------- n = int(input('Enter no of rows and col: ')) a,b,rowa,rowb = [],[],[],[] c = [[0 for i in range(n)] for j in range(n)] j = 0 print('Enter values for a') while(j < n): for i in range(n): rowa.append(int(input('Enter value for a: '))) rowb.append(int(input('Enter value for b: '))) a.append(rowa) b.append(rowb) rowa,rowb = [],[] j += 1 for i in range(n): for j in range(n): c[i][j] = a[i][j] * b[j][i] print('a: ',a) print('b: ',b) print('a * b: ',c)
9a0ceda7765af0638ec2a3c31f2665b7b7d7075a
vnikhila/PythonClass
/conditional.py
207
4.34375
4
#if else ODD EVEN EXAMPLE a = int(input('Enter a number\n')) if a%2==0: print('Even') else: print('Odd') # if elif else example if a>0: print('Positive') elif a<0: print('Negative') else: print('Zero')
fe7c10f251dc3f5c806709a006ed1e853fffe240
tarah-tamayo/aoc-2020
/day20/20a.py
11,881
3.5
4
import sys import re from copy import deepcopy class monster: monster = None def __init__(self): self.monster = [] lines = [" # ", "# ## ## ###", " # # # # # # "] for line in lines: print(line) m = ['1' if x == "#" else '0' for x in line] self.monster.append(int('0b' + ''.join(m), 2)) def find_monsters(self, t) -> int: c = 0 #for i in range(len(t.grid)-len(self.monster)): for i in range(1, len(t.grid)-1): for j in range(len(t.grid[i]) - 20): key = int('0b' + ''.join(t.bingrid[i][j:j+20]), 2) if (key & self.monster[1]) == self.monster[1]: print(f"OwO? [{i}][{j}]") print(''.join(t.grid[i-1][j:j+20])) print(''.join(t.grid[i][j:j+20])) print(''.join(t.grid[i+1][j:j+20])) print() key = int('0b' + ''.join(t.bingrid[i+1][j:j+20]), 2) if (key & self.monster[2]) == self.monster[2]: print(f"OwO? What's this? [{ i }][{ j }]") c += 1 else: print(f"no wo :'( ") #grid = [] #for k in range(len(self.monster)): # g = [True if x == '#' else False for x in t.grid[i+k][j:j+20]] # grid.append(g) #grid.append(int('0b'+''.join(g), 2)) #grid[k] = grid[k] & self.monster[k] #if self.check_grid(grid): # print("OwO!") # c += 1 #if grid == self.monster: # c += 1 return c def check_grid(self, grid: list) -> bool: for i in range(len(grid)): for j in range(len(grid[i])): grid[i][j] = grid[i][j] and self.monster[i][j] return grid == self.monster class tile: tid = 0 grid = None bingrid = None edges = None neighbors = None def __init__(self, lines, img=False): """ tile(lines, img) - Constructor. Boolean img defaults to False. If True this is a tile holding a full, stitched image. Edge detection is not required. """ self.grid = [] self.bingrid = [] self.edges = [] self.neighbors = [] self.parse(lines) if not img: self.find_edges() def parse(self, lines): for line in lines: match = re.match(r"Tile ([0-9]+):", line) if match: self.tid = int(match.groups()[0]) else: self.grid.append([x for x in line]) def create_bingrid(self): self.bingrid = [] for i in range(len(self.grid)): binstr = ['1' if x == '#' else '0' for x in self.grid[i]] self.bingrid.append(binstr) def find_edges(self): """ find_edges() - Finds the edges of the tile grid convention is that top and bottom edges are --> and left and right edges are top-down In order, edges are defined as: [0] - TOP [1] - RIGHT [2] - BOTTOM [3] - LEFT """ self.edges = [deepcopy(self.grid[0]), [], deepcopy(self.grid[-1]), []] for g in self.grid: self.edges[3].append(g[0]) self.edges[1].append(g[-1]) self.edges[2] self.edges[3] def lr_flip(self): """ lr_flip() - Flips grid Left / Right """ for g in self.grid: g.reverse() def td_flip(self): """ td_flip() - Flips grid Top / Down """ self.cw_rotate() self.cw_rotate() self.lr_flip() self.find_edges() def cw_rotate(self): """ cw_rotate() - Rotates grid clockwise 90 deg """ self.grid = [list(x) for x in zip(*self.grid[::-1])] self.find_edges() def orient(self, t2, left=False): """ orient(t2, left) - reorients this tile to match t2. Left defaults to False and, if true, indicates that t2 is to the left of this tile. Otherwise it assumes t2 is above this tile. """ # In order, edges are defined as: # [0] - TOP # [1] - RIGHT # [2] - BOTTOM # [3] - LEFT edge_i = self.get_edge(t2) if left: edge_t = 3 target = 1 else: edge_t = 2 target = 0 while edge_i != edge_t: self.cw_rotate() edge_i = self.get_edge(t2) if list(reversed(self.edges[edge_t])) == t2.edges[target]: if left: self.td_flip() else: self.lr_flip() def get_edge(self, t2) -> int: """ get_edge(t2) -> int - Returns the edge index of this tile that matches t2. If there is no common edge returns -1. """ for i in range(len(self.edges)): e = self.edges[i] for e2 in t2.edges: if e == e2: if t2 not in self.neighbors: self.neighbors.append(t2) if self not in t2.neighbors: t2.neighbors.append(self) return i if list(reversed(e)) == e2: if t2 not in self.neighbors: self.neighbors.append(t2) if self not in t2.neighbors: t2.neighbors.append(self) return i return -1 def compare(self, t2) -> bool: """ compare(t2) - Finds whether a common edge with tile t2 is present """ return True if self.get_edge(t2) >= 0 else False def find_common_neighbors(self, t2) -> list: """ find_common_neighbors(t) - Returns a list of common neighbors """ neighs = [] for n in self.neighbors: if n in t2.neighbors: neighs.append(n) return neighs def remove_edges(self): self.grid = self.grid[1:-1] for g in self.grid: g = g[1:-1] def __len__(self): self.create_bingrid() c = 0 for bg in self.bingrid: g = [1 if x == '1' else 0 for x in bg] c += sum(g) return c def __str__(self): s = f"\n ----- Tile { self.tid } -----" for g in self.grid: s += "\n" + ''.join(g) return s class image: # Dict of tiles by id tiles = None # 2d grid of tile IDs and rotations grid = None # Found corners corners = None # image stitched together image = None def __init__(self, lines): """ image() - Constructor Takes ALL tile lines and parses them to make a dictionary of tiles """ self.tiles = {} self.parse(lines) self.find_neighbors() self.find_corners() self.build_grid_top() self.build_grid_left() self.fill_grid() self.stitch_image() def parse(self, lines): tile_lines = [] for line in lines: if 'Tile' in line: if len(tile_lines): t = tile(tile_lines) self.tiles[t.tid] = t tile_lines = [line] elif len(line): tile_lines.append(line) t = tile(tile_lines) self.tiles[t.tid] = t def find_neighbors(self): for i in range(len(self.tiles.keys())): t1 = self.tiles[list(self.tiles.keys())[i]] for j in range(0, len(self.tiles.keys())): t2 = self.tiles[list(self.tiles.keys())[j]] if t1 != t2: t1.compare(t2) def find_corners(self): self.corners = [] for tile in self.tiles.values(): if len(tile.neighbors) == 2: self.corners.append(tile) s = "" for t in self.corners: s += f" { t.tid }" print(s) def build_grid_top(self): c = self.corners[0] t = c.neighbors[0] # orient to right side neighbor as top c.orient(t) # rotate clockwise to change top to right side c.cw_rotate() self.grid = [[c, t]] n = len(t.neighbors) while n == 3: for nbr in t.neighbors: if len(nbr.neighbors) == 3 and nbr not in self.grid[0]: t = nbr elif len(nbr.neighbors) == 2 and nbr not in self.grid[0]: t = nbr self.grid[0].append(t) n = len(t.neighbors) def build_grid_left(self): c = self.corners[0] t = c.neighbors[1] left = [c, t] n = len(t.neighbors) while n == 3: for nbr in t.neighbors: if len(nbr.neighbors) == 3 and nbr not in left: t = nbr elif len(nbr.neighbors) == 2 and nbr not in left: t = nbr left.append(t) n = len(t.neighbors) for i in range(1, len(left)): self.grid.append([None for _ in range(len(self.grid[0]))]) self.grid[i][0] = left[i] def fill_grid(self): for i in range(1,len(self.grid[0])): self.grid[0][i].orient(self.grid[0][i-1], left=True) for i in range(1,len(self.grid)): for j in range(1,len(self.grid[i])): neighs = self.grid[i][j-1].find_common_neighbors(self.grid[i-1][j]) for n in neighs: if n not in self.grid[i-1]: self.grid[i][j] = n self.grid[i][j].orient(self.grid[i-1][j]) for t in self.tiles.values(): t.remove_edges() def print_grid_ids(self): for g in self.grid: s = "" for t in g: if t is None: s += " None -" else: s += f" { t.tid } -" print(s) def stitch_image(self): # Create an empty tile object for the full image tile_lines = ["Tile 1:"] self.image = tile(tile_lines, img=True) line = 0 for g in self.grid: self.image.grid.extend([[] for _ in range(len(g[0].grid))]) for t in g: for i in range(len(t.grid)): self.image.grid[line+i].extend(t.grid[i]) line += len(g[0].grid) self.image.create_bingrid() if __name__ == '__main__': if len(sys.argv) > 1: file = sys.argv[1] else: file = 'day20/day20.in' with open(file) as f: lines = f.read().splitlines() img = image(lines) mult = 1 for t in img.corners: mult *= t.tid print(f"Day 20 Part 1: { mult }") m = monster() c = m.find_monsters(img.image) i = 0 while c == 0 and i < 4: print("...rotating...") img.image.cw_rotate() img.image.create_bingrid() i += 1 if c == 0: print("...flipping...") img.image.lr_flip img.image.create_bingrid() c = m.find_monsters(img.image) i = 0 while c == 0 and i < 4: print("...rotating...") img.image.cw_rotate() i += 1 print(img.image) print(c) print(f"Day 20 Part 2: { len(img.image) }") #lines = ['Tile 99:', '#...#', '.#...', '..#..', '...#.', '....#'] #t = tile(lines) #print(t) #t.td_flip() #print(t)
b5418dbfb626ef9a83a73a5de00da17e8e3822b5
Kristjamar/Verklegt-namskei-
/Breki/Add_to_dict.py
233
4.1875
4
x = {} def add_to_dict(x): key = input("Key: ") value = input("Value: ") if key in x: print("Error. Key already exists.") return x else: x[key] = value return x add_to_dict(x) print(x)
2f6070d909963b329e87f5a220c3c9b65c4e9a24
diksha-zodape/Miniproject
/generatePassword.py
361
3.640625
4
import random import string def generatePassword(stringLength=10): password_characters = string.ascii_letters + string.digits + string.punctuation return ''.join(random.choice(password_characters) for i in range(stringLength)) print("Random String password is generating...\n", generatePassword()) print ("\nPassword generated successfully!")
6c3ef65cf9d656edcec4dc65982a7fcc8c1527fb
codewithpom/Factor-finder
/main.py
171
3.90625
4
factors = [] i = 0 number = int(input("Enter the number")) while i <= number: i = i+1 if number % i == 0: factors.append(i) print(factors)
130f575d861172289c27e110441b5719a1adda61
kwax21/secu
/petite.py
983
3.671875
4
def premier(a): if a == 1: return False for i in range(a - 1, 1, -1): if a % i == 0: return False return True def findEverythingForTheWin(a): p = 2 q = 2 while 1 == 1: if premier(p) and (n % p == 0): q = int(n/p) print("P : ", p) print("Q : ",q) break else: p += 1 phiN = (p-1) * (q-1) print("phiN : ", phiN) if p < q: d = q else: d = p while 1 == 1: if((e * d % phiN == 1)): print("d : ", d) break d = d + 1 print("\nCle privee : (",d,",",phiN,")") print("\nDecryptage du message") ligne = pow(this,d)%n print("Fin : ", ligne) a = "o" e = int(input("entrez e : ")) n = int(input("entrez n : ")) while a == "o": print("\n") this = int(input("entrez le message a decrypter : ")) findEverythingForTheWin(n) a = input("\nEncore ? o/n : ")
2cbf2c0fc7ba8e74f40c1bcf6c1e9fbaf50af798
Talalkanjo01/GlobalAIHubPythonCourse
/Homeworks/HW2.py
528
4.03125
4
#Explain your work first i took value from user then i used for loop to check numbers between 0 and number user has entered if are odd or even then i printed to screen #Question 1 n = int(input("Entre single digit integer: ")) for number in range(1, int(n+1)): if (number%2==0): print(number) #Question 2 my_list = [1, 2 , 3 , 4, 5, 6, 7, 8, 9, 10] my_list[0:round(len(my_list)/2)] , my_list[round(len(my_list)/2):len(my_list)] = my_list[round(len(my_list)/2):len(my_list)] , my_list[0:round(len(my_list)/2)] print(my_list)
b7da43bd8f29aab4f61c7a9d4e6e918ce606eef0
gachiemchiep/source_code
/courses/problem_solving_with_algorithm_and_data_structures_using_python/4.5.stack.py
2,590
3.90625
4
class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items)-1] def size(self): return len(self.items) # Write a function revstring(mystr) that uses a stack to reverse the characters in a string. def revstring(mystr:str) -> str: s = Stack() # put into stack for char in mystr: s.push(char) # pop again to form a reverse string new_string = "" while not s.isEmpty(): new_string+= s.pop() return new_string # Simple Balanced Parentheses : def parChecker(symbolString:str) -> bool: s = Stack() is_balanced = True index = 0 while (index < len(symbolString)) and is_balanced: char = symbolString[index] if char == "(": s.push(char) elif char == ")": if s.isEmpty(): is_balanced = False else: s.pop() index += 1 return is_balanced # Simple Balanced Parentheses : [{()}] def parChecker2(symbolString): s = Stack() balanced = True index = 0 while index < len(symbolString) and balanced: symbol = symbolString[index] if symbol in "([{": s.push(symbol) else: if s.isEmpty(): balanced = False else: top = s.pop() if not matches(top,symbol): balanced = False index = index + 1 if balanced and s.isEmpty(): return True else: return False def matches(open,close): opens = "([{" closers = ")]}" return opens.index(open) == closers.index(close) # Converting Decimal Numbers to Binary Numbers def baseConverter(decNumber, base=2): digits = "0123456789ABCDEF" remstack = Stack() while decNumber > 0: rem = decNumber % base remstack.push(rem) decNumber = decNumber // base binString = "" while not remstack.isEmpty(): binString = binString + digits[remstack.pop()] return binString if __name__ == '__main__': s=Stack() print(s.isEmpty()) s.push(4) s.push('dog') print(s.peek()) s.push(True) print(s.size()) print(s.isEmpty()) s.push(8.4) print(s.pop()) print(s.pop()) print(s.size()) print(parChecker('((()))')) print(parChecker('(()')) print(baseConverter(256, 16))
a1a96cb2f60c516e63b861e96479ae5c9937f857
ritopa08/30-Days-Coding-Challenge
/day_26.py
556
4.0625
4
#-----Day 25: Running Time and Complexity-------# import math def isprime(data): x=int(math.ceil(math.sqrt(data))) if data==1: return "Not prime" elif data==2: return"Prime" else: for i in range(2,x+1): if data%i==0: return "Not prime" #break else: return "Prime" return "-1" s=int(input()) while s: d=int(input()) v=isprime(d) print(v)
95d846c051abad8b7a718db79dd33c5f5e308923
sabian2008/speciation_patterns
/analyze_interactive.py
3,852
3.765625
4
import numpy as np import pickle import matplotlib.pyplot as plt from matplotlib.widgets import Slider def gen_dist(genes): """Computes the genetic distance between individuals. Inputs: - genes: NxB matrix with the genome of each individual. Output: - out: NxN symmetric matrix with (out_ij) the genetic distance from individual N_i to individual N_j. """ # First generate an NxNxB matrix that has False where # i and j individuals have the same kth gene and True # otherwise (XOR operation). Then sum along # the genome axis to get distance return np.sum(genes[:,None,:] ^ genes, axis=-1) def classify(genes, G): """Classifies a series of individuals in isolated groups, using transitive genetic distance as the metric. If individual 1 is related to invidual 2, and 2 with 3, then 1 is related to 3 (independently of their genetic distance). Based on: https://stackoverflow.com/questions/41332988 and https://stackoverflow.com/questions/53886120 Inputs: - genes: NxB matrix with the genome of each individual. - G: Integer denoting the maximum genetic distance. Output: - out: list of lists. The parent lists contains as many elements as species. The child lists contains the indices of the individuals corresponding to that species. """ import networkx as nx # Calculate distance gendist = gen_dist(genes) N = gendist.shape[0] # Make the distance with comparison "upper triangular" by # setting lower diagonal of matrix extremely large gendist[np.arange(N)[:,None] >= np.arange(N)] = 999999 # Get a list of pairs of indices (i,j) satisfying distance(i,j) < G indices = np.where(gendist <= G) indices = list(zip(indices[0], indices[1])) # Now is the tricky part. I want to combine all the (i,j) indices # that share at least either i or j. This non-trivial problem can be # modeled as a graph problem (stackoverflow link). The solution is G = nx.Graph() G.add_edges_from(indices) return list(nx.connected_components(G)) # Load simulation S = 5 G = 20 target = "S{}-G{}.npz".format(S,G) data = np.load(target, allow_pickle=True) genes, pos, params = data['genes'], data['pos'], data['params'][()] G = params['G'] # Max. genetic distance tsave = params["tsave"] # Saves cadency # Load classification. If missing, perform it try: with open("S{}-G{}.class".format(S,G), 'rb') as fp: species = pickle.load(fp) except: print("Classification not found. Classyfing...") species = [] for t in range(0, genes.shape[0]): print("{} of {}".format(t, genes.shape[0]), end="\r") species.append(classify(genes[t], G)) with open("S{}-G{}.class".format(S,G), 'wb') as fp: pickle.dump(species, fp) # Create figure, axes and slider fig, ax = plt.subplots(1,1) axtime = plt.axes([0.25, 0.01, 0.5, 0.03], facecolor="lightblue") stime = Slider(axtime, 'Generation', 0, len(species), valfmt='%0.0f', valinit=0) fig.tight_layout(rect=[0, 0.03, 1, 0.95]) # Initial condition for s in species[0]: ax.scatter(pos[0,list(s),0], pos[0,list(s),1], s=5) # Function to update plots def update(val): i = int(round(val)) # Update plots ax.clear() for s in species[i]: ax.scatter(pos[i,list(s),0], pos[i,list(s),1], s=5) stime.valtext.set_text(tsave*i) # Update label # Draw fig.canvas.draw_idle() # Link them stime.on_changed(update) # Function to change slider using arrows def arrow_key_control(event): curr = stime.val if event.key == 'left': stime.set_val(curr-1) if event.key == 'right': stime.set_val(curr+1) fig.canvas.mpl_connect('key_release_event', arrow_key_control) plt.show()
935a2a6d789116d14739fc3572f1c283b0ea020d
akshatfulfagar12345/EDUYEAR-PYTHON-20
/day 3.py
176
3.8125
4
int=a,b,c b = int(input('enter the year for which you want to calculate')) print(b) c = int(input('enter your birth year')) a = int((b-c)) print('your current age is',a)
58a8258c74f852fb7d0e44c79827ea23cd25bbbd
akshatfulfagar12345/EDUYEAR-PYTHON-20
/day 6( Remove duplicate elements ).py
266
3.609375
4
data = [10,20,30,30,40,50,50,60,60,70,40,80,90] def remove_duplicates(duplist): noduplist = [] for element in duplist: if element not in noduplist: noduplist.append(element) return noduplist print(remove_duplicates(data))
32caa7eb3f40feade5b973c7b3f3c0b1b5650ca1
Jordan71214/PythonPractice
/0425/pyPrac0425_02.py
263
3.890625
4
a = range(10) print(a) for i in a: print(i) name = (1, 2, 3, 5, 4, 6) for i in range(len(name)): print('第%s個資料是:%s' % (i, name[i])) for i in range(1, 10, 2): print(i) b = list(range(10)) print(b) print(type(b)) c = [1, 2] print(type(c))
3141cca11b98778e6a419ec614939839ef906b3e
Jordan71214/PythonPractice
/0419/hello.py
372
3.5
4
import math r = 15 print('半徑 %.0f 的圓面積= %.4f' % (r, r * r * math.pi)) print('半徑15的圓面積=', math.ceil(15 * 15 * math.pi)) print('半徑15的圓面積=', math.floor(15 * 15 * math.pi)) #math.ceil() -> 向上取整 換言之 >= 的最小整數 print(math.ceil(10.5)) #math.floor() -> 向下取整 換言之 <= 的最大整數 print(math.floor(10.5))
a181420a345cd7cb8a9d8ec6cc8a9fbd5624492c
RoncoGit/Uniquindio
/CondicionalesAnidadas.py
1,434
4.03125
4
print("================") print("Conversor") print("================ \n") print("Menú de opciones: \n") print("Presiona 1 para convertir de número a palabra.") print("Presiona 2 para convertir de palabra a número. \n") conversor = int(input("¿Cuál es tu opción deseada?:")) if conversor == 1: print("Conversor de Número a palabras. \n") num = int(input("¿Cual es el número que deseas convertir?:")) if num == 1: print("el número es 'uno'") elif num == 2: print("el número es 'dos'") elif num == 3: print("el número es 'tres'") elif num == 4: print("el número es 'cuatro'") elif num == 5: print("el número es 'cinco'") else: print("el número máximo de conversion es 5.") elif conversor == 2: print("Conversor de palabras a números. \n") tex = input("¿Cual es la palabra que deseas convertir?:") tex = tex.lower() if tex == "uno" : print("el número es '1'") elif tex == "dos" : print("el número es '2'") elif tex == "tres" : print("el número es '3'") elif tex == "cuatro" : print("el número es '4'") elif tex == "cinco" : print("el número es '5'") else: print("el número máximo de conversion es cinco.") else: print("Respuesta no válida. Intentalo de nuevo.") print("Fin.")
bdc16e91fac7d1045b84f248b0fbb929e44bff0e
RoncoGit/Uniquindio
/CondicionalesMultiples.py
571
4.1875
4
print("===================================") print("¡¡Convertidor de números a letras!!") print("===================================") num = int(input("Cuál es el número que deseas convertit?:")) if num == 4 : print("El número es 'Cuatro'") elif num == 1 : print("El número es 'Cinco'") elif num == 2 : print("El número es 'Cinco'") elif num == 3 : print("El número es 'Cinco'") elif num == 5 : print("El número es 'Cinco'") else: print("Este programa solo puede convertir hasta el número 5") print("Fin.")
0d2653d959843341a061b39ae6150472d43297dd
PWalis/Graphs
/projects/ancestor/ancestor.py
1,915
3.90625
4
from graph import Graph from util import Queue def bfs(graph, starting_vertex): """ Return a list containing the longest path from starting_vertex """ earliest_an = None # Create an empty queue and enqueue A PATH TO the starting vertex ID q = Queue() initial_path = [starting_vertex] q.enqueue(initial_path) # Create a Set to store visited vertices visited = set() # While the queue is not empty... while q.size() > 0: # Dequeue the first PATH path = q.dequeue() # save the length of the path path_length = len(path) # Grab the last vertex from the PATH last_vert = path[-1] # If that vertex has not been visited... if last_vert not in visited: # Mark it as visited... visited.add(last_vert) # Then add A PATH TO its neighbors to the back of the for v in graph.vertices[last_vert]: # COPY THE PATH path_copy = path[:] # APPEND THE NEIGHOR TO THE BACK path_copy.append(v) q.enqueue(path_copy) # If the new path is longer than previous path # Save the longer path as earliest_ancestor if len(path_copy) > path_length: earliest_an = path_copy if earliest_an: return earliest_an[-1] return -1 def earliest_ancestor(ancestors, starting_node): graph = Graph() for a in ancestors: # Add all vertices to graph graph.add_vertex(a[0]) graph.add_vertex(a[1]) for a in ancestors: # Create child to parent relationship graph.add_edge(a[1], a[0]) return bfs(graph, starting_node) test_ancestors = [(1, 3), (2, 3), (3, 6), (5, 6), (5, 7), (4, 5), (4, 8), (8, 9), (11, 8), (10, 1)] print(earliest_ancestor(test_ancestors, 1))
68683ee483f4bf0d25de8e9c6d8ae3d89c057be3
syamms/Deep-Learning-Projects
/Deep Learning A-Z/Volume 1 - Supervised Deep Learning/Part 3 - Recurrent Neural Networks (RNN)/Recurrent_Neural_Networks/rnn_pratice.py
2,416
4
4
# -*- coding: utf-8 -*- """ 08:08:21 2017 @author: SHRADDHA """ #Recurrent Neural Network #PART 1 DATA PREPROCESSING #importing libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd #importing training set training_set = pd.read_csv('Google_Stock_Price_Train.csv') training_set = training_set.iloc[:,1:2].values #Feature Scaling #Normalization used here where only min and max values are needed #Once known min and max they are transformed #Not Standardization from sklearn.preprocessing import MinMaxScaler sc = MinMaxScaler() training_set = sc.fit_transform(training_set) #Getting Input and Output #In RNNs, here we take the input as the current price of Stocks today #Using the current, we predict the next day's value #That is the what happens, and hence we divide the ds into two parts X_train = training_set[0:1257] y_train = training_set[1:1258] #Reshaping #It's used by RNN X_train = np.reshape(X_train,(1257,1,1)) #PART 2 BUILDING THE RNNs #Importing the libraries from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM #Initializing the RNNs regressor = Sequential() #Adding the LSTM Layer and input layer regressor.add(LSTM(units = 4, activation = 'sigmoid', input_shape = (None,1))) regressor.add(Dense(units = 1)) #Compile the Regressor, compile method used regressor.compile(optimizer = 'adam', loss = 'mean_squared_error') #Fitting the training set regressor.fit(X_train, y_train, batch_size = 32, epochs = 200) #PART 3 PREDICTING AND VISUALIZING THE TEST SET #Importing the test_Set test_set= pd.read_csv('Google_Stock_Price_Test.csv') real_stock_price = test_set.iloc[:,1:2].values #Getting the predicted Stock Prices of 2017 inputs = real_stock_price inputs = sc.transform(inputs) inputs = np.reshape(inputs, (20,1,1)) predicted_stock_price = regressor.predict(inputs) predicted_stock_price = sc.inverse_transform(predicted_stock_price) #Visualizing the Stock Prices plt.plot(real_stock_price, color = 'red', label = 'Real Stock Price') plt.plot(predicted_stock_price , color = 'blue', label = 'Predicted Stock Price') plt.title('Google Stock Price Predictions') plt.xlabel('Time') plt.ylabel('Google Stock Price') plt.legend() plt.show() #PART 4 EVALUATING THE RNN import math from sklearn.metrics import mean_squared_error rmse = math.sqrt(mean_squared_error(real_stock_price, predicted_stock_price))
d199f3982f11b3c74a62f2ae3184acf486f990db
arren1234/Turtle-Race-Ultimate
/turtle race ultimate.py
2,403
3.75
4
import turtle #adds turtle functions import random #adds random functions t3 = turtle.Turtle() t1 = turtle.Turtle() t4 = turtle.Turtle() #adds turtles 3,1,4,6,7 t6 = turtle.Turtle() t7 = turtle.Turtle() wn = turtle.Screen() #adds screen t1.shape("turtle") t1.color("green") #colors and shapes bg and t1 wn.bgcolor("tan") t2 = turtle.Turtle() t2.shape("turtle")#adds shapes and colors turtle 2 t2.color("blue") t4.shape("turtle")#shapes and colors turtle 4 t4.color("yellow") t4.up() t1.up()#raises pen of turtle 1,2,6 and 4 t2.up() t6.up() t5 = turtle.Turtle() #adds shapes colors and lifts pen of turtle 5 t5.color("purple") t5.shape("turtle") t5.up() t6.color("black")#colors and shapes turtle 6 t6.shape("turtle") t7.color("orange")#colors shape a lifts pen of turtle 7 t7.shape("turtle") t7.up() t8 = turtle.Turtle() t8.color("grey")#adds colors shape a lifts pen of turtle 8 t8.shape("arrow") t8.up() t9 = turtle.Turtle() t9.shape("turtle")#adds colors shape a lifts pen of turtle 9 t9.color("pink") t9.up() t3.pensize(15) t3.color("red") t3.up() t3.goto(350,-500)#makes finish line using turtle 3 t3.lt(90) t3.down() t3.fd(1100) t1.goto(-350,20) t2.goto(-350,-20) t4.goto(-350,-60) t5.goto(-350, 60)#puts racers in starting position t6.goto(-350, 100) t7.goto(-350,-100) t8.goto(-1400,140) t9.goto(-350,-140) t1.speed(1) t2.speed(1) t4.speed(1)#sets racer speed t5.speed(1) t6.speed(1) t7.speed(1) t8.speed(1) t9.speed(1) for size in range(1000):#functions as endless loop t1.fd(random.randrange(30,70)) #t1 is a green turtle with the very consistent movement t2.fd(random.randrange(-20,120)) #t2 is a blue turtle with a slightly higher max but lower min t4.fd(random.randrange(10,90))#t4 is a a yellow turtle with a very slightly lower max and higher min t5.fd(random.randrange(0,100))#t5 is a purple turtle with standard stats t6.fd(random.randrange(-100,200))#t6 is a black turtle with a very high max and low min t7.rt(random.randrange(0,360))#t7 is an orange turtle with high max and normal low but random turns t7.fd(random.randrange(200,300)) t8.fd(150)#t8 is a grey space ship with a non random movement of a high 150 but starts much farther back t9.fd(random.randrange(-1000,1000))#t9 is a pink turtle with the most random movement with a max of 1000 and min of -1000
683d036de36a774b4c26ff328c0ab1c6aa722bbb
houjf/PycharmProjects
/进阶/字典.py
664
3.828125
4
# class Student(object): # def __init__(self, name, score): # self.__name = name # self.__score = score # # def print_score(self): # print('%s, %s'%(self.__name, self.__score)) # # def get_grade(self): # if self.__score > 90: # return print('A') # elif 90 > self.__score > 80: # return print('B') # elif 80 > self.__score > 60: # return print('C') # else: # print('C') # # student = Student('hello', 60) # student.print_score() # student.get_grade() # print(student.__name) # n = student.__score # print(n) add = lambda x,y:x*y b=add(2,6) print(b)
956d9f7797c6c5294ea475fc30cf8fec65ef0c3c
Vitoria0/Notepad
/Observações-07.py
440
3.921875
4
#Tratamento de Erros e Exceções try: #-------tente a = int(input('Numerador: ')) b = int(input('Dennominador: ')) r = a / b except ZeroDivisionError: print('Não se pode dividir por zero') except Exception as erro: print(f'O erro encontrado foi {erro.__cause__}') else: #------Se não der erro: print(f'O resultado é {r:.1f}') finally: #-------Finaliza com: print('Volte sempre!')
df86c8f38f511f08aa08938abba0c79875727eb9
green-fox-academy/hanzs_solo
/Foundation/week_02-week_04/PythonBasicsProject/week_02/expressions_and_control_flow/conditionals/odd_even.py
234
4.46875
4
# Write a program that reads a number from the standard input, # then prints "Odd" if the number is odd, or "Even" if it is even. number = int(input("enter an integer: ")) if number % 2 == 0: print("Even") else: print("Odd")
39147e634f16988b71a0aee7d825d8e93def5359
green-fox-academy/hanzs_solo
/Foundation/week_02-week_04/PythonBasicsProject/week_02/expressions_and_control_flow/user_input/average_of_input.py
316
4.34375
4
# Write a program that asks for 5 integers in a row, # then it should print the sum and the average of these numbers like: # # Sum: 22, Average: 4.4 sum = 0 number_of_numbers = 5 for x in range(number_of_numbers): sum += int(input("enter an integer: ")) print("sum:", sum, "average:", sum / number_of_numbers)
a314a1eef3981612f213986b9d261adaf2ff85ce
green-fox-academy/hanzs_solo
/Foundation/week_02-week_04/PythonBasicsProject/week_02/arrays/reverse_list.py
327
4.46875
4
# - Create a variable named `numbers` # with the following content: `[3, 4, 5, 6, 7]` # - Reverse the order of the elements of `numbers` # - Print the elements of the reversed `numbers` numbers = [3, 4, 5, 6, 7] temp = [] for i in range(len(numbers)): temp.append(numbers[len(numbers)-i-1]) numbers = temp print(numbers)
31170eab6926b9a475fe8fb1b7258571d762b96e
green-fox-academy/hanzs_solo
/Foundation/week_02-week_04/PythonBasicsProject/week_02/data_structures/list_introduction_1.py
1,247
4.78125
5
# # List introduction 1 # # We are going to play with lists. Feel free to use the built-in methods where # possible. # # - Create an empty list which will contain names (strings) # - Print out the number of elements in the list # - Add William to the list # - Print out whether the list is empty or not # - Add John to the list # - Add Amanda to the list # - Print out the number of elements in the list # - Print out the 3rd element # - Iterate through the list and print out each name # ```text # William # John # Amanda # ``` # - Iterate through the list and print # ```text # 1. William # 2. John # 3. Amanda # ``` # - Remove the 2nd element # - Iterate through the list in a reversed order and print out each name # ```text # Amanda # William # ``` # - Remove all elements names = [] print(len(names)) print() names.append("William") print(len(names)) print() print(len(names) == 0) print() names.append("John") names.append("Amanda") print(len(names)) print() print(names[2]) print() for name in names: print(name) print() for i in range(len(names)): print(i + 1, ".", names[i]) print() names.remove(names[1]) i = len(names) - 1 while i >= 0: print(names[i]) i -= 1 print() names[:] = []
e5da5de6c4ab02f17214140dfff12d23b5d9d4ba
green-fox-academy/hanzs_solo
/Foundation/week_02-week_04/PythonBasicsProject/week_03/oop/blog_post/blog_post.py
1,713
3.890625
4
# # BlogPost # # - Create a `BlogPost` class that has # - an `authorName` # - a `title` # - a `text` # - a `publicationDate` class BlogPost: def __init__(self, author_name, title, text, publication_date): self.author_name = author_name self.title = title self.text = text self.publication_date = publication_date # - Create a few blog post objects: # - "Lorem Ipsum" titled by John Doe posted at "2000.05.04." # - Lorem ipsum dolor sit amet. post1_text = "Lorem ipsum dolor sit amet." post1 = BlogPost("John Doe", "Lorem Ipsum", post1_text, "2000.05.04.") # - "Wait but why" titled by Tim Urban posted at "2010.10.10." # - A popular long-form, stick-figure-illustrated blog about almost # everything. post2_text = "A popular long-form, stick-figure-illustrated blog about almost everything." post2 = BlogPost("Tim Urban", "Wait but why", post2_text, "2010.10.10.") # - "One Engineer Is Trying to Get IBM to Reckon With Trump" titled by William # Turton at "2017.03.28." # - Daniel Hanley, a cybersecurity engineer at IBM, doesn’t want to be the # center of attention. When I asked to take his picture outside one of IBM’s # New York City offices, he told me that he wasn’t really into the whole # organizer profile thing. post3_text = "Daniel Hanley, a cybersecurity engineer at IBM, doesn’t want to be the center of attention. When I " \ "asked to take his picture outside one of IBM’sNew York City offices, he told me that he wasn’t really " \ "into the wholeorganizer profile thing. " post3 = BlogPost("William Turton", "One Engineer Is Trying to Get IBM to Reckon With Trump", post3_text, "2017.03.28.")
e10add30914bc94d9ce15807c45746ad49175d5b
green-fox-academy/hanzs_solo
/Foundation/week_02-week_04/PythonBasicsProject/week_03/oop/pokemon/pokemon.py
1,164
4
4
class Pokemon(object): def __init__(self, name, type, effective_against): self.name = name self.type = type self.effectiveAgainst = effective_against def is_effective_against(self, another_pokemon): return self.effectiveAgainst == another_pokemon.type def initialize_pokemons(): pokemon = [] pokemon.append(Pokemon("Bulbasaur", "grass", "water")) pokemon.append(Pokemon("Pikachu", "electric", "water")) pokemon.append(Pokemon("Charizard", "fire", "grass")) pokemon.append(Pokemon("Pidgeot", "flying", "fighting")) pokemon.append(Pokemon("Kingler", "water", "fire")) return pokemon pokemons = initialize_pokemons() # Every pokemon has a name and a type. # Certain types are effective against others, e.g. water is effective against fire. def choose(pokemon_list, opponent): for pokemon in pokemon_list: if pokemon.is_effective_against(opponent): return pokemon.name # Ash has a few pokemon. # A wild pokemon appeared! wild_pokemon = Pokemon("Oddish", "grass", "water") # Which pokemon should Ash use? print("I choose you, " + choose(pokemons, wild_pokemon))
238f272124f13645a7e58e8de1aaee8d9a433967
green-fox-academy/hanzs_solo
/Foundation/week_02-week_04/PythonBasicsProject/week_02/expressions_and_control_flow/loops/count_from_to.py
634
4.28125
4
# Create a program that asks for two numbers # If the second number is not bigger than the first one it should print: # "The second number should be bigger" # # If it is bigger it should count from the first number to the second by one # # example: # # first number: 3, second number: 6, should print: # # 3 # 4 # 5 a = -999 b = -1999 while a > b: if a != -999: print("\nthe second number should be bigger") a = int(input("gimme a number to count from: ")) b = int(input("gimme a number to count to: ")) while a < b: print(a) a += 1 # for x in range(b): # if x < a: # continue # print(x)
ca2c31265c491c989bdd6b34fb2e66f05614750f
ec36339/evescripts
/evepraisal.py
2,223
4.03125
4
""" Convert JSON output from https://evepraisal.com/ into CSV data that can be pasted into Excel. The script arranges the output in the same order as the input list of items, so the price data can be easily combined with existing data already in the spreadsheet (such as average prices, market volume, etc.) It requires two input files: - items.txt: List of items (one item name per line) - prices.json: JSON output from https://evepraisal.com/ Usage: 1. Copy the item list from your spreadsheet (usually a column containing item names) 2. Paste the item list into items.txt 3. Paste the item list into https://evepraisal.com/ 4. Export the data from https://evepraisal.com/ as JSON and paste it into prices.json 5. Run this script 6. Paste the output into your spreadsheet. Note: If you misspelled an item name, then its buy and sell price will be listed as zero. """ import json def make_price(price): """ Convert an ISK price (float) to a format acceptable by Excel :param price: Float ISK price :return: ISK price as Excel string """ return ('%s' % price).replace('.', ',') def print_csv(name, buy, sell): """ Print a row for an Excel sheet :param name: Name of item :param buy: Float buy order ISK price :param sell: Float sell order ISK price :return: ISK price as tab-separated Excel row """ print("%s\t%s\t%s" % (name, make_price(buy), make_price(sell))) def main(): # Load list of items (copy column from Excel sheet) with open('items.txt') as f: items = [l.split('\n')[0] for l in f.readlines()] # Load price data (export JSON from evepraisal.com after pasting same item list) with open('prices.json') as f: j = json.load(f) # Arrange prices in lookup table by item name item_db = {i['name']: i['prices'] for i in j['items']} # Print item data as Excel row with items in same order as original item list. for i in items: found = item_db.get(i) if found is not None: print_csv(i, found['buy']['max'], found['sell']['min']) else: print_csv(i, 0, 0) if __name__ == '__main__': main()
eacc98d8a0ccf38be757c6693c93ebdaf33848c1
carrillobenjamin/Carrillo_B_Dataviz
/data/medalprogress.py
484
3.5
4
import matplotlib.pyplot as plt years = [1924, 1928, 1932, 1936, 1948, 1952, 1956, 1960, 1964, 1968, 1972, 1976, 1980, 1984, 1988, 1992, 1994, 1998, 2002, 2006, 2010, 2014] medals = [9, 12, 20, 13, 20, 17, 20, 21, 7, 20, 1, 3, 2, 4, 6, 37, 40, 49, 75, 68, 91, 90] plt.plot(years, medals, color=(255/255, 100/255, 100/255), linewidth=5.0) plt.ylabel("Medals Won") plt.xlabel("Competition Year") plt.title("Canada's Medal Progression 1924-2014", pad=20) # show the chart plt.show()
598836e5e5920d1ba4c73c4e4b9e143690a0af95
Lord-Chronos/DoorBellBotPlus
/tictactoe.py
970
3.953125
4
def game(player1, player2): turn = 1 game_over = False start_board = ('```' ' 1 | 2 | 3 \n' ' - + - + - \n' ' 4 | 5 | 6 \n' ' - + - + - \n' ' 7 | 8 | 9 ' '```') while not game_over: current_board = '' if turn == 1: current_board = start_board print_game(current_board, turn) if turn % 2 == 0: print('hello player2') else: print('hello player1') board_update(current_board, next_move) print(board) def print_game(current_board, turn): print('Turn: ' + turn + '\n\n' + current_board) def board_update(current_board, next_move): new_board = '' return new_board def print_board(): return ('``` | | \n' ' - + - + - \n' ' | | \n' ' - + - + - \n' ' | | \n```')
99dc9f1f0571c4511567a1d5e6bd83d2e7ab2a96
Vitor-Aguiar/TheTools
/Wordlist-Gen.py
1,436
3.796875
4
import os import sys # -t @,%^ # Specifies a pattern, eg: @@god@@@@ where the only the @'s, ,'s, # %'s, and ^'s will change. # @ will insert lower case characters # , will insert upper case characters # % will insert numbers # ^ will insert symbols if len(sys.argv) != 3: print "Usage: python gen.py word wordlist.txt" sys.exit() word = sys.argv[1] wordlist = sys.argv[2] masks = [word+"^%" , word+"^%%" , word+"^%%%" , word+"^%%%%" , #word+"^%%%%%" , word+"^%%%%%%" , word+"%^" , word+"%%^" , word+"%%%^" , word+"%%%%^" , #word+"%%%%%^" , word+"%%%%%%^" , "^%"+word , "^%%"+word , "^%%%"+word , "^%%%%"+word , #"^%%%%%"+word , "^%%%%%%"+word , "%^"+word , "%%^"+word , "%%%^"+word , "%%%%^"+word , #"%%%%%^"+word , "%%%%%%^"+word "^"+word , word+"^" , "^"+word+"%" , "^"+word+"%%" , "^"+word+"%%%" , "^"+word+"%%%%" , # "^"+word+"%%%%%" , "%"+word+"^" , "%%"+word+"^" , "%%%"+word+"^" , "%%%%"+word+"^" , # "%%%%%"+word+"^" , word , word+"%" , word+"%%" , word+"%%%" , word+"%%%%" , "%"+word , "%%"+word , "%%%"+word , "%%%%"+word ] for n,mask in enumerate(masks): tamanho = str(len(mask)) comando = "crunch "+tamanho+" "+tamanho+" -t "+mask+" -o "+str(n)+wordlist+".txt" print "Comando: ",comando os.system(comando) os.system('cat *'+wordlist+'.txt >> '+wordlist+'_wordlist.txt') os.system('rm *'+wordlist+'.txt')
27a458c5355a32cf2bc9eb53cef586a8120e9e36
hr4official/python-basic
/td.py
840
4.53125
5
# nested list #my_list = ["mouse", [8, 4, 6], ['a']] #print(my_list[1]) # empty list my_list1 = [] # list of integers my_list2 = [1, 2, 3] # list with mixed datatypes my_list3 = [1, "Hello", 3.4] #slice lists my_list = ['p','r','o','g','r','a','m','i','z'] # elements 3rd to 5th print(my_list[2:5]) # elements beginning to 4th print(my_list[:-5]) # elements 6th to end print(my_list[5:]) # elements beginning to end print(my_list[:]) #We can add one item to a list using append() method or add several items using extend() method. #Here is an example to make a list with each item being increasing power of 2. pow2 = [2 ** x for x in range(10)] # Output: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512] print(pow2) #This code is equivalent to pow2 = [] for x in range(10): pow2.append(2 ** x)
38277e97e74594103b4eb709affdbfb99d3c3457
hr4official/python-basic
/dict.py
544
4.09375
4
# empty dictionary my_dict = {} # dictionary with integer keys my_dict = {1: 'apple', 2: 'ball'} # dictionary with mixed keys my_dict = {'name': 'John', 1: [2, 4, 3]} # using dict() my_dict = dict({1:'apple', 2:'ball'}) # from sequence having each item as a pair my_dict = dict([(1,'apple'), (2,'ball')]) """ marks = {}.fromkeys(['Math','English','Science'], 0) # Output: {'English': 0, 'Math': 0, 'Science': 0} print(marks) for item in marks.items(): print(item) # Output: ['English', 'Math', 'Science'] list(sorted(marks.keys())) """
8971b06f5b722e21f4f48faf778e4ffa758146a4
CircuitLaunch/colab_reachy_ros
/src/head_motor_control.py
4,983
3.6875
4
#!/usr/bin/env python3 # creates a ros node that controls two servo motors # on a arduino running ros serial # this node accepts JointState which is # --------------- # would the datastructure look like # jointStateObj.name = ["neck_yaw", "neck_tilt"] # jointStateObj.position = [180,0] # jointStateObj.velocity# unused # jointStateObj.effort#unused # --------------- # by oran collins # github.com/wisehackermonkey # [email protected] # 20210307 import rospy import math from std_msgs.msg import UInt16 # from sensor_msgs.msg import JointState from trajectory_msgs.msg import JointTrajectory from trajectory_msgs.msg import JointTrajectoryPoint global yaw_servo global tilt_servo global sub global yaw_servo_position global tilt_servo_position # standard delay between moving the joints DELAY = 1.0 # setting up interger variables # the arduino only accepts integers yaw_servo_position = UInt16() tilt_servo_position = UInt16() yaw_min = 0 # in degrees from x to y angles are accepted positions yaw_max = 360 tilt_min = 75 tilt_max = 115 # helper function # keeps the input number between a high and alow def constrain(input: float, low: float, high: float) -> float: """ input: radian float an number to be constrained to a range low<-> high low: radian float minimum value the input can be high: radian float maximum value the input can be """ return max(min(input, high), low) def move_servos(msg: JointTrajectoryPoint) -> None: print(msg) print(msg.positions[0]) print(msg.positions[1]) yaw_degrees = constrain(math.degrees(msg.positions[0]), yaw_min, yaw_max) tilt_degrees = constrain(math.degrees(msg.positions[1]), tilt_min, tilt_max) print("Yaw: ", yaw_degrees, "tilt: ", tilt_degrees) # convert float angle radians -pi/2 to pi/2 to integer degrees 0-180 yaw_servo_position.data = int(yaw_degrees) tilt_servo_position.data = int(tilt_degrees) # send an int angle to move the servo position to 0-180 yaw_servo.publish(yaw_servo_position) tilt_servo.publish(tilt_servo_position) # im only dulpicating this one betcause i cant think in radians and its a identical function to the one above # exept i dont convert to degrees from radians def move_servos_degrees_debug(msg: JointTrajectoryPoint) -> None: print(msg) print(msg.positions[0]) print(msg.positions[1]) yaw_degrees = constrain((msg.positions[0]), yaw_min, yaw_max) tilt_degrees = constrain((msg.positions[1]), tilt_min, tilt_max) print("Yaw: ", yaw_degrees, "tilt: ", tilt_degrees) # convert float angle radians -pi/2 to pi/2 to integer degrees 0-180 yaw_servo_position.data = int(yaw_degrees) tilt_servo_position.data = int(tilt_degrees) # send an int angle to move the servo position to 0-180 yaw_servo.publish(yaw_servo_position) tilt_servo.publish(tilt_servo_position) # runs though all the JointTrajectoryPoint's inside a JointTrajectory # which basically runs though an array of angles for each of the joints in this case # a joint is a servo motor (and a diamixel motor for the antenna) # and waits `DELAY` time before setting the motors to go to the next position def process_positions(msg: JointTrajectory) -> None: print(msg) for joint_point in msg.points: print("Here") move_servos(joint_point) rospy.sleep(DELAY) def process_positions_debug_degrees(msg: JointTrajectory) -> None: print(msg) for joint_point in msg.points: print("Here") move_servos_degrees_debug(joint_point) rospy.sleep(DELAY) if __name__ == "__main__": rospy.init_node("position_animator_node") # setup topics to control into arduino servo angles # publishing a integer between angle 0-180 /servo1 or /servo2 yaw_servo = rospy.Publisher("/head/neck_pan_goal", UInt16, queue_size=1) tilt_servo = rospy.Publisher("/head/neck_tilt_goal", UInt16, queue_size=1) # waiting for a JointState data on the topic "/move_head" # example data # DOCS for joint state # http://wiki.ros.org/joint_state_publisher # Data format # http://docs.ros.org/en/api/sensor_msgs/html/msg/JointState.html # Header headerx # string[] name <- optional # float64[] position # float64[] velocity # float64[] effort # rostopic pub /move_head "/{header:{}, name: ['servo1', 'servo2'], position: [0.5, 0.5], velocity:[], effort:[]}"" sub = rospy.Subscriber("/head/position_animator", JointTrajectory, process_positions) sub = rospy.Subscriber("/head/position_animator_debug_degrees", JointTrajectory, process_positions_debug_degrees) sub = rospy.Subscriber("/head/position_animator/debug_point", JointTrajectoryPoint, move_servos) sub = rospy.Subscriber( "/head/position_animator/debug_point_degrees", JointTrajectoryPoint, move_servos_degrees_debug ) rate = rospy.Rate(10) print("servo_mover: Running") while not rospy.is_shutdown(): rate.sleep()
03ffdbf920e309ebb68d396e033b44d8848a6952
bk2coady/ProjectEuler
/ProjectEulerS1.py
499
4.03125
4
#Problem1 #Find sum of all numbers which are multiples of more than one value (ie 3 and 5) #remember to not double-count numbers that are multiples of both 3 and 5 (ie multiples of 15) def sumofmultiples(value, max_value): total = 0 for i in range(1,max_value): if i % value == 0: #print(i) total = total+i #print(total) return total upto = 1000 cumulative_total = sumofmultiples(3,upto) + sumofmultiples(5,upto) - sumofmultiples(15,upto) print(cumulative_total)
6d09a3651b149aad6a6d4c96626062b969ca88db
bk2coady/ProjectEuler
/ProjectEulerS9.py
444
3.890625
4
#Problem9 #find pythagorean triplet where a + b + c = 1000 def pythag_check(a, b): c = (a*a + b*b) ** 0.5 #print(c) if c == int(c): return True return False def pythag_triplet(k): for i in range(1,k-1): for j in range(1,k-i): if pythag_check(i,j): c = int((i*i + j*j) ** 0.5) if i + j + c == k: return i+j+c, i, j, c, i*j*c return False print(pythag_check(3, 4)) print(pythag_triplet(1_000))
c0355b2269c01bed993270e4472d1771ffab9527
sharikgrg/week3.Python-Theory
/104_data_type_casting.py
316
4.25
4
# casting # casting is when you change an object data type to a specific data type #string to integer my_var = '10' print(type(my_var)) my_casted_var = int(my_var) print(type(my_casted_var)) # Integer/Floats to string my_int_vaar = 14 my_casted_str = str(my_int_vaar) print('my_casted_str:', type(my_casted_str))
cff7d4a762f14e761f3c3c46c2e656f74cb19403
sharikgrg/week3.Python-Theory
/exercises/exercise1.py
745
4.375
4
# Define the following variable # name, last name, age, eye_colour, hair_colour # Prompt user for input and reassign these # Print them back to the user as conversation # Eg: Hello Jack! Welcome, your age is 26, you eyes are green and your hair_colour are grey name = input('What is your name?') last_name = input('What is your surname?') age = int(input('What is your age?')) eye_colour = input('What is the colour of your eye?') hair_colour = input('What is the colour of your hair?') print('Hello',name.capitalize(), f'{last_name.capitalize()}!', 'Welcome, your age is', f'{age},', 'your eyes are', eye_colour, 'and your hair is', hair_colour) print(f'Hello {name} {last_name}, Welcome!, your age is') print('You were born in', 2019 - age)
cda99da103298b6c26c29b9083038a732826be11
sharikgrg/week3.Python-Theory
/102_data_types.py
1,736
4.5
4
# Numerical Data Types # - Int, long, float, complex # These are numerical data types which we can use numerical operators. # Complex and long we don't use as much # complex brings an imaginary type of number # long - are integers of unlimited size # Floats # int - stmads for integers # Whole numbers my_int = 20 print(my_int) print(type(my_int)) # Operator - Add, Subtract, multiply and devide print(4+3) print(4-3) print(4/2) # decimals get automatically converted to float print(4//2) # keeps it as integer/ drops the decimal print(4*2) print(3**2) # square # Modules looks for the number of remainder # % # print(10%3) ## --> 3*3 =9, so 1 is the remainder # Comparison Operators ## --> boolean value # < / > - Bigger and Smaller than # <= - Smaller than or equal # >= Bigger than or equal # != Not equal # is and is not my_variable1 = 10 my_variable2 = 13 # example of using operators print(my_variable1== my_variable2) # output is false print(my_variable1 > my_variable2) print(my_variable1 < my_variable2) print(my_variable1 >= my_variable2) print(my_variable1 != my_variable2) print(my_variable1 is my_variable2) print(my_variable1 is not my_variable2) # Boolean Values # Define by either True or False print(type(True)) print(type(False)) print (0 == False) print(1 == True) ## None print(None) print(type(None)) print(bool(None)) #Logical And & Or a = True b = False print('Logical and & or -------') # Using *and* both sides have to be true for it to result in true print(a and True) print((1==1) and (True)) print((1==1) and False) #Use or only one side needs to be true print('this will print true-----') print(True or False) print(True or 1==2) print('this will print false -----------') print(False or 1==2)
d42b8c1bfab1011862b843d6166ee0bb41f857b8
pranjay04/algorithms-and-data-structures
/search/python/binarysearch_rec.py
393
3.796875
4
def binarysearch_rec(array, key): l = 0 h = len(array) - 1 def search(array, l, h, key): if l > h: return False mid = (l + h)//2 if array[mid] == key: return mid if key < array[mid]: h = mid - 1 else: l = mid + 1 return search(array, l, h, key) return search(array, l, h, key)
f56178664ed321ef7b8ad9a3696f5fe7cf0cee10
clarkmyfancy/Hangman
/Console.py
1,033
3.703125
4
class Console: def printStartupSequence(self): print("Let's play Hangman!") def printScoreboardFor(self, game): word = game.secretWord isLetterRevealed = game.lettersRevealed outputString = "" for x in range(0, len(word)): outputString += word[x] if isLetterRevealed[x] == True else "_" outputString += ' ' print(outputString) print("\n") def printGuessedLettersFor(self, game): for i, x in enumerate(game.guessedLetters): if i == len(game.guessedLetters) - 1: print(x) print() else: print(x + " ", end="") def retrieveGuessFrom(self, player): print(player.name + ", enter guess: ") def printGuessFor(self, player): print(str(player.name) + " guessed: " + player.currentGuess) def printStatusFor(self, player, game): context = "Incorrect guesses left for " print(context + player.name + ": " + str(game.wrongGuessesLeft)) def printGameOverMessageFor(self, player): print("And that's it, \'" + player.name + "\' is out of guesses.") print(player.name + ", Game Over")
a826b8384e312b2ccfdeb01f0d84446870734b5c
knutss/PyWake
/py_wake/deflection_models/deflection_model.py
1,068
3.5
4
from abc import ABC, abstractmethod class DeflectionModel(ABC): args4deflection = ["ct_ilk"] @abstractmethod def calc_deflection(self, dw_ijl, hcw_ijl, dh_ijl, **kwargs): """Calculate deflection This method must be overridden by subclass Arguments required by this method must be added to the class list args4deflection See documentation of EngineeringWindFarmModel for a list of available input arguments Returns ------- dw_ijlk : array_like downwind distance from source wind turbine(i) to destination wind turbine/site (j) for all wind direction (l) and wind speed (k) hcw_ijlk : array_like horizontal crosswind distance from source wind turbine(i) to destination wind turbine/site (j) for all wind direction (l) and wind speed (k) dh_ijlk : array_like vertical distance from source wind turbine(i) to destination wind turbine/site (j) for all wind direction (l) and wind speed (k) """
4173a8b376cb1c007c103999e1f352299bb8f810
TeresaRem/CodingDojo
/Python/selectionSort.py
829
3.84375
4
## selectionSort.py import random, datetime def selectionSort(arr): a = datetime.datetime.now() min = arr[0] start = 0 for i in range(0,len(arr)-1): for j in range(start,len(arr)): if arr[j] < min: min = arr[j] index = j # print "current minimum is {} at index {}".format(min,index) if arr[start] > min: temp = arr[start] arr[start] = arr[index] arr[index] = temp # print "swap {} and {}".format(arr[index],arr[start]) # print "array is:" # print arr start+=1 min = arr[start] b = datetime.datetime.now() time = b - a print "{} seconds".format(time.total_seconds()) return arr # selectionSort([6,5,3,1,8,7,2,4]) def randomArr(): # create random array arr = [] for i in range(1000): arr.append(random.randint(0,10000)) return arr hundred = randomArr() selectionSort(hundred)
54ce45e8ca61bcdbe1df2a33b3abf1250dac665a
TeresaRem/CodingDojo
/Python/animal.py
1,006
3.890625
4
# animal.py class Animal(object): def __init__(self,name): self.name = name self.health = 100 def walk(self): self.health -= 1 return self def run(self): self.health -= 5 return self def displayHealth(self): print "name is {}".format(self.name) print "health is {}".format(self.health) return self animal = Animal('animal').walk().walk().walk().run().run().displayHealth() class Dog(Animal): def __init__(self,name): super(Dog,self).__init__(self) self.health = 150 self.name = name def pet(self): self.health += 5 return self dog = Dog('dog').walk().walk().walk().run().run().pet().displayHealth() class Dragon(Animal): def __init__(self,name): super(Dragon,self).__init__(self) self.health = 170 self.name = name def fly(self): self.health -= 10 return self def displayHealth(self): print "this is a dragon!" super(Dragon,self).displayHealth() return self dragon = Dragon('dragon').walk().walk().walk().run().run().fly().fly().displayHealth()
a0cd809b0d43cbb95f2e80b7459959e23c76d4c2
TeresaRem/CodingDojo
/pylot/restful_routes/app/models/Product.py
1,414
3.703125
4
from system.core.model import Model class Product(Model): def __init__(self): super(Product, self).__init__() """ Below is an example of a model method that queries the database for all users in a fictitious application Every model has access to the "self.db.query_db" method which allows you to interact with the database """ def get_products(self): query = "SELECT * from products" return self.db.query_db(query) def get_product(self, id): query = "SELECT * from products where id = :id" data = {'id': id} return self.db.get_one(query, data) def add_product(self, data): if data['price'].isdecimal(): sql = "INSERT into products (name, description, price) values(:name, :description, :price)" self.db.query_db(sql, data) return True else: return False def update_product(self, data): if data['price'].isdecimal(): query = '''UPDATE products SET name=:name, description=:description, price=:price WHERE id = :id''' self.db.query_db(query, data) return True else: return False def destroy_product(self, id): query = "DELETE FROM products WHERE id = :id" data = {'id' : id} return self.db.query_db(query, data)
e9d15c1e46656bbed8240b591c5c848d6bc13dcf
TeresaRem/CodingDojo
/pylot/login/app/controllers/Users.py
3,002
4.125
4
""" Sample Controller File A Controller should be in charge of responding to a request. Load models to interact with the database and load views to render them to the client. Create a controller using this template """ from system.core.controller import * class Users(Controller): def __init__(self, action): super(Users, self).__init__(action) """ This is an example of loading a model. Every controller has access to the load_model method. """ self.load_model('User') self.db = self._app.db """ This is an example of a controller method that will load a view for the client """ def index(self): """ A loaded model is accessible through the models attribute self.models['WelcomeModel'].get_users() self.models['WelcomeModel'].add_message() # messages = self.models['WelcomeModel'].grab_messages() # user = self.models['WelcomeModel'].get_user() # to pass information on to a view it's the same as it was with Flask # return self.load_view('index.html', messages=messages, user=user) """ return self.load_view('index.html') def success(self): return self.load_view('success.html') def register(self): data = { "first_name" : request.form['first_name'], "last_name" : request.form['last_name'], "email" : request.form['email'], "password" : request.form['password'], "confirm" : request.form['confirm'] } # call create_user method from model and write some logic based on the returned value # notice how we passed the user_info to our model method create_status = self.models['User'].create_user(data) if create_status['status'] == True: # the user should have been created in the model # we can set the newly-created users id and name to session session['id'] = create_status['user']['id'] session['first_name'] = create_status['user']['first_name'] # we can redirect to the users profile page here return redirect('/success') else: # set flashed error messages here from the error messages we returned from the Model for message in create_status['errors']: flash(message, 'regis_errors') # redirect to the method that renders the form return redirect('/') def login(self): data = request.form user = self.models['User'].login_user(data) if not user: flash("Your login information is incorrect. Please try again.") return redirect('/') session['id'] = user['id'] session['first_name'] = user['first_name'] return redirect('/success') def logout(self): session.clear() return redirect('/')
5cba492f9034b07ca9bc7d266dca716ea684ba3c
sdhanendra/coding_practice
/DataStructures/linkedlist/linkedlist_classtest.py
1,647
4.5
4
# This program is to test the LinkedList class from DataStructures.linkedlist.linkedlist_class import LinkedList def main(): ll = LinkedList() # Insert 10 nodes in linked list print('linked list with 10 elements') for i in range(10): ll.insert_node_at_end(i) ll.print_list() # delete three nodes at the end in the linked list print('\ndelete last three elements') for i in range(3): ll.delete_node_at_end() ll.print_list() # insert a node at the Head print('\ninsert a node at head') ll.insert_node_at_head(10) ll.print_list() # delete a node at the Head print('\ndelete a node from head') ll.delete_node_at_head() ll.print_list() # Insert a node 20 after node 2 print('\ninsert a node after a given node') ll.insert_node_after_give_node(20, 2) ll.print_list() # delete the node 20 print('\ndelete a given node') ll.delete_given_node(20) ll.print_list() # search for node 4 in the linked list print('\nsearch for a node in linked list') ll.search_node(4) # sum all elements of the linked list print('\nsum all elements of a linked list') elem_sum = ll.sum_all_elements() print('Sum of the linked list: {}'.format(elem_sum)) # count the number of nodes in the linked list print('\ncount the number of elements of a linked list') num_nodes = ll.count_nodes() print('Total number of nodes in linked list: {}'.format(num_nodes)) # reverse a linked list print('\nreverse a linked list') ll.reverse_list() ll.print_list() if __name__ == '__main__': main()
518b0d4700b932388532ed42c21614a78006015c
jaxmandev/Python_OOP
/python.py
815
4.09375
4
# Creating a python class as child class of our Snake class from snake import Snake class Python(Snake): def __init__(self): super().__init__() self.large = True self.two_lungs = True self.venom = False # creating functions for our python class def digest_large_prey(self): return " Yum Yummyyy...." def clim(self): return "up we go....." def shed_skin(self): return "time to grow up.... fast......myself!" python_object = Python() # creating an object of our python class print(python_object.breathe()) # function from our Animal class print(python_object.hunt()) # function from our Reptile class print(python_object.use_venum())# fucntion from our Snake class print(python_object.shed_skin()) # function from our python class
058dc3932000b0d290652ff758d3d8653ac1c5f5
GIS-PuppetMaster/EVO-TSP
/Selection.py
2,796
3.78125
4
from math import * import random import copy def fitnessProportional(problem, population): """ # because our fitness is the distance of the traveling salesman # so we need to replace 'fitness' with '1/fitness' to make sure the better individual # get greater chance to be selected :param problem: the problem to be solved :param population: the population :return: new population after selection """ sum = 0 new_population = [] for i in population: sum += 1 / fitness(problem, i) for i in population: pro = (1 / fitness(problem, i)) / sum flag = random.uniform(0, 1) if flag <= pro: new_population.append(i) return new_population def fitness(problem, individual): """ calculate fitness :param problem: problem graph :param individuals: an individual :return: fitness """ graph = problem.getGraph() last_city = None dis = 0 for city in individual.solution: if last_city is not None: cor1 = graph[city] cor2 = graph[last_city] dis += sqrt(pow((cor1[0] - cor2[0]), 2) + pow((cor1[1] - cor2[1]), 2)) last_city = city # calculate go back distance cor1 = graph[last_city] cor2 = graph[individual.solution[0]] dis += sqrt(pow((cor1[0] - cor2[0]), 2) + pow((cor1[1] - cor2[1]), 2)) return dis def tournamentSelection(problem, population, unit, number): """ :param problem: the problem to solve :param population: the population for selection ,[Individuals] :param unit: how many individuals to sample at once :param number: how many individuals to return :return: new population """ new_population = [] i = 1 while i < number: samples = random.sample(population, unit) min_fitness = 1e20 best_sample = None for sample in samples: f = fitness(problem, sample) if f < min_fitness: min_fitness = f best_sample = sample if best_sample not in new_population: new_population.append(best_sample) else: # prevent repeat reference new_population.append(copy.deepcopy(best_sample)) i += 1 return new_population def elitismSelection(problem, population): """ return the best fitness individual, which won't mutate and cross :param problem: the problem to solve :param population: the population for selection ,[Individuals] :return: the best fitness individual """ best = None min_fitness = 1e20 for individual in population: f = fitness(problem, individual) if f <= min_fitness: min_fitness = f best = individual return best
804ebb78ded35b6817a5a1a32b15f8bfa7b0605a
tonimk/testi
/myscript.py
814
3.8125
4
# Kommentti esimerkin vuoksi tähän def inputNumber(message): while True: try: userInput = int(input(message)) except ValueError: print("Anna ikä kokonaislukuna, kiitos!") continue else: return userInput break i = 0 while i < 3: nimi = input("Anna nimesi: ") print("Sinä olet " + nimi) ikä = inputNumber("Anna ikäsi: ") print("Ikäsi on:",ikä) kaverikä = inputNumber("Kuinka vanha mielikuvituskaverisi on? ") if ikä > kaverikä: print("Sinä olet vanhempi") elif ikä < kaverikä: print("Kaveri on vanhempi") else: print("Olette yhtä vanhoja") i = i + 1 if i < 3: print("Tämä käydään vielä", 3 - i,"kertaa") else: print("Tämä\nohjelma\non\nnyt\nloppu")
f3532d2e768187aa39d756f763755bdf3ebf4f75
pilot-github/programming
/leetcode/rotateRight.py
1,646
3.984375
4
########################################################### ## Given a linked list, rotate the list to the right by k places, where k is non-negative. ## ## Example 1: ## ## Input: 1->2->3->4->5->NULL, k = 2 ## Output: 4->5->1->2->3->NULL ## Explanation: ## rotate 1 steps to the right: 5->1->2->3->4->NULL ## rotate 2 steps to the right: 4->5->1->2->3->NULL ## ########################################################### def my_rotateRight(self, head: ListNode, k: int) -> ListNode: if head is None or head.next is None or k == 0: return head length = 1 curr_node = head while curr_node.next: curr_node = curr_node.next length += 1 curr_node.next = head k = k%length for i in range(length-k): curr_node = curr_node.next head = curr_node.next curr_node.next = None return head def rotateRight(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ if not head: return None if head.next == None: return head pointer = head length = 1 while pointer.next: pointer = pointer.next length += 1 rotateTimes = k%length if k == 0 or rotateTimes == 0: return head fastPointer = head slowPointer = head for a in range (rotateTimes): fastPointer = fastPointer.next while fastPointer.next: slowPointer = slowPointer.next fastPointer = fastPointer.next temp = slowPointer.next slowPointer.next = None fastPointer.next = head head = temp return head
d80e7ee5b9580fc2ac5978eef24763447b87f820
pilot-github/programming
/Sorting Algorithms/insertion_sort.py
299
3.890625
4
def insertion_sort(num): for i in range(1, len(num)): next = num[i] j = i-1 while num[j] > next and j>=0: num[j+1] = num[j] j = j-1 num[j+1] = next return num num = [19,2,31,45,6,11,121,27] print (insertion_sort(num))
82a55c0b7128beec9f63e1ffe47b1ce9ba78e26a
PabloMtzA/cse-30872-fa20-assignments
/challenge18/program.py
1,198
3.875
4
#!/usr/bin/env python3 ## Challenge 18 ## Pablo Martinez-Abrego Gonzalez ## Template from Lecture 19-A import collections import sys # Graph Structure Graph = collections.namedtuple('Graph', 'edges degrees') # Read Graph def read_graph(): edges = collections.defaultdict(set) degrees = collections.defaultdict(int) for line in sys.stdin: l = [char for char in line.rstrip()] for t, s in enumerate(l): if t + 1 < len(l) and l[t + 1] not in edges[s]: edges[s].add(l[t + 1]) degrees[l[t + 1]] += 1 degrees[s] return Graph(edges, degrees) # Topological Sort def topological_sort(graph): frontier = [v for v, d in graph.degrees.items() if d == 0] visited = [] while frontier: vertex = frontier.pop() visited.append(vertex) for neighbor in graph.edges[vertex]: graph.degrees[neighbor] -= 1 if graph.degrees[neighbor] == 0: frontier.append(neighbor) return visited # Main Execution def main(): graph = read_graph() vertices = topological_sort(graph) print(''.join(vertices)) if __name__ == '__main__': main()
6ff19bcd3f99699c58fa6b659b9840126591e386
willianresille/Learn-Python-With-DataScience
/DSA-Python-Capitulo2-Numeros.py
773
3.84375
4
# Operações Básicas # Soma 4 + 4 # Subtração 4 - 3 # Multiplicação 3 * 3 # Divisão 3 / 2 # Potência 4 ** 2 # Módulo 10 % 3 # Função Type type(5) type(5.0) a = 'Eu sou uma String' type(a) # Operações com números float # float + float = float 3.1 + 6.4 # int + float = float 4 + 4.0 # int + int = int 4 + 4 # int / int = float 4 / 2 # int // int = int 4 // 2 # int / float = float 4 / 3.0 # int // float = float 4 // 3.0 # Conversão float(9) int(6.0) int(6.5) # Hexadecimal e Binário hex(394) hex(217) bin(236) bin(390) # Funções abs, round e pow # Retorna o valor absoluto abs(-8) # Retorna o valor absoluto abs(8) # Retorna o valor com arredondamento round(3.14151922,2) # Potência pow(4,2) # Potência pow(5,3) # FIM
2a21f0fda2b30dc18f20e798182d285ab7f4b9e1
lepoidev/blossom
/blossom/structures.py
2,796
3.5
4
from helpers import sorted_pair # represents an undirected edge class Edge: def __init__(self, start, end, num_nodes): self.start, self.end = sorted_pair(start, end) self.id = (self.start * num_nodes) + self.end def __hash__(self): return hash(self.id) def __eq__(self, other): return other.id == self.id def __repr__(self): return '{start=' + str(self.start) + ' end=' + str(self.end) + '}' def __contains__(self, item): return item == self.start or item == self.end class Tree: def __init__(self, root): self.root = root self.edges = set() self.nodes = {root} self.dists = {root : 0} self.parent_map = {root : None} def __repr__(self): return self.nodes.__repr__() def add(self, edge): if edge.start in self.nodes: new_node = edge.end old_node = edge.start else: new_node = edge.start old_node = edge.end self.nodes.add(new_node) self.edges.add(edge) self.dists[new_node] = self.dists[old_node] + 1 self.parent_map[new_node] = old_node def has_node(self, node): return node in self.nodes def has_edge(self, edge): return edge in self.edges def dist_from_root(self, node): return self.dists[node] def path_to_root(self, node): path = [] cur = node while cur is not None: path.insert(0, cur) cur = self.parent_map[cur] return path def contract_edges(num_nodes, edges, B, blossom_root): contracted = set() B = set(B) for edge in edges: start = edge.start end = edge.end if start in B and end in B: continue if start in B and end not in B: start = blossom_root elif end in B and start not in B: end = blossom_root contracted.add(Edge(start, end, num_nodes)) return contracted class Matching: def __init__(self, num_nodes): self.num_nodes = num_nodes self.edges = set() def __repr__(self): return self.edges.__repr__() def augment(self, path): add = True for i in range(0, len(path) - 1): j = i + 1 start = path[i] end = path[j] edge = Edge(start, end, self.num_nodes) if add: self.edges.add(edge) elif edge in self.edges: self.edges.remove(edge) add = not add def get_contraction(self, B, blossom_root): contraction_M = Matching(self.num_nodes) contraction_M.edges = contract_edges(self.num_nodes, self.edges, B, blossom_root) return contraction_M
0eb37e3ffbd4addfa7e642bfd5fe0c39032285af
gingerComms/gingerCommsAPIs
/utils/metaclasses.py
870
3.609375
4
import types class DecoratedMethodsMetaClass(type): """ A Meta class that looks for a "decorators" list attribute on the class and applies all functions (decorators) in that list to all methods in the class """ def __new__(cls, class_name, parents, attrs): if "decorators" in attrs: decorators = attrs["decorators"] # Iterating over all attrs of the class and applying all of the # decorators to all attributes that are methods for attr_name, attr_value in attrs.items(): if isinstance(attr_value, types.FunctionType): method = attr_value for decorator in decorators: method = decorator(method) attrs[attr_name] = method return type.__new__(cls, class_name, parents, attrs)
5b0ab335563146599a579b204110ff11d6b70604
DragonWolfy/hw7
/hw8.py
1,143
3.984375
4
def get_words(filename): words=[] with open(filename, encoding='utf8') as file: text = file.read() words=text.split(' ') return words def words_filter(words, an_input_command): if an_input_command==('min_length'): print('1') a=('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') for word in words: if len(word)<len(a): a=word print(len(a)) elif an_input_command==('contains'): print('1') the_contained=input('What is contained? ') for word in words: for letter in word: if the_contained==letter: print(word) else: continue else: print('0') print('Can not work with', '"',an_input_command, '"') def main(): words = get_words('example.txt') a=input('input second variable: ') filtered_words = words_filter(words, a) __name__=input('input command: ') if __name__ == '__main__': main()
70917209c731ea36c0df05a94def58233f28a736
dendilz/30-Days-of-Code
/Day 6: Let's Review
356
3.84375
4
#!/usr/bin/env python x = int(input()) for _ in range(x): string = input() new_string = '' for index in range(len(string)): if index % 2 == 0: new_string += string[index] new_string += ' ' for index in range(len(string)): if index % 2 != 0 : new_string += string[index] print(new_string)
41c20076d3e9ba1433191c4f267605ccb6b351bf
zha0/punch_card_daily
/第二期-python30天/day2 变量/基础.py
554
4.15625
4
#coding: utf-8 #pring print("hello,world") print("hello,world","my name is liangcheng") #len #输出5 print(len("hello")) #输出0 a = "" print(len(a)) #输出3,tuple b = ("a","b","c") print(len(b)) # list 输出5 c = [1,2,3,4,5] print(len(c)) # range 输出9 d = range(1,10) print(len(d)) # dict 字典 输出1 e = {"name":"liangcheng"} print(len(e)) # set 输出5 f = {1,2,3,4,"laohu"} print(len(f)) # str ## 输出<type 'str'> print(type(str(10))) # int ## 输出:<type 'int'> print(type(int('123'))) #float ## print(type(float(10)))
21007e7b568b8ec5c39231759d282ec9d77f2f49
zha0/punch_card_daily
/第二期-python30天/day4 字符串/strings.py
5,298
4.5625
5
#coding: utf-8 #创建字符串 letter = 'P' print(letter) print(len(letter)) greeting = 'Hello World' print(greeting) print(len(greeting)) sentence = "this is a test" print(sentence) # 创建多行字符串 multiline_string = '''I am a teacher and enjoy teaching. I didn't find anything as rewarding as empowering people. That is why I created 30 days of python.''' print(multiline_string) multiline_string = """I am a teacher and enjoy teaching. I didn't find anything as rewarding as empowering people. That is why I created 30 days of python.""" print(multiline_string) # 字符串连接 first_name = 'liang' last_name = 'cheng' space = ' ' full_name = first_name + space + last_name print(full_name) print(len(first_name)) print(len(last_name)) print(len(first_name) > len(last_name)) print(len(full_name)) # 转义字符 print('I hope everyone is enjoying the python challage.\n Are you?') print('Days\tTopics\tExercises') print('Day 1\t3\t5') print('Day 2\t3\t5') print('Day 3\t3\t5') print('Day 4\t3\t5') print('This is a backslash symbol (\\)') print('this is a \"test\".') #output ''' I hope everyone is enjoying the python challage. Are you? Days Topics Exercises Day 1 3 5 Day 2 3 5 Day 3 3 5 Day 4 3 5 This is a backslash symbol (\) this is a "test". ''' # 格式化字符串 # 字符串 first_name = 'liang' last_name = 'cheng' language = 'python' format_sting = 'I am %s %s. I teach %s' %(first_name, last_name, language) print(format_sting) #字符串和数字 radius = 10 pi = 3.14 area = pi * radius ** 2 format_sting = 'The area of circle with a radius %d is %.2f.' %(radius, pi) print(format_sting) python_libraries = ['Django', 'Flask', 'NunPy', 'Matplotlib', 'Pandas'] format_sting = 'the following are python libraries: %s' %(python_libraries) print(format_sting) first_namem = 'liang' last_name = 'cheng' language = 'python' format_sting = 'i am {} {}. i study {}'.format(first_name,last_name,language) print(format_sting) # num运算 a = 4 b = 3 print('{} + {} = {}'.format(a, b, a + b)) print('{} - {} = {}'.format(a, b, a - b)) print('{} * {} = {}'.format(a, b, a * b)) print('{} / {} = {:.2f}'.format(a, b, a / b)) # 保留小数点后两位 print('{} % {} = {}'.format(a, b, a % b)) print('{} // {} = {}'.format(a, b, a // b)) print('{} ** {} = {}'.format(a, b, a ** b)) # output # 4 + 3 = 7 # 4 - 3 = 1 # 4 * 3 = 12 # 4 / 3 = 1.00 # 4 % 3 = 1 # 4 // 3 = 1 # 4 ** 3 = 64 # string and num radius = 10 pi = 3.14 area = pi * radius ** 2 format_sting = '半径为 {} 圆的面积为:{:.2f}'.format(radius, area) print(format_sting) #f-sting , 报语法错误 # a = 4 # b = 3 # print(f'{a} + {b} = {a + b}') # print(f'{a} - {b} = {a - b}') # print(f'{a} * {b} = {a * b}') # print(f'{a} / {b} = {a / b}') # print(f'{a} % {b} = {a % b}') # print(f'{a} // {b} = {a // b}') # print(f'{a} ** {b} = {a ** b}') # unpacking characters language = 'python' a,b,c,d,e,f = language print(a) print(b) print(c) print(d) print(e) print(f) # strings by index language = 'python' first_letter = language[0] print(first_letter) # p second_letter = language[1] print(second_letter) #y last_index = len(language) - 1 last_letter = language[last_index] print(last_letter) # n print('-------------------') last_letter = language[-1] # n second_letter = language[-2] # o print(last_letter,second_letter) # 切割字符串 language = 'python' first_three = language[0:3] # pyt print(first_three) last_three = language[3:6] print(last_three) #hon last_three = language[-3:] print(last_three) #hon last_three = language[3:] print(last_three) #hon # 反转字符串 greeting = 'hello, world' print(greeting[::-1]) # dlrow ,olleh # 切割时跳过字符 ## 通过向切片方法传递步骤参数,可以在切片时跳过字符。 language = 'python' pto = language[0:6:2] print(pto) #pto # capitalize challenge = 'thirty days of python' print(challenge.capitalize()) # Thirty days of python #count challenge = 'thirty days of python' print(challenge.count('y')) # 3 print(challenge.count('y',7,14)) #1 print(challenge.count('th')) #2 #endswith challenge = 'thirty days of python' print(challenge.endswith('on')) # True print(challenge.endswith('tion')) # False # expandtabs() challenge = 'thirty\tdays\tof\tpython' print(challenge.expandtabs()) # thirty days of pytho print(challenge.expandtabs(10)) # thirty days of python # find challenge = 'thirty days of python' print(challenge.find('on')) # 19 print(challenge.find('th')) # 0 # rfind challenge = 'thirty days of python' print(challenge.rfind('y')) # 16 print(challenge.rfind('th')) # 17 #format first_name = 'liang' last_name= 'cheng' age = 230 job = 'teacher' country = 'Findlan' sentence = 'I am {} {}. I am a {}. I am {} years old. I live in {}.'.format(first_name,last_name,age,job,country) print(sentence) # index challenge = 'thirty days of python' sub_string = 'da' print(challenge.index(sub_string)) # 7 # print(challenge.index(sub_string, 9)) # ValueError print(challenge.index('th')) # 0 print(challenge.index('o')) # 12 # rindex challenge = 'thirty days of python' sub_string = 'da' print(challenge.rindex(sub_string)) # 7 # print(challenge.rindex(sub_string, 9)) # ValueError print(challenge.rindex('th')) # 0 print(challenge.rindex('o')) # 12
d29c3d2cbfc84a08e26f7128431b91a9ddacd489
zha0/punch_card_daily
/第二期-python30天/day17 异常处理(exception handling)/day17_ Unpacking.py
2,542
3.53125
4
# coding: utf-8 def sum_of_five_nums(a,b,c,d,e): return a + b + c + d + e lst = [1,2,3,4,5] # TypeError: sum_of_five_nums() missing 4 required positional arguments: 'b', 'c', 'd', and 'e' # print(sum_of_five_nums(lst)) def sum_of_five_nums(a,b,c,d,e): return a + b + c + d + e lst = [1,2,3,4,5] print(sum_of_five_nums(*lst)) # 15 numbers = range(2, 7) print(list(numbers)) # [2, 3, 4, 5, 6] args = [2, 7] numbers = range(*args) print(list(numbers)) # [2, 3, 4, 5, 6] countries = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland'] fin, sw, nor, *rest = countries print(fin, sw, nor, rest) # Finland Sweden Norway ['Denmark', 'Iceland'] numbers = [1,2,3,4,5,6,7] one, *middle, last = numbers print(one, middle, last) # 1 [2, 3, 4, 5, 6] 7 def unpacking_person_info(name, country, city, age): return f'{name} lives in {country}, {city}. he is {age} year old.' dct = {'name':'liang', 'country':'china', 'city':'beijing', 'age':28} print(unpacking_person_info(**dct)) # liang lives in china, beijing. he is 28 year old. # packing list def sum_all(*args): s = 0 for i in args: s += i return s print(sum_all(1,2,3)) # 6 print(sum_all(1,2,3,4,5,6,7)) # 28 def packing_person_info(**kwargs): for key in kwargs: print(f"{key} = {kwargs[key]}") return kwargs # {'name': 'liang', 'country': 'china', 'city': 'shanghai', 'age': 18} print(packing_person_info(name='liang',country='china',city='shanghai',age=18)) # Spreading in Python lst_one = [1,2,3] lst_two = [4,5,6] lst = [0, *lst_one, *lst_two] print(lst) # [0, 1, 2, 3, 4, 5, 6] country_lst_one = ['Finland', 'sweden', 'norway'] country_lst_two= ['denmak', 'icelang', 'china'] nordic_country = [*country_lst_one, * country_lst_two] # ['Finland', 'sweden', 'norway', 'denmak', 'icelang', 'china'] print(nordic_country) # enumerate for index, item in enumerate([20, 30, 40]): print(index, item) # 0 20 # 1 30 # 2 40 for index, i in enumerate(countries): print('hi') if i == 'Finland': print(f'the country {i} has been found at index {index}') # zip fruits = ['banana', 'orange', 'mango', 'lemon','lime'] vegetables = ['tomato','potato', 'cabbage', 'onion','carrot'] fruits_and_vegetables = [] for f,v in zip(fruits, vegetables): fruits_and_vegetables.append({'fruit':f, 'veg':v}) # [{'fruit': 'banana', 'veg': 'tomato'}, {'fruit': 'orange', 'veg': 'potato'}, {'fruit': 'mango', 'veg': 'cabbage'}, {'fruit': 'lemon', 'veg': 'onion'}, {'fruit': 'lime', 'veg': 'carrot'}] print(fruits_and_vegetables)
d5f417eb2376e467d58c96d9d31fc10a2379dff6
LakshmiSaicharitha-Yallarubailu/TSF_TASKS
/Exploratory Data Analysis-Retail.py
3,181
3.8125
4
#!/usr/bin/env python # coding: utf-8 # # THE SPARKS FOUNDATION # NAME: Y.LAKSHMI SAICHARITHA # # # 1.Perform ‘Exploratory Data Analysis’ on dataset ‘SampleSuperstore’ 2.As a business manager, try to find out the weak areas where you can work to make more profit. # In[34]: #Importing the libraries import numpy as np import pandas as pd import seaborn as sb import matplotlib.pyplot as plt # In[2]: #loading dataset ds=pd.read_csv(r"C:\Users\Saicharitha\Downloads\SampleSuperstore.csv") ds # In[3]: ds.head(6) # In[4]: ds.tail(3) # In[5]: ds.info() # In[6]: ds.describe() # In[7]: ds.isnull().sum() # In[8]: ds.isna().sum() # In[9]: ds.drop(['Postal Code'],axis=1,inplace=True) # In[10]: ds # In[11]: sales_ds = ds.groupby('Category', as_index=False)['Sales'].sum() subcat_ds = ds.groupby(['Category','Sub-Category'])['Sales'].sum() subcat_ds['Sales']=map(int,subcat_ds) sales_ds # # Exploratory Data Analysis # In[12]: ds.plot(x='Quantity',y='Sales',style='.') plt.title('Quantity vs Sales') plt.xlabel('Quantity') plt.ylabel('Sales') plt.grid() plt.show() # In[13]: ds.plot(x='Discount',y='Profit',style='.') plt.title('Discount vs Profit') plt.xlabel('Discount') plt.ylabel('Profit') plt.grid() plt.show() # In[14]: sb.pairplot(ds) # In[15]: sb.pairplot(ds,hue='Category',diag_kind='hist') # In[16]: sb.pairplot(ds,hue='Region') # In[17]: ds['Category'].value_counts() sb.countplot(x=ds['Category']) # In[18]: ds.corr() # In[21]: sb.heatmap(ds.corr(), annot=True) # In[32]: fig,axs=plt.subplots(nrows=2,ncols=2,figsize=(10,7)); sb.countplot(ds['Category'],ax=axs[0][0]) sb.countplot(ds['Segment'],ax=axs[0][1]) sb.countplot(ds['Ship Mode'],ax=axs[1][0]) sb.countplot(ds['Region'],ax=axs[1][1]) axs[0][0].set_title('Category',fontsize=20) axs[0][1].set_title('Segment',fontsize=20) axs[1][0].set_title('Ship Mode',fontsize=20) axs[1][1].set_title('Region',fontsize=20) # In[35]: fig, axs = plt.subplots(ncols=2, nrows = 2, figsize = (10,10)) sb.distplot(ds['Sales'], color = 'red', ax = axs[0][0]) sb.distplot(ds['Profit'], color = 'green', ax = axs[0][1]) sb.distplot(ds['Quantity'], color = 'orange', ax = axs[1][0]) sb.distplot(ds['Discount'], color = 'blue', ax = axs[1][1]) axs[0][0].set_title('Sales Distribution', fontsize = 20) axs[0][1].set_title('Profit Distribution', fontsize = 20) axs[1][0].set_title('Quantity distribution', fontsize = 20) axs[1][1].set_title('Discount Distribution', fontsize = 20) plt.show() # In[22]: plt.title('Region') plt.pie(ds['Region'].value_counts(),labels=ds['Region'].value_counts().index,autopct='%1.1f%%') plt.show() # In[23]: plt.title('Ship Mode') plt.pie(ds['Ship Mode'].value_counts(),labels=ds['Ship Mode'].value_counts().index,autopct='%1.1f%%') plt.show() # In[24]: ds.groupby('Segment')['Profit'].sum().sort_values().plot.bar() plt.title("Profits on various Segments") # In[25]: ds.groupby('Region')['Profit'].sum().sort_values().plot.bar() plt.title("Profits on various Regions") # In[26]: plt.figure(figsize=(14,6)) ds.groupby('State')['Profit'].sum().sort_values().plot.bar() plt.title("Profits on various States")
8764b0e4ca1d4a8ca5c3995bddb193f959204385
skyworksinc/ACG
/ACG/VirtualObj.py
865
3.859375
4
import abc class VirtualObj(metaclass=abc.ABCMeta): """ Abstract class for creation of primitive objects """ def __init__(self): self.loc = {} def __getitem__(self, item): """ Allows for access of items inside the location dictionary without typing .loc[item] """ return self.export_locations()[str(item)] def export_locations(self): """ This method should return a dict of relevant locations for the virtual obj""" return self.loc @abc.abstractmethod def shift_origin(self, origin=(0, 0), orient='R0'): """ This method should shift the coordinates of relevant locations according to provided origin/transformation, and return a new shifted object. This is important to allow for deep manipulation in the hierarchy """ pass
6085c6ada49aeee0f84a290d490cf12dd683f5f3
cw2yuenberkeley/w205-fall-17-labs-exercises
/exercise_2/extweetwordcount/scripts/finalresults.py
810
3.546875
4
import sys import psycopg2 from tcount_db import TCountDB if __name__ == "__main__": if len(sys.argv) > 2: print "Please input only one or zero argument." exit() # Get DB connection c = TCountDB().get_connection() cur = c.cursor() # Check if there is exactly one argument if len(sys.argv) == 2: word = sys.argv[1] cur.execute("SELECT count FROM tweetwordcount WHERE word = '%s'" % word) results = cur.fetchall() c.commit() count = 0 if len(results) == 0 else results[0][0] print 'Total number of occurrences of "%s": %d' % (word, count) # Check if there is no argument elif len(sys.argv) == 1: cur.execute("SELECT word, count FROM tweetwordcount ORDER BY word") results = cur.fetchall() for r in results: print "(%s, %d)" % (r[0], r[1]) c.commit() c.close()
feffbb540e544c11f4ff843f19f81fb5171c4de3
xuwei1997/CNN
/convelution3.py
2,227
3.53125
4
from keras.models import Sequential from keras.layers import Dense, Activation,convolutional,pooling,core import keras from keras.datasets import cifar10 if __name__ == "__main__": (X_train,Y_train),(X_test,Y_test)=cifar10.load_data() Y_train=keras.utils.to_categorical(Y_train) Y_test=keras.utils.to_categorical(Y_test) print (X_train.shape, Y_train.shape, X_test.shape, Y_test.shape) model=Sequential() model.add(convolutional.Conv2D(filters=32,kernel_size=3,strides=1,padding="same",data_format="channels_last",input_shape=X_train.shape[1:])) model.add(Activation("relu")) model.add(pooling.MaxPool2D(pool_size=2,strides=2,padding="same",data_format="channels_first")) model.add(core.Dropout(0.2)) model.add(convolutional.Conv2D(filters=48, kernel_size=3, strides=1, padding="same", data_format="channels_last", input_shape=X_train.shape[1:])) model.add(Activation("relu")) model.add(pooling.MaxPool2D(pool_size=2,strides=2,padding="same",data_format="channels_first")) model.add(core.Dropout(0.2)) model.add(convolutional.Conv2D(filters=128, kernel_size=3, strides=1, padding="same", data_format="channels_last",input_shape=X_train.shape[1:])) model.add(Activation("relu")) model.add(pooling.MaxPool2D(pool_size=2, strides=2, padding="same", data_format="channels_first")) model.add(core.Dropout(0.2)) model.add(core.Flatten()) model.add(Dense(units=512)) model.add(Activation("relu")) model.add(core.Dropout(0.2)) model.add(Dense(units=10)) model.add(Activation("softmax")) opt=keras.optimizers.Adam(lr=0.0001,decay=1e-6) model.compile(loss="categorical_crossentropy",optimizer=opt,metrics=['accuracy']) for i in range(15): print (i) print ("...........................................................................") for k in range(0,50000,32): X_data=X_train[k:k+32]/255 Y_data=Y_train[k:k+32] l_a=model.train_on_batch(X_data,Y_data) print (k) print (l_a) print (model.metrics_names) loss_and_metrics = model.evaluate(X_test, Y_test) print ("") print (loss_and_metrics) model.save('my_model_1.h5')
172253e3166a026da90af4c7b3d4896dc3b705e3
CeriseGoutPelican/ISEN
/Python/Séance 1/Exercice 1/liste.py
2,134
3.90625
4
import sys def min_value(liste): """Permet de recuperer le plus petit element (nombre) d'une liste""" # Pour rechercher le premier element first = False # Parcours la liste list element par element for e in liste: if isinstance(e, (int, float, bool)): if first == False: # Valeure minimale min = e # Premier element trouve first = True else: # Substitue l'element le plus petit if e <= min: min = e if first: return min else: return "/!\ Erreur" #raise Exception("Il n'y a pas de valeurs numeriques dans la liste") def min_value_rec(liste): """Permet de recuperer le plus petit element (nombre) d'une liste""" # Pour rechercher le premier element first = False # Parcours la liste list element par element for e in liste: if isinstance(e, (int, float, bool)): if first == False: # Valeure minimale min = e # Premier element trouve first = True else: # Substitue l'element le plus petit if e <= min: min = e elif isinstance(e, list): e = min_value_rec(e) if first == False: # Valeure minimale min = e # Premier element trouve first = True else: # Substitue l'element le plus petit if e <= min: min = e return min # map et filter sont deux éléments interessants en pythons print(sys.version) print('-'*50) list1 = ["hello", -5, False, 1.2323, {"a", 10, "c"}, [-18,45, "abcd"]] list2 = [1.1, "hello", 10, -True, 1.2323, {"a", 10, "c"}, [18,45, "abcd"]] list3 = [False] list4 = ["hello", [-18,45,"abcd"]] print(min_value_rec(list1)) print(min_value_rec(list2)) print(min_value_rec(list3)) print(min_value_rec(list4))
8e862b30b7af63b3110f0ce4efcf683f35d2bf5f
bertmclee/ML_Foundation_Techniques
/ml_foundation_hw3_pa/hw3_q8.py
3,714
3.828125
4
import numpy as np from scipy.special import softmax from collections import Counter import matplotlib.pyplot as plt import math from scipy.linalg import norm # Logistic Regression """ 19. Implement the fixed learning rate gradient descent algorithm for logistic regression. Run the algorithm with η=0.01 and T=2000, what is Eout(g) from your algorithm, evaluated using the 0/1 error on the test set? 20. Implement the fixed learning rate stochastic gradient descent algorithm for logistic regression. Instead of randomly choosing n in each iteration, please simply pick the example with the cyclic order n=1,2,…,N,1,2,… Run the algorithm with η=0.001 and T=2000. What is Eout(g) from your algorithm, evaluated using the 0/1 error on the test set? 8. (20 points, *) For Questions 19 and 20 of Homework 3 on Coursera, plot a figure that shows Eout(wt) as a function of t for both the gradient descent version and the stochastic gradient descent version on the same figure. Describe your findings. Please print out the figure for grading. """ def sigmoid(x): return 1 / (1 + math.exp(-x)) def logisticRegressionGD(x, y, eta, t, w): # compute gradient Ein and Ein N, dim = x.shape gradientEinSum = np.zeros(dim) gradientEin = np.zeros(dim) EinSum = 0 Ein = 0 for i in range(N): gradientEinSum += sigmoid(-y[i]*np.dot(w,x[i]))*(-y[i]*x[i]) EinSum += np.log(1+np.exp(-y[i]*np.dot(w,x[i]))) gradientEin = gradientEinSum/N Ein = EinSum/N # print(t, Ein) # update weight vector w -= eta * gradientEin # print(w) return w, Ein def logisticRegrssionSGD(x, y, eta, t, w): N, dim = x.shape gradientEin = np.zeros(dim) Ein = np.zeros(dim) # compute gradient Ein and Ein i = t % len(y) gradientEin = sigmoid(-y[i]*np.dot(w,x[i]))*(-y[i]*x[i]) Ein = np.log(1+np.exp(-y[i]*np.dot(w,x[i]))) # print(t, Ein) # update weight vector w -= eta * gradientEin # print(w) return w, Ein def calculateError(x, y, w): # calculate prediction accuracy testSize = len(y) yPredict = np.zeros(testSize) error = 0 for i in range(testSize): yPredict[i] = np.dot(w, x[i]) # print(yPredict[i]) if yPredict[i] > 0 and y[i] == -1: error += 1 elif yPredict[i] < 0 and y[i] == 1: error += 1 errorRate = error/testSize return errorRate # ------------------------- if __name__ == '__main__': # Read training and tesing data dataTrain = np.loadtxt('hw3_train.dat') N, dim = dataTrain.shape xTrain = dataTrain[:,:-1] xTrain = np.insert(xTrain, 0, 0, axis=1) yTrain = dataTrain[:,-1] dataTest = np.loadtxt('hw3_test.dat') xTest = np.insert(dataTest[:,:-1],0,0,axis=1) yTest = dataTest[:,-1] # training parameters T = 2000 eta = 0.001 Eout01ArrGD = [] Eout01ArrSGD = [] # Initialize weight vector w = np.zeros(dim) # print(w) for t in range(T): wGD, EoutGD = logisticRegressionGD(xTrain, yTrain, eta, t, w) # print(wGD) errorGD = calculateError(xTest, yTest, wGD) # print('GD',t, errorGD) Eout01ArrGD.append(errorGD) print('-------------------------') print('update t: {}, GD error: {:.1f}%'.format(t+1, errorGD*100)) w = np.zeros(dim) for t in range(T): wSGD, EoutSGD = logisticRegrssionSGD(xTrain, yTrain, eta, t, w) #print(wSGD) errorSGD = calculateError(xTest, yTest, wSGD) #print('SGD', t, errorSGD) Eout01ArrSGD.append(errorSGD) print('-------------------------') print('update t: {}, SGD error: {:.1f}%'.format(t+1, errorSGD*100)) t = list(range(0,T)) plt.plot(t, Eout01ArrSGD, label='Stochastic Gradient Descent') plt.plot(t, Eout01ArrGD, label='Gradient Descent') plt.title("Eout(wt)(0/1 error) vs t") plt.xlabel("t") plt.ylabel("Eout(wt)(0/1 error)") plt.legend(loc='lower left') plt.show()
9446b95ea3cb2f71014a9197aa934f03dbb12c5a
JiaoPengJob/PythonPro
/src/_instance_.py
2,780
4.15625
4
#!/usr/bin/python3 # 实例代码 # Hello World 实例 print("Hello World!") # 数字求和 def _filter_numbers(): str1 = input("输入第一个数字:\n") str2 = input("输入第二个数字:\n") try: num1 = float(str1) try: num2 = float(str2) sum = num1 + num2 print("相加的结果为:%f" % sum) except ValueError: print("请输入数字!") _filter_numbers() except ValueError: print("请输入数字!") _filter_numbers() # 判断奇偶数 # 0:偶数 # 1:奇数 def _odd_even(num): if num.isdigit(): if (float(num) % 2) == 0: return 0 else: return 1 else: print("这不是一个数字!") num = input("奇偶--请输入一个数字:\n") print(_odd_even(num)) # 判断闰年 # 如果一年是闰年,它要么能被4整除但不能被100整除;要么就能被400整除 # True:是闰年 # False:是平年 def _leap_year(year): if (year % 4) == 0 and (year % 100) != 0 or (year % 400) == 0: return True else: return False year = input("闰年--请输入一个年份:\n") print(_leap_year(int(year))) # 判断质数 # 一个大于1的自然数,除了1和它本身外,不能被其他自然数(质数)整除(2, 3, 5, 7等),换句话说就是该数除了1和它本身以外不再有其他的因数。 import math # 0:既不是质数,也不是合数 # 1:是质数 # 2:是合数 def _prime(num): if num > 1: square_num = math.floor(num ** 0.5) for i in range(2, (square_num + 1)): if (num % i) == 0: return 2 break else: return 1 else: return 0 num = int(input("质数--输入一个数字:\n")) print(_prime(num)) # 阶乘 # 整数的阶乘(英语:factorial)是所有小于及等于该数的正整数的积,0的阶乘为1。即:n!=1×2×3×...×n。 def _factorial(num): if num < 0: # 负数是没有阶乘的 return num else: return math.factorial(num) num = int(input("阶乘--输入一个数字:\n")) print(_factorial(num)) # 阿姆斯特朗数 # 如果一个n位正整数等于其各位数字的n次方之和,则称该数为阿姆斯特朗数。 # 当n=3时,又称水仙花数,特指一种三位数,其各个数之立方和等于该数。 def _armstrong(num): sum = 0 n = len(str(num)) temp = num while temp > 0: digit = temp % 10 sum += digit ** n temp //= 10 if num == sum: return True else: return False print(_armstrong(int(input("阿姆斯特朗--输入一个数字:\n"))))
15d7ba4a79abd8f79d4349d310eae243a9191960
alecordev/web-screenshotter
/web_screenshotter.py
4,034
3.546875
4
""" Module to automate taking screenshots from websites. Current features: - URLs list from file (one URL per line) given from command line - Specify one URL from command line """ import os import sys import logging import datetime import argparse from selenium import webdriver from bs4 import BeautifulSoup import requests logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) console_handler = logging.StreamHandler() formatter = logging.Formatter('[%(asctime)s] - %(name)s - %(levelname)s - %(message)s') console_handler.setFormatter(formatter) logger.addHandler(console_handler) logger.info('Logging initialized') visited = set() to_visit = set() HEADERS = {'User-Agent': 'Mozilla/5.0'} navigate = False def save_screenshot(driver, url): """ Saves screenshot from URL under screenshots/YYYY-MM-DD directory. :param driver: Selenium webdriver instance :type driver: webdriver instance :param url: Web address :type url: str """ try: driver.get(url) dt = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d') file_name = url.replace('http://', '').replace('/', '-').replace(':', '-').replace('.html', '') + '.png' path = os.path.join(os.path.abspath(os.curdir), 'screenshots/{}'.format(dt)) os.makedirs('screenshots/{}'.format(dt), exist_ok=True) f = os.path.join(path, file_name) logger.info(f) driver.get_screenshot_as_file(f) except Exception as e: logger.error(e) def take_screenshot(): """ Goes to every filtered link within the given URL, taking screenshots. """ try: driver = webdriver.Firefox() for url in list(to_visit): save_screenshot(driver, url) visited.add(url) to_visit.remove(url) except Exception as e: logger.error(e) finally: driver.quit() def fix_url(url): """ Ensures url format is valid, fixes it if necessary :param url: The web address to verify :type url: str """ if 'http://' not in url and 'https://' not in url: url = 'http://' + url return url def process(base_url): """ Collects all 'filtered' links within an URL :param base_url: Main web address to parse :type base_url: str """ logger.info('Processing {}'.format(base_url)) exceptions = ['.css', '.js', '.zip', '.tar.gz', '.jar', '.txt', '.json'] logger.info('Ignoring links containing: {}'.format(exceptions)) soup = BeautifulSoup(requests.get(base_url).content, 'lxml') urls = [href['href'] for href in soup.find_all(href=True) if href['href'] not in exceptions] for url in urls: if base_url in url: to_visit.add(url) def process_url(url): """ Wraps functionality & logic to take screenshots for every 'filtered link' in URL :param url: Web address to take screenshots from :type url: str """ process(url) while to_visit: take_screenshot() logging.info('No urls left to process from {}. Finishing...'.format(url)) if __name__ == '__main__': try: parser = argparse.ArgumentParser() parser.add_argument('-u', '--url', help='URL of the website to screenshot') parser.add_argument('-f', '--file', help='Filename path of list of URLs to screenshot (one URL per line)') args = parser.parse_args() if len(sys.argv) < 2: parser.print_help() sys.exit() if args.url: process_url(args.url) elif args.file: with open(args.file) as urls: try: driver = webdriver.Firefox() for url in urls: save_screenshot(driver, url) except Exception as e: logger.error(e) finally: driver.quit() except Exception as e: logger.error(e)
1be8d27189ffd3e447915108db7618325189afe4
MrClub/Poker
/dealer.py
1,427
3.53125
4
# This is a place to add all my functions # Todo Full House detection # TODO betting import random deck_of_cards = [] def deck_builder(list): # builds the deck because I'm too lazy to type everything out suit_list = ["Diamonds","Hearts","Clubs","Spades"] for suit in suit_list: for n in range(2, 15): list.append([n, suit]) random.shuffle(list) return list # test def deal(howmany, deck, list): # deals how many cards you want to a selected list for n in range(0, howmany): list.append(deck.pop()) return list def show_player_hand(hand_list, player): # show the player's hand if player == "hero": print("Your hand".center(22, "-")) else: print("Villian's hand".center(22, "-")) for card in hand_list: print(str(card[0]) + " of " + card[1]) print() def show_the_board(board_list): # shows the board i.e. community cards print("The board".center(22, "-")) for card in board_list: print(str(card[0]) + " of " + card[1]) print() def state_of_game(player_hand, villian_hand, board,show_villian): # combines show_the_board and show_player_hand_function into one # show villians hand if show_villian is set to "y" show_player_hand(player_hand, "hero") if show_villian == "y": show_player_hand(villian_hand,"villian") else: pass show_the_board(board)