blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
61048636c092d7e01ee28c913938b59ae939a235
Malonk/unemployment_stats
/data/move_script.py
678
3.765625
4
import os """Script to move files from folders (a, b, c, ...) to folder x.""" old = "old" base = os.path.abspath(os.path.join(os.path.dirname(__file__), old)) # Create list of directories to process dirs = [x for x in os.listdir(base) if os.path.isdir(os.path.join(base, x))] # Creat new dir if it doesn't alreay exist new = os.path.join(base, "data") if not os.path.exists(new): os.mkdir(new) # Move files within folders for folder in dirs: for filename in os.listdir(os.path.join(base, folder)): a = os.path.join(base, folder, filename) b = os.path.join(base, "data", filename) os.rename(a, b) print(f"Moved {a} to {b}")
7da09559f7aa445eec24035de91f901c9328d3d4
karolSuszczynski/GamesName
/units/attack_and_defence.py
1,710
3.640625
4
from enum import Enum class AttackType(Enum): BLUNT=0 PIERCE=1, SLASH=2, HEAT=3 COLD=4 POISON=5 MAGIC=6 ELECTRIC=7 class SingleParams: def __init__(self, value, type=AttackType.BLUNT): self.value = value self.type = type class Attack: def __init__(self, single_attacks:list): self.single_attacks = single_attacks def __str__(self): result = "" for attack in self.single_attacks: result += f"\n {attack.type.name} {attack.value}" return result class Armor: def __init__(self, armor_map={}): self.armor_map = armor_map def get_value(self, type:AttackType): return self.armor_map.get(type, 0) def __str__(self): result = "" for armor_type in self.armor_map: result += f"\n {armor_type.name} {self.armor_map[armor_type]}" return result class Resistance: def __init__(self, resistance_map={}): self.resistance_map = resistance_map def get_value(self, type:AttackType): return self.resistance_map.get(type, 0) def __str__(self): if len(self.resistance_map) == 0: return "---" result = "" for resistance_type in self.resistance_map: result += f"\n {resistance_type.name} {self.resistance_map[resistance_type]}" return result def calculate_damage(attacks, armor, resistance): total_damage = 0 for single_attacks in attacks.single_attacks: damage = single_attacks.value - armor.get_value(single_attacks.type) damage *= (1 - resistance.get_value(single_attacks.type)) total_damage += damage return total_damage
743350e00f5ce1a81701f34e5c539c908ec1c50b
jang1563/2010_Python_class
/Homework/Homework3/templete.py
12,361
3.640625
4
from cs1graphics import * ################################# # Global variables index_list = [ ( 0, (0, 0) ), ( 1, (0, 2) ), ( 2, (2, 0) ), ( 3, (2, 4) ), ( 4, (4, 2) ) ] word_list = [ ( 'ACROSS', 0, (0, 0), 3, 'BAA' ), ( 'ACROSS', 2, (2, 0), 5, 'SOLID' ), ( 'ACROSS', 4, (4, 2), 3, 'WIT' ), ( 'DOWN', 0, (0, 0), 3, 'BUS' ), ( 'DOWN', 1, (0, 2), 5, 'ALLOW' ), ( 'DOWN', 3, (2, 4), 3, 'DOT' ) ] word_description = [ ( 'ACROSS', 0, 'Sheep sound' ), ( 'ACROSS', 2, 'Neither liquid nor gas' ), ( 'ACROSS', 4, 'Humour' ), ( 'DOWN', 0, 'Road passenger transport' ), ( 'DOWN', 1, 'Permit' ), ( 'DOWN', 3, 'Shortened form of Dorothy' ) ] word_state = [ 0, 0, 0, 0, 0, 0 ] cell_size = 70 row_size = 5 col_size = 5 canvas_width = cell_size * col_size canvas_height = cell_size * row_size canvas = Canvas( canvas_width, canvas_height, 'black', 'CS101 - Crossword Puzzle' ) ################################# # Definition of functions def draw_indices( _canvas, _index_list, _cell_size ) : for i in range( len( _index_list ) ) : a_word_index = Text() ''' [ Goal ] Draw each index in the '_index_list' on the right location of the crossword game canvas. [ Requirements ] Each index is represented by a 'Text' object, which has attributes as follows : (1) The color of a 'Text' object is 'black'. (2) The size of a 'Text' object is 15. (3) The depth of a 'Text' object is 30. (4) The proper index should be set to a 'Text' object. (5) The position of a 'Text' object is upper-left corner of the cell. Note : Do not use global variables. Otherwise, you will get penalized. Hint : getDimensions() function returns the size of a 'Text' object by 'tuple' object. x_pos, y_pos = a_word_index.getDimensions() x_pos = x_pos/2 + _cell_size * (column_of_the_text_object) y_pos = y_pos/2 + _cell_size * (row_of_the_text_object) ''' # Do something on here !!! _canvas.add( a_word_index ) def draw_horizontal_line( _canvas, _row_size, _cell_size ) : _canvas_width = _canvas.getWidth() for y in range( 1, _row_size ) : line = Path() ''' [ Goal ] Draw each horizontal line on the right location of the crossword game canvas. [ Requirements ] Each horizontal line is represented by a 'Path' object, which has attributes as follows : (1) The border color of a 'Path' object is 'dark gray'. (2) The depth of a 'Path' object is 10. (3) Each line must stretch from the left-side border of the canvas to the right-side border of the canvas. Note : Do not use global variables. Otherwise, you will get penalized. Hint : addPoint() function is used to add points to a 'Path' object by using 'Point' object. ''' # Do something on here !!! _canvas.add( line ) def draw_vertical_line( _canvas, _col_size, _cell_size ) : _canvas_height = _canvas.getHeight() for x in range( 1, _col_size ) : line = Path() ''' [ Goal ] Draw each horizontal line on the right location of the crossword game canvas. [ Requirements ] Each horizontal line is represented by a 'Path' object, which has attributes as follows : (1) The border color of a 'Path' object is 'dark gray'. (2) The depth of a 'Path' object is 10. (3) Each line must stretch from the top-side border of the canvas to the bottom-side border of the canvas. Note : Do not use global variables. Otherwise, you will get penalized. Hint : addPoint() function is used to add points to a 'Path' object by using 'Point' object. ''' # Do something on here !!! _canvas.add(line) def get_a_word( _length, _word, _cell_size, _direction, _empty ) : a_word = Layer() for i in range( _length ) : a_word_cell = Square() a_word_text = Text() ''' [ Goal ] Draw each word cell on the right location of a word layer. [ Requirements ] Each word cell is represented by a 'Square' object, which has attributes as follows : (1) The size of a 'Square' object is '_cell_size'. (1) A 'Square' object must be filled by 'white' color. If a word is not empty, there will be a letter on each word cell. And each letter is represented by a 'Text' object, wich has attributes as follows : (1) The font size is 20. (2) The font color is 'black' (3) The depth of a 'Text' object is 30. (4) The proper letter should be set to a 'Text' object. Note : Do not use global variables. Otherwise, you will get penalized. Note : A word layer has a direction 'across' or 'down'. If the direction of a word layer is 'across', each word cell must be put in 'horizontal' direction. If the direction of a word layer is 'down', each word cell must be put in 'vertical' direction. For example, the word layer for 'down0' consists of 'B', 'U', and 'S', and the direction of the word layer is 'down'. So, the layer must be formed like following : == | B | == | U | == | S | == The word layer for 'across2' consists of 'S', 'O', 'L', 'I', and 'D', and the direction of the word layer is 'across'. So, the layer must be formed like following : == == == == == | S | O | L | I | D | == == == == == ''' # Do something on here !!! a_word.add( a_word_cell ) if not _empty : a_word.add( a_word_text ) if not _empty : a_word.setDepth( 30 ) return a_word def draw_a_word( _canvas, _row, _col, _a_word, _cell_size ) : _a_word.moveTo( _cell_size*_col, _cell_size*_row ) _canvas.add( _a_word ) def draw_word_list( _canvas, _word_list, _word_state, _cell_size ) : for i in range( len( _word_list ) ) : a_word = get_a_word( _word_list[i][3], _word_list[i][4], _cell_size, _word_list[i][0], ( _word_state[i] == 0 ) ) draw_a_word( _canvas, _word_list[i][2][0], _word_list[i][2][1], a_word, _cell_size ) def is_all_found( _word_state ) : all_found = False ''' [ Goal ] Check if there is a word not found yet. [ Requirements ] If there are still words left which are not found, 'is_all_found' function should return 'False'. If there is no word left which are not found, 'is_all_found' function should return 'True' Note : Do not use global variables. Otherwise, you will get penalized. ''' # Do something on here !!! return all_found def print_description( _word_state, _word_description ) : ''' [ Goal ] Print out all the descriptions for the words, which are not found yet. [ Requirements ] Each line should keep the format of 'direction_num : description'. For example, if a word 'BAA' for 'across_0' and a word 'BUS' for 'down_0' are not found yet, then the text like follwing is expected : across_0 : Sheep sound down_0 : Road passenger transport Note : Do not use global variables. Otherwise, you will get penalized. Note : The descriptions only for the words not found yet should be print out. ( Do not print the descriptions for the word which are already found. ) ''' # Do something on here !!! def is_right_choice( _user_choice, _word_description, _word_state ) : right_input = False ''' [ Goal ] Check if an user's choice is correct. [ Requirements ] If an user's choice is in the list of words which are not found yet, 'is_right_choice' function should return 'True'. If an user's choice is not in the list of words which are not found yet, 'is_right_choice' function should return 'False' Note : Do not use global variables. Otherwise, you will get penalized. ''' # Do something on here !!! return right_input def is_right_word( _user_word, _user_choice, _word_list, _word_state ) : right_word = False ''' [ Goal ] Check if an user's input word is correct. [ Requirements ] If an user's input word is in the list of words which are not found yet, 'is_right_word' function should return 'True' and set the word state of the chosen word from 0 to 1. If an user's input word is not in the list of words which are not found yet, 'is_right_word' function should return 'False' Note : Do not use global variables. Otherwise, you will get penalized. Note : Do not forget to set the word state of the word found from 0 to 1. ''' # Do something on here !!! return right_word ################################# # Run of the program print 'Welcome to CS101 Crossword Puzzle!' print '' while not is_all_found(word_state) : canvas.clear() draw_indices( canvas, index_list, cell_size ) draw_horizontal_line( canvas, row_size, cell_size ) draw_vertical_line( canvas, col_size, cell_size ) draw_word_list( canvas, word_list, word_state, cell_size ) print_description( word_state, word_description ) print '' user_choice = raw_input( 'Enter a direction and number : ' ) if is_right_choice( user_choice, word_description, word_state ) : user_word = raw_input( 'Enter a word : ' ) if not is_right_word( user_word, user_choice, word_list, word_state ) : print 'Please, enter a word, correctly!' else : print 'Please, enter a direction and number, correctly!' print '' print 'Game complete!' print '' draw_indices( canvas, index_list, cell_size ) draw_horizontal_line( canvas, row_size, cell_size ) draw_vertical_line( canvas, col_size, cell_size ) draw_word_list( canvas, word_list, word_state, cell_size )
ebfd35ab13d1b55fe3b78f1974a512a1dccb7a4d
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/921 Minimum Add to Make Parentheses Valid.py
1,116
4.21875
4
#!/usr/bin/python3 """ Given a string S of '(' and ')' parentheses, we add the minimum number of parentheses ( '(' or ')', and in any positions ) so that the resulting parentheses string is valid. Formally, a parentheses string is valid if and only if: It is the empty string, or It can be written as AB (A concatenated with B), where A and B are valid strings, or It can be written as (A), where A is a valid string. Given a parentheses string, return the minimum number of parentheses we must add to make the resulting string valid. Example 1: Input: "())" Output: 1 Example 2: Input: "(((" Output: 3 Example 3: Input: "()" Output: 0 Example 4: Input: "()))((" Output: 4 Note: S.length <= 1000 S only consists of '(' and ')' characters. """ c_ Solution: ___ minAddToMakeValid S: s..) __ i.. """ stk """ ret 0 stk # list ___ s __ S: __ s __ "(": stk.a..(s) ____ __ stk: stk.p.. ) ____ ret += 1 ret += l..(stk) r.. ret
33cabbc93635f4f0ab7d0c877f8e1c979d542c47
JoelSchott/MST
/constant_acceleration.py
285
4.15625
4
x_0 = input('What is the initial x? :') v_0 = input('What is the initial velocity? :') a = input('What is the constant acceleration? :') max_x = input('What is the max x? :') zero_x = input("When is x zero? :") def get_position(x, v, a, t): return x + (v*t) + float(1/2)*a*(t**2)
f12d8a32252ec655f8c016e345d440082517b3d3
daniel-reich/ubiquitous-fiesta
/wsCshmu5zkN5BfeAC_17.py
227
3.546875
4
def divisible_by_left(n): s = str(n) return [f(s,i, x) for i, x in enumerate(s)] ​ def f(s, i, x): if i == 0: return False if s[i-1] == '0': return False return int(x) % int(s[i-1]) == 0
e31d64b03e79270c662765ba2c780c401de7c272
huit-sys/progAvanzada
/72.py
581
4.1875
4
# Ejercicio 72 #Una cadena es un palíndromo si es idéntica hacia adelante y hacia atrás. #Por ejemplo, "anna", "civic", "level" y "hannah" son ejemplos de palabras palindrómicas. #Escriba un programa que lea una cadena del usuario y use un bucle para determinar si es o no un palíndromo. #Muestra el resultado, incluido un mensaje de salida significativo. palabra = input('Introduce la palabra: ') palindromo = palabra [::-1] if palindromo == palabra: print('la palabra',palabra, 'es un palindromo') else: print('la plabra',palabra, 'no es un palindromo')
4ea3ebaf35be9ca8fb38fdae52a9abdb0ddf693b
2q45/Python-crash-course
/7-9.py
392
3.734375
4
import random Poll = [] active = True while active: prompt = "Enter your name Here" name = input("Input your name for the lottery") age = input("input your age for the lottery") if age < 69: print("You're not poggers enough") else: Poll.append(name) if active == False: def winners(name): random.random(name) return name print(name)
0d19a9af0227f60dcec5317c8c4d4ecf9869b43c
jimhendy/AoC
/2020/06/a.py
750
3.828125
4
import os def run(inputs): total = 0 data = set() # Use a set to store the answers from each group for line in inputs.split(os.linesep): if not len(line.strip()): # Reaching an empty line means a new group so add the current total and reset total += len(data) data = set() else: for letter in list(line.strip()): # Add each letter to the current group's answers # As data is a set we don't have to worry about duplicates data.add(letter) # We may still have some un-counted results for the final group if the input did not end on a blank line, otherwise we will add zero below total += len(data) return total
464cfcccd48b3597164737d4478f559ca070fbb3
hermanschaaf/advent-of-code-2017
/day16.py
1,688
3.625
4
class Circle(object): def __init__(self, values): self.head = 0 self.A = values self.m = len(values) def spin(self, n): self.head = (self.head - n) % self.m def exchange(self, a, b): a = (self.head + a) % self.m b = (self.head + b) % self.m self.A[a], self.A[b] = self.A[b], self.A[a] def partner(self, a, b): ia, ib = self.A.index(a), self.A.index(b) self.A[ia], self.A[ib] = self.A[ib], self.A[ia] def __repr__(self): return "".join(self.A[self.head:self.m] + self.A[0:self.head]) chars = 'abcdefghijklmnop' # chars = 'abcde' cmds = input().strip().split(",") def dance(circle, cmds, iterations=1): seen = {} found = False i = 0 while True: if i >= iterations: break for cmd in cmds: t = cmd[0] if t == 's': n = int(cmd[1:]) circle.spin(n) elif t == 'x': a, b = map(int, cmd[1:].split("/")) circle.exchange(a, b) elif t == 'p': a, b = cmd[1:].split("/") circle.partner(a, b) else: raise Exception("unknown {}".format(cmd)) if not found: v = str(circle) if v in seen: cycle_len = i - seen[v] i += cycle_len * ((iterations - i) // cycle_len) found = True else: seen[v] = i i += 1 return circle circle = Circle(list(chars)) print("Part1:", dance(circle, cmds)) circle = Circle(list(chars)) print("Part2:", dance(circle, cmds, 1000000000))
893cbe38fd79d9136100b2bb3fc77c8b77e3f361
Priyansh-Kedia/MLMastery
/23_identify_outliers.py
3,875
4.1875
4
# An outlier is an observation that is unlike the other observations. # It is rare, or distinct, or does not fit in some way. from numpy.random import seed, randn from numpy import mean, std from matplotlib import pyplot as plt # seed the random number generator seed(1) # generate univariate observations data = 5 * randn(10000) + 50 # summarize print('mean=%.3f stdv=%.3f' % (mean(data), std(data))) plt.plot(data) plt.show() # Standard deviation method data_mean, data_std = mean(data), std(data) # identify outliers cut_off = data_std * 3 lower, upper = data_mean - cut_off, data_mean + cut_off # identify outliers outliers = [x for x in data if x < lower or x > upper] print('Identified outliers: %d' % len(outliers)) # remove outliers outliers_removed = [x for x in data if x >= lower and x <= upper] print('Non-outlier observations: %d' % len(outliers_removed)) plt.plot(outliers_removed) plt.show() # Interquartile Range Method # The IQR is calculated as the difference between the 75th and the 25th # percentiles of the data and defines the box in a box and whisker plot. #The IQR can be used to identify outliers by defining limits on the sample # values that are a factor k of the IQR below the 25th percentile or above # the 75th percentile. The common value for the factor k is the value 1.5. # A factor k of 3 or more can be used to identify values that are extreme # outliers or “far outs” when described in the context of box and whisker plots. from numpy import percentile # seed the random number generator seed(1) # generate univariate observations data = 5 * randn(10000) + 50 # calculate interquartile range q25, q75 = percentile(data, 25), percentile(data, 75) iqr = q75 - q25 print('Percentiles: 25th=%.3f, 75th=%.3f, IQR=%.3f' % (q25, q75, iqr)) # calculate the outlier cutoff cut_off = iqr * 1.5 lower, upper = q25 - cut_off, q75 + cut_off # identify outliers outliers = [x for x in data if x < lower or x > upper] print('Identified outliers: %d' % len(outliers)) # remove outliers outliers_removed = [x for x in data if x >= lower and x <= upper] print('Non-outlier observations: %d' % len(outliers_removed)) # Automatic outlier detection # The local outlier factor, or LOF for short, is a technique that attempts to harness # the idea of nearest neighbors for outlier detection. Each example is assigned a scoring # of how isolated or how likely it is to be outliers based on the size of its local neighborhood. # Those examples with the largest score are more likely to be outliers. from pandas import read_csv from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_absolute_error from sklearn.neighbors import LocalOutlierFactor # load the dataset df = read_csv('boston-housing-dataset.csv', header=None) # retrieve the array data = df.values # split into input and output elements X, y = data[:, :-1], data[:, -1] # summarize the shape of the dataset print(X.shape, y.shape) # split into train and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=1) # summarize the shape of the train and test sets print(X_train.shape, X_test.shape, y_train.shape, y_test.shape) model = LinearRegression() model.fit(X_train, y_train) pred = model.predict(X_test) mae = mean_absolute_error(y_test, pred) print('MAE: %.3f' % mae) lof = LocalOutlierFactor() yhat = lof.fit_predict(X_train) # select all rows that are not outliers mask = yhat != -1 X_train, y_train = X_train[mask, :], y_train[mask] # summarize the shape of the updated training dataset print(X_train.shape, y_train.shape) # fit the model model = LinearRegression() model.fit(X_train, y_train) # evaluate the model yhat = model.predict(X_test) # evaluate predictions mae = mean_absolute_error(y_test, yhat) print('MAE: %.3f' % mae)
9445f1b97dfaff8cfab0c3d5b4d567fa14e539d1
EduardoCastro15/Algoritmos-Geneticos
/Practicas/Pracs/GENETIC_ALGORITHMS/SimpleAG/GA_Project.py
35,056
3.640625
4
import random from tkinter import * from tkinter import Checkbutton, Entry, messagebox import matplotlib.pyplot as plt from sympy import * from sympy.combinatorics.graycode import bin_to_gray import math import cmath class GUI(): def partition(self, arr, low, high): i = (low-1) # index of smaller element pivot pivot = arr[high] for j in range(low , high): # If current element is smaller than the pivot if arr[j] < pivot: # increment index of smaller element i = i+1 arr[i],arr[j] = arr[j],arr[i] arr[i+1],arr[high] = arr[high],arr[i+1] return (i+1) def quickSort(self, arr,low,high): if low < high: # pi is partitioning index, arr[p] is now at right place pi = self.partition(arr,low,high) # Separately sort elements before partition and after partition self.quickSort(arr, low, pi-1) self.quickSort(arr, pi+1, high) #This function transform a list in a string reading each data in the list def listToString(self, s): str1 = '' for ele in s: str1 += str(ele) return str1 #This function transform a list in a string reading each data in the list separating by a comma and a space #each data with the next to avoid confusion when the text is showed def listToString4Real(self, s): str1 = '' for ele in s: str1 += str(ele)+', ' return str1 #This function give us the size of the list we need based on the range that user specified def cuentaBits(self, n): aux = 0 while n>0: n = n>>1 aux+=1 return aux #Given a number n returns a string with n zeros def sizeZero(self, n): s = '' while n > 0: s += '0' n -= 1 return s #Given a list L with elements type int returns a list with elements type binary string def int2Bin(self, L): L1 = [] aux = 0 cad = '' for i in L: if aux < len(bin(i).split('0b')[1]): aux = len(bin(i).split('0b')[1]) for i in L: cad = self.sizeZero(aux-len(bin(i).split('0b')[1])) + bin(i).split('0b')[1] L1.append(cad) return L1 #This function apply a sin(x) function to each data in the list def sinFunction(self, L): aux = 0 for i in L: aux = math.sin(i) self.L2.append(aux) return self.L2 #This function apply a sin^2(x) function to each data in the list def sin2Function(self, L): aux = 0 for i in L: aux = pow(math.sin(i), 2) self.L2.append(aux) return self.L2 #This function apply a cos(x) function to each data in the list def cosFunction(self, L): aux = 0 for i in L: aux = math.cos(i) self.L2.append(aux) return self.L2 #This function apply a cos^2(x) function to each data in the list def cos2Function(self, L): aux = 0 for i in L: aux = pow(math.cos(i), 2) self.L2.append(aux) return self.L2 #This function read the entry line that user write to generate a new fit function def fitFunction(self, L): aux = 0 try: for x in L: aux = eval(self.fitFunc.get()) self.L2.append(aux) except: self.info1 = messagebox.showerror('Ooops!', 'That kind of instruction is not supported! :(') self.root.destroy() return self.L2 #This function generate randomly data in type binary def binData(self, r, q1): self.r = int(r) self.q1 = int(q1) self.r = self.cuentaBits(self.r) #print(self.r) for _ in range(self.q1): for _ in range(self.r): if(random.random()>0.5): self.L.append(1) else: self.L.append(0) self.L1.append(self.listToString(self.L)) self.L.clear() self.info1 = messagebox.showinfo('Binary Data', self.L1) for i in self.L1: self.valInt = int(i, 2) self.L.append(self.valInt) self.info1 = messagebox.showinfo('Binary Int Representation Data', self.L) #plt.plot(self.sinFunction(self.L), 'c--v') self.quickSort(self.L,0,len(self.L)-1) #plt.plot(self.sinFunction(self.L), 'g--^') self.L1.clear() self.L1 = self.int2Bin(self.L).copy() #plt.figure(1) self.info2 = messagebox.showinfo('Binary Sorted Data', self.L1) self.info2 = messagebox.showinfo('Binary Sorted Int Representation Data', self.L) return self.L #This function generate randomly data in type gray code def grayData(self, r, q): self.r = int(r) self.q1 = int(q) self.r = self.cuentaBits(self.r) #print(self.r) for _ in range(self.q1): for _ in range(self.r): if(random.random()>0.5): self.L.append(1) else: self.L.append(0) self.L1.append(self.listToString(self.L)) self.L.clear() for i in self.L1: self.valGray = bin_to_gray(i) self.L.append(self.valGray) # print('Binary', self.L1) # print('Gray code', self.L) self.info1 = messagebox.showinfo('Binary Data', self.L1) for i in self.L1: self.valInt = int(i, 2) self.L2.append(self.valInt) self.info1 = messagebox.showinfo('Binary Int Representation Data', self.L2) self.L1.clear() for i in self.L: self.valInt = int(i, 2) self.L1.append(self.valInt) #plt.plot(self.L1, 'r--d') self.quickSort(self.L1,0,len(self.L1)-1) self.L.clear() self.L = self.int2Bin(self.L1).copy() self.info2 = messagebox.showinfo('Gray Code Data', self.L) self.info2 = messagebox.showinfo('Gray Code Int Representation Data', self.L1) return self.L1 #This function execute the Roulette Selection Operation def roulOp(self, L): counter = 0 prob = 0 L1 = L.copy() for i in L: counter += i print(counter) for i in L: prob = i/counter self.L3.append(prob) counter = 0 for i in self.L3: counter += i self.L5.append(counter) counter = 0 for i in self.L5: counter += i print(self.L3) print(self.L5) print(counter) self.L3.clear() ran = 0 print('----------------------------------') tam = len(L) while len(self.L3) < tam: ran = random.uniform(0, counter) for i in self.L5: if i < ran: print(i) print(ran) print('--------------------------------------') print() else: print(self.L5.index(i)) print() self.L3.append(L[self.L5.index(i)]) L.pop(self.L5.index(i)) self.L5.remove(i) print(ran) print('--------------------------------------') print('Esto es la copia de L en roulOp') print(L1) print('Esto es L4 en roulOp') print(self.L4) print() print('Esto es el mensaje de roulOp') print(self.L3) for i in self.L3: self.L5.append(L1.index(i)) print() print('Esto es el retorno de roulOp') print(self.L5) return self.L5 #Tournament Selection Operator def tournament(self, L): aux = 0 aux1 = 0 L1 = L.copy() print('Esto es L') print(L) random.shuffle(L) print('Esto es shuffle(L)') print(L) for _ in range(len(L)): aux = random.choice(L) aux1 = random.choice(L) if float(aux) < float(aux1): self.L3.append(aux1) else: self.L3.append(aux) print('Esto es el mensaje de Tournament') print(self.L3) for i in self.L3: self.L5.append(L1.index(i)) print() print('Esto es el retorno de Tournament') print(self.L5) return self.L5 #Probabilistic Tournament Selection def tournamentProb(self, L): aux = 0 aux1 = 0 L1 = L.copy() print('Esto es L') print(L) random.shuffle(L) print('Esto es shuffle(L)') print(L) for _ in range(len(L)): aux = random.choice(L) aux1 = random.choice(L) if(random.random()>0.5): if float(aux) < float(aux1): self.L3.append(aux1) else: self.L3.append(aux) else: if float(aux) > float(aux1): self.L3.append(aux1) else: self.L3.append(aux) print('Esto es el mensaje de TournamentProb') print(self.L3) for i in self.L3: self.L5.append(L1.index(i)) print() print('Esto es el retorno de TournamentProb') print(self.L5) return self.L5 #1 Point Mating Operator def point(self, Li, Ls, n): aux = [] aux1 = [] L = [] num = random.randint(1, len(Li)-1) print(num) print(Li) print(Ls) if n > 0: for i in range(num): print(i) aux.append(Li[i]) aux1.append(Ls[i]) Li.reverse() Ls.reverse() for i in range(num): Li.pop() Ls.pop() print(aux) print(aux1) Li.reverse() Ls.reverse() for i in Li: aux1.append(i) for i in Ls: aux.append(i) print(aux) print(aux1) return self.point(aux, aux1, n-1) else: L.append(self.listToString(Li)) L.append(self.listToString(Ls)) return L #This Function choose the pairs that will mating def matPoint(self, Li, Ls, n): L = [] #From Li we take the index for each pair that will mating for i in range(0, len(Li), 2): print('Esto es el valor de i en Li') print(Li[i]) print('Esto es el valor de i+1 en Li') print(Li[i+1]) print('Esto es el valor de de Ls[Li[i]]') print(Ls[int(Li[i])]) print('Esto es el valor de Ls[Li[i+1]]') print(Ls[int(Li[i+1])]) L.extend(self.point(list(Ls[int(Li[i])]), list(Ls[int(Li[i+1])]), n)) print(L) for i in L: self.valInt = int(i, 2) self.L4.append(self.valInt) return L #With this function we can make the insertion and displacement mutation def Insert(self, L, n): aux = 0 aux1 = 0 aux2 = 0 if random.random() < 0.3: while n > 0: aux = random.randint(0, len(L)-1) aux1 = L[aux] L.pop(aux) aux2 = random.randint(0, len(L)-1) while aux2 == aux: aux2 = random.randint(0, len(L)-1) L.insert(aux2, aux1) print(L) n -= 1 return L else: return L def mutInsert(self, L, n): L1 = [] L2 = [] valInt = 0 for i in L: L1 = self.Insert(list(i), n).copy() print('Esto es L1 de la función mutInsert') print(L1) L2.append(self.listToString(L1)) L1.clear() for i in L2: valInt = int(i, 2) self.L4.append(valInt) return L2 #Reciprocal Exchange Mutation def Exchange(self, L): aux = 0 aux1 = 0 aux2 = 0 aux3 = 0 if random.random() < 0.3: aux = random.randint(0, len(L)-1) aux1 = L[aux] L.pop(aux) aux2 = random.randint(0, len(L)-1) while aux2 == aux: aux2 = random.randint(0, len(L)-1) aux3 = L[aux2] L.pop(aux2) L.insert(aux2, aux1) L.insert(aux, aux3) print('Esto es L en if') print(L) return L else: print('Esto es L en else') print(L) return L def mutExchange(self, L): L1 = [] L2 = [] valInt = 0 for i in L: L1 = self.Exchange(list(i)).copy() print('Esto es L1 de la función mutExchange') print(L1) L2.append(self.listToString(L1)) L1.clear() for i in L2: valInt = int(i, 2) self.L4.append(valInt) return L2 #This function permits that the program know what kind of mutation operator will be use in the GA def mutOP(self, L, n): aux = random.randint(0, len(L)-2) if self.mutType.get()==1: print('Esto es L en mutType') print(self.L) self.L.clear() print('Esto es L1 en mutType') print(self.L1) self.L1.clear() self.L = self.mutInsert(L, 1).copy() print('Esto es L2 en mutOP') print(self.L2) self.L2.clear() print('Esto es L3 en mutOp') print(self.L3) self.L3.clear() print('Esto es L4 en mutOP') plt.plot(self.L4, 'c--*') print(self.L4) self.L4.clear() print('Esto es L5 en mutOp') print(self.L5) self.L5.clear() self.info1 = messagebox.showinfo('Insertion Mutation Generated Data', self.L) plt.title('Genetic Algorithm') plt.legend(('Original Data', 'Fitness Data', 'Selected Parents', 'Generated Sons', 'Mutated Sons'), prop = {'size': 10}, loc='upper left') plt.show() self.info1 = messagebox.showinfo('New Generation', 'Click next') self.newGen(self.L, n-1) elif self.mutType.get()==2: print('Esto es L en mutType') print(self.L) self.L.clear() print('Esto es L1 en mutType') print(self.L1) self.L1.clear() self.L = self.mutInsert(L, aux).copy() print('Esto es L2 en mutOP') print(self.L2) self.L2.clear() print('Esto es L3 en mutOp') print(self.L3) self.L3.clear() print('Esto es L4 en mutOP') plt.plot(self.L4, 'c--*') print(self.L4) self.L4.clear() print('Esto es L5 en mutOp') print(self.L5) self.L5.clear() self.info1 = messagebox.showinfo('Displacement Mutation Generated Data', self.L) plt.title('Genetic Algorithm') plt.legend(('Original Data', 'Fitness Data', 'Selected Parents', 'Generated Sons', 'Mutated Sons'), prop = {'size': 10}, loc='upper left') plt.show() self.info1 = messagebox.showinfo('New Generation', 'Click next') self.newGen(self.L, n-1) elif self.mutType.get()==3: print('Esto es L en mutType') print(self.L) self.L.clear() print('Esto es L1 en mutType') print(self.L1) self.L1.clear() self.L = self.mutExchange(L).copy() print('Esto es L2 en mutOP') print(self.L2) self.L2.clear() print('Esto es L3 en mutOp') print(self.L3) self.L3.clear() print('Esto es L4 en mutOP') plt.plot(self.L4, 'c--*') print(self.L4) self.L4.clear() print('Esto es L5 en mutOp') print(self.L5) self.L5.clear() self.info1 = messagebox.showinfo('Reciprocal Mutation Generated Data', self.L) plt.title('Genetic Algorithm') plt.legend(('Original Data', 'Fitness Data', 'Selected Parents', 'Generated Sons', 'Mutated Sons'), prop = {'size': 10}, loc='upper left') plt.show() self.info1 = messagebox.showinfo('New Generation', 'Click next') self.newGen(self.L, n-1) else: self.info1 = messagebox.showerror('No Mutation Operator Selected!', 'Select a Mutation Operator') #This function permits that the program know what kind of pairing operator will be use in the GA def matingOp(self, L, n): aux = 0 if self.matingType.get()==1: if len(self.L) == 0: self.L3 = self.matPoint(L, self.L1, 1).copy() else: self.L3 = self.matPoint(L, self.L, 1).copy() print('Esto es L2 en matingOP') print(self.L2) self.L2.clear() print('Esto es L3 en matingOp') print(self.L3) print('Esto es L4 en matingOP') plt.plot(self.L4, 'y--^') print(self.L4) self.L4.clear() print('Esto es L5 en matingOp') print(self.L5) self.L5.clear() self.info1 = messagebox.showinfo('1 Point Mating Generated Data', self.L3) self.mutOP(self.L3, n) elif self.matingType.get()==2: if len(self.L) == 0: self.L3 = self.matPoint(L, self.L1, 2).copy() else: self.L3 = self.matPoint(L, self.L, 2).copy() print('Esto es L2 en matingOP') print(self.L2) self.L2.clear() print('Esto es L3 en matingOp') print(self.L3) print('Esto es L4 en matingOP') plt.plot(self.L4, 'y--^') print(self.L4) self.L4.clear() print('Esto es L5 en matingOp') print(self.L5) self.L5.clear() self.info1 = messagebox.showinfo('2 Points Mating Generated Data', self.L3) self.mutOP(self.L3, n) elif self.matingType.get()==3: aux = random.randint(1, len(L)-2) if len(self.L) == 0: self.L3 = self.matPoint(L, self.L1, aux).copy() else: self.L3 = self.matPoint(L, self.L, aux).copy() print('Esto es L2 en matingOP') print(self.L2) self.L2.clear() print('Esto es L3 en matingOp') print(self.L3) print('Esto es L4 en matingOP') plt.plot(self.L4, 'y--^') print(self.L4) self.L4.clear() print('Esto es L5 en matingOp') print(self.L5) self.L5.clear() self.info1 = messagebox.showinfo('Uniform Mating Generated Data for '+str(aux)+' Points', self.L3) self.mutOP(self.L3, n) else: self.info1 = messagebox.showerror('No Mating Operator Selected!', 'Select a Mating Operator') #This function permits that the program know what kind of selection operator will be use in the GA def selecOp(self, L, n): if self.selecType.get()==1: self.L2 = self.roulOp(L).copy() self.info1 = messagebox.showinfo('Roulette Selection', self.listToString4Real(self.L3)) print('Esto es L en selecOp') print(self.L) print('Esto es L1 en selecOp') print(self.L1) print('Esto es L2 en selecOp') print(self.L2) print('Esto es L3 en selecOp') print(self.L3) plt.plot(self.L3, 'g--v') self.L3.clear() print('Esto es L4 en selecOp') print(self.L4) self.L4.clear() self.matingOp(self.L2, n) elif self.selecType.get()==2: self.L2 = self.tournament(L).copy() self.info1 = messagebox.showinfo('Tournament Selection', self.listToString4Real(self.L3)) print('Esto es L en selecOp') print(self.L) print('Esto es L1 en selecOp') print(self.L1) print('Esto es L2 en selecOp') print(self.L2) print('Esto es L3 en selecOp') print(self.L3) plt.plot(self.L3, 'g--v') self.L3.clear() print('Esto es L4 en selecOp') print(self.L4) self.L4.clear() self.matingOp(self.L2, n) elif self.selecType.get()==3: self.L2 = self.tournamentProb(L).copy() self.info1 = messagebox.showinfo('Probabilistic Tournament Selection', self.listToString4Real(self.L3)) print('Esto es L en selecOp') print(self.L) print('Esto es L1 en selecOp') print(self.L1) print('Esto es L2 en selecOp') print(self.L2) print('Esto es L3 en selecOp') print(self.L3) plt.plot(self.L3, 'g--v') self.L3.clear() print('Esto es L4 en selecOp') print(self.L4) self.L4.clear() self.matingOp(self.L2, n) else: self.info1 = messagebox.showerror('No Selection Operator Selected!', 'Select a Selection Operator') #This function permits that the program know what kind of fit function will be use to implement in the GA def function(self, L, n): if self.fitFun.get()==1: self.L4 = self.sinFunction(L).copy() plt.plot(self.L4, 'r--d') self.info1 = messagebox.showinfo('Sin(x) Function of Generated Data', self.listToString4Real(self.L4)) print('Esto es L en function') print(self.L) print('Esto es L1 en function') print(self.L1) print('Esto es L2 en function') print(self.L2) self.L2.clear() print('Esto es L3 en function') print(self.L3) self.L3.clear() print('Esto es L4 en function') print(self.L4) self.selecOp(self.L4, n) elif self.fitFun.get()==2: self.L4 = self.sin2Function(L).copy() plt.plot(self.L4, 'r--d') self.info1 = messagebox.showinfo('Sin^2(x) Function of Generated Data', self.listToString4Real(self.L4)) print('Esto es L en function') print(self.L) print('Esto es L1 en function') print(self.L1) print('Esto es L2 en function') print(self.L2) self.L2.clear() print('Esto es L3 en function') print(self.L3) self.L3.clear() print('Esto es L4 en function') print(self.L4) self.selecOp(self.L4, n) elif self.fitFun.get()==3: self.L4 = self.cosFunction(L).copy() plt.plot(self.L4, 'r--d') self.info1 = messagebox.showinfo('Cos(x) Function of Generated Data', self.listToString4Real(self.L4)) print('Esto es L en function') print(self.L) print('Esto es L1 en function') print(self.L1) print('Esto es L2 en function') print(self.L2) self.L2.clear() print('Esto es L3 en function') print(self.L3) self.L3.clear() print('Esto es L4 en function') print(self.L4) self.selecOp(self.L4, n) elif self.fitFun.get()==4: self.L4 = self.cos2Function(L).copy() plt.plot(self.L4, 'r--d') self.info1 = messagebox.showinfo('Cos^2(x)Function of Generated Data', self.listToString4Real(self.L4)) print('Esto es L en function') print(self.L) print('Esto es L1 en function') print(self.L1) print('Esto es L2 en function') print(self.L2) self.L2.clear() print('Esto es L3 en function') print(self.L3) self.L3.clear() print('Esto es L4 en function') print(self.L4) self.selecOp(self.L4, n) elif self.fitFunc.get() == '': self.info1 = messagebox.showerror('No Fit Function Specified!', 'Select or write a fit function') else: self.L4 = self.fitFunction(L).copy() plt.plot(self.L4, 'r--d') self.txt = self.fitFunc.get() + ' Function of Generated data' self.info1 = messagebox.showinfo(self.txt, self.listToString4Real(self.L4)) print('Esto es L en function') print(self.L) print('Esto es L1 en function') print(self.L1) print('Esto es L2 en function') print(self.L2) self.L2.clear() print('Esto es L3 en function') print(self.L3) self.L3.clear() print('Esto es L4 en function') print(self.L4) self.selecOp(self.L4, n) def newGen(self, L, n): valInt = 0 if n > 0: L1 = [] for i in L: valInt = int(i, 2) L1.append(valInt) plt.plot(L1, 'b--o') self.function(L1, n) else: self.info1 = messagebox.showinfo('End of Genetic Algorithm') #This function permits that the program knows what kind of data will be use to work def dataSelec(self): if self.dataType.get()==1: self.L3 = self.binData(self.ran.get(), self.q.get()).copy() plt.plot(self.L3, 'b--o') print('Esto es L en dataSelec') print(self.L) self.L.clear() print('Esto es L1 en dataSelec') print(self.L1) print('Esto es L2 en dataSelec') print(self.L2) self.L2.clear() self.function(self.L3, int(self.generations.get())) elif self.dataType.get()==2: self.L3 = self.grayData(self.ran.get(), self.q.get()).copy() plt.plot(self.L3, 'b--o') print('Esto es L en dataSelec') print(self.L) print('Esto es L1 en dataSelec') print(self.L1) self.L1.clear() print('Esto es L2 en dataSelec') print(self.L2) self.L2.clear() self.function(self.L3, int(self.generations.get())) else: self.info1 = messagebox.showerror('No Data Type Selected!', 'Select a Data Type') def reset(self): self.txt = '' self.L = [] self.L1 = [] self.L2 = [] self.L3 = [] self.L4 = [] self.L5 = [] self.dataType.set(None) self.fitFun.set(0) self.selecType.set(None) self.matingType.set(None) self.mutType.set(None) #GUI function to generate a new window for users def __init__(self): #GUI Specs self.root = Tk() self.root.title('Genetic Algorithm Implementation') self.root.iconbitmap('C:/Users/irvin/OneDrive/Documentos/ESCOM/GENETIC_ALGORITHMS/SimpleAG/pythonIcon.ico') self.frame = Frame() self.frame.pack() self.frame.config(bd=20) #Range between 0 and user entry data self.lblRange = Label(self.frame, text = 'Insert the limit range of random numbers!') self.lblRange.grid(row=0, column=0, sticky='N') self.ran = Entry(self.frame) self.ran.grid(row=1, column=0, sticky='N') #Quantity of random data self.lblQuantity = Label(self.frame, text = 'Insert how many random numbers you want!') self.lblQuantity.grid(row=2, column=0, sticky='N') self.q = Entry(self.frame) self.q.grid(row=3, column=0, sticky='N') #Quantity of random data self.lblQuantity = Label(self.frame, text = 'Insert how many generations you want!') self.lblQuantity.grid(row=4, column=0, sticky='N') self.generations = Entry(self.frame) self.generations.grid(row=5, column=0, sticky='N') #Data type self.lblDataType = Label(self.frame, text="Select data type you want to show!") self.lblDataType.grid(row=6, column=0, sticky='N') self.dataType = IntVar() self.binButton = Radiobutton(self.frame, text='Binary', variable = self.dataType, value = 1) self.binButton.grid(row=7, column=0, sticky='W') self.grayButton = Radiobutton(self.frame, text='Gray Code', variable = self.dataType, value = 2) self.grayButton.grid(row=8, column=0, sticky='W') #Fit Function self.lblFunction = Label(self.frame, text='Select defined fitness function below...') self.lblFunction.grid(row=0, column=1, sticky='N') self.fitFun = IntVar() self.sinButton = Radiobutton(self.frame, text='sin(x)', variable = self.fitFun, value = 1) self.sinButton.grid(row=1, column=1, sticky='N') self.sin2Button = Radiobutton(self.frame, text='sin^2(x)', variable = self.fitFun, value = 2) self.sin2Button.grid(row=2, column=1, sticky='N') self.cosButton = Radiobutton(self.frame, text='cos(x)', variable = self.fitFun, value = 3) self.cosButton.grid(row=3, column=1, sticky='N') self.cos2Button = Radiobutton(self.frame, text='cos^2(x)', variable = self.fitFun, value = 4) self.cos2Button.grid(row=4, column=1, sticky='N') self.lblFunction2 = Label(self.frame, text='Or you can introduce your own function in Python syntax ') self.lblFunction2.grid(row=5, column=1, sticky='N') self.fitFunc = Entry(self.frame) self.fitFunc.grid(row=6, column=1, sticky='N') self.lblFunction2 = Label(self.frame, text='Warning! Roulette Selection is inestable if your fitness function \ngenerates negative numbers or zeros') self.lblFunction2.grid(row=8, column=1, sticky='N') #Selection Operators self.lblSelec = Label(self.frame, text = 'Select the selection method that you want to use') self.lblSelec.grid(row=0, column=2, sticky='N') self.selecType = IntVar() self.roulButton = Radiobutton(self.frame, text='Roulette Wheel Selection', variable = self.selecType, value = 1) self.roulButton.grid(row=1, column=2, sticky='W') self.stocButton = Radiobutton(self.frame, text='Tournament Selection', variable = self.selecType, value = 2) self.stocButton.grid(row=1, column=2, sticky='E') self.otherButton = Radiobutton(self.frame, text='Probabilistic Tournament', variable = self.selecType, value = 3) self.otherButton.grid(row=2, column=2, sticky='W') #Mating Operators self.lblPair = Label(self.frame, text = 'Select the Mating method that you want to use') self.lblPair.grid(row=3, column=2, sticky='N') self.matingType = IntVar() self.pointButton = Radiobutton(self.frame, text='1 Point', variable = self.matingType, value = 1) self.pointButton.grid(row=4, column=2, sticky='W') self.npointsButton = Radiobutton(self.frame, text='2 Points', variable = self.matingType, value = 2) self.npointsButton.grid(row=4, column=2, sticky='E') self.uniformButton = Radiobutton(self.frame, text='Uniform', variable = self.matingType, value = 3) self.uniformButton.grid(row=5, column=2, sticky='W') #Mutation Operators self.lblMutation = Label(self.frame, text = 'Select the mutation method that you want to use') self.lblMutation.grid(row=6, column=2, sticky='N') self.mutType = IntVar() self.insertButton = Radiobutton(self.frame, text='Insertion', variable = self.mutType, value = 1) self.insertButton.grid(row=7, column=2, sticky='W') self.dispButton = Radiobutton(self.frame, text='Displacement', variable = self.mutType, value = 2) self.dispButton.grid(row=7, column=2, sticky='E') self.exchangeButton = Radiobutton(self.frame, text='Reciprocal Exchange', variable = self.mutType, value = 3) self.exchangeButton.grid(row=8, column=2, sticky='W') #Start and Finish of Program self.b1 = Button(self.frame, text = 'Go!', command = lambda: self.dataSelec()) self.b1.grid(row=10, column=2, pady=5) self.b2 = Button(self.frame, text = 'Exit', command = self.root.destroy) self.b2.grid(row=10, column=2, pady=5, sticky='E') self.b3 = Button(self.frame, text = 'Reset', command = lambda: self.reset()) self.b3.grid(row=10, column=0, pady=5, sticky='N') #Miscellaneous data self.txt = '' self.L = [] self.L1 = [] self.L2 = [] self.L3 = [] self.L4 = [] self.L5 = [] #Linecode to keep open the window while program is executing self.root.mainloop() #New instance of a GUI() function to start the execution of program gui = GUI()
ca68570c93575630df409f216e5b26235bd53721
harshraijiwala/python-
/quick.py
669
3.734375
4
def partition(a,start,end): pivot = a[end] pindex=start for i in range(start, end): if a[i] <= pivot: t=a[pindex] a[pindex] = a[i] a[i]=t pindex = pindex+1 t = a[pindex] a[pindex] = pivot a[end] = t print(a) print("pivot") print(pivot) print("pindex") print(pindex) return pindex def quicksort(a): last = len(a) - 1 first = 0 qsorting(a,first,last) def qsorting(a,first,last): if first<last: split_half=partition(a,first,last) print (a) qsorting(a,first,split_half-1) print(a) qsorting(a,split_half+1,last) print(a) a=[12,3,5,6,44,32,20,98,202, 2 , 345,50,7,87,59] quicksort(a) print("\n") print(a)
472acaa67e05ce05d20d85d1d1815d18a93989f3
Mahendran-Nadesan/LoLStatsAnal
/tryexcept_test.py
618
3.84375
4
# Test script for try...except ##def main(name, mydict): ## print "Checking if data exists..." ## try: ## is_data(name, mydict) ## except: ## print "Not found..." ## ## ##def is_data(name, mydict): ## if name in mydict: ## print "Name found!" ## ## ## ##x = {} ##x['a'] = 3 ##main('b', x) ##x = {} ##x['a'] = {} ##x['a']['1'] = 0 ##x['a']['2'] = 0 ## ##for i in x['a'].keys(): ## x['a'][i] = 1 a = 2 try: print "stuff" print a x = a print x x = None b = c x = a print x except: print "no c" print "more no c" print "This is a: ", a
8b473ccb6315120ca87783d87e0ebfda07f42030
wwtang/code02
/wordcount3.py
2,308
4.1875
4
""" The problem in you code: 1, you read the whole file one time, that will be slow for the large file 2, you have another method to sort the dict by its values 3, you do not have the clear train of thought Here is the train of thought(algorithm) first, do the base, derive a dict from the file secondly, define the two functions, so in you future program, remember how to get the dict from the file """ import sys import operator # derive the sorted word_count_dict from the file def word_count_dict(filename): try: input_file = open(filename,"r") except IOError: print "could not open the file" sys.exit() word_count = {} for line in input_file: words = line.split() # Special check for the fisrt word in the file for word in words: word = word.lower() if not word in word_count: word_count[word] = 1 else: word_count[word] +=1 input_file.close() return word_count # Print the word_count _dict XXXXXReturn the sorted dict def print_count(filename): word_dict = word_count_dict(filename) words = sorted(word_dict.keys()) # create an index of dict, but the dict not sorted, so loop as the index and print corresponding values for item in words: print item, word_dict[item] # used for sorted by dict values def get_value(tuples): return tuples[1] def top_count(filename): word_dict = word_count_dict(filename) #word_dict.item() concert the dict into a list of tuple # sorted_word = sorted(word_dict.item(), key= get_value, reverse=True) # for word in sroted_word[:20]: # print word, sorted_word[word] sorted_word = sorted(word_dict.iteritems(), key=operator.itemgetter(1), reverse=True) for item in sorted_word: print item[0], item[1] def main(): if len(sys.argv) != 3: print "usage: python wordcount.py {--count|--topcount} \"filename\" " sys.exit(1) option = sys.argv[1] filename = sys.argv[2] if option == "--count": print_count(filename) elif option == "--topcount": top_count(filename) else: print "unkonwn " + option sys.exit(1) if __name__ == "__main__": main()
fb749aea8930eca69d3ce510e4276edf91a2ae24
happiness11/Twitter_Api
/fridaychallange.py
2,035
4.125
4
// #friday challange solution // https://richardadalton.github.io/HTML_Notes/practical_python/file_io/07_walkthrough_quiz_game.html def show_menu(): print("Menu") print() print("1. Add a person") print("2. View People") print("3. Stats") print("4. Exit") option = input("Enter Option\n>") return option def add_a_person(): first_name = input("Enter first name: ") last_name = input("Enter last name: ") age = input("Enter age: ") team = input("Enter team: ") line = first_name + "," + last_name + "," + age + "," + team + "\n" with open("people.txt", "a") as people_file: people_file.write(line) def load_people(): people = [] with open("people.txt", "r") as people_file: lines = people_file.read().splitlines() for line in lines: fields = line.split(",") people.append(fields) return people def view_people(): people = load_people() print("List Of People") for person in people: print ("{1}, {0} ({2}), Team: {3}".format(person[0], person[1], person[2], person[3])) def view_stats(): people = load_people() team_lists = {} total_age = 0 for person in people: total_age += int(person[2]) list = team_lists.get(person[3], []) list.append(person) team_lists[person[3]] = list average_age = total_age / len(people) print("The number of people is {0}".format(len(people))) print("The average age is {0}".format(average_age)) for team, players in team_lists.items(): print(team) print(players) def program_loop(): while True: option = show_menu() if option == "1": add_a_person() elif option == "2": view_people() elif option == "3": view_stats() elif option == "4": break else: print("Invalid Option") program_loop()
e16ed5cbb254b1c179470e91814aa2b1fc7773ab
minhhoangbui/CEA_Internship
/training/neural_network.py
2,812
3.578125
4
import numpy as np import random # not done def sigmoid(z): return 1.0 / (1.0 + np.exp(-z)) def sigmoid_prime(z): return sigmoid(z) / (1 - sigmoid(z)) class Network(): """ A self-defined class which helps to initialize Neural network """ def __init__(self, size): self.num_layers = len(size) self.size = size self.biases = [np.random.rand(y, 1) for y in size[1:]] self.weights = [np.random.rand(j, i) for i, j in zip(size[:-1], size[1:])] def feed_forward(self, a): for b, w in zip(self.biases, self.weights): a = np.dot(w, a) + b return a def SGD(self, training_data, epochs, mini_batch_size, eta, test_data=None): """ Choose the mini batch for each parameter based on Stochastic Gradient Descent :param training_data: numpy.ndarray A list of training data given to the neural network :param epochs: int :param mini_batch_size: int Size of each batch in one update of parameters :param eta: float Learning rate of Gradient Descent :param test_data: A list of test data for performance evaluation :return: """ if test_data: n_test = len(test_data) n_training = len(training_data) for i in xrange(epochs): random.shuffle(training_data) mini_batches = [training_data[k:k + mini_batch_size] for k in xrange(0, n, mini_batch_size)] for mini_batch in mini_batches: self.update_mini_batch(mini_batch=mini_batch, eta=eta) if test_data: print "Epoch {0}: {1} / {2}".format(i, self.evaluate(test_data) / n_test) else: print "Epoch {0} complete".format(i) def update_mini_batch(self, mini_batch, eta): """ Apply the Gradient Descent to update the parameter :param mini_batch: numpy.ndarray Mini batch for the approximation of the gradient of loss function :param eta: int Learning rate of Gradient Descent :return: """ nabla_w = [np.zeros_like(w) for w in self.weights] nabla_b = [np.zeros_like(b) for b in self.biases] for x, y in mini_batch: delta_nabla_w, delta_nabla_b = self.backprob(x, y) nabla_w = [nw + dnw for nw, dnw in zip(nabla_w, delta_nabla_w)] nabla_b = [nb + dnb for nb, dnb in zip(nabla_b, delta_nabla_b)] self.weights = [w - eta / len(mini_batch) * nw for w, nw in zip(self.weights, nabla_w)] self.biases = [b - eta / len(mini_batch) * nb for b, nb in zip(self.biases, nabla_b)] def backprob(self): return 0
48c5beab9235bf6abfda10100ca48cbbe47e5345
sfeng77/myleetcode
/sortCharactersByFreq.py
1,049
4.09375
4
# Given a string, sort it in decreasing order based on the frequency of characters. # # Example 1: # # Input: # "tree" # # Output: # "eert" # # Explanation: # 'e' appears twice while 'r' and 't' both appear once. # So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. # # Example 2: # # Input: # "cccaaa" # # Output: # "cccaaa" # # Explanation: # Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer. # Note that "cacaca" is incorrect, as the same characters must be together. # # Example 3: # # Input: # "Aabb" # # Output: # "bbAa" # # Explanation: # "bbaA" is also a valid answer, but "Aabb" is incorrect. # Note that 'A' and 'a' are treated as two different characters. class Solution(object): def frequencySort(self, s): """ :type s: str :rtype: str """ from collections import Counter ctr = Counter(s) l = sorted([(c, ctr[c]) for c in Counter(s)], key = lambda x:x[1], reverse = True) return "".join([c * ct for c, ct in l])
40237368c60caffa4172f59a735faf2a1ef04c81
upasek/python-learning
/conditional_statements_and_loops/csl_type.py
308
4.25
4
#Write a Python program that prints each item and its corresponding type from the following list. datalist = [1452, 11.23, 1+2j, True, 'w3resource', (0, -1), [5, 12], {"class":'V', "section":'A'}] print("Original list :",datalist,"\n") for m in datalist: print("Type of {} is {} ".format(m, type(m)))
db786ab71e89c22bfcc5a347f0789ff1cb0cc6c4
syn7hgg/ejercicios-python
/1_6/4_prof.py
2,489
3.53125
4
nombre = "solo_dolar.txt" def archivo_ver(nombre): archivo = open(nombre, "r") datos = archivo.readlines() print("Inicio Lectura de Archivo ", nombre) for reg in datos: i = reg.split("\t") j = i[0] m = i[1] print("Para la fecha: ", j, " el valor del dólar es: ", m) return print("Fin Lectura de Archivo", nombre) def maximo_valor(nombre): archivo = open(nombre, "r") datos = archivo.readlines() print("\nInicio Lectura de Archivo para determinar el valor máximo del Dólar y su fecha", nombre) maximo_valor = None for reg in datos: i = reg.split("\t") j = i[0] num = i[1] if (maximo_valor is None or num > maximo_valor): maximo_valor = num fecha = j limpio = maximo_valor.strip() limpio = str(limpio) # l=datos.index(maximo_valor) # print(l) return print("Máximo valor del Dólar es: ", limpio, "que corresponde a la fecha: ", fecha) def promedio_valor(nombre): archivo = open(nombre, "r") datos = archivo.readlines() # print("\nInicio Lectura de Archivo para determinar el valor promedio del Dólar", nombre) suma = 0 contador = 0 for reg in datos: i = reg.split("\t") j = i[0] num = i[1] suma += float(num) contador += 1 # print(suma,contador) promedio = round(suma / contador, 2) return promedio def separar_promedio(nombre): promedio = promedio_valor(nombre) archivo = open(nombre, "r") datos = archivo.readlines() archivo_ma = open("dolar_mayor_prom.txt", "w") archivo_me = open("dolar_menor_prom.txt", "w") print("\n.... Se comienza a generar los archivos ....") for reg in datos: i = reg.split("\t") j = i[0] num = i[1] if float(num) >= promedio: linea = j + "\t" + num archivo_ma.write(linea) else: linea = j + "\t" + num archivo_me.write(linea) print("Archivo %s con valor dólar mayor igual al promedio %.2f GENERADO" % ("dolar_mayor_prom.txt", promedio)) print("Archivo %s con valor dólar menor al promedio %.2f GENERADO" % ("dolar_menor_prom.txt", promedio)) return print(".... Termino de generación de los archivos ....") archivo_ver(nombre) maximo_valor(nombre) print("\nEl promedio del Dólar es: ", promedio_valor(nombre)) separar_promedio(nombre)
4abe8cccad0100f755e30e09b64f95bb0af9009f
Qiumy/leetcode
/Python/50Pow(x, n).py
701
3.703125
4
# Implement pow(x, n). # x^n = x ^ (n /2) * x ^(n / 2) (n %2 == 0)或者x^n = x ^ (n /2) * x ^(n / 2) * x(n %2 == 1)。 # n < 0 的时候,x ^ n =1 / (x ^(-n)) class Solution(object): def myPow(self, x, n): """ :type x: float :type n: int :rtype: float """ if n < 0: return 1 / self.myPow(x, -1 * n) if x == 0: return 0.0 if n == 0: return 1.0 if n == 1: return x tmp = self.myPow(x,n // 2) if n % 2 == 0: return tmp*tmp else: return tmp*tmp * x s = Solution() print(s.myPow(0.00001,2147483647))
47a5b7728bb1feb396e0ca35cfffec5711dfe8f8
satyar3/PythonLearning
/PythonPractice/ClassConcept_2.py
721
4.25
4
class Employee: def __init__(self, arg_name, arg_salary, arg_age): self.name = arg_name self.salary = arg_salary self.age = arg_age def print_name(self): print(f'Employee name is {self.name}, salary is {self.salary}, and age is {self.age}') # Without Constructor # rohan = Employee() # rohan.name = 'Rohan' # rohan.salary = 100 # rohan.age = 23 # Since rohan has the above attributes, then it'll print all the details # rohan.print_name() # Here as an argument, rohan object will be given # Below will throw error as there is no attribute as name, salary,age # satya = Employee() # satya.print_name() # With Constructor rohan = Employee("Rohan", 200, 25) print(rohan.age)
69d190a72f8cd5d62aea0fdd7d8d51db6b77ec5f
equals-zero/adventure
/props.py
4,041
3.890625
4
class Inventory(object): """ Inventar - Kann Inventar von Spieler oder Objekt Initialisierung: InventarName = Inventory((int)Inventargroesse) """ def __init__(self, maxsize): super(Inventory, self).__init__() self.Inventory = [] self.MaxSpace = maxsize def showAllContents(self): if len(self.Inventory) == 0: print("Das Inventar ist leer.") else: print("Im Inventar befindet sich:") for Gegenstand in self.Inventory: print(Gegenstand.Name) def addToInventory(self, DasObjekt): if len(self.Inventory) >= self.MaxSpace: print(DasObjekt.Name + " konnte nicht hinzugefügt werden. " "Inventar voll ("+str(len(self.Inventory))+"/"+str(self.MaxSpace)+")!") self.Inventory.append(DasObjekt) print(DasObjekt.Name + " wurde zu Ihrem Inventar hinzugefügt!") def deleteFromInventory(self, Gegenstand): for Inventareintrag in self.Inventory: if Gegenstand == Inventareintrag: self.Inventory.remove(Inventareintrag) print(Gegenstand.Name + " wurde aus Ihrem Inventar entfernt!") # TODO: Liest die uebergebene Variable als Inventar ein def readInventoryFromSave (self, Savegame): pass class Gegenstand(object): """ Initialisiert einen Gegenstand - Bitte nicht fuer Moebel nutzen! JEDER GEGENSTAND DARF NUR EINMAL INITIALISIERT WERDEN! Initialisierung: derGegenstand = Gegenstand((str)"Name des Gegenstands",(int)TypDesGegenstands,(int)WertDesGegestands) Typ = Schwert, Schild, Ruestung, was auch immer ABER(!) ueber die ID Wert = Abhaengig von Typ, z.B. Verteidigungspunkte, Angriffspunkte... was auch immer """ def __init__(self, nameDesGegenstands, beschreibungDesGegenstands, typDesGegenstands, wertDesGegenstands): super(Gegenstand, self).__init__() self.Name = nameDesGegenstands self.Beschreibung = beschreibungDesGegenstands self.Typ = typDesGegenstands self.Wert = wertDesGegenstands class Moebelstueck(object): """ Initialisiert ein Moebelstueck, z.B. eine Truhe oder eine Schachtel JEDES MOEBELSTUECK DARF NUR EINMAL INITIALISIERT WERDEN! """ def __init__(self, nameDesMoebelstuecks, beschreibungDesMoebelstuecks, inventarGroesse, inventarInhalt, verschlossen, schluessel): super(Moebelstueck, self).__init__() self.Name = nameDesMoebelstuecks self.Beschreibung = beschreibungDesMoebelstuecks self.__Inventargroesse = inventarGroesse self.Verschlossen = verschlossen self.__Schluessel = schluessel self.__Inhalt = inventarInhalt def overwriteInventory(self, NeuesInventar): """ NeuesInventar = Array! """ self.__Inhalt = NeuesInventar pass def showAllContents (self): if self.Verschlossen: print(self.Name + " ist verschlossen.") else: if len(self.__Inhalt) == 0: print(self.Name + " ist leer.") else: print(self.Name + " enthält:") for GegenstandAusInventar in self.__Inhalt: print(GegenstandAusInventar.Name) class Raum (object): """ Raeume werden untereinander verbunden und enthalten Moebelstuecke und Gegenstaende. Der Spieler bewegt sich durch die einzelnen Raeume. ausgaengeDesRaumes = Array aus Int. Werten! Jeder Eintrag muss auf Key des GameMap-Arrays zeigen! """ def __init__(self, idDesRaumes, beschreibungDesRaumes, ausgaengeDesRaumes, inhaltDesRaumes, verschlossen, schluessel): super(Raum, self).__init__() self.Name = idDesRaumes self.Beschreibung = beschreibungDesRaumes self.Rauminhalt = inhaltDesRaumes self.Verschlossen = verschlossen self.Ausgaenge = ausgaengeDesRaumes self.__Schluessel = schluessel #
f24cbb910d3733725580c6c296f27c465f93371c
SensationS/Robotframework-CassandraLibrary
/test/csvlibrary.py
1,012
3.96875
4
#-*- coding: utf-8 -*- import sys import csv from time import localtime, strftime reload(sys) sys.setdefaultencoding('utf-8') def write_CSV_file(filename,*itemlist): """ This Keyword saves list to 'csv' File with timestamp.\n If you input file name like "query" and then output file name will be "Test.csv".\n Return value is full name with timestamp. e.g. "Test.csv"\n """ items = [i.decode('UTF-8') if isinstance(i, basestring) else i for i in itemlist] fi=filename + ".csv" with open(fi, "wb") as f: writer = csv.writer(f) writer.writerows(items) return fi def read_CSV_file(filename): '''This creates a keyword named "Read CSV File" This keyword takes one argument, which is a path to a .csv file. It returns a list of rows, with each row being a list of the data in each column. ''' data = [] with open(filename, 'rb') as csvfile: reader = csv.reader(csvfile) for row in reader: data.append(row) return data
e2fb0febbe02e8f4a58d9da56898e34f80abc64a
ankurjain8448/leetcode
/search-insert-position.py
692
3.53125
4
#https://leetcode.com/problems/search-insert-position/description/ class Solution(object): def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ start = 0 end = len(nums) - 1 s = 0 e = len(nums)-1 index = -1 if target < nums[0]: index = 0 elif target > nums[e]: index = e + 1 else: while s <= e: mid = (s+e)/2 if nums[mid] == target: index = mid break elif target < nums[mid]: if start < mid and target > nums[mid-1]: index = mid break e = mid - 1 else: if mid < end and target < nums[mid+1]: index = mid + 1 break s = mid + 1 return index
c5a171a634a7c6108434b93f61c7983735bb55a7
matejbolta/project-euler
/Problems/07.py
1,095
3.984375
4
''' By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? ''' # def je_deljivo_s_katerim_od(n, seznam): # if seznam == []: # return False # else: # return n % seznam[0] == 0 or je_deljivo_s_katerim_od(n, seznam[1:]) # # def prastevila_do(n): # if n <= 1: # return [] # elif je_deljivo_s_katerim_od(n, prastevila_do(n - 1)): # return prastevila_do(n - 1) # else: # return prastevila_do(n - 1) + [n] # # x = prastevila_do(10 ** 6) # # print(x[1001]) # # #presežemo rekurzijo, vendar bi to moglo delovati. def prime(n): if n <= 2: return n == 2 elif n % 2 == 0: return False else: #vsa liha ostanejo d = 3 while d ** 2 <= n: if n % d == 0: return False d += 2 return True zaporedno = 0 n = 2 while True: if prime(n): zaporedno += 1 if zaporedno == 10001: print(n) break n += 1
f3649882869a3ee962ff4a6fc1776f4558200438
RJEGR/IIIBSS
/python/scripts/exploring_np_plt-2.py
5,653
3.609375
4
#!/usr/bin/python # -*- coding: utf-8 -*- # #------------------------------ # # @uthor: acph - dragopoot@gmail.com # Licence: GNU GENERAL PUBLIC LICENSE, Version 3, 29 June 2007 # # This file contains code that helps to explore numpy and matplotlib modules # # WARNING: This file is not intend to be executed as a script, so if you execute # it from a command line, it may not function as you expect. #------------------------------ # Prepare ipython for interactive mode %matplotlib qt # first import the modules import numpy as np import matplotlib.pyplot as plt #################################### # 4. MORE PLOTTING AND A LITTLE OF # # SCIPY STATS # #################################### from scipy import stats # ----- # ----- What about a simple correlation example? # ----- # scipy stats submodule has a lot of commonly used # statistics functions # lets create some data x = np.arange(26) pcor = stats.pearsonr(x, x) print('r = ', pcor[0]) print('p-value = ', pcor[1]) # now, some noise to the data r_factor = random.normal(loc=0, scale=5, size=len(x)) y = x + r_factor # - Pearson correlation pcor = stats.pearsonr(x, y) # Least squares with numpy polyfit fit = np.polyfit(x, y, 1) m, b = fit[0], fit[1] def lin_func(x): return m*x + b # To plot the fitted line we need to create the corrsponding # x,y points x2 = np.linspace(0, 25, 1000) # a lot of points (1000) y2 = lin_func(x2) # Corresponding y values # Lets plot the data plt.scatter(x, y, color='g', s=20, label='Data') plt.plot(x2, y2, color='r', label='Linear fit') plt.xlabel('x') plt.ylabel('y') plt.legend() annotation = 'Linear fit : $y = {:.2}x + {:.2}$\n $r = {:.2}$\n $p = {:.2}$' annotation = annotation.format( m, b, pcor[0], pcor[1]) ann = plt.annotate(annotation, xy=(0, 18), fontsize='small') # ---- # ---- What about a t-test? # ---- # Lets create 2 independent samples from random normal distributions # First visualize the distributions that we are going to sample # Means 18 and 22 (~20% of difference between means) # Same standard deviation = 2 plt.subplot(211) plt.hist(random.normal(18, 2, size=10000), bins=20) plt.title('Distribution 1') plt.xlim((10, 30)) plt.subplot(212) plt.hist(random.normal(22, 2, size=10000), bins=20) plt.title('Distribution 2') plt.xlim((10, 30)) ######################## # Now lets sample data # ######################## n1 = 10 n2 = 10 sample1 = random.normal(18, 2, size=n1) sample2 = random.normal(22, 2, size=n2) # Mean value mean1 = sample1.mean() mean2 = sample2.mean() # Standard deviation std1 = sample1.std() std2 = sample2.std() # Standard error of the mean sem1 = std1 / np.sqrt(n1) sem2 = std2 / np.sqrt(n2) # Now, plot the data # boxplot plt.subplot(311) plt.boxplot([sample1, sample2]) plt.title('Boxplot') plt.ylabel('Arbitrary units') plt.xticks([1, 2], ['Sample 1', 'Sample 2']) # point plot with standard deviation of the mean plt.subplot(312) plt.errorbar([1, 2], [mean1, mean2], yerr=[ std1, std2], label='Mean +- std', fmt='o') plt.title('Point plot (std)') plt.ylabel('Arbitrary units') plt.xticks([1, 2], ['Sample 1', 'Sample 2']) plt.xlim((0.5, 2.5)) # bar plot with standard error of the mean plt.subplot(313) plt.bar([1, 2], [mean1, mean2], yerr=[sem1, sem2], label='Mean +- s.e.m', width=0.4) plt.title('Bar plot (s.e.m.)') plt.ylabel('Arbitrary units') plt.xticks([1, 2], ['Sample 1', 'Sample 2']) plt.xlim((0, 3)) plt.ylim((15, 24)) plt.tight_layout() # Are there statistically significant differences between the measn? # -- Hypothesis testing -- # What about a simple t-test # Are the data normally distributed? def is_normal(x, pvalue=0.05): """Returns True if the data is normally distributed with a given p-value threshold - x : numpy 1d array or list of integers|floats - pvalue : threshold to reject null hypothesis """ s, pv = stats.shapiro(x) if pv > pvalue: return True else: return False print('sample1', is_normal(sample1)) print('sample2', is_normal(sample2)) # if both samples are normally distributed you can # use student's t tstat = stats.ttest_ind(sample1, sample2) print('T test p-value:', tstat.pvalue) # Is there a statistically significant difference between the # sample means (t >= 0.05)? # If not, how can you simulate samples that are statistically different? ### -- Exercise # What would happen to the samples parameters # (std, s.e.m.) if you change the sample size to: # 1) n1 = 3, n2 = 3 # 2) n1 = 20, n2 = 20 # Take special attention to the s.e.m. and to the boxplot # save the plots and take note of the differences. # Is there a statistically significant difference between the # sample means? # If not, how can you simulate samples that are statistically different? ################################################### ################################################### ################################################### ################################################### ################################################### ### -- Another exercise # t-test brute force simulation # Try different sample sizes # maintaining the same mean and stds!!!! samples = {3: 0, 10: 0, 20: 0} # making 1000 simulations for i in range(1000): # testing each sample sizes for j in [3, 10, 20]: # samples s1 = random.normal(18, 2, size=j) s2 = random.normal(22, 2, size=j) # testing ttest = stats.ttest_ind(s1, s2) # Reject Ho? if ttest.pvalue <= 0.05: samples[j] += 1 samples ###################################################
c2934ff8199ef89788561ea6c892ff7617290be0
huanglesi0605/room-seeker
/ourRecommendationAlgorithms/files/src/ballTree.py
3,973
3.515625
4
# encoding=utf-8 """ Description : class for ballTree """ import numpy as np import heapq from collections import Counter import random class BallTreeNode(object): """ treeNode class """ def __init__(self, val, radius, leafs): """ Args: val : vector value for user or item radius : float radius for the ball leafs : int number of leafs under this node """ self.val = val self.radius = radius self.left = None self.right = None self.leafs = leafs class BallTree(object): """ class for ballTree """ def __init__(self, data): """ Args: data: str file path for the training data """ print('building the ball tree .....') self.root = self.constructBallTree(data) print('ball tree construction completed') def getDistance(self, val1, val2): """ calculate the distance for vector val1 and vector val2 """ sqrSum = 0 for i in range(len(val1)): if val1[i] * val2[i] != 0: dif = val1[i] - val2[i] sqrSum += dif * dif else: sqrSum += 0.001 return sqrSum def getCentroid(self, allPoints): """ calculate the centroid point for the cluster """ sums = [0 for _ in range(len(allPoints[0]))] for p in allPoints: for i in range(len(p)): sums[i] += p[i] for i in range(len(allPoints[0])): sums[i] /= len(allPoints) return sums def getFurthest(self, target, allPoints): """ find the point among the allPoints cluster which has the largest distance to the target point """ furthest = (-1, allPoints[0]) for p in allPoints: distance = self.getDistance(target, p) if distance > furthest[0]: furthest = (distance, p) return furthest[1] def seperateTwoBalls(self, allPoints, f1, f2): """ separate the allPoints cluster into two balls based on the two center points f1 and f2 """ balls = [[], []] for p in allPoints: distance1 = self.getDistance(p, f1) distance2 = self.getDistance(p, f2) if distance1 < distance2: balls[0].append(p) else: balls[1].append(p) if len(balls[0]) == 0: balls[0].append(balls[1][0]) balls[1] = [balls[1][1]] elif len(balls[1]) == 0: balls[1].append(balls[0][0]) balls[0] = [balls[0][1]] return balls def constructBallTree(self, data): """ recursively construct the tree """ if len(data) == 1: return BallTreeNode(data[0], 0, 0) else: n = len(data) startPointIdx = random.randint(0, n-1) startPoint = data[startPointIdx] f1 = self.getFurthest(startPoint, data) f2 = self.getFurthest(f1, data) centroid = self.getCentroid([f1, f2]) balls = self.seperateTwoBalls(data, f1, f2) radius = self.getDistance(f1, centroid) ballNode = BallTreeNode(centroid, radius, n) # print(np.array(balls[0]).shape, np.array(balls[1]).shape) if len(balls[0]) > 0: ballNode.left = self.constructBallTree(balls[0]) if len(balls[1]) > 0: ballNode.right = self.constructBallTree(balls[1]) return ballNode def searchBallTree(self, target, k, heap, treeNode, distance = -1): """ find the k nearest points among the tree for the target point """ d = self.getDistance(target, treeNode.val) if distance == -1 else distance if len(heap) >= k: (curMax, val) = heap[-1] #[curMax, val] = heapq.heappop(heap) #heapq.heappush(heap, (curMax, val)) if d - treeNode.radius >= curMax: return if treeNode.leafs == 0: heap.append((d, treeNode.val)) #heapq.heappush(heap, (d, treeNode.val)) if len(heap) > k: #heapq.heappop(heap) heap = sorted(heap, key = lambda k: k[0]) heap.pop(-1) else: d1 = self.getDistance(target, treeNode.left.val) d2 = self.getDistance(target, treeNode.right.val) if d1 < d2: self.searchBallTree(target, k, heap, treeNode.left, d1) self.searchBallTree(target, k, heap, treeNode.right, d2) else: self.searchBallTree(target, k, heap, treeNode.right, d2) self.searchBallTree(target, k, heap, treeNode.left, d1)
b94de9029c2d5934121b17f9b81b9223894ddddb
krishppuria/Regex
/uk_postcode_check.py
1,121
3.515625
4
import re example_codes = ["SW1A 0AA", # House of Commons "SW1A 1AA", # Buckingham Palace "SW1A 2AA", # Downing Street "BX3 2BB", # Barclays Bank "DH98 1BT", # British Telecom "N1 9GU", # Guardian Newspaper "E98 1TT", # The Times "TIM E22", # a fake postcode "A B1 A22", # not a valid postcode "EC2N 2DB", # Deutsche Bank "SE9 2UG", # University of Greenwhich "N1 0UY", # Islington, London "EC1V 8DS", # Clerkenwell, London "WC1X 9DT", # WC1X 9DT "B42 1LG", # Birmingham "B28 9AD", # Birmingham "W12 7RJ", # London, BBC News Centre "BBC 007" # a fake postcode ] expr=re.compile('^([A-Z]{1,2}[0-9A-Z]{0,2}\s[0-9][^CIKMOV0-9\s\W]{2})$') for code in example_codes: if len(expr.findall(code))>0: print("Valid Zip code",code) print(expr.findall(code)) else: print("Invalid zip code",code)
31866cacff287714f2c36a8f99c02f6da7925df2
wuzy361/machine-learning
/explore_enron_data.py
1,138
3.796875
4
#coding:utf-8 #!/usr/bin/python """ Starter code for exploring the Enron dataset (emails + finances); loads up the dataset (pickled dict of dicts). The dataset has the form: enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict } {features_dict} is a dictionary of features associated with that person. You should explore features_dict as part of the mini-project, but here's an example to get you started: enron_data["SKILLING JEFFREY K"]["bonus"] = 5600000 """ #位置udacity ml 数据集与问题 25/35 import pickle #加载数据 enron_data = pickle.load(open("../final_project/final_project_dataset.pkl", "r")) #要找的人名 lis =['Lay','Skilling','Fastow'] #由于数据集人名是大写的,所以全转化成大写 lis = map(lambda x:x.upper(),lis) #把这三个人的人名和数据同时存到pay这个列表里 pay=[] for x in enron_data: if x[0:x.find(' ')] in lis: pay.append ((x[0:x.find(' ')],enron_data[x]['total_payments'])) #排序,输出根据payment排序结果的最大值 pay = sorted(pay,key=lambda x:x[1],reverse=1) print pay[0]
779b5a22bb5004e9bc143ee59642249a341a2b05
guocheng45/Projects
/Python_Basic/decorators.py
3,903
4.4375
4
''' def hi(name="yasoob"): return "hi " + name print(hi()) # output: 'hi yasoob' # 我们甚至可以将一个函数赋值给一个变量,比如 greet = hi # 我们这里没有在使用小括号,因为我们并不是在调用hi函数 # 而是在将它放在greet变量里头。我们尝试运行下这个 print(greet()) # output: 'hi yasoob' # 如果我们删掉旧的hi函数,看看会发生什么! del hi print(hi()) # outputs: NameError print(greet()) # outputs: 'hi yasoob' ''' ''' def hi(name="yasoob"): print("now you are inside the hi() function") def greet(): return "now you are in the greet() function" def welcome(): return "now you are in the welcome() function" print(greet()) print(welcome()) print("now you are back in the hi() function") hi() # output:now you are inside the hi() function # now you are in the greet() function # now you are in the welcome() function # now you are back in the hi() function # 上面展示了无论何时你调用hi(), greet()和welcome()将会同时被调用。 # 然后greet()和welcome()函数在hi()函数之外是不能访问的,比如: #greet() # outputs: NameError: name 'greet' is not defined ''' ''' def hi(name="yasoob"): def greet(): return "now you are in the greet() function" def welcome(): return "now you are in the welcome() function" if name=='yasoob': return greet else: return welcome a=hi() print(a) # outputs: <function greet at 0x7f2143c01500> # 上面清晰地展示了`a`现在指向到hi()函数中的greet()函数 # 现在试试这个 print(a()) # outputs: now you are in the greet() function print(hi(123)()) # now you are in the welcome() function ''' ''' def hi(): return "hi yasoob!" def doSomethingBeforeHi(func): print("I am doing some boring work before executing hi()") print(func()) doSomethingBeforeHi(hi) #outputs:I am doing some boring work before executing hi() # hi yasoob! ''' ''' def a_new_decorator(a_func): def wrapTheFunction(): print("I am doing some boring work before executing a_func()") a_func() print("I am doing some boring work after executing a_func()") return wrapTheFunction def a_function_requiring_decoration(): print("I am the function which needs some decoration to remove my foul smell") a_function_requiring_decoration() # outputs: "I am the function which needs some decoration to remove my foul smell" a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration) # now a_function_requiring_decoration is wrapped by wrapTheFunction() a_function_requiring_decoration() # outputs:I am doing some boring work before executing a_func() # I am the function which needs some decoration to remove my foul smell # I am doing some boring work after executing a_func() @a_new_decorator def a_function_requiring_decoration(): """Hey you! Decorate me!""" print("I am the function which needs some decoration to " "remove my foul smell") a_function_requiring_decoration() # outputs: I am doing some boring work before executing a_func() # I am the function which needs some decoration to remove my foul smell # I am doing some boring work after executing a_func() # the @a_new_decorator is just a short way of saying: # a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration) ''' from functools import wraps def decorator_name(f): @wraps(f) def decorated(*args, **kwargs): if not can_run: return "Function will not run" return f(*args, **kwargs) return decorated @decorator_name def func(): return ("Function is running") can_run = True print(func()) # Output: Function is running can_run = False print(func()) # Output: Function will not run
a2747a2e6ea046c43888c675ccf5369dcbacd105
TanushreeVedula14/18031J0068_Python
/Python/Module 2/Assignment 1_PS_B_7.py
214
4.15625
4
# When two integer lists 'a' and 'b' are given, create a new list containing # middle elements of the given lists 'a' and 'b'. list1 = [1,3,5,7,9] list2 = [2,4,6,8,10] list3 = list1[1:4]+list2[1:4] print(list3)
7cc0383ff6c395fd13704ab261b34c7f7e1be530
ozcayci/python_examples
/examples_07/q1.py
499
4.125
4
# -*- coding: utf-8 -*- import string def caesar_encryption(number_of_letters_to_scroll, text: str): text = text.lower() letters = string.ascii_lowercase result = "" for letter in text: if letter.isalpha(): new_letter = letters[(letters.index(letter) + number_of_letters_to_scroll) % 26] result += new_letter else: result += letter return result print(caesar_encryption(1, "alihan bayraktarz"))
8788613503f42ffb480018c1f90871bfdd559a88
siddheshsule/100_days_of_code_python_new
/day_1/length_of_a_string.py
189
4.28125
4
# This program prints length of a string. name = input("Enter any name: ") print(len(name)) # OPTION 2: # letter_count = 0 # for i in name: # letter_count += 1 # print(letter_count)
66b185abdabced55b1cb9ba8b9b87197e3e0e2a9
ziyeZzz/python
/machine_learning/02_gradient_descent.py
2,085
3.546875
4
# -*- coding: utf-8 -*- # 梯度下降和随机梯度下降法求解 # Q:argmin1/2*[(x1+x2-4)^2 + (2x1+3x2-7)^2 + (4x1+x2-9)^2] import random # 要最小化的函数 def f(x1, x2): return 1/2 * ((x1 + x2 - 4) ** 2 + (2 * x1 + 3 * x2 - 7) ** 2 + (4 * x1 + x2 - 9) ** 2) # x1的偏导 def f_x1(x1, x2): return (x1+x2-4)*1 + (2*x1+3*x2-7)*2 + (4*x1+x2-9)*4 # x2的偏导 def f_x2(x1, x2): return (x1+x2-4)*1 + (2*x1+3*x2-7)*3 + (4*x1+x2-9)*1 # 梯度下降 def gradient_descent(x1, x2, a): f_best = f(x1, x2) # 当前最优 x1_update = x1 - a * f_x1(x1, x2) x2_update = x2 - a * f_x2(x1, x2) f_update = f(x1_update, x2_update) if f_best - f_update > 0.01: return(gradient_descent(x1_update, x2_update, a)) else: return x1, x2, f_best # 随机取一个数据求x1,x2偏导, 并更新x1, x2 => 相当于以偏概全 def f_random(x1, x2, a): dice = random.randint(1,3) if dice == 1: x1_update = x1 - a * ((x1+x2-4)*1) x2_update = x2 - a * ((x1+x2-4)*1) elif dice == 2: x1_update = x1 - a * ((2*x1+3*x2-7)*2) x2_update = x2 - a * ((2*x1+3*x2-7)*3) else: x1_update = x1 - a * ((4*x1+x2-9)*4) x2_update = x2 - a * ((4*x1+x2-9)*1) return x1_update, x2_update # 随机梯度下降 def random_gradient_descent(x1, x2, a): f_best =f(x1, x2) x1_update, x2_update = f_random(x1, x2, a) f_update = f(x1_update, x2_update) if f_best - f_update > 0.01: return(random_gradient_descent(x1_update, x2_update, a)) else: return x1, x2, f_best if __name__ == '__main__': # a is the step length. x1_0 and x2_0 are initial value of x1 and x2. a = 0.01 x1_0, x2_0 = 0, 0 # 经过梯度下降后,最好的x1, x2 和 f x1, x2, f_best = gradient_descent(x1_0, x2_0, a) print('x1:{}, x2:{}, minimal_f:{}'.format(x1, x2, f_best)) # 经随机梯度下降后,算出的最好的x1, x2 和 f a = 0.05 x1, x2, f_best = random_gradient_descent(x1_0, x2_0, a) print('x1:{}, x2:{}, minimal_f:{}'.format(x1, x2, f_best))
818c49cf2490eb1f7b9d0fa083e974ee6a718334
hjorthjort/advent2020
/day1/1.py
639
3.609375
4
with open('input.txt', 'r') as f: input = f.readlines() def get_pair(nums, base): needs = {} for n in nums: if n in needs: m = base - n return (n, m) needs[(base - n)] = True return None nums = list(map(lambda x: int(x), input)) base = 2020 (n, m) = get_pair(nums, base) print("The pair is %d, %d.\n%d*%d=%d" % (n, m, n, m, n*m)) # Part 2 for n in nums: filtered = filter(lambda x: x != n, nums) res = get_pair(filtered, base - n) if res is not None: (m, l) = res print("The triple is %d, %d, %d\n%d*%d*%d=%d" % (n,m,l,n,m,l,n*m*l)) exit(0)
749be04d4d853c6086f65c5bf4b0ecf98a044128
Bayoslav/Libraria
/Users.py
958
3.53125
4
import datetime from peewee import * db = SqliteDatabase('books.db') class User(Model): Name = CharField() Age = IntegerField() Adress = CharField() Phone = IntegerField() Datet = DateField() def addbook(self,num): pass #f=open('users.dat','r') def cita(self): citad = User.select() for korisnik in citad: print(korisnik.Name, " ", korisnik.Adress) class Meta: database = db def newuser(self): self.name = input("Name of the user: ") self.age = (int(input("User's age: "))) self.adress = (input("User's adress: ")) self.phone = (input("User's phone: ")) dudu = User(Name=self.name,Age=self.age,Adress=self.adress,Phone=self.phone,Datet=datetime.date.today()) dudu.save() def readnumus(self): numnum = (int(input("Enter the users number"))) bob = User.get(User.id == numnum) print(bob.Name)
a69ae3f8092673ce18eeda7d40e69d060317d45e
Santhoshkumard11/Day_2_Day_Python
/alphabet_detect.py
730
4.125
4
# Program to check the alphabets in the given string print("Enter the string:") strin = str(input()) alp= ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] i,j=0,0 # Finding the letters in the given string while(i<(len(strin))): while(j<(len(alp))): if(strin[i]==alp[j]): print(strin[i],alp[j]) alp.remove(alp[j]) j = j+1 i = i+1 j=0 # Checking for the condition if(len(alp)==0): print("String has all the alphabets") else: print("String don't have all the alphabets") ''' Input : asnd Output : String don't have all the alphabets '''
6ce856cfe418b177feaddf31bbe6f4ca18f57f3c
Berteun/adventofcode2020
/day03/part02.py
539
3.921875
4
def read_board(): f = open('input') return [l.strip() for l in f] def count_trees(board, down, right): width = len(board[0]) trees = 0 pos = 0 while pos < len(board): trees += board[pos][((pos//down) * right) % width] == '#' pos += down return trees def main(): board = read_board() solution = 1 for (right, down) in [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]: solution *= count_trees(board, down=down, right=right) print(solution) if __name__ == '__main__': main()
8d9d4c38e62e4087d317edac939154fb750aa8fc
KwonAndy/SP2018-Python220-Accelerated
/Student/AndyKwon/Lesson03/locke.py
3,025
4.59375
5
# Andy K # Lesson03 # Context Manager """ Write a context manager class Locke to simulate the overall functioning of the system. When the locke is entered it stops the pumps, opens the doors, closes the doors, and restarts the pumps. Likewise when the locke is exited it runs through the same steps: it stops the pumps, opens the doors, closes the doors, and restarts the pumps. Don’t worry for now that in the real world there are both upstream and downstream doors, and that they should never be opened at the same time; perhaps you’ll get to that later. During initialization the context manger class accepts the locke’s capacity in number of boats. If someone tries to move too many boats through the locke, anything over its established capacity, raise a suitable error. Since this is a simulation you need do nothing more than print what is happening with the doors and pumps, like this: "Stopping the pumps." "Opening the doors." "Closing the doors." "Restarting the pumps." This is how you might interact with your Locke class. small_locke = Locke(5) large_locke = Locke(10) boats = 8 # Too many boats through a small locke will raise an exception with small_locke as locke: locke.move_boats_through(boats) # A lock with sufficient capacity can move boats without incident. with large_locke as locke: locke.move_boats_through(boats) """ class Locke(): def __init__(self, locke_capacity, handle_error=None): self.locke_capacity = locke_capacity self.handle_error = handle_error def __enter__(self): print("...Stopping Pumps...\n", "...Opening Gates...") return self def __exit__(self, exc_type, exc_value, exc_traceback): if exc_type is AssertionError: self.handle_error = True print("%s\n" % (exc_value), "...Closing Gates...\n" "...Starting Pumps...") return self.handle_error print("...Closing Gates...\n", "...Starting Pumps...") return self.handle_error def boats_through_locke(self, num_boats): """ compares Locke's capacity to the number of boats seeking passage """ assert num_boats <= self.locke_capacity, ( "Number of boats exceed locke capacity") print("Boats have passed through the locke") # l = Locke(9) # with l as foo: # l.boats_through_locke(5) # l = Locke(9) # with l as foo: # l.boats_through_locke(10) """ SAMPLE RESULTS: -------------------------------------------- l = Locke(9) with l as foo: l.boats_through_locke(5) >>> ...Stopping Pumps... ...Opening Gates... Boats have passed through the locke ...Closing Gates... ...Starting Pumps... -------------------------------------------- l = Locke(9) with l as foo: l.boats_through_locke(10) >>> ...Stopping Pumps... ...Opening Gates... Number of boats exceed locke capacity ...Closing Gates... ...Starting Pumps... -------------------------------------------- """
f0142a718ea8a37ea888bfcff8a3f7aaec0d9a9b
lutece-awesome/spartan
/src/input/parser.py
2,971
3.5
4
import json from abc import ABC, abstractmethod from src.conf.config import Setting from .type import RunningData class DataParser(ABC): setting: Setting def __init__(self, setting: Setting): self.setting = setting @abstractmethod def parse(self, input_data: str) -> RunningData: pass class JsonDataParser(DataParser): def parse(self, input_data: str) -> RunningData: running_data_json = json.loads(input_data) setting = self.setting running_data = RunningData.parse(data=running_data_json.get('data', setting.DEFAULT_DATA), data_type=running_data_json.get( 'data_type', setting.DEFAULT_DATA_TYPE), time_limit=running_data_json.get( 'time_limit', setting.DEFAULT_TIME_LIMIT), memory_limit=running_data_json.get( 'memory_limit', setting.DEFAULT_MEMORY_LIMIT), cpu_number_limit=running_data_json.get('cpu_number_limit', setting.DEFAULT_CPU_NUMBER_LIMIT), output_limit=running_data_json.get('output_limit', setting.DEFAULT_OUTPUT_LIMIT), compile_time_limit=running_data_json.get('compile_time_limit', setting.DEFAULT_COMPILE_TIME_LIMIT), compile_memory_limit=running_data_json.get('compile_memory_limit', setting.DEFAULT_COMPILE_MEMORY_LIMIT), checker_time_limit=running_data_json.get('checker_time_limit', setting.DEFAULT_CHECKER_TIME_LIMIT), checker_memory_limit=running_data_json.get('checker_memory_limit', setting.DEFAULT_CHECKER_MEMORY_LIMIT), checker_type=running_data_json.get('checker_type', setting.DEFAULT_CHECKER_TYPE), checker_data=running_data_json.get('checker_data', setting.DEFAULT_CHECKER_DATA)) return running_data class ProtoDataParser(DataParser): def parse(self, input_data: str) -> RunningData: # TODO(qscqesze): impl it pass
ab2d9d1070a92c891a724e254b8fde927617accc
alanbeavan/impractical_python_problems
/4/projects/automating_possible_keys/all_possible_keys.py
975
4.25
4
#!/usr/bin/env python3.6 """Enumerate possible keys for a route cipher given a number of columns.""" import itertools def key_permutations(ncol): """Return a list of possible keys for the number of columns. Returns a list of lists. """ cols = list(range(1, ncol + 1)) initial_perms = list(itertools.permutations(cols)) total_perms = [] for perm in initial_perms: total_perms.append(list(perm)) for i in range(1, ncol+1): combos = itertools.combinations(perm, i) for combo in combos: to_modify = list(perm) for j in combo: to_modify[j-1] = to_modify[j-1] * -1 total_perms.append(to_modify) return total_perms def main(): """Do the things.""" ncol = int(input("How many columns?")) keys = key_permutations(ncol) for key in keys: print(" ".join(list(map(str, key)))) if __name__ == "__main__": main()
06397603b0f11eeb41c82da8ce844b3114019ff4
MaT1g3R/csc148
/exercises/ex6/ex6_test.py
3,020
3.53125
4
"""CSC148 Exercise 6: Binary Search Trees === CSC148 Fall 2016 === Diane Horton and David Liu Department of Computer Science, University of Toronto === Module description === This module contains sample tests for Exercise 6. Warning: This is an extremely incomplete set of tests! Add your own to practice writing tests and to be confident your code is correct. For more information on hypothesis (one of the testing libraries we're using), please see <http://www.teach.cs.toronto.edu/~csc148h/fall/software/hypothesis.html>. Note: this file is for support purposes only, and is not part of your submission. """ import unittest from ex6 import BinarySearchTree deep1 = BinarySearchTree(5) deep2 = BinarySearchTree(25) deep3 = BinarySearchTree(66) deep4 = BinarySearchTree(80) deep5 = BinarySearchTree(92) deep6 = BinarySearchTree(111) deep7 = BinarySearchTree(166) deep8 = BinarySearchTree(200) mid1 = BinarySearchTree(20) mid1._left = deep1 mid1._right = deep2 mid2 = BinarySearchTree(75) mid2._left = deep3 mid2._right = deep4 mid3 = BinarySearchTree(95) mid3._left = deep5 mid3._right = deep6 mid4 = BinarySearchTree(175) mid4._left = deep7 mid4._right = deep8 s1 = BinarySearchTree(50) s1._left = mid1 s1._right = mid2 s2 = BinarySearchTree(150) s2._left = mid3 s2._right = mid4 tree = BinarySearchTree(90) tree._left = s1 tree._right = s2 class BSTNumLessThanTest(unittest.TestCase): def test_one(self): bst = BinarySearchTree(1) self.assertEqual(bst.num_less_than(10), 1) self.assertEqual(bst.num_less_than(0), 0) def test_bigger(self): bst = BinarySearchTree(1) bst._left = BinarySearchTree(-10) bst._right = BinarySearchTree(100) self.assertEqual(bst.num_less_than(5), 2) self.assertEqual(bst.num_less_than(-100), 0) self.assertEqual(bst.num_less_than(1000), 3) def test_huge(self): self.assertEqual(tree.num_less_than(50), 3) self.assertEqual(tree.num_less_than(90), 7) self.assertEqual(tree.num_less_than(95), 9) self.assertEqual(tree.num_less_than(-1), 0) class BSTItemsTest(unittest.TestCase): def test_one(self): bst = BinarySearchTree(1) self.assertEqual(bst.items_at_depth(1), [1]) def test_empty(self): bst = BinarySearchTree(None) self.assertEqual(bst.items_at_depth(1), []) def test_huge(self): self.assertEqual(tree.items_at_depth(1), [90]) self.assertEqual(tree.items_at_depth(2), [50, 150]) self.assertEqual(tree.items_at_depth(3), [20, 75, 95, 175]) self.assertEqual(tree.items_at_depth(4), [5, 25, 66, 80, 92, 111, 166, 200]) class BSTLevelsTest(unittest.TestCase): def test_one(self): bst = BinarySearchTree(1) self.assertEqual(bst.levels(), [(1, [1])]) def test_huge(self): self.assertEqual(tree.levels(), [(1, [90]), (2, [50, 150]), (3, [20, 75, 95, 175]), (4, [5, 25, 66, 80, 92, 111, 166, 200])]) if __name__ == '__main__': unittest.main(exit=False)
5fda1720f60d151273233cf82c3fdfc92a205792
daniel-reich/turbo-robot
/RX6eLpSqZENJcGAWf_8.py
337
3.859375
4
""" Create a function whose return value always passes equality checks. ### Examples equals() == 0 ➞ True equals() == [] ➞ True equals() == (lambda: 1) ➞ True ### Notes The challenge is passable. """ class AlwaysTrue: def __eq__(self,other): return True ​ def equals(): return AlwaysTrue()
12f58cc8e808964c86277a8304c2e97f22cd7a33
priyaSNHU/Practice-Questions
/Algorithmanalysis/Stacks/infix_postfix.py
904
3.5
4
from classtak import Stack def infix_postfix(exp): prec = {} prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 s = Stack() postfix_list = [] infix_list = exp.split() for ch in infix_list: if ch in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or ch in "0123456789": postfix_list.append(ch) elif ch == "(": s.push(ch) elif ch == ")": top_element = s.pop() while top_element != "(": postfix_list.append(top_element) top_element = s.pop() else: while (not s.is_empty()) and (prec[s.peek()] >= prec[ch]) : postfix_list.append(s.pop()) s.push(ch) while (not s.is_empty()) : postfix_list.append(s.pop()) return " ".join(postfix_list) print(infix_postfix("5 * 3 ** (4 - 2)"))
6888a5cd26822f95ffbd32431d2d2114256e6b7d
askachen/LeetCode
/Python/LC344.py
790
3.921875
4
import time class Solution(object): def reverseString(self, s): """ :type s: str :rtype: str """ #SOLUTION 1 #return s[::-1] #SOLUTION 2 rs = list("") length = len(s) for i in range(length): rs.append(s[length-i-1]) return "".join(rs) #--------------------------- a = Solution() start_time = time.time() print a.reverseString("hello") print a.reverseString("Tesla is accelerating the world's transition to sustainable energy, offering the safest, quickest electric cars on the road and integrated energy solutions. Tesla products work together to power your home and charge your electric car with clean energy, day and night.") print time.time() - start_time
60ae7c4c24a3e48d2e516c9c40703e268779257e
EllaHunt/Lucky_Unicorn
/00_LU_base_v_01.py
1,341
4.15625
4
# function goes here... def yes_no(question): valid = False while not valid: response = input(question).lower() if response == "yes" or response == "y": response = "yes" return response elif response == "no" or response =="n": response = "no" return response else: print("please answer yes /no") def instructions(): print("**** how to play ****") print() print("the rules of the game go here") print() return "" def num_check(question, low, high): error = "please enter a whole number between 1 and 10\n" valid = False while not valid: try: # ask the question response = int(input(question)) # if the amount is to low / to high give if low < response <= high: return response # output an error else: print(error) except ValueError: print(error) # the main routine goes here... played_before = yes_no("Have you played the game before? ") if played_before == "no": instructions() # ask user how much they would like to play with... how_much = num_check("how much would you like to play with? ", 0, 10) print("you will be spending ${}".format(how_much))
112ce9cf35489c17fba6183a85fc84ed06ece61d
MarceloBritoWD/URI-online-judge-responses
/Estruturas e Bibliotecas/1259.py
349
3.84375
4
vezes = int(input()); cont = 0; numerosPares = []; numerosImpares = []; while (cont < vezes): valor = int(input()); if (valor%2) == 0: numerosPares.append(valor); else: numerosImpares.append(valor); cont += 1; numerosPares.sort() numerosImpares.sort(reverse=True); for i in numerosPares: print(i); for i in numerosImpares: print(i);
8bc635369878e5b487dd391637cc796933ecf8e7
niksm7/Data-Structures-Implementation
/Trees/TreeFromInorderPreoder.py
4,703
4.21875
4
class Node: def __init__(self, data): self.val = data self.left = None self.right = None class Tree: preIndex = 0 ''' This function may be called recursively and will help us to construct the tree''' def createTree(self,inOrder,preOrder,inStart,inEnd): if inStart > inEnd: return None # We get hold of the current element in the preOrder traversal by using the preIndex variable and keep on incrementing it curr_ele = preOrder[self.preIndex] self.preIndex += 1 # Create a new node with the current element we got from preOrder new_node = Node(curr_ele) # If there are no child nodes i.e. left and right nodes to current node then we simply return the node if inStart == inEnd: return new_node # If there are child nodes present then we get the index of this current element inIndex = self.hash_map[curr_ele] # And then assign its left and right node as per the recursive call # the left node will be present to the left of the current node so we pass the start index of inorder node and current node's index - 1 new_node.left = self.createTree(inOrder,preOrder,inStart,inIndex-1) # The right node will be present to the right of the current node so we pass starting index as index of current node + 1 and inEnd as ending index new_node.right = self.createTree(inOrder,preOrder,inIndex+1,inEnd) # Finally we return the node that is created return new_node ''' This function is used to optimize code by using functionality of hash maps storing the indices of the elements in the inorder traversal''' def optimizeInformation(self,inOrder,preOrder): self.hash_map = {} # We iterate through the inorder storing the elements as key and indices as their values for i in range(len(inOrder)): self.hash_map[inOrder[i]] = i # We then return with the function to create tree which will provide the root of the tree return self.createTree(inOrder,preOrder,0,len(inOrder)-1) ########### This code is taken from StackOverflow to Visually Represent the tree (NOT IMPORTANT) ############ def print_tree(root, val="val", left="left", right="right"): def display(root, val=val, left=left, right=right): """Returns list of strings, width, height, and horizontal coordinate of the root.""" # No child. if getattr(root, right) is None and getattr(root, left) is None: line = '%s' % getattr(root, val) width = len(line) height = 1 middle = width // 2 return [line], width, height, middle # Only left child. if getattr(root, right) is None: lines, n, p, x = display(getattr(root, left)) s = '%s' % getattr(root, val) u = len(s) first_line = (x + 1) * ' ' + (n - x - 1) * '_' + s second_line = x * ' ' + '/' + (n - x - 1 + u) * ' ' shifted_lines = [line + u * ' ' for line in lines] return [first_line, second_line] + shifted_lines, n + u, p + 2, n + u // 2 # Only right child. if getattr(root, left) is None: lines, n, p, x = display(getattr(root, right)) s = '%s' % getattr(root, val) u = len(s) first_line = s + x * '_' + (n - x) * ' ' second_line = (u + x) * ' ' + '\\' + (n - x - 1) * ' ' shifted_lines = [u * ' ' + line for line in lines] return [first_line, second_line] + shifted_lines, n + u, p + 2, u // 2 # Two children. left, n, p, x = display(getattr(root, left)) right, m, q, y = display(getattr(root, right)) s = '%s' % getattr(root, val) u = len(s) first_line = (x + 1) * ' ' + (n - x - 1) * '_' + s + y * '_' + (m - y) * ' ' second_line = x * ' ' + '/' + (n - x - 1 + u + y) * ' ' + '\\' + (m - y - 1) * ' ' if p < q: left += [n * ' '] * (q - p) elif q < p: right += [m * ' '] * (p - q) zipped_lines = zip(left, right) lines = [first_line, second_line] + [a + u * ' ' + b for a, b in zipped_lines] return lines, n + m + u, max(p, q) + 2, n + u // 2 if root is None: print("Tree is Empty!") return lines, *_ = display(root, val, left, right) for line in lines: print(line) if __name__ == "__main__": inOrder = [9,3,15,20,7] preOrder = [3,9,20,15,7] tree = Tree() root = tree.optimizeInformation(inOrder,preOrder) print_tree(root)
48964a1ea312f9bee0ccac0f7cbce15049362ae9
conversekuang/GoF23
/singleton2.py
850
3.578125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: converse @version: 1.0.0 @file: singleton2.py @time: 2021/9/3 15:25 """ # 函数实现装饰器,来修饰单例的类。 import threading import time def singleton(cls): _instance = {} _lock = threading.Lock() def _inner(): if cls not in _instance: with _lock: if cls not in _instance: time.sleep(0.2) _instance[cls] = cls() return _instance[cls] return _inner @singleton class Singleton: pass def multi_thread(i): obj = Singleton() # obj = Singleton.get_instance_static() # obj = Singleton.get_instance_class() print(obj, i) if __name__ == '__main__': for i in range(10): t = threading.Thread(target=multi_thread, args=[i, ]) t.start()
0b5f4c07fb474db8d6166451fff4edd250ec6ccb
principia12/Algorithm-Lickers
/Seungwoo/binary_tree_maximum_sum_path.py
2,578
3.578125
4
# Definition for a binary tree node. from pprint import pprint def stringToTreeNode(input): input = input.strip() input = input[1:-1] if not input: return None inputValues = [s.strip() for s in input.split(',')] root = TreeNode(int(inputValues[0])) nodeQueue = [root] front = 0 index = 1 while index < len(inputValues): node = nodeQueue[front] front = front + 1 item = inputValues[index] index = index + 1 if item != "null": leftNumber = int(item) node.left = TreeNode(leftNumber) nodeQueue.append(node.left) if index >= len(inputValues): break item = inputValues[index] index = index + 1 if item != "null": rightNumber = int(item) node.right = TreeNode(rightNumber) nodeQueue.append(node.right) return root def main(line): root = stringToTreeNode(line); ret = Solution().maxPathSum(root) out = str(ret) print(out) class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def mymax(pos, *args): print(pos) pprint(args) return max(*args) class Solution: def maxRootPathSum(self, root): if root.left is None and root.right is None: return root.val elif root.left is None: # right is not None return max(root.val, root.val + self.maxRootPathSum(root.right)) elif root.right is None: return max(root.val, root.val + self.maxRootPathSum(root.left)) return max(root.val, root.val + self.maxRootPathSum(root.right), root.val + self.maxRootPathSum(root.left), ) def maxPathSum(self, root): return self.result(root)[0] def result(self, root): # maxPathSum, maxRootPathSum if root.left is None and root.right is None: return root.val, root.val elif root.left is None: # right is not None a, b = self.result(root.right) return max(a, root.val + b, root.val), max(root.val, root.val + b) elif root.right is None: a, b = self.result(root.left) return max(a, root.val + b, root.val), max(root.val, root.val + b) a, b = self.result(root.right) c, d = self.result(root.left) return max(root.val, a, c, root.val + b, root.val + d, root.val + b + d,), \ max(root.val, root.val + b, root.val + d,) main('[-1,5,null,4,null,null,2,-4]')
ab469b2c744e3a34041de30c4c03915cf6bbb915
FilipovichSv/PythonHomeTasks
/Task4Variant1.2.py
486
3.90625
4
a = [1,2,3,4] point = 5 for a[0] in a: for a[1] in a: x=(a[0] + a[1]) if x == point: print(x) else: print('not found') for a[1] in a: for a[2] in a: x=(a[1] + a[2]) if x == point: print(x) else: print('not found') for a[2] in a: for a[3] in a: x=(a[2] + a[3]) if x == point: print(x) else: print('not found')
151bba65c82c2b256b92183f36fcf7a241e5d7cf
ElenaVasyltseva/Beetroot-Homework
/lesson_ 4/task_4_1.py
866
4.3125
4
# Task 1 # The Guessing Game. # Write a program that generates a random number between 1 and 10 # and lets the user guess what number was generated. # The result should be sent back to the user via a print statement. import random print('I thought of a number, from 1 to 10, guess what?') print('You have three attempts!') print('If you want to stop, enter: 0') hidden_number = random.randint(1, 10) count = 1 while count < 4: user_number = int(input('Enter a number:')) count += 1 if user_number == hidden_number: print(f'You win! The hidden number was: {hidden_number}') break elif user_number == 0: print('End games') else: print('Sorry you didn\'t guess! Try again!') continue if count == 4 and user_number != 0 and user_number != hidden_number: print('You lose!')
b1fcdcdd547fd81fb79feaa41314b85afa173855
satishrn/DiscardChatBotApp
/DiscordChatBot/Data_storage.py
804
4.09375
4
import sqlite3 class DataStoreSqlite(object): """ Database class to create , insert and fetch the data """ def __init__(self): self.conn = sqlite3.connect('search.sqlite') # connecting to database and creating table self.cur = self.conn.cursor() self.table = self.cur.execute('CREATE TABLE if not exists SearchModel(value text)') def insert_values(self, value): self.cur.execute('insert into SearchModel values(?)', (value,)) self.conn.commit() # Fetching the distinct column value def fetch_value(self): return self.cur.execute('SELECT DISTINCT value FROM SearchModel').fetchall() def remove_duplicates(self): pass # We can create different database also an store that object here database_obj = DataStoreSqlite()
f84fcd128d6dac48545f9828e2c26e4907bedeb0
adityamhatre/DCC
/dcc #6/double_linked_list_with_xor.py
5,260
4.4375
4
import unittest """ An XOR linked list is a more memory efficient doubly linked list. Instead of each node holding next and prev fields, it holds a field named both, which is an XOR of the next node and the previous node. Implement an XOR linked list; it has an add(element) which adds the element to the end, and a get(index) which returns the node at index. If using a language that has no pointers (such as Python), you can assume you have access to get_pointer and dereference_pointer functions that converts between nodes and memory addresses. """ # Since python has no pointer system, create one virtually # Memory map of id->Node where id=id(Node) nodes = {} def dereference_pointer(address): """ Returns the Node object at the address :param address: Memory address of the desired node :return: Node at the provided memory address """ return nodes[address] def get_pointer(node): """ Returns the pointer to the node :param node: The node whose pointer is desired :return: Pointer to the node """ return id(node) class Node: data = None both = None def __init__(self, data=None): self.data = data def get_next_node(self, previous): """ Retrieves the next node from the current node using self address XOR'ed with the previous node's address :param previous: Previous node's memory address :return: Returns next node in the list or None if this is the last node """ try: return dereference_pointer(get_pointer(previous) ^ self.both) except KeyError: return None def __repr__(self): return "{}: {}, {}".format(id(self), self.data, self.both) class DoublyLinkedList: size = 0 def __init__(self): head_node = Node() self.head = get_pointer(head_node) nodes[get_pointer(head_node)] = head_node # Saving head node's pointer in the memory map def add(self, data): """ Adds a new node to the list Set the 'both' field of the current node to be XOR of current memory address and previous node address. next_node_address = previous_node_address XOR current_node_address Future me: WORK IT OUT. I worked out for this. Try and recreate with basic binary addresses like 00,01,10,11 Read problem description. :param data: The data to be added in the new node """ # Edge case --> if data is None: raise ValueError("Cannot add None. NoneType provided.") # <-- Edge case new_node = Node(data) # Creating new node if dereference_pointer(self.head).both is None: dereference_pointer(self.head).both = get_pointer(new_node) ^ 0 nodes[get_pointer(new_node)] = new_node else: prev = dereference_pointer(self.head) curr = dereference_pointer(prev.both) while curr.both is not None: t = curr curr = curr.get_next_node(prev) prev = t curr.both = get_pointer(prev) ^ get_pointer(new_node) nodes[get_pointer(new_node)] = new_node self.size += 1 # Increment size of list def get(self, i): """ Gets the node at the ith index :param i: The index :return: Node at the index """ if type(i) is not int: raise TypeError('{} provided. Required: int'.format(type(i))) if i < 0 or i >= self.size: raise IndexError("index {} out of bounds".format(i)) return self.traverse(get_mode=True, index=i) def traverse(self, get_mode=False, index=None): """ Traverses the whole list :param get_mode: Optional param; only used by get() :param index: Optional param; only used by get() """ prev = dereference_pointer(self.head) curr = dereference_pointer(prev.both) counter = 0 while curr is not None: if get_mode: if counter == index: return curr if not get_mode: print(curr.data) t = curr if curr.both is not None: curr = curr.get_next_node(prev) else: break prev = t counter += 1 class TestSolution(unittest.TestCase): def setUp(self): self.dll = DoublyLinkedList() def test_add(self): self.dll.add(1) self.assertTrue(self.dll.get(0).data, 1) self.dll.add(2) self.assertTrue(self.dll.get(1).data, 2) def test_add_none(self): self.assertRaises(ValueError, self.dll.add, None) def test_get(self): for i in range(5): self.dll.add(i) for i in range(5): self.assertEqual(self.dll.get(i).data, i) def test_get_index_out_of_bounds(self): self.dll.add(1) self.dll.add(2) self.assertRaises(IndexError, self.dll.get, -1) self.assertRaises(IndexError, self.dll.get, 2) def test_invalid_get(self): self.dll.add(1) self.assertRaises(TypeError, self.dll.get, 1.5) if __name__ == '__main__': unittest.main()
a7ff57694d4ee056fabbd309879818508c7463fa
ksaubhri12/ds_algo
/practice_450/graph/13_topological_sorting.py
600
3.609375
4
def topological_sorting(v, adj_graph: [[]]): data_stack = [] visited = [False] * v for i in range(v): if not visited[i]: dfs_util(i, visited, data_stack, adj_graph) return list(reversed(data_stack)) def dfs_util(vertex: int, visited: [], data_stack: [], graph: [[]]): if visited[vertex]: return visited[vertex] = True for neighbor in graph[vertex]: dfs_util(neighbor, visited, data_stack, graph) data_stack.append(vertex) if __name__ == '__main__': adj_data = [[], [0], [0], [0]] print(topological_sorting(4, adj_data))
2016c31d837c5bcdd7c9eb851fb82d7a8bcb99ad
Banti374/Sorting-Algorithms
/heapsort.py
770
4
4
from array import * def heapify(arr, n, i): largest = i l = 2 * i + 1 r = 2 * i + 2 if l < n and arr[i] < arr[l]: largest = l if r < n and arr[largest] < arr[r]: largest = r if largest != i: arr[i],arr[largest] = arr[largest],arr[i] def heapSort(arr): n = len(arr) for i in range(n, -1, -1): heapify(arr, n, i) for i in range(n-1, 0, -1): arr[i], arr[0] = arr[0], arr[i] heapify(arr, i, 0) arr = array('i',[]) r = int(input("Enter the length of the array : ")) i=1 while i <= r: x = int(input("Enter the value : ")) i += 1 arr.append(x) heapSort(arr) n = len(arr) print("Sorted array is") for i in range(n): print(arr[i])
b75ce2600829c3b65ea40f999948d667386e5138
HNoorazar/Public
/My-Image-Analysis-Codes/imageanalysis/play_movie.py
724
3.578125
4
import scipy.io as sio import matplotlib.pyplot as plt import matplotlib.animation as animation import matplotlib.image as mpimg from time import sleep import glob import os def play_movie(image_matrix, time_range=[0, 59], color_map = 'Greys', pause_time=0.01): """ This function takes a 3D matrix and plays it as a movie. start_time is the slice we want the movie to start. it has to be` between 0-57. end_time is the slice which we want to stop at. it has to be between 1-58. Yunfeng """ count = 0 for time in xrange(time_range[0], time_range[1]): plt.imshow(image_matrix[time, :, :], cmap= color_map) plt.pause(pause_time) count += 1 plt.show(block=True)
ca7de5833c1f6f1705b15c2c5455677511a0f855
gaurava45/PythonProjectRepo
/dictionary.py
504
3.734375
4
d1 = {} print(type(d1)) d2 = {"harry":"burger", "rohan":"fish", "shubham":{"B":"maggi","L":"roti","D":"chicken"}} print(d2["shubham"]["L"]) name = "harry" d3 = {name:"burger", "rohan":"fish", "shubham":{"B":"maggi","L":"roti","D":"chicken"}} name = "shubham" print(d3[name]) d3[420] = "kebabs" print(d3) del d3[420] print(d3) d4 = d3.copy() #d4 is a copy of d3 del d4["harry"] print(d3) print(d4) d4 = d3 #d4 points to d3 del d4["harry"] print(d3) print(d4) print(d3.keys()) print(d3.items())
3113c83136fb51002505d1e2a1ce88d51db13023
arthurDz/algorithm-studies
/bloomberg/first_missing_positive.py
577
3.671875
4
# Given an unsorted integer array, find the smallest missing positive integer. # Example 1: # Input: [1,2,0] # Output: 3 # Example 2: # Input: [3,4,-1,1] # Output: 2 # Example 3: # Input: [7,8,9,11,12] # Output: 1 # Note: # Your algorithm should run in O(n) time and uses constant extra space. def firstMissingPositive(self, nums): dp = [False] * len(nums) for i in nums: if i > 0 and i <= len(nums): dp[i - 1] = True for t, v in enumerate(dp): if not v: return t + 1 return len(nums) + 1
39cff26197a0dbf4730ac65b05afb666c620afd7
busraeskiyurt/Python-projects
/prime number.py
602
4.125
4
number1=int(input("please enter to number for learn your want number if your number is prime or not.")) #ı wanted you enter a number here counter=0 # I create a variable ı wanted you enter a number here for i in range(2, number1+1): # If the number is prime, the counter must be 1. if number1% i == 0 : counter = counter + 1 if counter == 1: print("this number is prime") here if counter is one , print; this number is prime.and if not, print; this number isn't prime. else : print("this number isn't prime")
5d1da33b871daa3b0f42896355d4176a6d9f4b78
RobertoLocatelli02/Python-Learning
/Estrutura sequencial/TintaPorMetroQuadrado.py
410
3.78125
4
import math metrosQuadrados = float(input("Informe quantos metros quadrados serão pintados: ")) litrosTinta = metrosQuadrados / 3 latasTinta = math.ceil(litrosTinta / 18) totalAPagar = latasTinta * 80 print(f"Metros quadrados a serem pintados: {metrosQuadrados} \nLitros de tinta a serem precisos: {litrosTinta} \nQuantidade de latas de tinta que serão usadas: {latasTinta} \nTotal a pagar: R${totalAPagar}")
d46d6cea6ae94baffda547171a30223c3d714471
codecell/pythonAlgos
/strings/firstUnique.py
456
3.703125
4
# Q. https://leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/881/ ''' Runtime - O(n) space complexity - O(1) ''' from collections import defaultdict def firstUniqChar(s): d = defaultdict(int) for char in s: d[char] += 1 for x in d: if d[x] == 1: return s.index(x) return -1 print(firstUniqChar('leetcode')) print(firstUniqChar('aabb')) print(firstUniqChar('x'))
9f12608ff303537235804a58cc734c0c03fe6d75
mrxuying/apitest
/Python/flightwar/property.py
1,090
4.0625
4
##class Num(object): ## def __init__(self): ## self.__num = 100 ## ## @property ## def num(self): ## ## print('-----getter------') ## return self.__num ## ## @num.setter ## def num(self,new_num): ## ## print('-----setter------') ## self.__num = new_num ## ##test = Num() ## ##test.num += 200 ##print(test.num) ## ##print('-'*50) ## ##sample = Num() ##sample.num = 888 ##print(sample.num) class Num(object): def __init__(self): self.__num = 100 def setNum(self): print('-----getter------') return self.__num def getNum(self,new_num): print('-----setter------') self.__num = new_num num = property(setNum, getNum) test = Num() test.num += 200 print(test.num) print('-'*50) sample = Num() sample.num = 888 print(sample.num)
ce8565b135ec253695787ea9078fd1f90add6a57
ganjianfeng96/review
/q2/ut_fibonacci.py
801
3.640625
4
import unittest from fibonacci import * class SzTestCase(unittest.TestCase): def setUp(self): print "test path_parse start" def tearDown(self): print "test path_parse stop" def test_fibonacci_0(self): #self.assertTrue('./test.txt', parse_path(path, name)) self.assertEqual([0], fibonacci(0)) def test_fibonacci_1(self): self.assertEqual([0,1], fibonacci(1)) def test_fibonacci_2(self): self.assertEqual([0,1,1], fibonacci(2)) def test_fibonacci_3(self): self.assertEqual([0,1,1,2],fibonacci(3)) def test_fibonacci_5(self): self.assertEqual([0,1,1,2,3,5], fibonacci(5)) def test_abnormal_fibonacci(self): self.assertEqual([0], fibonacci(-1)) if __name__ == "__main__": unittest.main()
0e10cf435f85393a795701132e17821a85449ad4
AbderrahimAI/Projects-portfolio
/Sorting algorithm/algorithmes_animes-master/main.py
1,800
3.640625
4
#Main file import tkinter as tk from tkinter import font as tkfont from startpage import StartPage from display import Display from compare import Compare import tkinter.font as tkFont from tkinter import ttk #Class implements the basic architecture of the app class App(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) #Declaration of fonts self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic") s = ttk.Style() buttonFont = tkFont.Font(family='Arial', size=12) s.configure('my.TButton', font=buttonFont) self.restFont = tkFont.Font(family="Arial", size=12) s.configure("TMenubutton", font=self.restFont) # the container is where a bunch of frames are stacked # on top of each other, then the one to be visible # will be raised above the others container = tk.Frame(self) self.iconbitmap("icon.ico") container.grid(row=1, column=1) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} for F in (StartPage, Display, Compare): page_name = F.__name__ frame = F(parent=container, controller=self) self.frames[page_name] = frame # put all of the pages in the same location; # the one on the top of the stacking order # will be the one that is visible. frame.grid(row=0, column=0, sticky="nsew") self.show_frame("StartPage") def show_frame(self, page_name): #Show a frame for the given page name frame = self.frames[page_name] frame.tkraise() if __name__ == "__main__": app = App() app.mainloop()
886c0ee16aca8503f8b6cca1a174f233e4b78d93
Clementol/Python
/Even_Odd/Even_Odd.py
1,061
4.34375
4
""" By Clement Phone: 08167515092 """ all_numbers = [] #Empty list of all numbers #To enter the length of numbers n = int(input("How many numbers: ")) #To print the length of numbers print("Enter any", n, "numbers") #Loop To input the arrays of numbers according to the length and #put it in all_numbers list for i in range(1, n+1): arr = int(input('{}-- '.format(i))) all_numbers.append(arr) # #array of all even numbers even_numbers = [] #array of all odd numbers odd_numbers = [] #Loop to seperate all_number into even and odd lists for j in all_numbers: if j % 2 == 0: even_numbers.append(j) else: odd_numbers.append(j) #To print out all even numbers print("Even numbers are:", ) for i in range(len(even_numbers)): print('\t', i+1, "\b.", even_numbers[i]) if len(even_numbers) == 0: print("\tNo even numbers") #Loop to print out all odd numbers print("Odd numbers are:") for i in range(len(odd_numbers)): print('\t',i+1, "\b.", odd_numbers[i]) if len(odd_numbers) == 0: print("\tNo odd numbers")
db01e618b8428be95c672fa6daef04604cabf7fe
turab45/Travel-Python-to-Ml-Bootcamp
/Day 1/fibonacci.py
350
3.921875
4
# Author: Muhammad Turab size = 100 # first two terms n1, n2 = 0, 1 count = 0 if size == 1: print("Fibonacci sequence in range ", size, ":") print(n1) else: print("Fibonacci sequence is :") while count < size: print(n1, end=" ") nth = n1 + n2 # update values n1 = n2 n2 = nth count += 1
bbb48f22620d7f9b6be015d20e8a5bf6c0a82c68
AChen24562/Python-QCC
/Homework/Homework-wk-6-ifStatements/test/overtimePay.py
388
3.96875
4
hourlywage = float(input("Enter hourly wage: ")) hoursWorked = float(input("Enter number of hours worked: ")) if(hoursWorked > 40): overtimeWage = (40 * hourlywage) + (1.5 * hourlywage * (hoursWorked - 40)) print(f"Gross pay for week is: ${overtimeWage:.2f}") elif(hoursWorked < 40): weeklypay = hourlywage * hoursWorked print(f"Gross pay for week is: ${weeklypay:.2f}")
69b50757cef4990993b898161526cef5e1f428fa
mariane-sm/python_scripts
/e06-12.py
329
3.9375
4
def primes(n): primes = [] for number in range(2,n): if number % 2 != 0: is_prime = True for divisor in range(2, ((number/2) + 1)): if number % divisor == 0: is_prime = False if is_prime == True: primes.append(number) return primes #2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43 print primes(46)
2bacece6b82e5e442d68e9c4b5b8f42e817d104f
JianboTang/a2c
/a2c.py
2,500
3.5625
4
# -*- coding: utf-8 -*- """ Convert to Chinese numerals """ # Define exceptions class NotIntegerError(Exception): pass def to_chinese(number): """ convert integer to Chinese numeral """ chinese_numeral_dict = { '0': '零', '1': '一', '2': '二', '3': '三', '4': '四', '5': '五', '6': '六', '7': '七', '8': '八', '9': '九' } chinese_unit_map = [('', '十', '百', '千'), ('万', '十万', '百万', '千万'), ('亿', '十亿', '百亿', '千亿'), ('兆', '十兆', '百兆', '千兆'), ('吉', '十吉', '百吉', '千吉')] chinese_unit_sep = ['万', '亿', '兆', '吉'] reversed_n_string = reversed(str(number)) result_lst = [] unit = 0 for integer in reversed_n_string: if integer is not '0': result_lst.append(chinese_unit_map[unit // 4][unit % 4]) result_lst.append(chinese_numeral_dict[integer]) unit += 1 else: if result_lst and result_lst[-1] != '零': result_lst.append('零') unit += 1 result_lst.reverse() # clean convert result, make it more natural if result_lst[-1] is '零': result_lst.pop() result_lst = list(''.join(result_lst)) for unit_sep in chinese_unit_sep: flag = result_lst.count(unit_sep) while flag > 1: result_lst.pop(result_lst.index(unit_sep)) flag -= 1 ''' length = len(str(number)) if 4 < length <= 8: flag = result_lst.count('万') while flag > 1: result_lst.pop(result_lst.index('万')) flag -= 1 elif 8 < length <= 12: flag = result_lst.count('亿') while flag > 1: result_lst.pop(result_lst.index('亿')) flag -= 1 elif 12 < length <= 16: flag = result_lst.count('兆') while flag > 1: result_lst.pop(result_lst.index('兆')) flag -= 1 elif 16 < length <= 20: flag = result_lst.count('吉') while flag > 1: result_lst.pop(result_lst.index('吉')) flag -= 1 ''' return ''.join(result_lst) if __name__ == '__main__': foo = '' for i in range(1, 100001): foo += to_chinese(i) + '\n' print(foo) # print('对不起,第{0}遍'.format(to_chinese(i)))
d22be8a58071b30c3a7e4f228b7b276d24b7f0d6
Dinesh-Sunny/sdesworkshop
/week3/python/elapsed.py
319
3.75
4
def elapsed(str1, str2): """Get elapsed time between two times""" list1 = str1.split(':') list2 = str2.split(':') hrdiff = int(list1[0]) - int(list2[0]) mindiff =int(list1[1]) - int(list2[1]) secdiff =int(list1[2]) - int(list2[2]) seconds = hrdiff * 3600 + mindiff * 60 + secdiff return abs(seconds)
96251d4cd0106e2810ffe86b9231da09b449b403
RIMEL-UCA/RIMEL-UCA.github.io
/chapters/2023/Qualité logicielle dans les notebooks Jupyter/assets/python-scripts/NLP_C1_W4_lecture_nb_02.py
9,366
4.5625
5
#!/usr/bin/env python # coding: utf-8 # # Hash functions and multiplanes # # # In this lab, we are going to practice the most important concepts related to the hash functions explained in the videos. You will be using these in this week's assignment. # # A key point for the lookup using hash functions is the calculation of the hash key or bucket id that we assign for a given entry. In this notebook, we will cover: # # * Basic hash tables # * Multiplanes # * Random planes # ## Basic Hash tables # # Hash tables are data structures that allow indexing data to make lookup tasks more efficient. # In this part, you will see the implementation of the simplest hash function. # In[1]: import numpy as np # library for array and matrix manipulation import pprint # utilities for console printing from utils_nb import plot_vectors # helper function to plot vectors import matplotlib.pyplot as plt # visualization library pp = pprint.PrettyPrinter(indent=4) # Instantiate a pretty printer # In the next cell, we will define a straightforward hash function for integer numbers. The function will receive a list of integer numbers and the desired amount of buckets. The function will produce a hash table stored as a dictionary, where keys contain the hash keys, and the values will provide the hashed elements of the input list. # # The hash function is just the remainder of the integer division between each element and the desired number of buckets. # In[2]: def basic_hash_table(value_l, n_buckets): def hash_function(value, n_buckets): return int(value) % n_buckets hash_table = {i:[] for i in range(n_buckets)} # Initialize all the buckets in the hash table as empty lists for value in value_l: hash_value = hash_function(value,n_buckets) # Get the hash key for the given value hash_table[hash_value].append(value) # Add the element to the corresponding bucket return hash_table # Now let's see the hash table function in action. The pretty print function (`pprint()`) will produce a visually appealing output. # In[3]: value_l = [100, 10, 14, 17, 97] # Set of values to hash hash_table_example = basic_hash_table(value_l, n_buckets=10) pp.pprint(hash_table_example) # In this case, the bucket key must be the rightmost digit of each number. # ## Planes # # Multiplanes hash functions are other types of hash functions. Multiplanes hash functions are based on the idea of numbering every single region that is formed by the intersection of n planes. In the following code, we show the most basic forms of the multiplanes principle. First, with a single plane: # In[4]: P = np.array([[1, 1]]) # Define a single plane. fig, ax1 = plt.subplots(figsize=(8, 8)) # Create a plot plot_vectors([P], axes=[2, 2], ax=ax1) # Plot the plane P as a vector # Plot random points. for i in range(0, 10): v1 = np.array(np.random.uniform(-2, 2, 2)) # Get a pair of random numbers between -4 and 4 side_of_plane = np.sign(np.dot(P, v1.T)) # Color the points depending on the sign of the result of np.dot(P, point.T) if side_of_plane == 1: ax1.plot([v1[0]], [v1[1]], 'bo') # Plot blue points else: ax1.plot([v1[0]], [v1[1]], 'ro') # Plot red points plt.show() # The first thing to note is that the vector that defines the plane does not mark the boundary between the two sides of the plane. It marks the direction in which you find the 'positive' side of the plane. Not intuitive at all! # # If we want to plot the separation plane, we need to plot a line that is perpendicular to our vector `P`. We can get such a line using a $90^o$ rotation matrix. # # Feel free to change the direction of the plane `P`. # In[5]: P = np.array([[1, 2]]) # Define a single plane. You may change the direction # Get a new plane perpendicular to P. We use a rotation matrix PT = np.dot([[0, 1], [-1, 0]], P.T).T fig, ax1 = plt.subplots(figsize=(8, 8)) # Create a plot with custom size plot_vectors([P], colors=['b'], axes=[2, 2], ax=ax1) # Plot the plane P as a vector # Plot the plane P as a 2 vectors. # We scale by 2 just to get the arrows outside the current box plot_vectors([PT * 4, PT * -4], colors=['k', 'k'], axes=[4, 4], ax=ax1) # Plot 20 random points. for i in range(0, 20): v1 = np.array(np.random.uniform(-4, 4, 2)) # Get a pair of random numbers between -4 and 4 side_of_plane = np.sign(np.dot(P, v1.T)) # Get the sign of the dot product with P # Color the points depending on the sign of the result of np.dot(P, point.T) if side_of_plane == 1: ax1.plot([v1[0]], [v1[1]], 'bo') # Plot a blue point else: ax1.plot([v1[0]], [v1[1]], 'ro') # Plot a red point plt.show() # Now, let us see what is inside the code that color the points. # In[6]: P = np.array([[1, 1]]) # Single plane v1 = np.array([[1, 2]]) # Sample point 1 v2 = np.array([[-1, 1]]) # Sample point 2 v3 = np.array([[-2, -1]]) # Sample point 3 # In[7]: np.dot(P, v1.T) # In[8]: np.dot(P, v2.T) # In[9]: np.dot(P, v3.T) # The function below checks in which side of the plane P is located the vector `v` # In[10]: def side_of_plane(P, v): dotproduct = np.dot(P, v.T) # Get the dot product P * v' sign_of_dot_product = np.sign(dotproduct) # The sign of the elements of the dotproduct matrix sign_of_dot_product_scalar = sign_of_dot_product.item() # The value of the first item return sign_of_dot_product_scalar # In[11]: side_of_plane(P, v1) # In which side is [1, 2] # In[12]: side_of_plane(P, v2) # In which side is [-1, 1] # In[13]: side_of_plane(P, v3) # In which side is [-2, -1] # ## Hash Function with multiple planes # # In the following section, we are going to define a hash function with a list of three custom planes in 2D. # In[14]: P1 = np.array([[1, 1]]) # First plane 2D P2 = np.array([[-1, 1]]) # Second plane 2D P3 = np.array([[-1, -1]]) # Third plane 2D P_l = [P1, P2, P3] # List of arrays. It is the multi plane # Vector to search v = np.array([[2, 2]]) # The next function creates a hash value based on a set of planes. The output value is a combination of the side of the plane where the vector is localized with respect to the collection of planes. # # We can think of this list of planes as a set of basic hash functions, each of which can produce only 1 or 0 as output. # In[15]: def hash_multi_plane(P_l, v): hash_value = 0 for i, P in enumerate(P_l): sign = side_of_plane(P,v) hash_i = 1 if sign >=0 else 0 hash_value += 2**i * hash_i return hash_value # In[16]: hash_multi_plane(P_l, v) # Find the number of the plane that containes this value # ## Random Planes # # In the cell below, we create a set of three random planes # In[ ]: np.random.seed(0) num_dimensions = 2 # is 300 in assignment num_planes = 3 # is 10 in assignment random_planes_matrix = np.random.normal( size=(num_planes, num_dimensions)) print(random_planes_matrix) # In[ ]: v = np.array([[2, 2]]) # The next function is similar to the `side_of_plane()` function, but it evaluates more than a plane each time. The result is an array with the side of the plane of `v`, for the set of planes `P` # In[ ]: # Side of the plane function. The result is a matrix def side_of_plane_matrix(P, v): dotproduct = np.dot(P, v.T) sign_of_dot_product = np.sign(dotproduct) # Get a boolean value telling if the value in the cell is positive or negative return sign_of_dot_product # Get the side of the plane of the vector `[2, 2]` for the set of random planes. # In[ ]: sides_l = side_of_plane_matrix( random_planes_matrix, v) sides_l # Now, let us use the former function to define our multiplane hash function # In[ ]: def hash_multi_plane_matrix(P, v, num_planes): sides_matrix = side_of_plane_matrix(P, v) # Get the side of planes for P and v hash_value = 0 for i in range(num_planes): sign = sides_matrix[i].item() # Get the value inside the matrix cell hash_i = 1 if sign >=0 else 0 hash_value += 2**i * hash_i # sum 2^i * hash_i return hash_value # Print the bucket hash for the vector `v = [2, 2]`. # In[ ]: hash_multi_plane_matrix(random_planes_matrix, v, num_planes) # #### Note # This showed you how to make one set of random planes. You will make multiple sets of random planes in order to make the approximate nearest neighbors more accurate. # ## Document vectors # # Before we finish this lab, remember that you can represent a document as a vector by adding up the word vectors for the words inside the document. In this example, our embedding contains only three words, each represented by a 3D array. # In[ ]: word_embedding = {"I": np.array([1,0,1]), "love": np.array([-1,0,1]), "learning": np.array([1,0,1]) } words_in_document = ['I', 'love', 'learning', 'not_a_word'] document_embedding = np.array([0,0,0]) for word in words_in_document: document_embedding += word_embedding.get(word,0) print(document_embedding) # **Congratulations! You've now completed this lab on hash functions and multiplanes!**
e19e1d4de0ec402b49f7c199b4870b7cd61c48dd
danikav/gym_management_project
/tests/booking_test.py
560
3.5
4
import unittest from models.booking import Booking from models.member import Member from models.gymclass import Gymclass class TestBooking(unittest.TestCase): def setUp(self): member = Member("Dani") gymclass = Gymclass("Zumba", "12/03/21", "19:00", "Exercise and dance and have fun!") self.booking = Booking(member, gymclass) def test_booking_has_member(self): self.assertEqual("Dani", self.booking.member.name) def test_booking_has_gymclass(self): self.assertEqual("Zumba", self.booking.gymclass.name)
66c43babf5869eff183dc6d52b3e3a15584da641
ThiagoMourao/Python-POO
/pessoa/pessoa.py
1,759
3.78125
4
from datetime import datetime from random import randint class Pessoa: ano_atual = int(datetime.strftime(datetime.now(), '%Y')) def __init__(self, nome, idade, comendo=False, falando=False): self.nome = nome self.idade = idade self.comendo = comendo self.falando = falando def comer(self, alimento): if self.comendo: print(f'{self.nome} já está comendo.') return print(f'{self.nome} esta comendo {alimento}') self.comendo = True def stop_comer(self, alimento): if not self.comendo: print(f'{self.nome} não está comendo mais') return elif self.falando: print(f'{self.nome} esta falando, acabe de falar primeiro.') return self.comendo = False print(f'{self.nome} acabou de comer a {alimento}') def falar(self, assunto): if self.falando: print(f'{self.nome} ja esta falando sobre {assunto}.') return elif self.comendo: print(f'{self.nome} esta comendo, acabe de comer primeiro.') return print(f'{self.nome} esta falando sobre {assunto}') self.falando = True def stop_falar(self): if not self.comendo: print(f'{self.nome} não está falando mais') return self.falando = False print(f'{self.nome} já acabou de falar') def get_ano_nascimento(self): return self.ano_atual - self.idade @classmethod def cria_pessoa(cls, nome, ano_nascimento): idade = cls.ano_atual - ano_nascimento return cls(nome, idade) @staticmethod def gera_random(): return randint(1, 99999)
5b27502a57a5dfe0d0a76f71d121d288f472e29f
BrunoCaputo/ac309-pyExercises
/Exercises2/Q3.py
1,685
3.90625
4
# Crie um programa que leia nome, sexo e idade de várias pessoas, # guardando os dados de cada pessoa em um dicionário e todos os dicionários em uma lista. # No final, mostre: # a. Quantas pessoas foram cadastradas; # b. A média de idade do grupo; # c. Uma lista com todas as mulheres; # d. Uma lista com todas as pessoas com idade acima da média from random import randint qtt = randint(1, 4) #Gera um número aletatório entre 1 e 4, inclusive person = [] women = [] overMean = [] for i in range(qtt): name = input("Entre com o nome da " + str(i + 1) + "ª pessoa: ") gender = input("Entre com o sexo da " + str(i + 1) + "ª pessoa: ") age = int(input("Entre com a idade da " + str(i + 1) + "ª pessoa: ")) person.append({"name": name, "gender": gender, "age": age}) if gender == 'F': women.append({"name": name, "gender": gender, "age": age}) personQtt = len(person) print("Quantidade de pessoas cadastradas:", personQtt) totalAge = 0 for i in person: totalAge += i["age"] mean = totalAge / personQtt print("A média da idade do grupo é de %0.1f anos" %mean) if len(women) > 0: print("Mulheres do grupo:") for i in women: print( "Nome: %s, Idade: %d anos" %(i["name"], i["age"])) else: print("Não há mulheres no grupo") for i in person: if i["age"] > mean: overMean.append(i) if len(overMean) > 0: print("Pessoas com idade acima da média:") for i in overMean: print( "Nome: %s, Sexo: %s, Idade: %d anos" %(i["name"], "Masculino" if i["gender"] == "M" else "Feminino", i["age"]) ) else: print("Não há pessoas com idade acima da média")
4f9c8830c4c6f789a36c4deea6e20e8d4bfd4604
yuzhenbo/leetcode
/leetcode/self/13_RomanToInteger.py
861
3.6875
4
class Solution: def romanToInt(self, s): symbols_integer = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000, 'IV':4, 'IX':9, 'XL':40, 'XC':90, 'CD':400, 'CM':900} length = len(s) integer = 0 isPass = False for i in range(length): if isPass: isPass = False continue if s[i] in symbols_integer and s[i:i+2] not in symbols_integer: integer = integer + symbols_integer[s[i]] isPass = False continue if s[i:i+2] in symbols_integer: integer = integer + symbols_integer[s[i:i+2]] isPass = True return integer Input = 'DCXXI' A = Solution() B = A.romanToInt(Input) print(B)
2688b8148bf5272e6f6e82f61a4c5fc004674234
chohan3036/algo_study
/Simulation/64061_크레인 인형뽑기 게임.py
912
3.578125
4
from collections import deque def solution(board, moves): # board 를 접근하기 쉽게 조작 # 접근을 쉽게 하기 위해 전치행렬로 만듦 # 빈 공간을 없애 바로 popleft 할 수 있게 만듦 trans_board = [list(x) for x in zip(*board)] final_board = deque([]) for i in range(len(board)): final_board.append(deque(map(int, [x for x in trans_board[i] if x != 0]))) stack = [] moves = deque(moves) cnt = 0 while moves: cur_move = moves.popleft() - 1 if final_board[cur_move]: cur_doll = final_board[cur_move].popleft() else: continue if stack and stack[-1] == cur_doll: stack.pop() cnt += 2 else: stack.append(cur_doll) return cnt print(solution([[0,0,0,0,0],[0,0,1,0,3],[0,2,5,0,1],[4,2,4,4,2],[3,5,1,3,1]], [1, 5, 3, 5, 1, 2, 1, 4]))
30e7c5c9f78ebf6446e056b534f6e998cc564fa4
mraduldubey/HackerRank-Python-Challenge
/Basic Data Types/l9.py
752
3.859375
4
if __name__ == '__main__': N = int(raw_input()) lists = [] while N: st = raw_input() action = str(st.split(" ")[0]) if action == "insert": i,j = map(int,st.split(" ")[1:]) lists.insert(i,j) elif action == "print": print lists elif action == 'remove': i = int(st.split(" ")[1]) lists.remove(i) elif action == 'append': i = int(st.split(" ")[1]) lists.append(i) elif action == 'sort': lists=sorted(lists) elif action == 'pop': lists.pop() elif action == 'reverse': lists.reverse() #print lists,action N -= 1
0474b321b92fa02a39d502466f9485c1aaabe45c
Aasthaengg/IBMdataset
/Python_codes/p03486/s216036231.py
319
3.53125
4
s=list(input()) t=list(input()) s.sort() t.sort(reverse=True) s="".join(s) t="".join(t) for i in range(min(len(s),len(t))): if ord(s[i])==ord(t[i]): continue elif ord(s[i])<ord(t[i]): print("Yes") break else: print("No") break else: if len(s)<len(t): print("Yes") else: print("No")
2d1ae9a8cb7c613f2dfa0f4d4e0f849ad254815f
kersky98/stud
/coursera/pythonHse/fifth/23.py
1,170
3.671875
4
# Дан список целых чисел, число k и значение C. Необходимо вставить в список на # позицию с индексом k элемент, равный C, сдвинув все элементы, имевшие индекс # не менее k, вправо. Поскольку при этом количество элементов в списке # увеличивается, после считывания списка в его конец нужно будет добавить новый # элемент, используя метод append. Вставку необходимо осуществлять уже в # считанном списке, не делая этого при выводе и не создавая дополнительного # списка. s = list(map(int, input().split())) k, c = map(int, input().split()) # s = [7, 6, 5, 4, 3, 2, 1] # k, c = [2, 0] item1 = c tmp = 0 for index, item in enumerate(s): if index >= k: tmp = s[index] s[index] = item1 item1 = tmp s.append(item1) for item in s: print(item, end=' ')
5fcb91a8970dd97373bb42dc8c993fd13b692d01
gssxgss/leetcode-solutions
/python3/189_rotate_array.py
491
3.546875
4
# https://leetcode.com/problems/rotate-array/description/ class Solution: def rotate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead. """ if not nums or not k or len(nums) == 1: return count = k % len(nums) if not count: return nums[:] = nums[-count:] + nums[:-count] int_list = [1] Solution().rotate(int_list, 0)
363a4146c5c0f243339068cf6a449fbed3ff1f57
maximkavm/algorithms-and-data-structures
/part-1/06-recursia-dinamic-task-soldier/task-3.py
1,945
3.71875
4
''' Одномерная динамика Оловянный солдатик Он ходит по шахматной доске. В начале пути он стоит на линии 1 (не важно на какой вертикали, букве). У солдатика ограничена длина шага в клетках - d. Каждый шаг солдатик делает случайной длины в диапазоне [1,d]. Пусть дана размерность доски, например - 4 клетки (доска 4х4) и максимальная длина шага в клетках, например, 3. Вопрос: сколько разных способов у солдатика на то, чтобы дойти до края стола? ''' def get_1(n, m): # простая рекурсия if n <= 1: return 1 else: count = 0 for step in range(1, m + 1): if step <= n: count += get_1(n-step, m) return count def get_2(n, m): # рекурсия с кэшированием - сделать самостоятельно pass pass pass return 0 def get_3(n, m): # динамика - tab = [0] * (n + 1) tab[0] = 1 # солдатик, стоящий на клетке 1 имеет один путь for pos in range(n): for step in range(1, m + 1): if pos + step > n : continue tab[pos + step] += tab[pos] # print(tab) # для контроля return tab[n] import time n = 125 # размер доски n -= 1 # длина пути = размер доски - 1 (так как на 1 клетке уже стоит солдатик) m = 13 # длина максимального шага start = time.monotonic() # print('get_1 = %5d' % (get_1(n, m))) # print('get_2 = %5d' % (get_2(n, m))) # print('get_3 = %5d' % (get_3(n, m))) result = get_3(n, m) finish = time.monotonic() dif = finish - start print('%3d%3d%12d\t%10.3f' % (n, m, result, dif))
7299f3962e50caed2be460df8e42f5c9eb186597
MikBom/mikbom-github.io
/Python/Chapter 12 - Tehtävä 1.py
244
3.890625
4
lista = [] lista.append("Sininen") lista.append("Punainen") lista.append("Keltainen") lista.append("Vihreä") print("Listan ensimmäinen alkio on:",lista[0]) print("Lista tulostettuna alkio kerrallaan:") for i in lista: print(i)
4e1fa0a22578573f9ac5878c8bd999f757d7f54a
atmfaisal/assignment
/Problem1/main.py
9,147
3.75
4
import sqlite3 conn = sqlite3.connect('db.sqlite') cur = conn.cursor() sql_command = """ DROP TABLE IF EXISTS student; DROP TABLE IF EXISTS subject; CREATE TABLE student ( id INTEGER, name VARCHAR, current_class INTEGER, status INTEGER DEFAULT 1, PRIMARY KEY(id)); CREATE TABLE subject ( id INTEGER PRIMARY KEY, student_id INTEGER, subject VARCHAR, no_of_days_taught INTEGER, marks INTEGER); INSERT INTO student(id, name, current_class) VALUES (1, "Abu", 8); INSERT INTO student(id, name, current_class) VALUES (2, "Toha", 9); INSERT INTO student(id, name, current_class) VALUES (3, "Muhammad", 10); INSERT INTO student(id, name, current_class) VALUES (4, "Faisal", 8); INSERT INTO student(id, name, current_class) VALUES (5, "Rajib", 9); INSERT INTO student(id, name, current_class) VALUES (6, "Ahmed", 10); INSERT INTO student(id, name, current_class) VALUES (7, "Hemel", 8); INSERT INTO student(id, name, current_class) VALUES (8, "Sabbir", 9); INSERT INTO subject(student_id, subject, no_of_days_taught, marks) VALUES (1, "math", 10, 95); INSERT INTO subject(student_id, subject, no_of_days_taught, marks) VALUES (1, "english", 20, 90); INSERT INTO subject(student_id, subject, no_of_days_taught, marks) VALUES (1, "bangla", 30, 85); INSERT INTO subject(student_id, subject, no_of_days_taught, marks) VALUES (2, "math", 20, 80); INSERT INTO subject(student_id, subject, no_of_days_taught, marks) VALUES (3, "english", 20, 90); INSERT INTO subject(student_id, subject, no_of_days_taught, marks) VALUES (4, "bangla", 20, 70); INSERT INTO subject(student_id, subject, no_of_days_taught, marks) VALUES (5, "math", 20, 90); INSERT INTO subject(student_id, subject, no_of_days_taught, marks) VALUES (6, "english",20, 80); INSERT INTO subject(student_id, subject, no_of_days_taught, marks) VALUES (7, "bangla", 20, 90); INSERT INTO subject(student_id, subject, no_of_days_taught, marks) VALUES (7, "math", 20, 90); INSERT INTO subject(student_id, subject, no_of_days_taught, marks) VALUES (8, "english", 20, 90); INSERT INTO subject(student_id, subject, no_of_days_taught, marks) VALUES (8, "bangla", 20, 90); INSERT INTO subject(student_id, subject, no_of_days_taught, marks) VALUES (8, "math", 20, 90); """ cur.executescript(sql_command) conn.commit() def __show_operations(): print() operations = ["0 : Exit", "1 : Add a Student", "2 : Edit a Student", "3 : Delete a Student", "4 : See the List of Students Individually", "5 : See Overall Info"] for operation in operations: print(operation) def __show_operations_for_edit(): operations = ["1 : Adding days to the number of days taught", "2 : Adding marks"] for operation in operations: print(operation) def __show_operations_for_see(): operations = ["1 : Specific Class", "2 : Individual Student"] for operation in operations: print(operation) def __show_operations_for_overall(): operations = ["1 : Total Days Taught Across All Class", "2 : Individual Days Taught in Each Class", "3 : Total Earnings", "4 : Individual Earnings of Each Class", "5: Individual Earnings of Each Subject", "6 : Average Marks of All Students"] for operation in operations: print(operation) def get_operation_id(): __show_operations() operation_id = input("\nEnter Operation ID: ") return operation_id def get_operation_id_for_edit(): __show_operations_for_edit() operation_id = input("\nEnter Operation ID: ") return operation_id def get_operation_id_for_see(): __show_operations_for_see() operation_id = input("\nEnter Operation ID: ") return operation_id def get_operation_id_for_overall(): __show_operations_for_overall() operation_id = input("\nEnter Operation ID: ") return operation_id def add_a_student(): current_class = input("Enter Class :: 8, 9 or 10: ") name = input("Enter Name: ") cur.execute("INSERT INTO student (name, current_class) VALUES (?,?)", (name, current_class)) conn.commit() print("New Student Added\n") return def adding_no_of_days_taught(): student_id = input("Enter ID: ") sub = input("Enter Subject: 'math','english', 'bangla': ") days = input("Enter Number Days Taught: ") cur.execute("UPDATE subject SET no_of_days_taught=? WHERE id =? and subject=?", (days, student_id, sub)) if cur.rowcount < 1: cur.execute("INSERT INTO subject (student_id, subject, no_of_days_taught) VALUES (?,?,?)", (student_id, sub, days)) conn.commit() return def adding_marks(): student_id = input("Enter ID: ") sub = input("Enter Subject: 'math','english', 'bangla': ") mark = input("Enter Marks: ") cur.execute("UPDATE subject SET marks=? WHERE id =? and subject=?", (mark, student_id, sub)) if cur.rowcount < 1: cur.execute("INSERT INTO subject (student_id, subject, marks) VALUES (?,?,?)", (student_id, sub, mark)) conn.commit() return def edit_a_student(): operation_id = get_operation_id_for_edit() if operation_id == '1': adding_no_of_days_taught() elif operation_id == '2': adding_marks() else: print("Invalid Operation ID! Try Again...") edit_a_student() def delete_a_student(): cur.execute("SELECT id, name, current_class FROM student WHERE status=1 ") col = list(map(lambda x: x[0], cur.description)) print(col) stu_data = cur.fetchall() print(*stu_data, sep='\n') user_input = input("Enter ID Which You Want to Delete: ") cur.execute("UPDATE student SET status=0 WHERE id =?", user_input) conn.commit() return def specific_class(): user_input = input("Choose a Specific Class 8, 9 or 10: ") cur.execute("SELECT name, SUM(no_of_days_taught), AVG(marks) FROM student stu INNER JOIN subject sub ON stu.id=sub.student_id and current_class=? GROUP BY stu.id", user_input) specific = cur.fetchall() print(*specific, sep='\n') return def individual_student(): cur.execute("SELECT id, name, current_class FROM student WHERE status='1'") col = list(map(lambda x: x[0], cur.description)) print(col) stu_data = cur.fetchall() print(*stu_data, sep='\n') user_input = input("Enter an ID: ") cur.execute("SELECT * FROM subject WHERE student_id=?", user_input) col = list(map(lambda x: x[0], cur.description)) print(col) stu_data = cur.fetchall() print(*stu_data, sep='\n') return def see_the_list_of_students_individually(): operation_id = get_operation_id_for_see() if operation_id == '1': specific_class() elif operation_id == '2': individual_student() else: print("Invalid Operation ID! Try Again...") edit_a_student() def total_days_taught_across_all_class(): cur.execute("SELECT SUM(no_of_days_taught) FROM subject") total_days = cur.fetchone() print(*total_days, sep='\n') def individual_days_taught_in_each_class(): cur.execute("SELECT current_class, SUM(no_of_days_taught) FROM student stu INNER JOIN subject sub ON stu.id=sub.student_id GROUP BY current_class") total_days = cur.fetchall() print(*total_days, sep='\n') def total_earnings(): cur.execute("SELECT SUM(no_of_days_taught) FROM subject") total_earning = cur.fetchone() print("The total earnings: ") print(*total_earning, sep='\n') def individual_earnings_of_each_class(): cur.execute("SELECT current_class, SUM(no_of_days_taught) FROM student stu INNER JOIN subject sub ON stu.id=sub.student_id GROUP BY current_class") earnings = cur.fetchall() print(*earnings, sep='\n') def individual_earnings_of_each_subject(): cur.execute("SELECT subject, SUM(no_of_days_taught) FROM subject GROUP BY subject") earnings = cur.fetchall() print(*earnings, sep='\n') def average_marks_of_all_students(): cur.execute("SELECT ROUND(AVG(marks),2) FROM subject") avg_marks = cur.fetchone() print(*avg_marks, sep='\n') def see_overall_info(): operation_id = get_operation_id_for_overall() if operation_id == '1': total_days_taught_across_all_class() elif operation_id == '2': individual_days_taught_in_each_class() elif operation_id == '3': total_earnings() elif operation_id == '4': individual_earnings_of_each_class() elif operation_id == '5': individual_earnings_of_each_subject() elif operation_id == '6': average_marks_of_all_students() else: print("Invalid Operation ID! Try Again...") see_overall_info() if __name__ == '__main__': while True: user_operation = get_operation_id() if user_operation == '0': break elif user_operation == '1': add_a_student() elif user_operation == '2': edit_a_student() elif user_operation == '3': delete_a_student() elif user_operation == '4': see_the_list_of_students_individually() elif user_operation == '5': see_overall_info() else: print("Invalid Operation ID! Try Again...\n")
a5e04c8c20eff1ff31b0ec035f9766b0cd5e906b
ecarlosfonseca/HackerRank
/Collections_ordereddict.py
525
3.5
4
from collections import OrderedDict d = {} for i in range(int(input())): article = input().split() product = '' price = 0 for v in article: if v.isdigit(): price += int(v) else: product += v + ' ' if product[:-1] not in d: d[product[:-1]] = int(price) else: d[product[:-1]] += price for v in d: print(v, d[v]) """" Input: 9 BANANA FRIES 12 POTATO CHIPS 30 APPLE JUICE 10 CANDY 5 APPLE JUICE 10 CANDY 5 CANDY 5 CANDY 5 POTATO CHIPS 30 """
f77556af118932d86d12508ac6b4fef5ded6a4f9
testdata6/python-test
/python3/python_numbers.py
468
4.15625
4
#!/usr/bin/python ## Printing numbers print(2) print(2.0) print(-2.0) print(2+2) ## Correct method to do arithmetic operation. print(2*(2+2)) ## Correct method print(2*2+2) ## Incorrect method ## Convert interger to string value. b=10 print(type(b)) print(str(b) + " is a Value of b") ## Print and convert absulate value . b=-10 # Negative Value print(abs(b)) # Absulate value c=(abs(b)) # Convert int to string print(str(c) + " is a Value of c")
249362a977c2644321431698268abe2b7bf3cfbc
NateRiehl/Python-Data-Structures
/LinkNode.py
186
3.578125
4
# Linked list node implementation class LinkNode: def __init__(self, next, data): self.next = next self.data = data def __str__(self): return "Link Node: " + str(self.data)
7a05ab4e5bb99b46d76330e989e16acab52468a0
lingyun666/algorithms-tutorial
/leetcode/MajorityElement/majority_element.py
3,225
3.921875
4
# coding:utf8 ''' LeetCode: 169. Majority Element Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. You may assume that the array is non-empty and the majority element always exist in the array. 题目大意: 给定一个大小为 n 的数组, 找一个特定的元素, 这个元素满足在这个数组至少出现 n / 2 次, 你可以假设数组非空, 并且这个元素是真实存在的 ''' # 解题思路: # 可以成对地排除那些不相等的元素, 直到剩下最后一个元素. # 因为这个元素一定是存在的并且多于占数组元素的一半, 那么我们可以指定一个 count 和 selectedItem, # 一开始可以令第一个元素为 selectedItem, 并且 count += 1, 如果下个元素不是 selectedItem, 则将 count -= 1, 否则 count += 1 # 如果 count == 0 的话就重新指定下一个元素为 selectedItem, 并且 count 置为 1, 不管新值与旧值是否相等 # 这样最后剩下来的元素就是所求元素 # 时间复杂度: O(n) 空间复杂度: O(1) class Solution(object): @staticmethod def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ selected_item = None count = 0 for i in range(0, len(nums)): if count == 0: selected_item = nums[i] count += 1 else: if selected_item == nums[i]: count += 1 else: count -= 1 return selected_item if __name__ == '__main__': print(Solution.majorityElement(None, [2, 1, 4, 1, 6, 1, 7, 1, 8, 1, 1])) # 因为这里明确该数组中必包含主元素, 所以我们前面的代码才成立, 如果去掉假设 (数组非空, 并且这个元素是真实存在的) # 考虑数组为: [1, 2, 3, 4, 5, 6, 7, 8, 1, 1, 1] 最后输出还是为 1,而实际 1 并不是主元素 # 如果去掉假设的话, 可以使用一个字典来存储元素的 key 和出现的次数来遍历整个数组 # 最后查看字典中是否有元素的 value 大于 len(arr) / 2 # 时间复杂度: O(n) def find_majority_element1(nums): if len(nums) == 0: return None elems = dict() n = len(nums) for i in range(0, n): if nums[i] in elems.keys(): elems[nums[i]] += 1 else: elems[nums[i]] = 1 for k, v in elems.iteritems(): if v > n / 2: return k return None # 或者修改下之前的代码: def find_majority_element2(nums): if len(nums) == 0: return None selected_item = None count = 0 for i in range(0, len(nums)): if count == 0: selected_item = nums[i] count += 1 else: if selected_item == nums[i]: count += 1 else: count -= 1 count = 0 for i in range(0, len(nums)): if selected_item == nums[i]: count += 1 if count >= len(nums) / 2: return selected_item # print(find_majority_element1([1, 2, 3, 5, 1, 1, 1, 1, 1, 1])) # print(find_majority_element2([1, 2, 3, 5, 1, 1, 1, 1, 1, 1]))
7f34d63e66dedfd9b2ae8e56ed04ff567e4bba4e
tamaragmnunes/Exerc-cios-extra---curso-python
/Desafio026.py
226
3.96875
4
'''Faça um programa que leia uma frase pelo teclado e mostre: 1. Quantas vezes aparece a letra 'A' ''' frase = str(input('Digite uma frase qualquer: ')) print('A letra A aparece {} vezes.'.format(frase.count('A')))
b2018d69022289e49c0300681437fc78f2d02446
fabian017/MisionTIC
/CICLO 1 - PYTHON/Listas y Diccionarios/ejercicio2.py
730
3.75
4
'''Diseñe un algoritmo que pida un número al usuario un número de mes(por ejemplo, el 5) y diga cuántos días tiene(por ejemplo, 31)y el nombre del mes. Debes usar listas. Para simplificarlo vamos a suponer que febrero tiene 28 días''' meses = ["enero","Febrero","Marzo","Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"] dias = [31,28,31,30,31,30,31, 31, 30,31,30,31] while True: mes = int(input("Digite el mes (1-12): ")) while mes < 1 and mes > 12: mes = int(input("Valor incorecto, Digite el mes (1-12)")) if mes >= 1 and mes <= 12: print(f"El mes {mes} es: {meses[mes-1]} tiene {dias[mes-1]}") elif mes == 0: break
22a7f70868785a9c803020224aae1a5aabd74069
cvchakradharreddy/coursera
/week1/MaxPairwiseProduct_bkp.py
530
3.84375
4
size = int(input()) numbers = [int(x) for x in input().split()] def get_max_pairwise_product(): max_one_ind = 0 max_two_ind = 0 max_one = 0 max_two = 0 for i in range(0, size): if numbers[i] > max_one: max_one = numbers[i] max_one_ind = i for i in range(0, size): if numbers[i] > max_two and i != max_one_ind: max_two = numbers[i] max_two_ind = i return numbers[max_one_ind] * numbers[max_two_ind] print(get_max_pairwise_product())
e10adc110308c34e22a034f5aacb49275a2fb777
raulgfc/Estudos_Python
/guppe/7.Tipo_Booleano.py
785
3.828125
4
""" Tipo Booleano Algebra booleana, criada por George Boole 2 constantes, Verdadeiro ou Falso OBS: Sempre com a inicial maiúscula Errado: true or false Correto: True or False """ ativo = False print(ativo) ################################# ################################# """ OPERAÇÕES BÁSICAS: """ ################################# ################################# #USANDO NEGAÇÃO print (not ativo) #OR """ é uma operação binária, ou seja, depende de dois valores. Ou UM ou OUTRO deve ser verdadeiro LÓGICA BOOLEANA PYTHON T or T -> T T or F -> T F or T -> T F or F -> F """ #AND """ é uma operação binária, ou seja, depende de dois valores. AMBOS os valores devem ser verdadeiros LÓGICA BOOLEANA PYTHON T and T -> T T and F -> F F and T -> F F and F -> F """
5b3c6c0cb800365fd74e94ba237da98ed6ac19cd
abdullahf97/Lab-05
/Program 1, Lab -05, Abdullah Farooq, 18B-104-CS-A.py
312
3.703125
4
print('Abdullah Farooq') print('18B-104-CS-A') print('Lab-05, 24-11-2018') print('Program 1') count=0 f=eval(input("Enter your final condition where you want to break the loop: ")) while(count<f): print("The value of count:",count) count = count+1 print("I am using while loop", count, "time.")
acc65db5b94e798fd3354463faf4a6f79e17e45c
EruDev/Learn_Algorithms
/算法图解/chapter-10/10.py
418
3.84375
4
# coding: utf-8 """ 有一个长度为n序列,移除掉里面的重复元素,对于每个相同的元素保留最后出现的那个 示例: 1,8,7,3,8,3,1 输出: 7,8,3,1 """ def find_last(seq): li = list() for i in seq: if i not in li: li.append(i) else: li.remove(i) li.append(i) return li if __name__ == '__main__': seq = [1, 1, 7, 1, 8, 3, 1, 7, 8] # 3,1,7,8 print(find_last(seq))
0cab6617a873cc1b33d0d48f50a3c606ff2b2879
alvas-education-foundation/ECE-2year-Code-Challenge
/Securitycode(Vishwesh V Bhat).py
817
3.921875
4
#Objective: WAP to verify Username and Password, Username = 'Micheal' and Password = 'e3$WT89x', and with just 3 attempts for the user. user_name = "Micheal" user_input = input("Enter username : ".upper()) if user_input == user_name: for Attempts in range(3): password = 'x' pas_input = input("Enter password : ".upper()) if pas_input == password: print("You have successfully logged in!!!".upper()) break else: print("Wrong Password!!") else: print("Account locked!!") else: print("wrong Username!!") # Your code has bug, fix the bug File "<string>", line 5 if user_input == user_name: ^ IndentationError: unexpected indent >>>
f686111df92233823618a2433fff7fa4c50d56e0
UCDavisLibrary/scribeAPI
/project/label_this/tools/rotate_exif.py
817
3.5
4
from PIL import Image, ExifTags import os import sys import traceback import pprint def rotate(filename): try : image=Image.open(os.path.join(filename)) for orientation in ExifTags.TAGS.keys() : if ExifTags.TAGS[orientation]=='Orientation' : break exif=dict(image._getexif().items()) if exif[orientation] == 3 : image=image.rotate(180, expand=True) elif exif[orientation] == 6 : image=image.rotate(270, expand=True) elif exif[orientation] == 8 : image=image.rotate(90, expand=True) print("Rotating {}".format(filename)) image.save(os.path.join(filename)) except: #traceback.print_exc() pass if __name__ == '__main__': img = sys.argv[1] rotate(img)
5f3c51a4a7959c6be38c6b809e6403dc14efdd2e
rafaelperazzo/programacao-web
/moodledata/vpl_data/303/usersdata/283/82729/submittedfiles/testes.py
183
3.875
4
# -*- coding: utf-8 -*- #COMECE AQUI ABAIXO a=float(input('Constante 1: ')) b=float(input('Constante 2: ')) Constante3=c (1/c) == (1/a) + (1/b) print("Constante 3: c")
1b57bdcacb28845c0c1083c79a11376d28a521a3
alexanderbart/EulerProject
/euler28.py
1,525
3.796875
4
import numpy as np '''Euler 28''' def spiral_diag(N): ''' Starting at the middle, we move down the row once, then column once. Then we go up row twice, up column twice. Then up row thrice, column thrice. So even numbers of moves increase column and row. Odd numbers of moves decrease column and row. The final piece of the spiral has the same number of moves as previous, so I had to account for that. ''' mat = np.zeros((N,N)) mat[int((N-1)/2),int((N-1)/2)] = 1 moves = 1 num = 2 i = int((N-1)/2) j = int((N-1)/2) while mat[0,int(N-1)] == 0: if moves%2 != 0: for k in range(moves): j += 1 mat[i,j] = num num += 1 for k in range(moves): i += 1 mat[i,j] = num num += 1 if moves%2 == 0: for k in range(moves): j -= 1 mat[i,j] = num num += 1 for k in range(moves): i -= 1 mat[i,j] = num num += 1 if mat[0,0] != 0: for k in range(moves): j += 1 mat[i,j] = num num += 1 moves += 1 diag_sum = 0 for i in range(N): diag_sum += mat[i,i] for i in range(N): diag_sum += mat[i,N-1-i] diag_sum -= 1 #Accounts for middle being double-counted return diag_sum print('The sum of the diagonals is',spiral_diag(1001))
aae1af1f3439baedab4d111f482abb97237d31e4
Mengeroshi/Python-Crash-Course-exercises
/classes/9.5_login_attempts.py
922
3.578125
4
class User: def __init__(self, first_name, last_name, age): self.first_name = first_name self.last_name = last_name self.age = age self.loggin_attempts = 0 def describre_user(self): print(f"Name: {self.first_name.title()}") print(f"Last Name: {self.last_name.title()}") print(f"age: {self.age}") print(f"Loggin attempts: {self.loggin_attempts}\n") def greet_user(self): print(f"Hi {self.first_name.title()} {self.last_name.title()} \n") def increment_loggin_attempts(self): self.loggin_attempts += 1 def reset_loggin_attempts(self): self.loggin_attempts = 0 mgrsh = User("javier", "saviñon", 21) mgrsh.increment_loggin_attempts() mgrsh.describre_user() mgrsh.reset_loggin_attempts() mgrsh.describre_user() mandax = User("julian", "assange", 40) mandax.describre_user() mandax.greet_user()