Dataset Viewer
Auto-converted to Parquet
blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
2c6c08f97ea799ee9afc8bc6cc25f7f764e66d9f
mianguanwu/PySpark_tutorial
/data_frame/basic_exercise.py
880
3.546875
4
#!/usr/bin/python # -*- coding: utf-8 -*- """ example from spark official document """ import os from pyspark.sql import SparkSession os.environ["PYSPARK_PYTHON"] = "/usr/bin/python3" os.environ["PYSPARK_DRIVER_PYTHON"] = "/usr/bin/python3" os.environ['PYSPARK_SUBMIT_ARGS'] = \ '--packages org.apache.spark:spark-sql-kafka-0-10_2.11:2.3.0 ' \ '--master local[2] ' \ 'pyspark-shell' spark = SparkSession\ .builder\ .appName("basic_exercise")\ .getOrCreate() df = spark.read.json("/usr/local/spark/examples/src/main/resources/people.json") df.show() df.select("name").show() df.select(df["name"]).show() df.select(df["name"], df["age"] + 2).show() df.filter(df["age"] > 21).show() df.groupBy(df["age"]).count().show() print("sql operation", "-"*60) df.createOrReplaceTempView("people") sql_df = spark.sql("select * from people") sql_df.show()
7ecdb8efa0e752c0bd0ecd3fd4996687219eb617
CriistianRod/basicpy
/break_continue.py
584
3.5
4
def run(): # for contador in range(1000): # if contador % 2 != 0: # continue # print(contador) # for i in range(10000): # print(i) # if i == 5678: # break # texto = input('Escribe un texto: ') # for letra in texto: # if letra == 'o': # continue # print(letra) i = 0 frase = input('Ingresa una frase: ') while i < len(frase): if frase[i] == 'a': i+=1 continue print(frase[i]) i+=1 if __name__ == '__main__': run()
95f64791b97af372ed64912da0ff92d862250bbf
SoorejRB/Anandolody-python-exercises
/chapter 2/chapter2_problem6.py
121
3.9375
4
# reverse a list x = [ 22,55,33] # print(reverse(x)) not working x.sort() print(x) x.sort(reverse=True) print(x)
9a09d9260888b4e118991ebbba51a4ccf019ca53
klistwan/project_euler
/012.py
436
3.6875
4
#What is the value of the first triangle number to have over 500 divisors? import prime def triangle(n): return n*(n+1)/2 def num_of_divisors(num): return reduce(lambda k,y: k*y, [k+1 for k in prime.factorization(num).values()]) def main(index = 100): while 1: current = triangle(index) current_divisors = num_of_divisors(current) if current_divisors > 500: return current index += 1 print main()
df5716bda9637e27b0e820b11e8be1fa49ef5add
klistwan/project_euler
/60.py
1,472
3.765625
4
from math import sqrt from itertools import combinations, permutations def is_prime(n): if n == 2 or n == 3: return True if n < 2 or n%2 == 0: return False if n < 9: return True if n%3 == 0: return False r, f = int(sqrt(n)), 5 while f<= r: if n%f == 0: return False if n%(f+2) == 0: return False f += 6 return True def prime_sieve(limit): primes = [] cur_num = 2 remaining = range(2,limit) while cur_num <= sqrt(limit): primes.append(cur_num) remaining = filter(lambda n: n%cur_num != 0, remaining) cur_num = remaining[0] primes.extend(remaining) #Adds the rest of the primes into the list return primes def concatenable_primes(n1,n2): if is_prime(int(str(n1)+str(n2))): return is_prime(int(str(n2)+str(n1))) return False def get_concatenable_to_(num): l = [] for n in filter(lambda n: n>num, prime_sieve(100000)): if concatenable_primes(num,n): l.append(n) return l l_to_3 = get_concatenable_to_(13) l_to_7 = get_concatenable_to_(5197) intersect = list(set(l_to_3) & set(l_to_7)) + [13,5197] def has_property(lon): for pair in permutations(lon,2): check = int(str(pair[0]) + str(pair[1])) if not is_prime(check): return False print sum(lon) return True for i in combinations(intersect,5): print "currently at",i if has_property(list(i)): print "THIS IS THE ONE",list(i) break
0e2c1e6aae24313953f787b3f4b783484cc882a8
klistwan/project_euler
/022.py
447
3.734375
4
#What is the total of all the name scores in the file, 022.txt? def compute_score(name): """Calculuates the score of a name, where A = 1, ... Z = 26""" return sum(map(lambda k: ord(k)-64, list(name))) def main(): names = sorted(file("022.txt","r").read()[1:-1].split('","')) name_scores = map(lambda k: compute_score(k), names) return sum(map(lambda k: k[0]*k[1], zip(xrange(1,len(names)+1), name_scores))) print main()
41d2803ce4ce76b1761bf0ea64a510a9bf2aafa3
gva-jjoyce/gva_data
/gva/flows/operators/filter_operator.py
961
3.90625
4
""" Filter Operator Filters records, returns the record for matching records and returns 'None' for non-matching records. The Filter Operator takes one configuration item at creation - a Callable (function) which takes the data as a dictionary as it's only parameter and returns 'true' to retain the record, or 'false' to not pass the record through to the next operator. Example Instantiation: filter_ = FilterOperator(condition=lambda r: r.get('severity') == 'high') The condition does not need to be lambda, it can be any Callable including methods. """ from .internals.base_operator import BaseOperator def match_all(data): return True class FilterOperator(BaseOperator): def __init__(self, condition=match_all): self.condition = condition super().__init__() def execute(self, data={}, context={}): if self.condition(data): return data, context return None
17f35f58a74a074454afa00e65d35bfe9c2ffe7c
gva-jjoyce/gva_data
/gva/utils/trace_blocks.py
2,710
3.890625
4
""" Trace Blocks As data moves between the flows, Trace Blocks is used to create a record of operation being run. This should provide assurance that the data has not been tampered with as it passes through the flow. It uses an approach similar to a block-chain in that each block includes a hash of the previous block. The block contains a hash of the data, the name of the operation, a programatically determined version of the code that was run, a timestamp and a hash of the last block. This isn't distributed, but the intention is that the trace log writes the block hash at the time the data is processed which this Class creating an independant representation of the trace. In order to bypass this control, the user must update the trace log and this trace block. """ import datetime import hashlib import os from .json import serialize EMPTY_HASH = "0" * 64 def random_int() -> int: """ Select a random integer (16bit) """ ran = 0 for b in os.urandom(2): ran = ran * 256 + int(b) return ran class TraceBlocks(): __slots__ = ('blocks') def __init__(self, uuid="00000000-0000-0000-0000-000000000000"): """ Create block chain and seed with the UUID. """ self.blocks = [] self.blocks.append({ "block": 1, "timestamp": datetime.datetime.now().isoformat(), "uuid": uuid }) def add_block(self, **kwargs): """ Add a new block to the chain. """ previous_block = self.blocks[-1] previous_block_hash = self.hash(previous_block) # proof is what makes mining for bitcoin so hard, we're setting a low # target of the last character being a 0,5 (1/5 chance) # if you wanted to make this harder, set a different rule to exit # while loop proof = str(random_int()) while self.hash(''.join([proof, previous_block_hash]))[-1] not in ['0', '5']: proof = str(random_int()) block = { "block": len(self.blocks) + 1, "timestamp": datetime.datetime.now().isoformat(), "previous_block_hash": previous_block_hash, "proof": proof, **kwargs } self.blocks.append(block) def __str__(self): return serialize(self.blocks) def hash(self, block): try: bytes_object = serialize(block, indent=True) except: bytes_object = block raw_hash = hashlib.sha256(bytes_object.encode()) hex_hash = raw_hash.hexdigest() return hex_hash
f35e5923ef0a409e2da71af148865affebdaedf4
gva-jjoyce/gva_data
/tests/performance/timer.py
312
3.5625
4
import time class Timer(object): def __init__(self, name="unnamed"): self.name = name def __enter__(self): self.start = time.perf_counter() def __exit__(self, type, value, traceback): print("{} took {} seconds".format(self.name, time.perf_counter() - self.start))
533f6643fcb2ca8428f4331ada8871481b49e9c5
fbaroni/algorithmic-toolbox
/2_maximum_pairwise_product/sample_generator_max_pairwise_product.py
393
3.90625
4
# python3 from random import randint if __name__ == '__main__': print("Enter the total of numbers to generate the sample for the algorithm") input_number = int(input()) numbers_to_test = [None] * input_number for index, number in enumerate(numbers_to_test): numbers_to_test[index] = randint(1,99) for number in numbers_to_test: print(str(number), end =" ")
728eb185fd2c7793f26f33e60cd3c7119bc3828d
yoniavn/VSCODE
/PYTHON/stractured.py
446
4.21875
4
# list - is mutable (add,delete...) x = [1, 2, 3, 4] x.append("yoni") print(x) # tuple - cant be changed y = (1, 2, 3, 4, 5) print(y) # dictionary dic = {'a': 1, 'b': 2} print(dic) def printList(l): for i in l: print() def main(): letters = ['1', '2', '1', '2', '1', '2'] print(' : '.join(letters)) # join string : after each element printList(letters) print(letters) if __name__ == '__main__': main()
c91270295db3916514df3ab98b478db95254737a
benkk331/CPTAC
/CPTAC/Ovarian/utilities.py
16,533
3.53125
4
import pandas as pd import numpy as np class Utilities: def __init__(self): pass def compare_gene(self, df1, df2, gene, key_id_map): """ Parameters df1: omics dataframe (proteomics) to be selected from df2: other omics dataframe (transcriptomics) to be selected from gene: gene to select from each of the dataframes Returns Dataframe containing two columns. Each column is the data for the specified gene from the two specified dataframes """ if (type(df1) != pd.DataFrame) or (type(df2) != pd.DataFrame): print("Provided data not a dataframe, please check that both data inputs are dataframes") return if gene in df1.columns and gene in df2.columns: #check provided gene is in both provided dataframes common = df1.set_index("patient_key").index.intersection(df2.set_index("patient_key").index) #select for intersection of patient keys between two dataframes df1Matched = df1.set_index("patient_key").loc[common] #select for rows matching common patient keys in df1 df2Matched = df2.set_index("patient_key").loc[common] #select for rows matching common patient keys in df2 assert(hasattr(df1,"name")); assert(hasattr(df2,"name")) #check that both dataframes have a name, which is assined in DataFrameLoader class dict = {df1.name:df1Matched[gene], df2.name:df2Matched[gene]} #create prep dictionary for dataframe mapping name to specified gene column df = pd.DataFrame(dict, index = df1Matched.index) #create dataframe with common rows as rows, and dataframe name to specified gene column as columns df["patient_id"] = key_id_map[key_id_map["patient_key"].isin(list(df.index))].index df["patient_key"] = df.index df = df.set_index("patient_id") df.name = gene #dataframe is named as specified gene return df else: if gene not in df1.columns: if gene not in df2.columns: print(gene,"not found in either of the provided dataframes. Please check that the specified gene is included in both of the provided dataframes.") else: print(gene, "not found in", df1.name, "dataframe. Please check that the specified gene is included in both of the provided dataframes.") else: if gene not in df2.columns: print(gene, "not found in", df2.name, "dataframe. Please check that the specified gene is included in both of the provided dataframes.") else: #Shouldn't reach this branch print("Error asserting",gene,"in",df1.name,"and",df2.name,"dataframes.") def compare_genes(self, df1, df2, genes, key_id_map): """ Parameters df1: omics dataframe (proteomics) to be selected from df2: other omics dataframe (transcriptomics) to be selected from genes: gene or list of genes to select from each of the dataframes Returns Dataframe containing columns equal to the number of genes provided times two. Each two-column set is the data for each specified gene from the two specified dataframes """ if (type(df1) != pd.DataFrame) or (type(df2) != pd.DataFrame): print("Provided data not a dataframe, please check that both data inputs are dataframes") return common = df1.set_index("patient_key").index.intersection(df2.set_index("patient_key").index) common_index = key_id_map[key_id_map["patient_key"].isin(list(common))].index dfs = pd.DataFrame(index = common_index) #create empty returnable dataframe with common rows of df1 and df2 as rows for gene in genes: #loop through list of genes provided df = Utilities().compare_gene(df1, df2, gene, key_id_map) #create temp dataframe per gene in list (can Utilities().compare_gene be changed to self.compare_gene?) new_col1 = df1.name + "_" + gene #create first new column using first dataframe name and gene new_col2 = df2.name + "_" + gene #create second new column using second dataframe name and gene df = df.rename(columns = {df1.name:new_col1, df2.name:new_col2}) #rename columns in returned dataframe dfs = pd.concat([dfs,df[df.columns[0:2]]], axis=1) #append temp dataframe onto returnable dataframe, leaving off patient_key column until the end dfs["patient_key"] = key_id_map.loc[dfs.index] #add patient_key column dfs.name = str(len(genes)) + " Genes Combined" #Name returnable dataframe using number of genes provided return dfs def compare_clinical(self, clinical, data, clinical_col, key_id_map): """ Parameters clinical: clinical dataframe for omics data to be appended with data: omics data for clinical data to be appended with clinical_col: column in clinical dataframe to be inserted into provided omics data Returns Dataframe with specified column from clinical dataframe added to specified dataframe (i.e., proteomics) for comparison and easy plotting """ if clinical_col in clinical: df = data[data.columns].set_index("patient_key") #prep returnable dataframe due to DataFrame.insert() changing by reference. If only df = data, then insert() will change data as well clinical = clinical.set_index("patient_key") #set index as patient key for mapping clinical = clinical.reindex(df.index) #select clinical data with indices matching omics data values = clinical[clinical_col] #get values for clinical column df.insert(0, clinical_col, values) #inserts specified clinical column at the beginning of the returnable dataframe df = df.assign(patient_id = key_id_map[key_id_map["patient_key"].isin(list(df.index))].index) #make patient id (non-S number) df = df.assign(patient_key = df.index) #move index to column (S number) df = df.set_index("patient_id") #set index as patient id (non-S number) df.name = data.name + " with " + clinical_col #assigns dataframe name using data name and specified clinical column return df else: print(clinical_col, "not found in clinical dataframe. You can check the available columns by entering CPTAC.get_clincal().columns") def get_phosphosites(self, phosphoproteomics, gene): regex = gene + ".*" #set regular expression using specified gene phosphosites = phosphoproteomics.filter(regex = (regex)) #find all columns that match the regular expression, aka, all phosphosites for the specified gene if len(phosphosites.columns) == 0: print("Gene",gene, "not found in phosphoproteomics data") else: return phosphosites def compare_phosphosites(self, proteomics, phosphoproteomics, gene): """ Parameters gene: proteomics gene to query phosphoproteomics dataframe Searches for any phosphosites on the gene provided Returns Dataframe with a column from proteomics for the gene specified, as well as columns for all phosphoproteomics columns beginning with the specified gene """ if gene in proteomics.columns: df = proteomics[[gene]] #select proteomics data for specified gene phosphosites = self.get_phosphosites(phosphoproteomics, gene) #gets phosphosites for specified gene if len(phosphosites.columns) > 0: df = df.add(phosphosites, fill_value=0) #adds phosphosites columns to proteomics data for specified gene df.name = gene + " proteomics and phosphoproteomics" return df else: print(gene, "not found in proteomics dataframe. Available genes can be checked by entering CPTAC.get_proteomics().columns") def add_mutation_hierarchy(self, somatic): #private """ Parameters somatic: somatic data to add mutation hierarchy to Retunrs Somatic mutation dataframe with added mutation hierarchy """ mutation_hierarchy = {"Missense_Mutation":0,"In_Frame_Del":0,"In_Frame_Ins":0,"Splice_Site":1,"Frame_Shift_Ins":1,"Nonsense_Mutation":1,"Frame_Shift_Del":1,"Nonstop_Mutation":1} hierarchy = [] for x in somatic["Mutation"]: #for every value in the Mutation column, append its value in the hard coded mutation hierarchy if x in mutation_hierarchy.keys(): hierarchy.append(mutation_hierarchy[x]) else: hierarchy.append(float('NaN')) somatic["Mutation_Hierarchy"] = hierarchy return somatic def merge_somatic(self, somatic, gene, df_gene, key_id_map, multiple_mutations = False): #private """ Parameters somatic: somatic mutations dataframe that will be parsed for specified gene data gene: string of gene to be selected for in somatic mutation data df_gene: selection of omics data for particular gene to be merged with somatic data multiple_mutations: boolean indicating whether to include multiple mutations for specified gene in an individual Returns Dataframe of merged somatic and omics dataframes based on gene provided """ #TODO: use patient_key instead of patient_id, proteomics currently returning all na, therefore 155 gives all wildtypeov if sum(somatic["Gene"] == gene) > 0: somatic_gene = somatic[somatic["Gene"] == gene] #select for all mutations for specified gene somatic_gene = somatic_gene.drop(columns = ["Gene"]) #drop the gene column due to every value being the same somatic_gene = somatic_gene.set_index("patient_key") #set index as patient key (S number) if not multiple_mutations: #if you want to remove duplicate indices somatic_gene = self.add_mutation_hierarchy(somatic_gene) #appends hierachy for sorting so correct duplicate can be kept somatic_gene["forSort"] = somatic_gene.index.str[1:] #creates separate column for sorting somatic_gene[["forSort"]] = somatic_gene[["forSort"]].apply(pd.to_numeric) #converts string column of patient key numbers to floats for sorting somatic_gene = somatic_gene.sort_values(by = ["forSort","Mutation_Hierarchy"], ascending = [True,False]) #sorts by patient key, then by hierarchy so the duplicates will come with the lower number first somatic_gene = somatic_gene.drop(columns=["forSort"]) #drops sorting column somatic_gene = somatic_gene[~somatic_gene.index.duplicated(keep="first")] #keeps first duplicate row if indices are the same merge = df_gene.join(somatic_gene, how = "left") #merges dataframes based on indices, how = "left" defaulting to the df_gene indices. If indices don't match, then mutation column will be NaN merge[["Mutation"]] = merge[["Mutation"]].fillna(value = "Wildtype") #fill in all Mutation NA values (no mutation data) as Wildtype if multiple_mutations: patient_ids = [] patient_keys = list(merge.index) for key in patient_keys: patient_ids.append(key_id_map[key_id_map["patient_key"] == key].index.values[0]) assert(len(patient_ids) == len(patient_keys)) merge["patient_id"] = patient_ids merge = merge.sort_values(by = ["patient_id"]) else: merge["patient_id"] = key_id_map[key_id_map["patient_key"].isin(list(merge.index))].index #reverse lookup for patient key (S number) to patient id (non-S number) merge["patient_key"] = merge.index #move index to column merge = merge.set_index("patient_id") #set index to patient id (non-S number) merge["Sample_Status"] = np.where(merge.index <= "26OV013", "Tumor", "Normal") #26OV013 is the last patient id before the "N******" ids merge.name = df_gene.columns[0] + " omics data with " + gene + " mutation data" return merge else: print("Gene", gene, "not found in somatic mutations.") def merge_mutations(self, omics, somatic, gene, key_id_map, duplicates = False): """ Parameters omics: dataframe containing specific omics data somatic: dataframe of somatic mutation data gene: string of specific gene to merge omics and somatic data on duplicates: boolean value indicating whether to include duplicate gene mutations for an individual Returns Dataframe of merged omics and somatic data based on gene provided """ if gene in omics.columns: omics_gene_df = omics[[gene,"patient_key"]].set_index("patient_key") #select omics data for specified gene, setting index to patient key (S number) for merging if duplicates: #TODO: this breaks right now, merge_somatic can't handle duplicate samples return self.merge_somatic(somatic, gene, omics_gene_df, key_id_map, multiple_mutations = True) else: #filter out duplicate sample mutations return self.merge_somatic(somatic, gene, omics_gene_df, key_id_map)[[gene, "Mutation", "patient_key", "Sample_Status"]] elif omics.name.split("_")[0] == "phosphoproteomics": phosphosites = self.get_phosphosites(omics, gene) if len(phosphosites.columns) > 0: phosphosites = phosphosites.assign(patient_key = omics["patient_key"]) phosphosites = phosphosites.set_index("patient_key") if duplicates: return self.merge_somatic(somatic, gene, phosphosites, key_id_map, multiple_mutations = True) else: columns = list(phosphosites.columns) columns.append("Mutation") columns.append("patient_key") columns.append("Sample_Status") merged_somatic = self.merge_somatic(somatic, gene, phosphosites, key_id_map) return merged_somatic[columns] else: print("Gene", gene, "not found in", omics.name, "data") def merge_mutations_trans(self, omics, omicsGene, somatic, somaticGene, key_id_map, duplicates = False): #same functonality as merge_mutations, but uses somaticGene for merge_somatic """ Parameters omics: dataframe containing specific omics data (i.e. proteomics, transcriptomics) omicsGene: string of specific gene to merge from omics data somatic: dataframe of somatic mutation data somaticGene: string of specific gene to merge from somatic data duplicates: boolean value indicating whether to include duplicate gene mutations for an individual Returns Dataframe of merged omics data (based on specific omicsGene) with somatic data (based on specific somaticGene) """ if omicsGene in omics.columns: omics_gene_df = omics[[omicsGene,"patient_key"]].set_index("patient_key") if duplicates: return self.merge_somatic(somatic, somaticGene, omics_gene_df, key_id_map, multiple_mutations = True) else: return self.merge_somatic(somatic, somaticGene, omics_gene_df, key_id_map)[[omicsGene, "Mutation", "patient_key", "Sample_Status"]] elif omics.name.split("_")[0] == "phosphoproteomics": phosphosites = self.get_phosphosites(omics, omicsGene) if len(phosphosites.columns) > 0: phosphosites = phosphosites.assign(patient_key = omics["patient_key"]) phosphosites = phosphosites.set_index("patient_key") if duplicates: return self.merge_somatic(somatic, somaticGene, phosphosites, key_id_map, multiple_mutations = True) else: columns = list(phosphosites.columns) columns.append("Mutation") columns.append("patient_key") columns.append("Sample_Status") merged_somatic = self.merge_somatic(somatic, somaticGene, phosphosites, key_id_map) return merged_somatic[columns] else: print("Gene", omicsGene, "not found in", omics.name,"data")
c89694b3391ff817ea4235f91f8a9100a72d52d4
sevenbean/Machine-Learning
/面向对象编程/类方法和类属性/Tools.py
309
3.53125
4
class Tools: count=0 def __init__(self,name): self.name=name # 类属性 Tools.count+=1 @classmethod def show_count(cls): print("工具的数量%d"%(Tools.count)) tool1=Tools("铁锤") tool2=Tools("榔头") tool3=Tools("菜刀") Tools.show_count()
54fc9410656c16ab2c1f1ab3810f3bac12b0dfe3
sevenbean/Machine-Learning
/网络爬虫/BeautifulSoup/BeautifulSoup3.py
1,162
3.5
4
import requests from bs4 import BeautifulSoup html = """ <html> <head><title>标题</title></head> <body> <p class="title" name="dromouse"><b>标题</b></p> <div name="divlink"> <p> <a href="http://example.com/1" class="sister" id="link1">链接1</a> <a href="http://example.com/2" class="sister" id="link2">链接2</a> <a href="http://example.com/3" class="sister" id="link3">链接3</a> </p> </div> <p></p> <div name='dv2'></div> </body> </html> """ soup=BeautifulSoup(html,"html.parser") #通过标签选择器,选择 print(soup.select("title")[0]) # 通过标签逐层查找 print(soup.select("html head title")) #通过id选择器选择 print(soup.select("#link1")) #通过class标签来寻找 print(soup.select(".sister")) #通过组合进行选择 print(soup.select("p #link1")) print("*"*20) print(soup.select("p .sister")) print("*"*20) print(soup.select_one("head >title")) print(soup.select("p >#link2")) print(soup.select("p >a:nth-of-type(2)")) print("*"*50) print(soup.select("#link1~#link3")) print("*"*50) print(soup.select("#link1~.sister")) print("*"*20) print(soup.select("[name]"))
057b17ec2d60509a49367083972b9dd9436e7677
shekhar-joshi/Assignments
/compute.py
341
4
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun May 27 00:46:20 2018 @author: shekhar Write a function to compute 5/0 and use try/except to catch the exceptions. """ def compute(): return 5/0 try: compute() except ZeroDivisionError: print( "division by zero!!!!!!! " ) finally: print("Cleaning")
db07a4fce4ea8cdb1eaa7d9049eb816e1d8cac8f
Denvol10/lesson1
/peremen.py
410
4.28125
4
# Переменные a = 2 print(a + 3) # 5 # a = b значит "записать значение b в переменную a" a = 2 a = a + 1 print(a) # 3 ''' Правило именования переменных: 1. На английском(не называть транслитом); 2. snake_case 3. Отражать точный смысл 4. Обычно существительные '''
a438b0efcbeedf94e6f3c8ad364004dd25d5b125
dimeskigj/game-of-life
/gameoflife.py
3,336
3.90625
4
""" The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is a zero-player game, meaning that its evolution is determined by its initial state, requiring no further input. One interacts with the Game of Life by creating an initial configuration and observing how it evolves. It is Turing complete and can simulate a universal constructor or any other Turing machine. Rules: 1. Any live cell with fewer than two live neighbours dies, as if by underpopulation. 2. Any live cell with two or three live neighbours lives on to the next generation. 3. Any live cell with more than three live neighbours dies, as if by overpopulation. 4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction. src: https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life """ import os import matplotlib.pyplot as plot import numpy from PIL import Image from starters import * STEPS = ((-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)) def next_generation(matrix): """ :param matrix: a configuration :return: the next iteration, a new matrix """ next_gen = numpy.copy(matrix) for i in range(len(next_gen)): for j in range(len(next_gen[0])): count = count_living_neighbours(matrix, i, j) if matrix[i][j] == 1 and (count == 2 or count == 3): next_gen[i][j] = 1 elif matrix[i][j] == 0 and count == 3: next_gen[i][j] = 1 else: next_gen[i][j] = 0 return next_gen def count_living_neighbours(matrix, i, j): """ :return: the number of living neighbours of the element at (i, j) in the matrix """ valid_steps = [(x[0] + i, x[1] + j) for x in STEPS if 0 <= x[0] + i < len(matrix) and 0 <= x[1] + j < len(matrix[0])] return sum([matrix[x][y] for x, y in valid_steps]) DEF_PATH = "images\\generation_{}.png" def simulate_iterations(n, matrix): """ :param n: number of generations :param matrix: initial configuration :return: list of Image objects """ return recursive_helper(1, n, matrix, []) def recursive_helper(start, end, matrix, imgs): if start > end: return imgs path = DEF_PATH.format(start) # generating the image # plot.spy(matrix) plot.title("Iteration {}".format(start)) plot.xticks([]) plot.yticks([]) plot.savefig(path) ######################## # loading the image and appending it # imgs.append(Image.open(path)) new_gen = next_generation(matrix) return recursive_helper(start + 1, end, new_gen, imgs) if __name__ == '__main__': # find more initial configurations in starters.py # initial_config = gliders N = 30 images = simulate_iterations(N, initial_config) # saving a gif made up of the images # images[0].save("output.gif", format="GIF", append_images=images[1:], save_all=True, duration=150, loop=0) ###################################### # deleting the temp files # images = [] [os.remove(DEF_PATH.format(i)) for i in range(1, N + 1)] ############################ print("done")
500082ff7e91cb5db105454f1aea57eea82fde6a
elugens/leet-code-python
/two_sums.py
554
3.8125
4
''' Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Input: [1, 3, 2, 2], 4 Output: [0,1] ''' class Solution: def twoSum(self, nums, target): for i in range(len(nums)): if (target - nums[i] in nums) and (not nums.index(target - nums[i]) == i): return [i, nums.index(target - nums[i])] total = Solution() print(total.twoSum([1, 3, 2, 2], 4))
1d6a64bd3b580c308fe537a13380fe9c14fe7c0d
elugens/leet-code-python
/code_templates/BinarySearch/find_minimum_rotated_array.py
1,291
3.5625
4
# Find Minimum in Rotated Sorted Array [4,5,6,7,0,1,2] class Solution(object): def findMin(self, nums): """ :type nums: List[int] :rtype: int """ left = 0 right = len(nums)-1 # base case - find out if nums has only one value at index 0 # return that number as the minimum if len(nums) == 1: return nums[0] # Edge case - if last number is greater than the number at index 0 # return that num index 0 as the minimum if nums[right] > nums[0]: return nums[0] # Binary Search while right >= left: # Set the mid point mid = left + (right - left)//2 # if left nums are greater than the right return the right if nums[mid] > nums[mid+1]: return nums[mid + 1] # if right nums are greater that the left return left if nums[mid - 1] > nums[mid]: return nums[mid] # if left nums are greater nums on the right than the smallest element is on the right if nums[mid] > nums[0]: left = mid + 1 # Once you get here you should have the smallest element else: right = mid - 1
ed8fccc4e5810f6767cf7742d2828318a8812263
elugens/leet-code-python
/binarysearch.py
473
3.90625
4
# Binary Search on an orderd list def search(nums, target): first = 0 last = len(nums)-1 found = False while first <= last and not found: mid = (first+last)//2 if nums[mid] == target: found = True else: if target < nums[mid]: last = mid-1 else: first = mid+1 return found nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 20] result = search(nums, 21) print(result)
ff529e36ceed0654d9a531e284010393f8a8c4bb
elugens/leet-code-python
/Recursion/word_split.py
1,111
4.3125
4
# Problem 3 # ----------------- # Create a function called word_split() which takes in a string phrase and a # set list_of_words. The function will then determine if it is possible to split # the string in a way in which words can be made from the list of words. You can # assume the phrase will only contain words found in the dictionary if it is # completely splittable. def word_split(phrase, list_of_words, output=None): # Base Case if output is None: output = [] # Starting loop phrase to check word matching list of words for word in list_of_words: # Check for to see if word starts with first word in list_of_words if phrase.startswith(word): # if the word in phrase matches first word append word to output output.append(word) # Recursive Call to on next word in list of words return word_split(phrase[len(word):], list_of_words, output) return(output) result1 = word_split('themanran', ['clown', 'ran', 'man']) print(result1) result2 = word_split('themanran', ['the', 'ran', 'man']) print(result2)
fc06412eeed2c1f0f78afdee26e4092dc8d3ea24
elugens/leet-code-python
/Arrays n Sequences/find_the_missing_number2.py
493
3.671875
4
import collections def finder2(arr1, arr2): # Using default dict to avoid key errors d = collections.defaultdict(int) breakpoint() # Add a count for every instance in Array 1 for num in arr2: d[num] += 1 # Check if num not in dictionary for num in arr1: if d[num] == 0: return num # Otherwise, subtract a count else: d[num] -= 1 arr1 = [5, 5, 7, 9, 7] arr2 = [5, 5, 7, 7] print(finder2(arr1, arr2))
35e37340d42b20416c576f8a7521b222ae19d07d
harshavardhanak/ComputerNetworking
/Lab8/Lab8.py
1,763
3.984375
4
class Network: def __init__(self, n): self.matrix = [] self.n = n def addlink(self, u, v, w): self.matrix.append((u, v, w)) def printtable(self, dist, src): print("Vector Table of {}".format(chr(ord('A')+src))) print("{0}\t{1}".format("Dest", "cost")) for i in range(self.n): print("{0}\t{1}".format(chr(ord('A')+i), dist[i])) # The main function that finds shortest distances from src to # all other vertices using Bellman-Ford algorithm. The function # also detects negative weight cycle def algor(self, src): # Step 1: Initialize distances from src to all other vertices dist = [99] * self.n dist[src] = 0 # Step 2: Relax all edges |V| - 1 times. A simple shortest # path from src to any other vertex can have at-most |V| - 1 # edges for _ in range(self.n - 1): # Update dist value and parent index of the adjacent vertices of # the picked vertex. Consider only those vertices which are still in # queue for u, v, w in self.matrix: if dist[u] != 99 and dist[u] + w < dist[v]: dist[v] = dist[u] + w # print all distance self.printtable(dist, src) def main(): matrix = [] print("Enter No. of Nodes : ") n = int(input()) print("Enter the Adjacency Matrix :") for i in range(n): m = list(map(int, input().split(" "))) matrix.append(m) g = Network(n) for i in range(n): for j in range(n): if matrix[i][j] == 1: g.addlink(i, j, 1) for _ in range(n): g.algor(_) main()
6ddffa5f003a322dee549b1aee9da6ee9f780371
RicardoR22/Tweet-Generator
/Code/histogram_dictionary.py
562
4.15625
4
from histogram_functions import get_words def count_words(words_list): """Count occurences in the given list of words_list and return that data structure""" word_counts = {} for word in words_list: # check if we saw this word before if word in word_counts: # increase its count by 1 word_counts[word] += 1 else: # set it's count to 1 word_counts[word] = 1 return word_counts word_list = get_words('GoT_text.txt') counts = count_words(word_list) print_table(counts)
18af17c39f8d253c580a87d47965a734347b3fdc
RicardoR22/Tweet-Generator
/Code/histogram_lists.py
953
4.09375
4
from histogram_functions import get_words def count_words(words_list): """Count occurences in the given list of words_list and return that data structure""" word_counts = [] for word in words_list: # check if we saw this word before for list in word_counts: # increase its count by 1 if word in list: list[1] += 1 break else: # set it's count to 1 new_list = [word, 1] word_counts.append(new_list) return word_counts def print_table(word_counts): """Prints out a table of words and their counts.""" print('Word | Count') print('-----------------') for list in word_counts: count = list[1] word = list[0] print('{} | {}'.format(word, count)) if __name__ == '__main__': word_list = get_words('GoT_text.txt') counts = count_words(word_list) print_table(counts)
82f752147f144d731de92040ea7aa3479f672863
OhsterTohster/Project-Euler
/Python/q7.py
878
3.859375
4
# What is the 10 001st prime number? #idk whats wrong with the code but something is wrong somewhere because 10001st prime number would mean 10001 elements in the list and thus # primeNumbers[10000] right? import math def checkPrime(num): isPrime = True if (num % 2 == 0): isPrime = False return isPrime for i in range(3,math.ceil(math.sqrt(num))+1,2): if (num % i == 0): isPrime = False break return isPrime def solve(): primeNumbers = [2,3,5,7,11,13] currentNumber = 13 while True: if (len(primeNumbers) > 10001): break else: checkValue = checkPrime(currentNumber) if (checkValue == True): primeNumbers.append(currentNumber) currentNumber+=2 print(primeNumbers[10001]) print(len(primeNumbers)) solve()
a7f2bc6e50a631af23f1e9eacbbbce9fa3faf104
IvanicsSz/python-lightweight-erp-3rd-tw
/common.py
1,822
3.984375
4
# implement commonly used functions here import string import random # generate and return a unique and random string # other expectation: # - at least 2 special char()expect: ';'), 2 number, 2 lower and 2 upper case letter # - it must be unique in the list # # @table: list of list # @generated: string - generated random string (unique in the @table) def generate_random(table): """generate a random unique id""" generated = "" while(generated == "" or generated in [x[0] for x in table]): abc = [string.digits, string.ascii_uppercase, string.ascii_lowercase] generated = ''.join([random.choice(abc[abs(i)//2]) for i in range(-5, 6, 2)]) + "#&" return generated def sorting(list_sort, index=""): """sorting an unsorted list (with index)""" for i in range(len(list_sort)): for n in range(1, len(list_sort)): if index == "": if list_sort[n] < list_sort[n - 1]: list_sort[n - 1], list_sort[n] = list_sort[n], list_sort[n - 1] else: if list_sort[n][index].casefold() < list_sort[n - 1][index].casefold(): list_sort[n - 1], list_sort[n] = list_sort[n], list_sort[n - 1] return list_sort def removing(table, _id): """an id defined item remove from list""" return [x for x in table if x[0] != _id] def adding(table, add_list): """ ad new id element to a list""" return table + [[generate_random(table)] + add_list] def updating(table, _id, update_list): """updating a list with modification""" if [x for x in table if x[0] == _id]: table = [x for x in table if x[0] != _id] + [[_id] + update_list] return table def summing(sum_list): """sum of a list""" summa = 0 for i in sum_list: summa += i return summa
37b2a41de74f4bbdf2674f42a31cdd69fa8e68e1
el-hult/adventofcode2019
/day06/day6_lib.py
2,735
3.703125
4
from collections import namedtuple from typing import Dict, List, Callable Node = namedtuple('Node', 'name parent children data') def make_tree_from_adj_list(adj_list): root = 'COM' nodes: Dict['str', Node] = {root: Node(root, None, [], {})} for parent, child in adj_list: node = Node(child, parent, [], {}) nodes[child] = node # N.B. I modify node_lookup under iteration, so I cast to list and slice, to get a fixed iterator for node in list(nodes.values())[:]: if not (node.parent in nodes.keys()) and node.name != root: parent_node = Node(node.parent, root, [], {}) nodes[node.parent] = parent_node for node in nodes.values(): if node.name != root: nodes[node.parent].children.append(node) return nodes[root] def compute_descendants(tree_root, f_descendants='n_descendants'): topo_sorted_nodes = all_descendants_BFS(tree_root) reverse_topo_sort = reversed(topo_sorted_nodes) for n in reverse_topo_sort: if len(n.children) == 0: n.data[f_descendants] = 0 else: n.data[f_descendants] = len(n.children) + sum(nn.data[f_descendants] for nn in n.children) def all_descendants_BFS(tree_root: Node) -> List[Node]: """All descendents of a node, in Breadth First Search order""" topo_sorted_nodes = [tree_root] for n in topo_sorted_nodes: topo_sorted_nodes += n.children return topo_sorted_nodes def find_DFS(predicate: Callable[[Node], bool], node: Node) -> List[Node]: """Returns the path in the tree from the root node to the first element that fulfils the predicate""" def find_DFS_(predicate,node) -> List[Node]: if predicate(node): return [node] elif len(node.children) == 0: return [] else: for c in node.children: dfs1 = find_DFS_(predicate,c) if len(dfs1) > 0: return [node] + dfs1 return [] path_found = find_DFS_(predicate,node) if len(path_found) > 0: return path_found else: raise ValueError("There is no element in the tree that fulfils the predicate.") def calculate_hops(root: Node) -> int: nodes = all_descendants_BFS(root) bottom_up = reversed(nodes) for node in bottom_up: try: p1 = find_DFS(lambda n: n.name == 'YOU', node) p2 = find_DFS(lambda n: n.name == 'SAN', node) hops_to_santa = len(p1) + len(p2) - 4 #remove both endpoints of both paths return hops_to_santa except ValueError: pass raise ValueError("There is no common object that one can orbit hop through to get to Santa!")
ff619235455a64ff796c4b7c19b6c52345b5f067
muondu/Election-Platform
/Voter.py
3,317
4.125
4
import sqlite3 def Voter(): candidate = sqlite3.connect('candidates.db') can = candidate.cursor() donn = sqlite3.connect('voter.db') d = donn.cursor() conn = sqlite3.connect('voting.db') c = conn.cursor() c.execute('CREATE TABLE IF NOT EXISTS voted(name TEXT)') d.execute('CREATE TABLE IF NOT EXISTS voter(fName TEXT,sName TEXT,id_number INTEGER)') firstName = input("Enter your first name: ") if firstName == " ": print("You cannot put spaces") Voter() else: def secondName(): global second_name second_name = input("Enter your second name: ") secondName() if second_name == " ": print("You can't piut spaces") secondName() else: try: age = int(input("Enter your age: ")) if age < 18: print("You are not able to vote") elif age > 18: try: id_number = int(input("Enter your id_number(8 digits): ")) id_num = str(id_number) if len(id_num) < 7 or len(id_num) > 9: print("The id number does not reach the number of digits") else: d.execute("INSERT INTO voter(fName, sName,id_number)VALUES(?,?,?)",(firstName, second_name,id_number)) can.execute('SELECT * from candidate') print(can.fetchall()) def voting_canidate(): # for row in can.execute('SELECT * from candidate'): # list1 = list(row) # print(list1) # which_canidate = input("Which canidate do you want: ") # print("Thank you for voting. Good Bye") # c.execute('INSERT INTO voted VALUES(?)',(which_canidate,)) # # c.execute('SELECT * FROM voted') # conn.commit() # exit() # break which_canidate = input("Which canidate do you want: ") if which_canidate == " ": print("There are no spacebars") voting_canidate() else: print("Thank you for voting. Good bye") c.execute('INSERT INTO voted VALUES(?)',(which_canidate,)) conn.commit() exit() voting_canidate() except ValueError: print("That is not a number") id_number_function() except ValueError: print("Pls input a number") Voter()
40ce79c2be533f0e0e0cb144c6bb47a8fa356a49
JoeHall97/PathFinder
/Python/PathFinder.py
5,147
3.78125
4
""" Created on Wed Aug 21 17:11:14 2019 @author: Joseph Hall """ from math import sqrt from sys import argv class Map: def __init__(self,map: list[str],path: list[str]) -> None: self.map = map self.curr_pos = [] self.path = path self.start_pos = self.__getStartPos() self.goal_pos = self.__getGoalPos() self.directions: dict[str, int] = {"north":-1, "south":1, "east":1, "west":-1} self.__drawPath() def __str__(self) -> str: s = "" for m in self.map: s += m return f'{s}\nPath:{self.path}\nPath Length:{len(self.path)}\nCurrent Position:{self.curr_pos}' def __getStartPos(self) -> int | list[int]: pos = 0 for line in self.map: if(line.find('S')!=-1): return [pos,line.find('S')] pos += 1 return -1 def __getGoalPos(self) -> int | list[int]: pos = 0 for line in self.map: if(line.find('G')!=-1): return [pos,line.find('G')] pos += 1 return -1 def __drawPath(self) -> None: pos = self.start_pos if pos == -1: print("ERROR: No start position in given map file!") return for p in self.path: if(p=="north" or p=="south"): pos[0] += self.directions[p] else: pos[1] += self.directions[p] line = self.map[pos[0]] self.map[pos[0]] = line[0:pos[1]] + '.' + line[pos[1]+1:len(line)] self.curr_pos = pos def readMap(map_name) -> str: m = open(map_name,'r') map = [line for line in m] return map def cost(map) -> int: return len(map.path) def heuristic(map) -> float: goal_pos = map.goal_pos curr_pos = map.curr_pos # √((posX-goalX)^2 + (posY-goalY)^2) x_value = (curr_pos[0]-goal_pos[0]) * (curr_pos[0]-goal_pos[0]) y_value = (curr_pos[1]-goal_pos[1]) * (curr_pos[1]-goal_pos[1]) return sqrt(x_value+y_value) def heuristicAndCost(map) -> float: return(heuristic(map)+cost(map)) def expand(map,visted_positions) -> list[Map]: maps = [] pos = map.curr_pos # check north if pos[0]-1>0 and [pos[0]-1,pos[1]] not in visted_positions and (map.map[pos[0]-1][pos[1]]==' ' or map.map[pos[0]-1][pos[1]]=='G'): new_path = map.path.copy() new_path.append("north") maps.append(Map(map.map.copy(),new_path)) # check south if pos[0]+1<len(map.map) and [pos[0]+1,pos[1]] not in visted_positions and (map.map[pos[0]+1][pos[1]]==' ' or map.map[pos[0]+1][pos[1]]=='G'): new_path = map.path.copy() new_path.append("south") maps.append(Map(map.map.copy(),new_path)) # check west if pos[1]-1>0 and [pos[0],pos[1]-1] not in visted_positions and (map.map[pos[0]][pos[1]-1]==' ' or map.map[pos[0]][pos[1]-1]=='G'): new_path = map.path.copy() new_path.append("west") maps.append(Map(map.map.copy(),new_path)) # check east if pos[1]+1<len(map.map[pos[0]]) and [pos[0],pos[1]+1] not in visted_positions and (map.map[pos[0]][pos[1]+1]==' ' or map.map[pos[0]][pos[1]+1]=='G'): new_path = map.path.copy() new_path.append("east") maps.append(Map(map.map.copy(),new_path)) return maps def searchMap(debug,fileName,search_type) -> None: if search_type not in ["a-star", "best-first", "breadth-first", "depth-first"]: print(f"Search type {search_type} is not a valid search type.") return search_map = Map(readMap(fileName),[]) maps = [search_map] visted_positions = [search_map.start_pos] goal_pos = maps[0].goal_pos num_expansions = 0 while True: if(debug): print(maps[0]) print(f"Number of expansions: {str(num_expansions)}") time.sleep(1) num_expansions += 1 for m in expand(maps.pop(0),visted_positions): if(goal_pos==m.curr_pos): # add goal back to map goal_line = m.map[goal_pos[0]] goal_line = goal_line[0:goal_pos[1]] + 'G' + goal_line[goal_pos[1]+1:len(goal_line)] m.map[goal_pos[0]] = goal_line print(m) print(f"Number of expansions: {str(num_expansions)}") return if(search_type in ["a-star", "best-first", "breadth-first"]): maps.append(m) elif(search_type=="depth-first"): maps = [m] + maps visted_positions.append(m.curr_pos) if(search_type=="a-star"): maps = sorted(maps,key=heuristicAndCost,reverse=False) elif(search_type=="best-first"): maps = sorted(maps,key=heuristic) def main() -> None: # alogrithms = ["a-star", "best-first", "breadth-first", "depth-first"] if len(argv) == 4: searchMap(True,str(argv[2]),str(argv[3])) elif len(argv) == 3: searchMap(False,str(argv[1]),str(argv[2])) else: searchMap(False,"../Maps/map3.txt","a-star") if __name__ == "__main__": main()
e2aa7df1981591961ce86a0ae6ec86de66bb0341
akumarkk/Algorithms
/twenty_eight/2_matrix_region_sum/matrix_region_sum.py
1,701
4.09375
4
# Time complexity : O(m * n) # Space complexity : O(m * n) def print_matrix(matrix): for row in matrix: print(row) def matrix_sum(matrix): #x = 0, y=0 n_rows = len(matrix) n_cols = len(matrix[0]) print("Rows = ", n_rows, " Columns = ", n_cols) # Create sum_matrix with all 0's sum_matrix = [[0]*n_cols for rows in range(n_rows)] # Initialize first row to row sum sum_matrix[0][0] = matrix[0][0] for row in range(1, len(matrix)): sum_matrix[row][0] = matrix[row][0] + sum_matrix[row-1][0] print("Initialized rows...") print_matrix(sum_matrix) for col in range(1, n_cols): sum_matrix[0][col] = sum_matrix[0][col-1] + matrix[0][col] print("Initialized rows...") print_matrix(sum_matrix) for row in range(1, len(matrix)): for col in range(1, n_cols): sum_matrix[row][col] = matrix[row][col] + sum_matrix[row-1][col] + sum_matrix[row][col-1] - sum_matrix[row-1][col-1] print("Sum Matrix : ") print_matrix(sum_matrix) return sum_matrix def matrix_region_sum(matrix, A, D): sum_matrix = matrix_sum(matrix) row1, col1 = A row2, col2 = D if row1 == row2 and col1 == col2: return matrix[row1][col1] if row1 == 0 or col1 == 0: OA = 0 else: OA = sum_matrix[row1-1][col1-1] if row1 == 0: OB = 0 else: OB = sum_matrix[row1-1][col2] if col1 == 0: OC = 0 else: OC = sum_matrix[row2][col1-1] OD = sum_matrix[row2][col2] return (OD - OB - OC + OA) matrix = [[1, 2, 3], [4, 5, 6]] for row in matrix: print(row) matrix_sum(matrix) region_sum = matrix_region_sum(matrix, [0, 1], [1, 2]) print("Region sum (0, 1) to (2, 2) : ", region_sum)
26a52c038fffd009435c42c10f23fc54cd971482
RussellStauffer/developers
/Item_46.py
772
4.0625
4
# Python Item 46. # # Use Python 2.7 # # Demonstration of the Python Range function. # # Software Developer: Russell Stauffer # Date: 01 May 2017 # #====================================================================== # Part One # Print items 0,1,2,3 # for i in range(0,4): print i #====================================================================== # # Part Two # Print a countdown (3,2,1,0) # print ("\n") k = 0 firstSet = [] for j in range(3,-1,-1): firstSet.append(j) k = k + 1 print firstSet # #====================================================================== # # Part Three # Print a countdown by two from 8. # print ("\n") l=0 secondSet = [] for k in range(8,0,-2): secondSet.append(k) print secondSet
d6c4982be3ad8ee30d54ba5ca428c63b71c4b30f
Gupocca/CSCD110
/poker/PokerFinal.py
4,914
3.515625
4
from Card import * import datetime class Hand(): def __init__(self): self.values = [] # create value list for c in range(5): # draw hand card = Card() while card in self.values: # must be unique card = Card() self.values.append(card) # add to list self.values.sort() self.score = self.getHighestType() # get the score def __str__(self): return str(self.values) # return the value list def getHighestType(self): if (self.isStraight() and self.isFlush()): return 0 # straight flush elif (self.hasNumMatchingCards(4)): return 1 # four of a kind elif (self.hasGroups(3, 2)): return 2 # full house elif (self.isFlush()): return 3 # flush elif (self.isStraight()): return 4 # straight elif (self.hasNumMatchingCards(3)): return 5 # three of a kind elif (self.hasGroups(2, 2)): return 6 # two pairs elif (self.hasNumMatchingCards(2)): return 7 # one pair else: return 8 # high card def isFlush(self): for i in range(5): # all cards must have the same suit as the first if not self.values[i].isSameSuit(self.values[0]): return False return True def isStraight(self): flag = False self.values.sort() for i in range(5): # loop through values, check for pattern like: [1,2,3,4,5] if self.values[i].rank == self.values[0].rank + i: flag == True if self.values[0].rank == 0: # check for ace self.values[0].rank = 14 for i in range(5): # loop through values, check for pattern like: [1,2,3,4,5] if self.values[i].rank == self.values[0].rank + i: flag == True self.values[0].rank = 0 return flag def hasGroups(self, size1, size2): # size1 + size2 <= 5 hand = self.removeMatchingCards(self.values, size1) # a group hand = self.removeMatchingCards(hand, size2) # removes another # if both were removed w/ success, then the len() should equal... if (len(hand) == 5 - size1 - size2): return True return False def hasNumMatchingCards(self, number): ranks = [] for card in self.values: # add ranks to list ranks.append(card.rank) for i in range(1, 13): # find a match if ranks.count(i) >= number: return True return False def removeMatchingCards(self, p_hand, number): hand = [] hand.extend(p_hand) ranks = [] match = 0 for card in hand: # enumerate through cards and add ranks to list ranks.append(card.rank) for i in range(1, 13): # enumerate through numbers to find exact match if ranks.count(i) >= number: match = i if match != 0: # found result for i in range(number): # only removes first x results for precision ix = ranks.index(match) hand.pop(ix) ranks.pop(ix) return hand ################################################# def main(): # get number of hands from user handNum = 0 # ensure that the number is valid while (handNum == 0 or handNum == None): handNum = intInput() data = [0,0,0,0,0,0,0,0,0] titles = ['Straight Flush','Four of a Kind','Full House','Flush','Straight','Three of a Kind','Two Pairs','One Pair','High Card'] # loop for number of hands for h in range(handNum): hand = Hand() # draw hand data[hand.score] += 1 # increment cache = 'Hands drawn: ' + str(handNum) + '\n\n' # begin the cache for i in range(9): # add each data data score to the output cache cache += getScore(titles[i], data[i], handNum, [1,1,2,3,2,0,2,2,2][i]) # list at the end contains "tab #s" for display print('\n' + cache) # print cache to screen cache = cache.replace('\t',' ') # remove tabs for file formatting writeResults(cache) # write to file #----------------------------------------------- def getScore(title, score, total, tabs = 0): # returns formatted score -- "title: number (percent %)" return str(title) + ':' + '\t' * tabs + ' ' + str(score) + ' (' + str(score/total*100) + '%)\n' #----------------------------------------------- def writeResults(stats): try: with open('results.txt', 'a') as f: # general statistics (percentages) f.write('\n[' + str(datetime.datetime.now()) +']\n') f.write('\nRESULTS:\n\n' + stats + '\n' + '-' * 20 + '\n') except: print('Unable to write to file') def intInput(): # gets number of hands from user try: return int(input('Number of hands: ')) except: return None main()
5bd5bfc1887c623a4aab8a613fe0a4f705fc9879
adriculous/pythonbible
/while.py
218
4.0625
4
# playing around with loopy loops - count from 1 to 10 L = [] while len(L) <3: new_name = input("Please add a new name: ").strip().capitalize() L.append(new_name) print("Sorry, list is full.") print(L)
9d3083df49a761cd73e3fae4c6d7128ebd113978
renkeji/leetcode
/python/src/main/python/Q015.py
1,482
3.578125
4
from src.main.python.Solution import Solution # Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? # Find all unique triplets in the array which gives the sum of zero. # # Note: # Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c) # The solution set must not contain duplicate triplets. # # For example, given array S = {-1 0 1 2 -1 -4}, # A solution set is: # (-1, 0, 1) # (-1, -1, 2) class Q015(Solution): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ ans = [] if nums and len(nums) >= 3: nums.sort() i = 0 while i < len(nums)-2: j, k = i+1, len(nums)-1 while j < k: sum = nums[i] + nums[j] + nums[k] if sum == 0: ans.append([nums[i], nums[j], nums[k]]) k -= 1 while j < k < len(nums)-1 and nums[k] == nums[k+1]: k -= 1 j += 1 while k > j and nums[j] == nums[j-1]: j += 1 elif sum < 0: j += 1 else: k -= 1 i += 1 while i < len(nums)-2 and nums[i] == nums[i-1]: i += 1 return ans
19480df23eb7b8111cf1e2ffadc6712a3f66a281
renkeji/leetcode
/python/src/main/python/Q032.py
1,063
3.71875
4
from src.main.python.Solution import Solution # Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) # parentheses substring. # # For "(()", the longest valid parentheses substring is "()", which has length = 2. # # Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4. class Q032(Solution): def longestValidParentheses(self, s): """ :type s: str :rtype: int """ ans = 0 if s: stack = [] start = 0 for i in range(len(s)): if s[i] == '(': stack.append(i) else: if not stack: # s[i] == ')' start = i + 1 else: stack.pop() if not stack: ans = max(ans, i-start+1) else: ans = max(ans, i-stack[-1]) return ans
09ce63378ccfd087fb05fd0e80dd26e7e0b14d22
renkeji/leetcode
/python/src/main/python/Q123.py
1,131
3.75
4
from src.main.python.Solution import Solution # Say you have an array for which the ith element is the price of a given stock on day i. # # Design an algorithm to find the maximum profit. You may complete at most two transactions. # # Note: # You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). class Q123(Solution): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ max_p = 0 if prices: profits = [0] * len(prices) buy, sell = prices[0], prices[-1] diff1, diff2 = 0, 0 for i in range(len(prices)): if prices[i] > buy: diff1 = max(diff1, prices[i] - buy) else: buy = prices[i] if prices[-i-1] < sell: diff2 = max(diff2, sell - prices[-i-1]) else: sell = prices[-i-1] profits[i] += diff1 profits[-i-1] += diff2 max_p = max(profits) return max_p
64282b236720ea9745a5362a0df8f2a72dc2f60b
renkeji/leetcode
/python/src/main/python/Q113.py
1,099
3.90625
4
from src.main.python.Solution import Solution # Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. # # For example: # Given the below binary tree and sum = 22, # 5 # / \ # 4 8 # / / \ # 11 13 4 # / \ \ # 7 2 1 # return # [ # [5,4,11,2], # [5,8,4,5] # ] class Q113(Solution): def pathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: List[List[int]] """ def path_sum(root, sum, path, ans): if not root: return remainder = sum - root.val path.append(root.val) if not root.left and not root.right: if remainder == 0: ans.append(path[:]) else: path_sum(root.left, remainder, path, ans) path_sum(root.right, remainder, path, ans) path.pop() ans = [] if root: path_sum(root, sum, [], ans) return ans
6b2a262d6ee41a6a0b7bd08f64dc0a24db8dfe94
renkeji/leetcode
/python/src/main/python/Q002.py
1,102
3.84375
4
from src.main.python.Solution import Solution from src.main.python.datastructures.ListNode import ListNode # You are given two linked lists representing two non-negative numbers. # The digits are stored in reverse order and each of their nodes contain a single digit. # Add the two numbers and return it as a linked list. # # Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) # Output: 7 -> 0 -> 8 class Q002(Solution): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ prev, curr, head = None, None, None carry = 0 while l1 is not None or l2 is not None: l1_val = 0 if l1 is None else l1.val l2_val = 0 if l2 is None else l2.val sum = (l1_val + l2_val + carry) % 10 carry = (l1_val + l2_val + carry) / 10 curr = ListNode(sum) if head is None: head = curr else: prev.next = curr prev = curr if carry == 1: prev.next = ListNode(1) return head
dd09b9ff24c52057208c6feaa0f9ae8f8ca3e054
renkeji/leetcode
/python/src/test/python/test_q006.py
298
3.5625
4
from unittest import TestCase from src.main.python.Q006 import Q006 class TestQ006(TestCase): def test_convert(self): solution = Q006() s = "PAYPALISHIRING" numRows = 3 expected = "PAHNAPLSIIGYIR" actual = solution.convert(s, numRows) self.assertEqual(expected, actual)
f408829302226da12a8c228c8de5241a6a039aec
renkeji/leetcode
/python/src/main/python/Q038.py
1,005
3.953125
4
from src.main.python.Solution import Solution # The count-and-say sequence is the sequence of integers beginning as follows: # 1, 11, 21, 1211, 111221, ... # # 1 is read off as "one 1" or 11. # 11 is read off as "two 1s" or 21. # 21 is read off as "one 2, then one 1" or 1211. # Given an integer n, generate the nth sequence. # # Note: The sequence of integers will be represented as a string. class Q038(Solution): def countAndSay(self, n): """ :type n: int :rtype: str """ def count_and_say(s): char, count = s[0], 0 ans = "" for c in s: if c == char: count += 1 else: ans += str(count) + char char, count = c, 1 ans += str(count) + char return ans ans = "" if n >= 1: ans = "1" for i in range(2, n+1): ans = count_and_say(ans) return ans
ca097540c541bf8950acda127e4fbb89b114163e
renkeji/leetcode
/python/src/main/python/Q009.py
1,233
4.09375
4
import math from src.main.python.Solution import Solution # Determine whether an integer is a palindrome. Do this without extra space. # # Some hints: # Could negative integers be palindromes? (ie, -1) # # If you are thinking of converting the integer to string, note the restriction of using extra space. # # You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", # you know that the reversed integer might overflow. How would you handle such case? # # There is a more generic way of solving this problem. class Q009(Solution): def isPalindrome(self, x): """ :type x: int :rtype: bool """ def get_num_digits(x): ans = 1 while x >= 10: x //= 10 ans += 1 return ans if x < 0: return False num_digits = get_num_digits(x) for i in range(num_digits // 2): left = x // math.pow(10, num_digits - i - 1) right = x % math.pow(10, i + 1) // math.pow(10, i) if left != right: return False x -= left * math.pow(10, num_digits - i - 1) + right * math.pow(10, i) return True
61032acc754588d6d7108ed7d3ba23f8561474d2
renkeji/leetcode
/python/src/main/python/Q110.py
817
4.15625
4
from src.main.python.Solution import Solution # Given a binary tree, determine if it is height-balanced. # # For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees # of every node never differ by more than 1. class Q110(Solution): def isBalanced(self, root): """ :type root: TreeNode :rtype: bool """ def get_height(node): if not node: return 0 left = get_height(node.left) if left == -1: return -1 right = get_height(node.right) if right == -1: return -1 if abs(left - right) > 1: return -1 return max(left, right) + 1 return get_height(root) != -1
f4286e2dd9239a4c3d3bdef724efb5b4b956bffb
VitaliiHudukhin/ithub
/lesson6_tasks/task6_base_01.py
1,642
3.96875
4
from random import random,randint school = { '1A': 30, '1B': 30, '2B': 25, '6B': 31, '7C': 33, } print('Valuable commands in this program: ') valuableCommands = ['change number','new class','delete class','total amount','exit'] for i in valuableCommands: print(i) inputData = "" while inputData.lower() != 'exit': inputData = input('Please, enter one of the valuable command: ') if inputData == 'change number': classRandSelect = randint(0,5) classRandChange = randint(-5,5) school[list(school.keys())[classRandSelect]]+=classRandChange print('In '+list(school.keys())[classRandSelect]+' class now ' +str(school[list(school.keys())[classRandSelect]])+' pupils') continue elif inputData == 'new class': newClassName = input('Please, add a new class name ') if newClassName not in school: newClassPupilsCount = randint(25,36) school.update({newClassName:newClassPupilsCount}) print(newClassName+' class with '+str(newClassPupilsCount) +' pupils was added to school') continue elif inputData == 'delete class': print(school.keys()) delClassName = input('Please, delete class by name ') if delClassName in school: del school[delClassName] print(delClassName + ' class was deleted') continue elif inputData == 'total amount': print('Total amount of school pupils is '+ str(sum(list(school.values())))) else: print("You inputed unknown command.") continue print('Thanks for your attention!')
f6090db7af95ace48db52f89466a13d328070c66
VitaliiHudukhin/ithub
/lesson2_tasks/task2_01.py
970
4.21875
4
print('Let\'s try to find a max number of three given') #проверяем число на float #проверяем число на nan, если ошибка - False def is_number(strg): is_number = True try: num = float(strg) is_number = num == num except ValueError: is_number = False num = False return is_number, num print("Please, enter a first number: ") first = is_number(input()) while first[0] == False: print("Please, enter a correct first number: ") first = is_number(input()) print("Please, enter a second number: ") second = is_number(input()) while second[0] == False: print("Please, enter a correct second number: ") second = is_number(input()) print("Please, enter a third number: ") third = is_number(input()) while third[0] == False: print("Please, enter a correct third number: ") third = is_number(input()) print('The max number = '+str(max(first[1],second[1], third[1])))
0edb2d1857af22eb3434d1bac76fc302b0423efb
VitaliiHudukhin/ithub
/lesson4_tasks/task4_base_02.py
685
4.03125
4
def is_int(strg): try: int(strg) return int(strg) except ValueError: print("Entered data isn't int") print("Please, enter an int number: ") number = is_int(input()) while number == None: print("Please, enter correct number: ") number = is_int(input()) isPositive = True if number >= 0 else False if isPositive == True: start = 0 end = number else: start = number end = 0 listOfPaired = [] for i in range(start,end): if i % 2 != 0: listOfPaired.append(i) sumOfPaired = sum(listOfPaired) print('You entered number '+str(number)) print('') print('Sum of paired numbers, which < '+str(number)+' is '+str(sumOfPaired))
69a2d5a59cad01f7351963c9b25dbbfa03a92d70
VitaliiHudukhin/ithub
/lesson3_tasks/task3_advanced_02.py
318
4.1875
4
print('Let\'s find factorial of entered number') def factor(n): factorial = 1 if n == 1: return factorial elif n <1: factorial = 'Bad input data' else: for i in range(2, n + 1): factorial *= i return factorial n = factor(int(input())) print('Result is '+str(n))
88f19b46ef32ef0ad5dfdc1080a160debc62c152
vladson/bioinftools
/rearrangements.py
9,298
3.625
4
import re import dna class Permutation: def __init__(self, representation, dst = False): """ @param repr: list or str @param dst: list (opt) @return: Permutaion >>> Permutation([-3, 4, 1, 5, -2]) (-3 +4 +1 +5 -2) >>> Permutation(' (-3 +4 +1 +5 -2) ') (-3 +4 +1 +5 -2) >>> Permutation(' (-3 +4 +1 +5 -2) ').out_destination() '(+1 +2 +3 +4 +5)' """ if isinstance(representation, list): perm = representation else: perm =Permutation.parse_repr(representation)[0] self.perm = perm self.initital_perm = perm if dst: if isinstance(dst, list): self.dst = dst else: self.dst = map(lambda s: int(s), dst.strip()[1:-1].split(' ')) else: self.dst = self.default_destination() self.path = [] def greedy_sorting(self): """ >>> len(Permutation([-3, 4, 1, 5, -2]).greedy_sorting()) 7 >>> map(lambda x: Permutation.out_perm(x), Permutation([-3, 4, 1, 5, -2]).greedy_sorting()) ['(-1 -4 +3 +5 -2)', '(+1 -4 +3 +5 -2)', '(+1 +2 -5 -3 +4)', '(+1 +2 +3 +5 +4)', '(+1 +2 +3 -4 -5)', '(+1 +2 +3 +4 -5)', '(+1 +2 +3 +4 +5)'] """ for i in xrange(len(self.perm)): if self.perm[i] == self.dst[i]: continue else: self.greedy_sorting_iter(i) return self.path def greedy_sorting_iter(self, i): try: j = self.perm.index(self.dst[i]) except ValueError: j = self.perm.index(-self.dst[i]) self.perm = self.reversal(i, j) self.path.append(self.perm[:]) #record if -self.perm[i] == self.dst[i]: self.greedy_sorting_iter(i) def reversal(self, i, j): """ @param i: int @param j: int @return: list >>> Permutation([-3, 4, 1, 5, -2]).reversal(0,0) [3, 4, 1, 5, -2] >>> Permutation([-3, 4, 1, 5, -2]).reversal(0,2) [-1, -4, 3, 5, -2] """ return self.perm[:i] + map(lambda s: s*-1, self.perm[i:j+1][::-1]) + self.perm[j+1:] def breakpoints(self): """ @return: int >>> len(Permutation('(+3 +4 +5 -12 -8 -7 -6 +1 +2 +10 +9 -11 +13 +14)').breakpoints()) 8 """ breakpoints = [] perm = [0] + self.perm + [self.dst[-1]+1] last_j = 0 for i in xrange(1, len(perm)): if not self.adjacent(perm[last_j:i+1]): breakpoints.append(i-1) last_j = i return breakpoints @staticmethod def adjacent(lst): """ @param lst: list @return: bool >>> Permutation.adjacent([3,4,5]) True >>> Permutation.adjacent([-8, -7, -6]) True >>> Permutation.adjacent([10, 9]) False >>> Permutation.adjacent([5, -12]) False """ for i in range(1, len(lst)): if not lst[i-1] + 1 == lst[i]: return False return True def default_destination(self): """ @return: list >>> Permutation([-3, 4, 1, 5, -2]).default_destination() [1, 2, 3, 4, 5] """ return sorted(map(lambda x: abs(x), self.perm)) def __repr__(self): return self.__class__.out_perm(self.perm) def out_destination(self): return self.__class__.out_perm(self.dst) @staticmethod def out_perm(perm): """ @param perm: [] @return: str >>> Permutation.out_perm([1, 2, 3, 4, 5]) '(+1 +2 +3 +4 +5)' >>> Permutation.out_perm([-3, 4, 1, 5, -2]) '(-3 +4 +1 +5 -2)' """ repr = [] for i in perm: if i > 0: repr.append("+%i" % i) if i < 0: repr.append("%i" % i) return '(' + " ".join(repr) + ')' @staticmethod def parse_repr(repr): """ >>> Permutation.parse_repr('(+1 -3 -6 -5)(+2 -4)') [[1, -3, -6, -5], [2, -4]] >>> Permutation.parse_repr(' (-3 +4 +1 +5 -2) ')[0] [-3, 4, 1, 5, -2] """ return map(lambda literal: map(lambda item: int(item), literal.split()) ,re.findall('\(([^()]*)\)+', repr)) class CircularGenome: def __init__(self, genome): self.genome = genome self.genome.append(genome[0]) def pairs(self): for i in xrange(len(self.genome) - 1): yield self.genome[i:i+2] class BreakpointGraph: """ >>> BreakpointGraph.from_genome('(+1 +2 +3 +4 +5 +6)') (+1 +2 +3 +4 +5 +6) >>> BreakpointGraph.from_genome('(+1 -3 -6 -5)(+2 -4)') (+1 +2 +3 +4 +5 +6) >>> BreakpointGraph.from_genome('(+1 +2 +3 +4 +5 +6)').add_genomes('(+1 -3 -6 -5)(+2 -4)').calculate_cycles().cycles_num() 3 >>> BreakpointGraph.from_genome('(+1 +2 +3 +4 +5 +6)').add_genomes('(+1 -3 -6 -5)(+2 -4)').calculate_cycles().db_distance() 3 """ def __init__(self): self.cycles = [] self.nodes = {} self.blocks = set() @classmethod def from_genome(cls, genomes): graph = cls() if isinstance(genomes, str): genomes = Permutation.parse_repr(genomes) graph.add_genomes(genomes) return graph def add_genomes(self, genomes): if isinstance(genomes, str): genomes = Permutation.parse_repr(genomes) for genome in genomes: self.add_genome(genome) return self def add_genome(self, genome): if not isinstance(genome, CircularGenome): genome = CircularGenome(genome) for pair in genome.pairs(): self.add_pair(*pair) def calculate_cycles(self): tracker = list(self.nodes.keys()) while len(tracker): self.cycles.append(BreakpointCycle(self.get_node(tracker.pop())).traverse(tracker)) return self def add_pair(self, node_a, node_b): a = self.get_node(node_a) b = self.get_node(node_b * -1) a.add_edge(b) b.add_edge(a) def get_node(self, node): """ @return BreakpointNode """ if not self.nodes.has_key(node): self.nodes[node] = BreakpointNode(node) self.blocks.add(abs(node)) return self.nodes[node] def block_num(self): """ >>> BreakpointGraph.from_genome('(+1 +2 +3 +4 +5 +6)').block_num() 6 """ return len(self.blocks) def cycles_num(self): return len(self.cycles) def db_distance(self): return self.block_num() - self.cycles_num() def __repr__(self): return Permutation.out_perm(self.blocks) class BreakpointNode: def __init__(self, node): self.node = node self.edges = [] def __repr__(self): return "%i (%s)" % (self.node, ', '.join(map(lambda n: str(n.node), self.edges))) def add_edge(self, dst): self.edges.append(dst) def has_edges(self): return len(self.edges) def pop_edge(self): node = self.edges.pop() node.edges.remove(self) return node class BreakpointCycle: def __init__(self, node): self.cycle = [node] def __repr__(self): return self.cycle.__repr__() def traverse(self, tracker): while self.cycle[-1].has_edges(): node = self.cycle[-1].pop_edge() self.cycle.append(node) if node.node in tracker: tracker.remove(node.node) return self class SyntenyConstructor: """ >>> SyntenyConstructor('ACTG', 'ATGTA') SyntenyConstructor for dna_A of 4 bp and dna_B of 5 bp """ def __init__(self, dna_a, dna_b): if not isinstance(dna_a, dna.Dna): dna_a = dna.Dna(dna_a) if not isinstance(dna_b, dna.Dna): dna_b = dna.Dna(dna_b) self.dna_a = dna_a self.dna_b = dna_b def __repr__(self): return "SyntenyConstructor for dna_A of %i bp and dna_B of %i bp" % (len(self.dna_a), len(self.dna_b)) def shared_kmer_indices(self, k): """ >>> list(SyntenyConstructor('AAACTCATC', 'TTTCAAATC').shared_kmer_indices(3)) [(0, 4), (0, 0), (4, 2), (6, 6)] """ b_kmer_tree = {} for index, kmer in enumerate(self.dna_b.kmer_generator(k)): if b_kmer_tree.has_key(kmer): b_kmer_tree[kmer].append(index) else: b_kmer_tree[kmer] = [index] for index, kmer in enumerate(self.dna_a.kmer_generator(k)): if b_kmer_tree.has_key(kmer): for jindex in b_kmer_tree[kmer]: yield index, jindex # if b_kmer_tree.has_key(kmer[::-1]): # yield index, b_kmer_tree[kmer[::-1]] if b_kmer_tree.has_key(dna.Dna.complementary_fragment(kmer)): for jindex in b_kmer_tree[dna.Dna.complementary_fragment(kmer)]: yield index, jindex # if b_kmer_tree.has_key(dna.Dna.complementary_fragment(kmer)[::-1]): # yield index, b_kmer_tree[dna.Dna.complementary_fragment(kmer)[::-1]]
d5ef48b313e1eaaadaf270ad0d507b49039caac1
FreeDiscovery/FreeDiscovery
/examples/python/categorization_interpretation.py
2,113
3.75
4
""" Categorization Interpretation Example ------------------------------------- A visual interpretation for the binary categorization outcome for a single document by looking at the relative contribution of individual words """ from __future__ import print_function import os from sklearn.datasets import fetch_20newsgroups from sklearn.linear_model import LogisticRegression from sklearn.feature_extraction.text import TfidfVectorizer import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt from freediscovery.categorization import binary_sensitivity_analysis from freediscovery.interpretation import explain_categorization, _make_cmap newsgroups = fetch_20newsgroups(subset='train', categories=['sci.space', 'comp.graphics'], remove=('headers', 'footers', 'quotes')) document_id = 312 # the document id we want to visualize vectorizer = TfidfVectorizer(stop_words='english') X = vectorizer.fit_transform(newsgroups.data) clf = LogisticRegression() clf.fit(X, newsgroups.target) repr_proba = 'Predicted: {0}: {{0:.2f}}, {1}: {{1:.2f}}'.format(*newsgroups.target_names) print(repr_proba.format(*clf.predict_proba(X[document_id])[0])) print('Actual label :', newsgroups.target_names[newsgroups.target[document_id]]) weights = binary_sensitivity_analysis(clf, vectorizer.vocabulary_, X[document_id]) cmap = _make_cmap(alpha=0.2, filter_ratio=0.15) html, norm = explain_categorization(weights, newsgroups.data[document_id], cmap) fig, ax = plt.subplots(1, 1, figsize=(6, 1.2)) plt.subplots_adjust(bottom=0.4, top=0.7) cb1 = mpl.colorbar.ColorbarBase(ax, cmap=cmap, norm=norm, orientation='horizontal') cb1.set_label('{} < ----- > {}'.format(*newsgroups.target_names)) ax.set_title('Relative word weights', fontsize=12) # visualize the html results in sphinx gallery tmp_dir = os.path.join('..', '..', 'doc', 'python', 'examples') print(os.path.abspath(tmp_dir)) if os.path.exists(tmp_dir): with open(os.path.join(tmp_dir, 'out.html'), 'wt') as fh: fh.write(html) #################################### # .. raw:: html # :file: out.html
de659ac07f9a3748f4a56839556c592c292a1d16
scottt142/Python---Secuityish
/prog tut 11 part 2.py
888
4.0625
4
def main(): # dictionary of username : hashed_password users = { "mim" : 149, "mls" : 162, "bon" : 9 } # attempt a login success = login(users) if success: print("Successful login") else: print("Could not login") def login(users): # ask for a username and password username = input("Enter username:") password = input("Enter password for " + username) # compare the stored HASHED password to the HASHED password just entered if users.get(username) == hasher(password): return True # successful login else: return False # unsuccessful login def hasher(password): import random ascii_value = sum([ord(char) for char in password]) random.seed(ascii_value) hashed_password = (random.randint(0,255) + ascii_value) % 256 return hashed_password main()
c28adb7515b130ea500b54784f58e08050eea878
mayraberrones94/Flujo-en-Redes
/Reporte2/rep2.py
2,646
3.609375
4
from random import random from math import sqrt class Grafo: def __init__(self): self.n = None self.x = dict() # self.y = dict() # self.P = [] self.pesos = [] self.nodo2 = [] self.nodo3 = [] self.Ari = [] # self.archivo = None # def puntos(self, num): self.n = num for nodo in range(self.n): self.x = random() self.y = random() self.P.append((self.x, self.y, nodo)) def aristas(self, prob): for i in range(self.n - 1): self.nodo2.append(self.P[i]) for i in range(self.n): self.nodo3.append(self.P[i]) for(x1, y1, i) in self.nodo2: del self.nodo3[0] for(x2, y2, j) in self.nodo3: if random() < prob: self.Ari.append((x1, y1, x2, y2)) self.pesos.append((sqrt((x2 - x1) ** 2 + (y2 - y1 )** 2)*100, (x1+x2)/2, (y1+y2)/2)) print(len(self.Ari)) def imprimir(self, arch): self.archivo = arch with open (self.archivo, "w") as salida: for nodo in range(self.n): print(self.P[nodo][0], self.P[nodo][1], (random() * 10), file = salida) print(self.archivo) #di = 1 es simple #di = 2 es dirigido #di = 3 es ponderado #di = 4 es dirigido y ponderado def grafica (self, di): assert self.archivo is not None with open("nodos.plot", 'w') as salida: print('set term png', file = salida) print('set output "nodos.png"', file = salida) print('set size square', file = salida) print('set key off', file = salida) print ('set xrange [-.1:1.1]', file = salida) print ('set yrange [-.1:1.1]', file = salida) id = 1 for i in range(len(self.Ari)): if di is 2 : print('set arrow', id, 'from', self.Ari[i][0], ',', self.Ari[i][1], 'to', self.Ari[i][2], ',', self.Ari[i][3], 'head filled lw 1', file = salida) id +=1 elif di is 1: print('set arrow', id, 'from', self.Ari[i][0], ',', self.Ari[i][1], 'to', self.Ari[i][2], ',', self.Ari[i][3], 'nohead filled lw 1', file = salida) id +=1 elif di is 3: print('set arrow', id, 'from', self.Ari[i][0], ',', self.Ari[i][1], 'to', self.Ari[i][2], ',', self.Ari[i][3], 'nohead filled lw 1', file = salida) print('set label', "'", int(self.pesos[i][0]), "'", 'at', self.pesos[i][1], ',', self.pesos[i][2], file = salida) id +=1 elif di is 4: print('set arrow', id, 'from', self.Ari[i][0], ',', self.Ari[i][1], 'to', self.Ari[i][2], ',', self.Ari[i][3], 'head filled lw 1', file = salida) print('set label', "'", int(self.pesos[i][0]), "'", 'at', self.pesos[i][1], ',', self.pesos[i][2], file = salida) id +=1 print('plot "nodos.dat" using 1:2:3 with points pt 8 lc var ps 2 ', file = salida) print('quit()', file = salida)
2b141c83c179c28675b490988ee4ff6279863ce3
mazzalaialan/Python
/Coursera Course/3 - Programación Orientada a Objetos con Python/Ejercicios/caja.py
8,513
3.765625
4
#-*- coding: utf-8-*- import sys # ******************************************* # *********primera parte Gerente************* # ******************************************* articulos={} fulltotal=0 def ingreso_productos(): caja=True while caja==True: opcion =raw_input("Desea ingresar un producto SI/NO: ") try: if opcion.isalpha()==True: if opcion.lower()=="si": producto=input("ingrese el producto: ") precio=int(input("ingrese el precio: ")) articulos[producto]=precio elif opcion.lower()=="no": caja=False else: print("dato no reconocido") else: print("no se reconocen datos numericos") except: caja=True print ("sus articulos existentes son: ") for clave in articulos: print (clave,":",articulos[clave]) # ******************************************** # **********segunda parte Cliente************* # ******************************************** def compras(): if len(articulos)>0: caja_2=True total=0 while caja_2==True: for clave in articulos: print (clave,":",articulos[clave]) producto=input("Que productos desea llevar: ") for elemento in articulos: if elemento==producto: print ("usted escogio %s"%(elemento)) cantidad=input("cuantas cantidades desea del producto: ") cantida=cantidad*articulos[elemento] total=total+cantida print ("articulo %s: cantidad %s: subtotal de factura Q.%s "%(elemento, cantidad,total )) volver=True while volver==True: seguir=input("desea elegir otro articulo SI/NO: ") if seguir.lower()=="si": caja_2=True volver=False elif seguir.lower()=="no": caja_2=False volver=False return total else: print ("opcion invalida") volver=True else: print ("No hay productos existentes") # *************************************************** # *************tercera parte Factura***************** # *************************************************** def factura(): caja_2=True while caja_2==True: print ("1)Gold") print ("2)Silver") print ("3)Ninguna") tarjeta=input("Que tipo de tarjeta tiene?: ") try: if tarjeta.isalpha()==False: #************************** INGRESO PRODUCTO *********************************************************** #******************************************************************************************************* if tarjeta=="1": print ("Gold") print ("El cliente tiene un descuento del 5%:") print ("El subtotal de la factura esQ.%s"%(fulltotal)) IVA = (fulltotal*0.12) descuento = (fulltotal*0.05) totaltotal = fulltotal + IVA - descuento # aqui comienza facturación print ("Debe: %s"%(fulltotal)) print ("______________________") nombre_del_cliente = input("Nombre Del Cliente: ") nit = input("NIT: ") efectivo = input("Efectivo : ") cambio = efectivo - fulltotal print (("__________________________")) print (("Precio %.2f\t") % fulltotal) print (("IVA %.2f\t") % IVA) print (("Total %.2f\t") % totaltotal) print (("Efectivo %.2f\t") % efectivo) print ("__________________________") print ("cambio: %s"%(cambio)) break #******************************* COMPRA ***************************************************************** #******************************************************************************************************** elif tarjeta=="2": print ("Silver") print ("El cliente tiene un descuento del 2%:") print ("El subtotal de la factura esQ.%s"%(fulltotal)) IVA = ((fulltotal*0.12)) descuento = (fulltotal*0.02) totaltotal = fulltotal + IVA - descuento # aqui comienza facturación print ("Debe: ",totaltotal) print ("______________________") nombre_del_cliente = input("Nombre Del Cliente: ") nit = input("NIT: ") efectivo = input("Efectivo : ") cambio = efectivo - totaltotal print ("__________________________") print ("Precio %.2f\t") % fulltotal print ("IVA %.2f\t") % IVA print ("Total %.2f\t") % totaltotal print ("Efectivo %.2f\t") % efectivo print ("__________________________") print ("cambio: "),cambio caja_2=False #*************************************** FACTURA ******************************************************** #******************************************************************************************************** elif tarjeta =="3": IVA = (fulltotal*0.12) totaltotal = fulltotal + IVA # aqui comienza facturación print ("Debe: ",totaltotal) print ("______________________") nombre_del_cliente = input("Nombre Del Cliente: ") nit = input("NIT: ") efectivo = input("Efectivo : ") cambio = efectivo - totaltotal print ("__________________________") print ("Precio %.2f\t") % fulltotal print ("IVA %.2f\t") % IVA print ("Total %.2f\t") % totaltotal print ("Efectivo %.2f\t") % efectivo print ("__________________________") print ("cambio: "),cambio caja_2=False else: print ("opcion no valida") else: print ("solo se aceptan numeros") except: opcion3=True print ("Gracias por su compra, Regrese Pronto.") # *********************************************** # *******************Menu************************ # *********************************************** salir=False while salir==False: print ("Caja Registradora") print ("¿Qué desea realizar?") print ("1.) Ingreso productos") print ("2.) Compras") print ("3.) factura") opmenu = input("ingrese número de Menu: ") try: if opmenu.isalpha()==False: if opmenu =="1": ingreso_productos() opcionmenu=input("Desea volver al menu SI/NO: ") if opcionmenu.lower()=="si": salir=False else: break elif opmenu =="2": fulltotal= compras() print (fulltotal) opcionmenu=input("Desea volver al menu SI/NO: ") if opcionmenu.lower()=="si": salir=False else: break elif opmenu =="3": print (factura()) opcionmenu=input("Desea vover al menu SI/NO: ") if opcionmenu.lower()=="si": salir=False else: break except: print("Adios") #--------------------------------- import os import unittest APPLICATION_DIR = 'application.py' class TestApplication(unittest.TestCase): def test_lint(self): resultado = os.system('pylint' + " " +APPLICATION_DIR) return resultado if __name__ == '__main__': unittest.main()
110684361f456bd137abb19f8d5147695e859112
mazzalaialan/Python
/Coursera Course/2 - Estructuras de datos en Python/Modulo4/ta-te-ti.py
2,783
3.515625
4
t=[['_','_','_'],['_','_','_'],['_','_','_']] s='|' cont=0 print(s,t[0][0],s,t[0][1],s,t[0][2],s) print(s,t[1][0],s,t[1][1],s,t[1][2],s) print(s,t[2][0],s,t[2][1],s,t[2][2],s) simb=input('Indique con que simbolo quiere jugar (X/O): ') if simb != 'X' and simb !='O': while simb != 'X' and simb !='O': print('Los simbolos son la letra X o la letra O, ambas en mayuscula') simb=input('Indique con que simbolo quiere jugar (X/O): ') print('Muy bien, elegiste',simb) def posicion(): f=int(input('En que fila quieres colocar la marca? (0,1,2): ')) if f != 0 and f != 1 and f != 2: while f != 0 and f != 1 and f != 2: print('Las filas van del cero (0) al dos (2)') f=int(input('En que fila quieres colocar la marca? (0,1,2): ')) c=int(input('En que columna quieres colocar la marca? (0,1,2): ')) if c != 0 and c != 1 and c != 2: while c != 0 and c != 1 and c != 2: print('Las columnas van del cero (0) al dos (2)') c=int(input('En que columna quieres colocar la marca? (0,1,2): ')) print('La marca ira en la posicion',f,',',c) return(f,c) def juego_X(): print('Vamos con las X') fx,cx=posicion() while t[fx][cx]!='_': print('Poscion ocupada por',t[fx][cx]) fx,cx=posicion() t[fx][cx]='X' def juego_O(): print('Vamos con las O') fo,co=posicion() while t[fo][co]!='_': print('Poscion ocupada por',t[fo][co]) fo,co=posicion() t[fo][co]='O' def gen_tateti(cont): resultado="" while cont<9: if cont%2==0: juego_X() else: juego_O() cont+=1 print(s,t[0][0],s,t[0][1],s,t[0][2],s),print(s,t[1][0],s,t[1][1],s,t[1][2],s),print(s,t[2][0],s,t[2][1],s,t[2][2],s) if t[0]== ['X','X','X'] or t[1]== ['X','X','X'] or t[2]== ['X','X','X']: resultado='Ganó X' yield resultado break elif t[0]== ['O','O','O'] or t[1]== ['O','O','O'] or t[2]== ['O','O','O']: resultado='Ganó O' yield resultado break elif t[0][0]==t[1][0]==t[2][0]=='X' or t[0][1]==t[1][1]==t[2][1]=='X' or t[0][2]==t[1][2]==t[2][2]=='X' or t[0][0]==t[1][1]==t[2][2]=='X' or t[0][2]==t[1][1]==t[2][0]=='X': resultado='Ganó X' yield resultado break elif t[0][0]==t[1][0]==t[2][0]=='O' or t[0][1]==t[1][1]==t[2][1]=='O' or t[0][2]==t[1][2]==t[2][2]=='O' or t[0][0]==t[1][1]==t[2][2]=='O' or t[0][2]==t[1][1]==t[2][0]=='0': resultado='Ganó O' yield resultado break else: if cont==9: resultado='Empate' yield resultado result=gen_tateti(cont) for i in result: print(i)
73f30c86c17480141cdcd52cf27773c7693faa57
mazzalaialan/Python
/Curso Polotic/Clase 2 Estructuras de Datos con Python/TamanioCadenayCantA.py
324
3.921875
4
"""Escribe un programa en Python que acepte una cadena de caracteres y cuente el tamaño de la cadena y cuantas veces aparece la letra A (mayuscula y minúscula)""" cadena = input("Ingresar la cadena de texto a validar: ") print("El tamaño de cadena es:", len(cadena), "y la cantidad de A es:", cadena.lower().count('a'))
189ba96890ad52caeea10f7bb1c9307f0ee19d3f
hihiroo/Game
/blackJack.py
5,142
3.65625
4
#블랙잭 #프로그래밍 기초 수업 과제 import random def load_members(): file = open("members.txt","r") members = {} for line in file: name, passwd, tries, wins, chips = line.strip('\n').split(',') members[name] = (passwd,int(tries),int(wins),int(chips)) file.close() return members def login(members): username = input("Enter your name: (4 letters max) ") while len(username) > 4: username = input("Enter your name: (4 letters max) ") trypasswd = input("Enter your password: ") if username in members: if members[username][0] == trypasswd: passwd,tries,wins,chips = members[username] return username, tries, wins, chips, members else: return login(members) else: members[username] = (trypasswd,0,0,0) return username, 0, 0, 0, members def fresh_deck(): suits = {"Spade", "Heart", "Diamond", "Club"} ranks = {"A", 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K"} deck = [] for shape in suits: for x in ranks: card = {"suit": shape, "rank": x} deck.append(card) random.shuffle(deck) return deck def hit(deck): if deck == []: deck = fresh_deck() return (deck[0] , deck[1:]) def count_score(cards): score = 0 number_of_ace = 0 for card in cards: if card['rank'] == 'A': number_of_ace += 1 score += 1 elif card['rank'] == 'J' or card['rank'] == 'Q' or card['rank'] == 'K': score += 10 else: score += card['rank'] for x in range(number_of_ace): if score+10 <= 21: score += 10 else: return score return score def show_cards(cards,message): print(message) for card in cards: print(' '+card['suit'],card['rank']) def more(message): answer = input(message+' ') while not (answer == 'y' or answer == 'n'): answer = input(message) return answer == 'y' def Game(): card = fresh_deck() user_card = [] com_card = [] # 처음 2장씩 나눠 주기 for x in range(2): add, card = hit(card) user_card += [add] add, card = hit(card) com_card += [add] # 딜러의 첫 카드 보여주기 print("-----"+"\nMy cards are:") print(" **** **") print(" "+com_card[1]['suit']+' ',com_card[1]['rank']) # 유저 첫 카드 보여주기 show_cards(user_card,"Your cards are:") user_score = count_score(user_card) com_score = count_score(com_card) #블랙잭으로 이긴 경우 if user_score == 21: print("Blackjack! You won.") return 2 #유저가 버스트가 아닌 동안 while user_score < 21: #딜러는 점수가 16 이하면 무조건 카드 받음 if com_score <= 16: add, card = hit(card) com_card += [add] com_score = count_score(com_card) if more("Hit? (y/n)"): add, card = hit(card) user_card += [add] user_score = count_score(user_card) print(" "+add['suit']+' ',add['rank']) else: break show_cards(com_card,"My cards are:") if user_score > 21: print("You burst! I won.") return -1 if com_score > 21: print("I burst! You won.") return 1 if user_score < com_score: print("I won.") return -1 if user_score == com_score: print("We draw.") return 0 else: print("You won.") return 1 def store_members(members): file = open("members.txt","w") names = members.keys() for name in names: passwd, tries, wins, chips = members[name] line = name + ',' + passwd + ',' + \ str(tries) + ',' + str(wins) + "," + str(chips) + '\n' file.write(line) file.close() def show_top5(members): print("-----") sorted_members = sorted(members.items(),key = lambda x:x[1][3],reverse=True) print("All-time Top 5 based on the number of chips earned") cnt = 1; for x in range(len(sorted_members)): if sorted_members[x][1][3] > 0: print("%d. "%cnt+sorted_members[x][0]+" : %d"%sorted_members[x][1][3]) cnt += 1 if cnt > 5: break def main(): print("Welcome to SMaSH Casino!") play = True username, tries, wins, chips, members = login(load_members()) while play: tries += 1 result = Game() chips += result if result > 0: wins += 1 print("Chips = ",chips) play = more("Play more? (y/n)") print("You played "+str(tries)+" games and won "+ str(wins) + " of them.") print("Your all-time winning percentage is %.1f %%"%(wins/tries*100)) if chips >= 0: print("You have "+str(chips)+" chips.") else: print("You owe " + str(-chips) + " chips.") members[username]= (members[username][0],tries,wins,chips) store_members(members) show_top5(members) print("Bye!") main()
0a002b2379d7aa19acc37bb95718968c04d403b9
Mrityunjay87/DSMP19_GA
/GreyAtom/SuperHero Project/Hackathon.py
310
3.625
4
#Python Mini Challenge #Fibonacci Sequence import math import numpy as np def check_fib(num): num_sqr_plus=np.sqrt((5*num*num) + 4) num_sqr_minus=np.sqrt((5*num*num) - 4) return (num_sqr_plus - math.floor(num_sqr_plus)==0)|(num_sqr_minus - math.floor(num_sqr_minus)==0)
dc3e35533c858891cd9775ca217b036e8ad6866a
Mrityunjay87/DSMP19_GA
/GreyAtom/Day7/Function_defination.py
2,917
3.84375
4
# -*- coding: utf-8 -*- """ Created on Sun Mar 15 12:10:17 2020 @author: Mrityunjay1.Pandey """ # -*- coding: utf-8 -*- """ Created on Sun Mar 15 09:42:43 2020 @author: Mrityunjay1.Pandey """ import pandas as pd #Function Defination test1="sample text" def splitword(data): temp={} data.lower() split_data=data.split() for i in range(0,len(split_data)): temp.update({split_data[i]:len(split_data[i])}) output=pd.DataFrame(temp.items(),columns=['word','count']) return output #Call to Function test=splitword(test1) #Converting into dataframe #Longest even word length data1 = 'One great way to make predictions about an unfamiliar nonfiction text is to take a walk through the book before reading.' data2 = 'photographs or other images, readers can start to get a sense about the topic. This scanning and skimming helps set the expectation for the reading.' data3 = 'testing very9 important' test=splitword(data1) def q01_longest_even_word(sentence): test=splitword(sentence) if (test['count']%2==0).any(): output=test.word[test[test['count']%2==0]['count'].idxmax()] else: output=0 return output #Question 3 import numpy as np import math def q01_get_minimum_unique_square(x,y): #Counter for output increment count=0 #Arranging input paramters of function for the list num=np.arange(x,y+1) #Looping through till length of variable for i in num: #Condition check for squareroot if difference is 0 if (np.sqrt(i) - math.floor(np.sqrt(i))==0): count+=1 return count print("There are total of {} perfect square numbers".format(q01_get_minimum_unique_square(4,10))) def palindrome(num): #Incrementing to find next from given input num=str(num+1) #Looping untill True while True: if (num==num[::-1]): num=int(num) break else: num=str(int(num)+1) return num print(palindrome(1331)) #Method 1 def a_scramble1(str_1, str_2): mod_str_1=list((str_1.replace(" ", "").lower())) mod_str_2=list(str_2.lower()) return all(item in mod_str_1 for item in mod_str_2 ) #Method2 def a_scramble2(str_1, str_2): mod_str_1=list((str_1.replace(" ", "").lower())) mod_str_2=list(str_2.lower()) return (set(mod_str_2).issubset(set(mod_str_1))) #Method 3 def a_scramble3(str_1, str_2): mod_str_1=set((str_1.replace(" ", "").lower())) mod_str_2=set(str_2.lower()) return (mod_str_2.issubset(mod_str_1)) #Fibonacci Sequence def check_fib(num): num_sqr_plus=np.sqrt((5*num*num) + 4) num_sqr_minus=np.sqrt((5*num*num) - 4) return (num_sqr_plus - math.floor(num_sqr_plus)==0)|(num_sqr_minus - math.floor(num_sqr_minus)==0)
19285b09b1041be9c17bdc36dae44a9f1da9a133
Rodas-Nega/hungryness-python
/main.py
435
3.9375
4
# Created By: Rodas N. # Created On: Sept 28 2020 # # This program displays the "hungryness" variable using if and else if commands. hungryness = 0 def on_forever(): global hungryness if input.button_is_pressed(Button.A): hungryness = hungryness + 1 basic.show_number(hungryness) elif input.button_is_pressed(Button.B): hungryness = 0 basic.show_number(hungryness) basic.forever(on_forever)
440033c0c89af574eb5dfa8d1b15cc90b6524094
mzwandile316/Level_0
/Task 6.py
1,010
3.9375
4
#!/usr/bin/env python # coding: utf-8 # In[7]: num_1=int(input("Enter 1st number: ")); num_2=int(input("Enter 2nd number: ")); num_3=int(input("Enter 3rd number: ")); def maxium(): if(num_1>=num_2) and (num_1>=num_3): largest = num_1 elif(num_2>=num_1) and (num_2>=num_3): largest = num_2 else: largest = num_3 print("The maximum number is : ",largest) maxium() # In[8]: ## Bonus num_1=int(input("Enter 1st number: ")); num_2=int(input("Enter 2nd number: ")); num_3=int(input("Enter 3rd number: ")); num_4=int(input("enter 4th number: ")); def maxium(): if(num_1>=num_2) and (num_1>=num_3) and (num_1 >= num_4): largest = num_1 elif(num_2>=num_1) and (num_2>=num_3) and (num_2 >= num_4): largest = num_2 elif(num_3 >= num_2) and (num_3>=num_1) and (num_3 >= num_4): largest = num_3 else: largest = num_4 print("The maximum number is : ",largest) maxium() # In[ ]:
46c1aa93828ecd5f89a4919983f144a9de5c0545
Ushakek/Little_Games
/01_game_what_a_num.py
724
4.09375
4
import random def rand_num(): x = random.randint(1, 10) return x print('Hi, today I gonna play with you. Now i will think about number, and you will go guess this number\n I think...') user_exit = 'y' while user_exit != 'n' and 'N': my_num = rand_num() print('You can start!') user_input = 0 while user_input != my_num: try: user_input = int(input()) if user_input > my_num: print('My number is less') elif user_input < my_num: print('My number is bigger') except ValueError: print('Sorry, try again') print('You are right! Do you whant play again? (Yes - y, No - n)') user_exit = input()
a4f83eacad0f4af34e84fdb2bc8153aa25fccc0c
Vickyyzz/76-270
/LR Model For Diagnosing Breast Cancer.py
1,382
3.65625
4
#!/usr/bin/env python # coding: utf-8 # In[1]: from sklearn import datasets # Load the data data_set = datasets.load_breast_cancer() # Print out the feature names print ('Feature names:') print(data_set.feature_names) print('\n') # Print out the labels/classifications print ('Classification outcomes:') print(data_set.target_names) # In[2]: from sklearn.model_selection import train_test_split # Features X=data_set.data # Label('malignant'/'benign') y=data_set.target # Split the data into training data and testing data by ratio 3:1 # Training data features: X_train, training data labels: y_train # Testing data features: X_test, testing data labels: y_test X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.25, random_state=0) # In[3]: from sklearn.preprocessing import StandardScaler # Initialize a scaler for normalising input data sc=StandardScaler() # Transform the trainging data X_train = sc.fit_transform(X_train) # Transform the testing data X_test = sc.transform(X_test) # In[4]: from sklearn.linear_model import LogisticRegression # Initialize a classifier classifier = LogisticRegression(random_state = 0) # Fit the classifier classifier.fit(X_train, y_train) # In[5]: y_pred = classifier.predict(X_test) correct = (y_test == y_pred).sum() accuracy = correct / len(y_pred) * 100 print ('Accuracy:') print(accuracy) # In[ ]:
da99c9e04f428807d8a8ade14920aae82638f3f4
MatheusKauan/matheus-python
/pacote-download/atividades-python/genero.py
212
3.890625
4
genero = input('Qual o seu sexo? f- Feminino m- Masculino ') if genero == 'f': print('Você é do sexo feminino!') elif genero == 'm': print('Você é do sexo masculino') else: print('Sexo inválido')
746c7b8057ce68f82f927df489d04e9a2f04ebab
malmiski/bipartite_match
/bipartite_graph_generate.py
790
3.578125
4
from random import random from math import cos, sin, sqrt import sys def gen_circle_rand(x,y,r): rad = r*sqrt(random()) theta = random()*2*3.14159 return (x + rad*cos(theta), y + rad*sin(theta)) def generate(center_a_x, center_a_y, radius_1, center_b_x, center_b_y, radius_2, n, name): a = [] b = [] for i in range(int(n)): a.append(gen_circle_rand(center_a_x, center_a_y, radius_1)) b.append(gen_circle_rand(center_b_x, center_b_y, radius_2)) f = open(name, "w") f.write(str(a) + '\n' + str(b)) f.close() if(len(sys.argv) < 8): print("Too few args") for i in range(1, 8): sys.argv[i] = float(sys.argv[i]) generate(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4],sys.argv[5],sys.argv[6],sys.argv[7],sys.argv[8]) print("Done")
f787c8deba2cb741922dfe235a5a9662a0af27ba
HannahKnights/the-snake-and-the-mouse
/a-portable-paradise.py
2,568
4.46875
4
from lots_of_useful.things import * """ This python script will "read" a poem called `A portable paradise` by Roger Robinson (https://nationalpoetryday.co.uk/poem/a-portable-paradise/) Features of the display of this poem: - Each line of the poem will be "read" separately - Each line of the poem will be indented more to create a diagonal form - There will be a pause of 2.5 seconds after each line - If the line ends in a full stop (.) we will pause for 5 seconds - After we have printed the poem we will print the name of the author and the title of the poem You can see it like so: python a-portable-paradise.py """ poem_name = 'A portable paradise' authors_name = 'Roger Robinson' # here is the poem, line by line a_portable_paradise = [ 'And if I speak of Paradise,', 'then I\'m speaking of my grandmother', 'who told me to carry it always', 'on my person, concealed, so', 'no one else would know but me.', 'That way they can\'t steal it, she\'d say.', 'And if life puts you under pressure,', 'trace it\'s ridges in your pocket,', 'smell its piney scent on yout handkerchief,', 'hum its anthem under your breath.', 'And if your stresses are sustained and daily,', 'get yourself to an empty room - be it hotel,', 'hostel or hovel - find a lamp', 'and empty your paradise onto a desk:', 'your white sands, green hills and fresh fish.', 'Shine the lamp on it like the fresh hope', 'of morning, and keep staring at it till you sleep.' ] last_line = a_portable_paradise[-1] # it is useful to know which line is the last line, so we can print the credits number_of_spaces_for_the_indent = 0 # we will lay the poem out diagnoally, this sets a starting position of 0 # READ THE POEM... # a space at the beginning print('\n') for each_line in a_portable_paradise: this_line = each_line is_the_last_line = True if this_line == last_line else False number_of_spaces_for_the_indent = number_of_spaces_for_the_indent + 2 # to be increased by 2 each time print((' ' * number_of_spaces_for_the_indent) + this_line) if this_line.endswith('.'): take_a_breath(length_of_breath = 5, with_space = False) else: take_a_breath(length_of_breath = 2.5, with_space = False) if is_the_last_line: print('\n') print((' ' * number_of_spaces_for_the_indent) + ('*' * 10)) print((' ' * number_of_spaces_for_the_indent) + poem_name) print((' ' * number_of_spaces_for_the_indent) + 'by ' + authors_name) # a space at the end print('\n')
e6d7d29d98317555b2af0776dd5baaa674eaf818
HannahKnights/the-snake-and-the-mouse
/introductions/3-arrangements.py
819
4.34375
4
""" python (the snake): - some words have special meaning to python: - if - for - until - while - etc.. - if they find those words they expect a certain structure should follow - if it's not there then they won't know what to do * some 'words' have a particular structure associated with them * Tips: - if, for examples: today_is_a_tuesday = False if today_is_a_tuesday: print('It is Tuesday') parts_of_a_day = ['day','night'] for part in parts_of_a_day: print('It is ' + part) see these example by looking at the code and/ or running: python introductions/3-arrangements-examples.py python introductions/3-arrangements.py """ i_am = 'a mouse' if i_am me = i_am print('It is so nice to meet you, ' + me)
866a6752cfc31f42d90372b529ec4b40798a52c4
HannahKnights/the-snake-and-the-mouse
/example-spacing.py
449
3.53125
4
""" A poem which looks like a staircase python example-spacing.py """ from lots_of_useful.things import * new_page() print('a') print(' simple') print(' piece') print(' of') print(' text') print(' which') print(' looks') print(' like') print(' a') print(' staircase')
d2a5b4dff6650fe9c324443da4e621e84552c944
chengxxxxwang/Blog
/python/e001.py
411
4
4
#!/usr/bin/python #python version:2.7.2 print "Hello world!" i = 5 print i i = i + 1 print i s = '''This is a multi-line string This is the second line''' print s i = 7; print i; s = 'This ia a string \ This continues the string' print s width = 5 height = 2 area = width * height print 'area is', area print '------------------str--------------------' print 'age ' + str(5) print 'age', 6
3b520ae90d164b35b7ef52ba2b27eed6fbcd0d0e
pamelot/restaurant-ratings
/restaurant-ratings.py
759
3.515625
4
# your code goes here restaurant_ratings = {} scores = open("./scores.txt") for line in scores: restaurant, ratings = line.split(":") restaurant_ratings[restaurant.strip()] = ratings.strip() for restaurant in sorted(restaurant_ratings): ratings = restaurant_ratings[restaurant] print "Restaurant %s is rated at %s" % (restaurant, ratings) for restaurant in sorted(restaurant_ratings): ratings = restaurant_ratings[restaurant] print "Please tell us what your favorite restaurant is." restaurant = raw_input() print "What rating would you give to this restaurant?" ratings = int(raw_input()) restaurant_ratings[restaurant] = ratings print restaurant print ratings print restaurant_ratings
6997ca7ba795519a277c3a189d3f61ae9e6ef336
tabris1103/inf1340_2014_asst1
/test_exercise3.py
2,197
3.796875
4
#!/usr/bin/env python3 """ Module to test exercise3.py """ __author__ = 'Kyungho Jung & Christine Oh' __status__ = "Completed" # imports one per line import pytest from exercise3 import decide_rps # Test procedures to check whether the decide_rps function outputs # correct game results when player1 and player2 inputs are valid. def test_decide_rps(): """ Inputs that are valid (have the correct format and length) """ # Case - Player 1 Wins assert decide_rps("Paper", "Rock") == 1 assert decide_rps("Rock", "Scissors") == 1 assert decide_rps("Scissors", "Paper") == 1 # Case - Player 2 Wins assert decide_rps("Rock", "Paper") == 2 assert decide_rps("Scissors", "Rock") == 2 assert decide_rps("Paper", "Scissors") == 2 # Case - Ties assert decide_rps("Rock", "Rock") == 0 assert decide_rps("Scissors", "Scissors") == 0 assert decide_rps("Paper", "Paper") == 0 # Test procedures to check whether the decide_rps function correctly # raises an exception (error message) when player1 and player2 inputs are invalid. def test_inputs(): """ Inputs that are incorrect format """ with pytest.raises(TypeError): # One of the input is not string value decide_rps(1, "Rock") with pytest.raises(TypeError): decide_rps("Rock", 1) with pytest.raises(TypeError): #Float and integer passed decide_rps(2.231,1) with pytest.raises(TypeError): decide_rps("Rock", False) with pytest.raises(TypeError): # Boolean Value Passed decide_rps(True, "Rock") # One of the player input is wrong string value with pytest.raises(ValueError): decide_rps("Rock", "P") with pytest.raises(ValueError): decide_rps("R", "Paper") # One of the player input's first character is not capitalized properly with pytest.raises(ValueError): decide_rps("rock", "Paper") with pytest.raises(ValueError): decide_rps("Rock", "paper") # One of the player input is numeric string value with pytest.raises(ValueError): decide_rps("1", "2") with pytest.raises(ValueError): decide_rps("Rock", "1")
55d7600951abe87fbac24332f6ffd1431781770b
janliex/Data-Structure-Algorithm
/Leetcode/707_Design Linked List_06170201.py
2,359
4.09375
4
"""定義Node""" class Node(object): def __init__(self, val): self.val = val self.next = None """定義LinkedList""" class MyLinkedList: """ 基本結構 """ def __init__(self): self.head=None self.tail=None self.size=0 """ 取得某位置的數據 """ def get(self, index: int) -> None: """ Get the value of the index-th node in the linked list. If the index is invalid, return -1. """ if index<0 or index >= self.size: return -1 if self.head is None: return -1 a=self.head for i in range(index): a=a.next return a.val """ 開頭加Node """ def addAtHead(self, val: int) -> None: newHead=Node(val) newHead.next=self.head self.head=newHead self.size = self.size + 1 """ 尾巴加Node """ def addAtTail(self, val: int) -> None: a=self.head if a is None: self.head=Node(val) else: while a.next is not None: a=a.next a.next=Node(val) self.size = self.size+1 """ 中間加Node """ def addAtIndex(self, index: int, val: int) -> None: if index < 0 and index != -1: pass elif index > self.size: pass elif index == self.size or index == -1: self.addAtTail(val) elif index == 0: self.addAtHead(val) else: a = self.head for i in range(index - 1): a = a.next node = Node(val) node.next = a.next a.next = node self.size += 1 """ 刪除其中Node """ def deleteAtIndex(self, index: int) -> None: """ Delete the index-th node in the linked list, if the index is valid. """ if index < 0 or index >= self.size: return a = self.head if index == 0: self.head = a.next else: for i in range(index - 1): a = a.next a.next = a.next.next self.size -= 1
a7b11bbbc3f61a5cd6145b4c7d87ba434cdb3686
GauthamAjayKannan/coding
/MAX-HEAP.py
2,398
3.65625
4
class MaxHeap: def __init__(self,capacity): self.storage=[] self.size=0 self.capacity=capacity def hasParent(self,index): return (index-1)//2>=0 def getParentIndex(self,index): return (index-1)//2 def getParent(self,index): if self.hasParent(index): i=self.getParentIndex(index) return self.storage[i] def hasLeftChild(self,index): return 2*index+1<self.size def getLeftChildIndex(self,index): return 2*index+1 def getLeftChild(self,index): if self.hasLeftChild(index): i=self.getLeftChildIndex(index) return self.storage[i] def hasRightChild(self,index): return 2*index+2<self.size def getRightChildIndex(self,index): return 2*index+2 def getRightChild(self,index): if self.hasRightChild(index): i=self.getRightChildIndex(index) return self.storage[i] def swap(self,l,r): self.storage[l],self.storage[r]=self.storage[r],self.storage[l] def insert(self,value): if self.size==self.capacity: print("HEAP IS FULL") return else: self.storage.append(value) self.size+=1 self.heapifyUp() def heapifyUp(self): ind=self.size-1 while(self.hasParent(ind) and self.getParent(ind)<self.storage[ind]): t=self.getParentIndex(ind) self.swap(ind,t) ind=t def remove(self): if self.size==0: print("HEAP IS EMPTY") return else: self.swap(0,self.size-1) self.size-=1 self.storage.pop() self.heapifyDown() def heapifyDown(self): i=0 while self.hasLeftChild(i): t=self.getLeftChildIndex(i) if self.hasRightChild(i) and self.storage[t]<self.getRightChild(i): t=self.getRightChildIndex(i) if self.storage[i]>self.storage[t]: break else: self.swap(i,t) i=t def display(self): for i in self.storage: print(i) a=MaxHeap(10) a.insert(3) a.insert(4) a.insert(9) a.insert(5) a.insert(2) a.insert(1) a.display() print("******************") a.remove() a.display()
c1dcabda16d5a0e4636ee01a18cdd4009019ecd7
GauthamAjayKannan/coding
/zoho10.py
208
3.5
4
n=input() i=1 sum=0 while i<=5: sum=str(int(n)+int(n[::-1])) if sum==sum[::-1]: print(sum) break i+=1 n=sum else: print(-1)
8524eb5e734932c346419c91bb51ede806f6ec9c
sathishkumark27/LearningNewCPPFeatures
/graphs_python/list_ckeck.py
123
3.59375
4
l = [1,2,3] for i in range(len(l)): print("i = %d, l[i] = %d" %(i, l[i])) if (l[i] == 1): l.pop(i) print(l)
e50ac7b99c94d5d947e3fadd676e7159c7dff632
heatherstafford/unit5
/dictionaryDemo.py
289
4.0625
4
#Heather Stafford #4/25/18 #dictionaryDemo.py - most list practice words = ['computer','mortify','dog','firetruck','yes','python','cat'] words.sort() num = int(input('What number word do you want? ')) if num<= 0 or num >= len(words)+1: print('Invalid number') else: print(words[num - 1])
9c7ffa65a21cd11688fed98ec6440bf8cfe02ddc
Hemangi3598/p18.py
/p5.py
335
4
4
# wapp with using arithmetic operators a=3; b=4; print(a) print(b) print(a-b) print(a+b) print(a*b) print(a/b) print(a//b) print(a**b) print(a%b) # if we have to write a/b in round then we have to write print(round(a/b,2)) # if we have to take nos from user then type a=float(input("enter a")); b=float(input("enter b"));
6be985c31bee23e33f77baa9fa86100eb1bd6d89
Ramshil/musical-eureka
/estimate.py
367
3.703125
4
import math import random def wallis(n): product=1 for i in range(1,n+1): k=float(4*math.pow(i,2)) product*=(k/(k-1)) pi=2*product return pi def monte_carlo(n): count=0 for i in range(1,n+1): x=random.random() y=random.random() z=math.pow(x,2)+math.pow(y,2) distance=math.sqrt(z) if distance<1: count+=1 pi=4*(count/n) return pi
f3c12c95d58ae296635dcd2ff64d6dbc76c32626
SunilKumar-ugra/image_processing_bot
/test.py
45
3.5
4
numbers = [1,2,3,4] print(numbers.reverse())
1e61751a82e8ada4343b9238f2ac0317ce673a3a
JunYinghu/selenium-website-test-automation
/Backup/hr/elearning/dateTimedeltas.py
2,940
3.734375
4
import calendar from datetime import date from datetime import datetime from datetime import timedelta file = "testing" # format datetime def caludate(): now = datetime.now() print now.strftime("%Y") print now.strftime("%y") print now.strftime("%a,%d,%B,%y") print now.strftime("%c") print now.strftime("%x") print now.strftime("%X") print now.strftime("%I,%M,%S,%p") print now.strftime("%H,%M") caludate() # Print calendar for m in range(1, 13): cal =calendar.monthcalendar(2017, m) #if the first firday has be within the first two weeks weekone = cal[0] weektwo = cal[1] # if the first firday not in week 1 it must be in week 2 if weekone [calendar.FRIDAY] !=0: meetday = weekone[calendar.FRIDAY] else: meetday = weektwo [calendar.FRIDAY] print "%10s %2d" % (calendar.month_name[m],meetday) for name in calendar.month_name: print name for day in calendar.day_name: print day hc = calendar.TextCalendar(calendar.MONDAY) calstr = hc.formatmonth(2017, 9, 0, 0) print calstr hchtml = calendar.HTMLCalendar(calendar.SUNDAY) strcalhtml = hc.formatmonth(2017, 9) print strcalhtml for i in calendar.c.itermonthdays(2013, 9): print i # hc = calendar.LocaleHTMLCalendar(calendar.MONDAY) # str = hc.formatmonth(2017,1) # Timedeltas def datetimecau(): print timedelta(days=365, hours=5, minutes=3) print str(datetime.now()) print 'next 356 days ' + str(datetime.now() + timedelta(days=365)) print 'next 5 houws ' + str(datetime.now() + timedelta(hours=5)) a = datetime.now() + timedelta(days=-5) print '5 days ago ', a.strftime("%A, %B, %d, %Y") today = date.today() afd = date(today.year, 4, 1) if afd < today: print "april fools day already went by %d days agao" % ((today - afd).days) afd = afd.replace(year=today.year + 1) print "afd ddddd", afd time_to_afd = abs(afd - today) print time_to_afd, "days until next april fools day!" datetimecau() def gamce(): # x = raw_input() # (i,j) = map(int,raw_input().split( )) # print x # print 'ddd' pass def gettextglobel(): print 'ddddd {}', file gettextglobel() print gettextglobel() print gettextglobel def fun1(*arg1): result = 0 x = 3 for i, d in enumerate(arg1): if i == 1: continue result = result + d * x index = i print index, d # print x # print ("jlsjdfa"), arg1 + x return result print fun1(1, 2, 3, 4, 5) def caul(x, y): if x > y: st = ' x is morethan y' elif x == y: st = 'x is = y' else: st = 'x is less than y' return st print caul(4, 4) def fileexu(): # f = open("textfile.txt","w++") f = open("textfile.txt", "a+") for i in range (10): f.write("this is line %d\r\n" %(i+1)) f.close() fileexu() if __name__ == '__main__': gamce()
2dbee712457b4f2d72f7a43fb7eaf6163bff8ff5
JunYinghu/selenium-website-test-automation
/Backup/Assignment_junying/backupfobooking/airbook/airbook/utils/date_cal.py
1,130
3.59375
4
from datetime import datetime def datecovert(d, r): depature_date_dict = {1: '2017-7', 2: '2017-12', 3: '2018-7', 4: '2018-12', 5: "2019-7", 6: "2019-12"} return_date_dict = {1: '2017-7', 2: '2017-12', 3: '2018-7', 4: '2018-12', 5: "2019-7", 6: "2019-12"} depature_date = depature_date_dict.get(d, "") return_date = depature_date_dict.get(r, "") return (depature_date, return_date) def datecau(d, r): if d == 0 or r == 0: # print ("++++++++++++++++this is for date cau+++++++++++++"), d, r # status = "failed" # expected_result = "Unfortunately, this schedule is not possible. Please try again." # print expected_result return 0 else: (depature_date, return_date) = datecovert(d, r) # print ("+++++++++++++++++this is depature_date, return_date+++++++++++++++++++"), depature_date, return_date x1 = datetime.strptime(depature_date, "%Y-%m") x2 = datetime.strptime(return_date, "%Y-%m") diff = x2 - x1 #print ("++++++this is diff days between departure and return+++++++++"), diff.days return diff.days
bb327f9d1fbb418946bbb72f10f18ce51641c396
yashika-5/FlaskWork
/Flask_With_Database/CRUD.py
1,147
3.5
4
from basic import db,User from datetime import date # CREATE student1 = User('Charlie',22,date(1999,8,5),'Male') db.session.add(student1) db.session.commit() # READ all_students = User.query.all() # list of student objects in table print(all_students) print('\n') # SELECT BY ID studentById = User.query.get(1) if studentById: print(studentById.name, studentById.age, studentById.dob) print('\n') else: print(f"Student with this id = {studentById} not found\n") # FILTERS studentByFilter = User.query.filter_by(name='John') if studentByFilter: print(studentByFilter.all()) print('\n') else: print(f"student with this name not available" +'\n') # UPDATE studentAfterUpdate = User.query.get(1) studentAfterUpdate.name = 'AfterUpdateYashika' db.session.add(studentAfterUpdate) db.session.commit() # DELETE studentDelete = User.query.get(4) if studentDelete: db.session.delete(studentDelete) db.session.commit() print(f'Deleted USer of this id : {studentDelete.id}'+'\n') else: print("Not found student for deletion with this id"+'\n') # ALL STUDENTS all_students = User.query.all() print(all_students)
38169ebe0bf63302d4a992579f447734c10f3f1a
darouwan/photo_recognize
/recognize_main.py
1,094
3.546875
4
import sys from model_util import * if __name__ == "__main__": training_path = sys.argv[1] test_path = sys.argv[2] print("Training KNN classifier...") classifier = train(training_path, model_save_path="trained_knn_model.clf", n_neighbors=2) print("Training complete!") # STEP 2: Using the trained classifier, make predictions for unknown images for image_file in os.listdir(test_path): full_file_path = os.path.join(test_path, image_file) print("Looking for faces in {}".format(image_file)) # Find all people in the image using a trained classifier model # Note: You can pass in either a classifier file name or a classifier model instance predictions = predict(full_file_path, model_path="trained_knn_model.clf") # Print results on the console for name, (top, right, bottom, left) in predictions: print("- Found {} at ({}, {})".format(name, left, top)) # Display results overlaid on an image show_prediction_labels_on_image(os.path.join(test_path, image_file), predictions)
5c241af5756d372fab6366c9c0cea96dc8c4799c
swigder/word_segmentation
/word_segmentation/bigram_word_segmenter.py
3,347
4.25
4
from utilities.utilities import bisect_string class BigramWordSegmenter: """ Segments a sentence containing no spaces into a list of words, by finding the segmentation that maximizes the bigram probability. The score for of each possible sentence is the bigram probability of the sentence (probability of the first word times product of the probabilities of all bigrams), multiplied by the number of words in the sentence. The last multiplication helped compensate for fact that a sentence with many words will have many more fraction multiplication. """ def __init__(self, unigram_provider, bigram_provider): """ :param unigram_provider: unigram provider that can provide frequency counts for words in a corpus :param bigram_provider: bigram provider that can provide frequency counts for bigrams in a corpus """ self.unigram_provider = unigram_provider self.bigram_provider = bigram_provider self.total_words = unigram_provider.get_total_words() def segment_words(self, string): """ Segments a sentence into words by optimizing the bigram probability of the sentence. Uses dynamic programming under the hood. :param string: words without spaces separating them :return: list of words that are a word segmentation of the given string """ segmentation, frequency = self.segment_words_dynamically(string, {}) return segmentation def segment_words_dynamically(self, string, cache): """ Segments a sentence into words by optimizing the bigram probability of the sentence. Uses dynamic programming under the hood, adding to the cache of best segmentation for the given string and all substrings. This method is called recursively. :param string: words without spaces separating them :param cache: cache of best segmentations for the string (or any other strings in the global string) :return: list of words that are a word segmentation of the given string """ if string in cache: # dynamic programming part return cache[string] probability_whole = self.unigram_provider.get_frequency(string) / self.total_words if len(string) <= 1: # base case cache[string] = [string], probability_whole return cache[string] best_segmentation = [string] best_score = probability_whole for i in range(1, len(string)): # recursive case a, b = bisect_string(string, i) segmentation_a, score_a = self.segment_words_dynamically(a, cache) segmentation_b, score_b = self.segment_words_dynamically(b, cache) new_bigram = tuple([segmentation_a[-1], segmentation_b[0]]) frequency_first_word = max(self.unigram_provider.get_frequency(segmentation_a[-1]), 1) probability_new_bigram = max(1, self.bigram_provider.get_frequency(new_bigram)) / frequency_first_word score = score_a * score_b * probability_new_bigram if score * len(segmentation_a + segmentation_b) > best_score: best_score = score best_segmentation = segmentation_a + segmentation_b cache[string] = best_segmentation, best_score return cache[string]
fcadae0c7418165a154f84d1ced893cd40e44df3
swigder/word_segmentation
/word_segmentation/brown_cmu_unigram_provider.py
1,323
3.53125
4
from nltk.corpus import brown, cmudict import nltk from utilities.utilities import binary_search class BrownCmuUnigramProvider: """ Provides unigram counts for words in the Brown corpus. Keeps corpus in memory for speed. """ words = [word.casefold() for word in cmudict.words()] brown_words = [word.casefold() for word in brown.words()] word_distribution = nltk.FreqDist(brown_words) def get_frequency(self, word): """ Gets the absolute count of a given word in the Brown corpus. These counts are case-insensitive. :param word: word to find in the corpus :return: number of times the word appears in the corpus, ignoring letter case """ in_cmu = binary_search(self.words, word.casefold()) != -1 return self.word_distribution[word.lower()] + in_cmu def get_most_frequent_word(self, words): """ Finds the word in a list of words with the highest frequency in the Brown corpus (using rules of get_frequency) :param words: list of words for which to find the word with the highest frequency :return: word in the list with the high """ return max(words, key=lambda word: self.get_frequency(word)) def get_total_words(self): return len(self.words) + len(self.brown_words)
62748fb96117f100823384d6c6c504ca1607bac4
csp9527/ThinkInRedis
/section03/String_test.py
827
3.640625
4
## 字符串 # 字符串可以存储以下三种类型的值 # 字节串、整数、浮点数 import redis conn = redis.Redis() print(conn.get('key')) print(conn.incr('key')) print(conn.incr('key', 15)) conn.decr('key', 5) print(conn.get('key')) conn.set('key', '13') print(conn.incr('key')) print('-------------------') conn.set('new-string-key', '') conn.append('new-string-key', 'hello ') conn.append('new-string-key', 'world!') print(conn.get('new-string-key')) print(conn.getrange('new-string-key', 3, 7)) conn.setrange('new-string-key', 0, 'H') conn.setrange('new-string-key', 6, 'W') print(conn.get('new-string-key')) conn.setrange('new-string-key', 11, ', how are you?') print(conn.get('new-string-key')) print(conn.setbit('another-key', 2, 1)) print(conn.setbit('another-key', 7, 1)) print(conn.get('another-key'))
798b1d95900d3759475bbd229067d2af3a537e57
jgarte/stuff
/python/miscellaneous/rock_paper_scissors.py
935
3.90625
4
import random rps = ["Rock", "Paper", "Scissors"] computer = random.choice(rps).title() user = False while user is False: user = input("Rock, Paper, Scissors... ").title() if user == computer: print("Tie!") elif user == "Rock": if computer == "Paper": print(f"You Lost... {computer} Covers {user}") else: print(f"You Won... {user} Smashes {computer}") elif user == "Paper": if computer == "Rock": print(f"You Won... {user} Covers {computer}") else: print(f"You Lost... {computer} Cuts {user}") elif user == "Scissors": if computer == "Rock": print(f"You Lost... {computer} Smashes {user}") else: print(f"You Lost... {user} Cuts {computer}") else: print("Invalid Input... Try Again") user = False computer = random.choice(rps).title()
a49cfd6c46ac4cd83d0116a53381e2290add107a
jgarte/stuff
/python/miscellaneous/weight.py
420
4.15625
4
def weight_convert(weight, unit): if unit.upper() == "L": final_weight = weight * 0.45 unit = "kilos" elif unit.upper() == "K": final_weight = weight // 0.45 unit = "pounds" output = f"You are {final_weight} {unit}" return output if __name__ == "__main__": weight = int(input("Weight: ")) unit = input("(L)bs or (K)gs: ") print(weight_convert(weight, unit))
b03b7bda8c9914c243768fff9f261846043b304d
jgarte/stuff
/python/miscellaneous/even_numbers.py
569
4.25
4
def even_number(start, end): count = 0 number_list = [] type = input("From OR Between : ").lower() if type == "from": end += 1 elif type == "between": end -= 2 for number in range(start, end): if number % 2 == 0: number_list.append(number) count += 1 output = (f''' Even Numbers : {count} List Of Numbers : {number_list} ''') return output if __name__ == "__main__": start = int(input("Start: ")) end = int(input("End: ")) print(even_number(start, end))
07463bdf86ab4a88c37fb738115770f6ab709388
ahavrylyuk/hackerrank
/python3/maxsubarray.py
851
3.65625
4
#! /usr/bin/env python def max_subsum(n, a): positive_sum, current_sum, best_sum = (0,) * 3 has_positive = False max_negative = a[0] for i in range(n): if a[i] > 0: has_positive = True positive_sum += a[i] elif a[i] > max_negative: max_negative = a[i] val = current_sum + a[i] if val > 0: current_sum = val else: current_sum = 0 if current_sum > best_sum: best_sum = current_sum if has_positive: return (best_sum, positive_sum) else: return (max_negative, max_negative) if __name__ == '__main__': t = int(input()) for _ in range(t): n = int(input()) a = list(int(x) for x in input().split()) res = max_subsum(n, a) print(' '.join(map(str, res)))
8f43496c92dddd7866a3493e5dbbbaa631e74d59
ahavrylyuk/hackerrank
/python3/flipping_bits.py
691
3.921875
4
#! /usr/bin/env python def binary(value): """ return array of 32 binary bits """ res = [] while value > 0: res.append(value % 2) value = value // 2 return [0] * (32 - len(res)) + res[::-1] def flip_elements(iterable): return [1 if e == 0 else 0 for e in iterable] def decimal(binary): res = 0 for i, v in enumerate(reversed(binary)): if v: res += pow(2, i) return res def flip(a): return decimal(flip_elements(binary(a))) def flip_native(a): return a ^ (2 ** 32 - 1) if __name__ == '__main__': n = int(input()) for _ in range(n): a = input() res = flip(int(a)) print(res)
4fe5965dfcd299d2a5ce25611fad114fda9c89d8
ahavrylyuk/hackerrank
/python3/sherlock_and_the_beast.py
460
3.625
4
#! /usr/bin/env python def decent(n): count5, count3 = n // 3, 0 is_decent = lambda: 3 * count5 + 5 * count3 == n while count5 > 0 and count3 <= n // 5: if is_decent(): break count3 += 1 count5 = (n - 5 * count3) // 3 if is_decent(): return '555' * count5 + '33333' * count3 return -1 if __name__ == '__main__': t = int(input()) for _ in range(t): print(decent(int(input())))
a9d89e879a18b9141f9284e0240f454562b6599d
ahavrylyuk/hackerrank
/python3/palindrome_index.py
399
3.6875
4
#! /usr/bin/env python def is_pal(s): return s == s[::-1] def p_index(s): i, j = 0, len(s) - 1 while i < j and s[i] == s[j]: i += 1 j -= 1 if i == j: return -1 if is_pal(s[i + 1: j + 1]): return i if is_pal(s[i: j]): return j if __name__ == '__main__': t = int(input()) for i in range(t): print(p_index(input()))
949bc28a82e2d4f916c9d24398f7d14b3dbb1ef7
ahavrylyuk/hackerrank
/python3/acm_icpc_team.py
467
3.859375
4
#! /usr/bin/env python def get_team(n, m, person): teams = [] for i in range(n - 1): for j in range(i + 1, n): teams.append(bin(person[i] | person[j]).count('1')) max_topic = max(teams) return (max_topic, teams.count(max_topic)) if __name__ == '__main__': n, m = map(int, input().split()) person = [int(x, 2) for x in [input() for _ in range(n)]] team = get_team(n, m, person) print(team[0]) print(team[1])
27fa2d0adbffe9cab25c00a232001f96391a43fd
ahavrylyuk/hackerrank
/python3/halloween_party.py
248
3.546875
4
#! /usr/bin/env python def max_pieces(k): horizontal = int(k / 2) vertical = k - horizontal return horizontal * vertical if __name__ == '__main__': t = int(input()) for _ in range(t): print(max_pieces(int(input())))
7415884d1ee601807983075d278c99ca27e3c48e
ahavrylyuk/hackerrank
/python3/common_child.py
423
3.5
4
#! /usr/bin/env python def common_sub(a, b): prev = [0] * len(b) for i, ai in enumerate(a): current = [0] * len(b) for j, bj in enumerate(b): if j > 0: current[j] = prev[j - 1] + 1 if ai == bj \ else max(current[j - 1], prev[j]) prev = current return prev[len(b) - 1] if __name__ == '__main__': print(common_sub(input(), input()))
fa3d93fb09183d99a2b2c2cc8f3f50d6e0d04335
NicholasAllair/ITI1120
/exam prep/tst2.py
229
3.625
4
def min_or_max_index (lst, TF): s_lst = lst.sort() print (s_lst[0]) if TF == True: min_value = s_lst[0] pos = lst.index(min_value) return (min_value,pos)
499ef523e46734a5cd4aef2dc0b7dfaf5ec29252
NicholasAllair/ITI1120
/Assignments/A2_8147249/part_1_8147249.py
5,191
3.890625
4
import math import random def primary_school_quiz(flag, n): def performTest (mark,n): score = mark / n if score >= 0.9: print("Congradualtions" +name+ "! You'll probably get an A tomorrow. Now go eat you dinner and go to sleep.") elif (score >= 0.7) and (score < 0.9): print("You did well " +name+ " but I know you can do better") elif (score < 0.7): print("You did well " +name+ " but I know you can do better") return(score) question_n = 1 mark = 0 if flag == 0: while question_n <= n: a = (random.randint(0,9)) b = (random.randint(0,9)) r_answer = a-b print("Question ",question_n, ":") print("What is the result of" ,a,"-" ,b, "? ") i_answer = int(input("")) if (r_answer == i_answer): mark +=1 question_n += 1 if flag == 1: while question_n <= n: a = (random.randint(0,9)) b = (random.randint(0,9)) r_answer = a**b print("Question ",question_n, ":") print("What is the result of" ,a,"^" ,b, "? ") i_answer = int(input(questionstring))#################################### if (r_answer == i_answer): mark +=1 question_n += 1 performTest(mark,n) def high_school_eqsolver(a,b,c): if (a != 0) and (b != 0): print("The quadratic equation " ,a, "*x^2 + " ,b, "x + " ,c, " = 0") D = b**2 - 4*a*c if D<0: print("has the following complex roots:") root_real =(-b)/(2*a) root_i =((abs(D))**(1/2)) / (2*a) print (root_real, " + ",root_i,"i") print ("and") print (root_real, " - ",root_i,"i") elif D==0: root = (-b)/(2*a) print("has only one solution, a real root:") print(root) elif D>0: root_1 = ((-b)+((D)**(1/2)))/(2*a) root_2 = ((-b)-((D)**(1/2)))/(2*a) print("has the following real roots") print (root_1, " and " , root_2) if (a==0) and (b != 0): print("The linear equation " ,b, "x + ", c, " = 0") solution = (-c) / b print("has th following root/solution:" ,solution,) if (a == 0) and (b == 0) and (c != 0): print("The quadratic equation " ,a, "*x^2 + " ,b, "x + " ,c, " = 0\nis satisfied for no number x") if (a == 0) and (b == 0) and (c == 0): print("The quadratic equation " ,a, "*x^2 + " ,b, "x + " ,c, " = 0\nis satisfied for all number x") ########### main ########## print ("*************************************************************") print ("* *") print ("* __Welcome to my math quiz-generator / equation-solver__ *") print ("* *") print ("*************************************************************") print("") name=input("What is your name? ") status=input("Hi "+name+". Are you in? Enter \n1 for primary school\n2 for high school or\n3 for none of the above?\n") if status=='1': print('*'*(69+len(name))) print("*", end="") print(' '*(67+len(name)), end="") print("*") print("* __"+name+ ", welcome to my quiz-generator for primary school students.__ *") print("*", end="") print(' '*(67+len(name)), end="") print("*") print('*'*(69+len(name))) print("") print(name+ " what would you like to practice? Enter\n0 for subtraction\n1 for exponentiation") flag = int(input()) n = int(input("How many questions would you like to do?")) primary_school_quiz(flag, n) elif status=='2': print('*'*(61+len(name))) print("*", end="") print(' '*(59+len(name)), end="") print("*") print("* __quadratic equation, a·x^2 + b·x + c= 0, solver for " +name+ "__ *") print("*", end="") print(' '*(59+len(name)), end="") print("*") print('*'*(61+len(name))) loop=True while loop: question=input(name+", would you like a quadratic equation solved?") if (question == 'Yes') or (question == 'YEs') or (question == 'YeS') or (question =='yES') or (question =='YES') or (question =='yes') or (question =='yeS') or (question =='yEs'): print("Good choice!") a= int(input("Enter a number for the coefficient a:")) b= int(input("Enter a number for the coefficient b:")) c= int(input("Enter a number for the coefficient c:")) high_school_eqsolver(a,b,c) else: loop = False else: print("This Program is not for you") print("Good bye "+name+"!")
c39eb9819bead3531df1dc429736ad3611222aab
NicholasAllair/ITI1120
/Labs/lab11-solutions/prog_ex1.py
284
3.609375
4
def m(i): '''(int)->number returns the sum 1/3+2/5+3/7+...+i/(2i+1) Precondition: i>=1 ''' if i == 1: return 1 / 3 else: return m(i - 1) + i * 1 / (2 * i + 1) for i in range(1, 11): print('m('+str(i)+')=', m (i) )
8c543ea2d28fa3e673189c3e96fd57e4d9a426d1
daim77/engeto_repo
/palyndrom.py
554
3.859375
4
# tento program pozna zda uzivatel zadal palyndrom # header # print('=' * 40) # print('Tento program testuje zda zadany vyraz je PALYNDROM ci nikoliv') # print('=' * 40) # # zadani promene # slovo = input('Zadej slovo: ') # my_word_reverse = list(slovo) # my_word_reverse.reverse() # print('Slovo', slovo, ':') # if my_word_reverse == list(slovo): # print("JE Palyndrom!") # else: # print("NENI palyndrom!") # a nebo jednoduseji slovo = input('Zadej slovo: ') if slovo == slovo[::-1]: print('je palyndrom') else: print('neni palyndrom')
896b54abf3e32711a23221b592e40939bfaa7187
daim77/engeto_repo
/index.py
469
3.5625
4
# Extrahuj a vytiskni prvních 5 písmen print('=' * 20) my_index = "indexování" prvnich_pet = my_index[:5] # petku lze nahradit promennou INT print('first five letters: ', prvnich_pet) # Extrahuj a vytiskni posledních 5 písmen print('=' * 20) poslednich_pet = my_index[5:] print('last five letters: ', poslednich_pet) # Extrahuj a vytiskni každé 3 písmeno print('=' * 20) kazde_treti = my_index[::3] print('every 3rd letter (first included): ', kazde_treti)
172a680e1a803890507d4b2e165fa6ecf420e84c
daim77/engeto_repo
/generatory.py
938
3.703125
4
# def my_range(start, stop, step=1): # test = (lambda x, y: x < y and step > 0, # lambda x, y: x > y and step < 0)[start > stop] # # while test(start, stop): # yield start # start += step # # # gen = my_range(0, 10) # # for i in gen: # # print(i) # print(next(gen)) # print(next(gen)) # print(next(gen)) # print(next(gen)) # print(next(gen)) # text = '[email protected] hjgsfgsag sgfsahgfag [email protected]' # r = list( # map(lambda x: x.rstrip('.,/\\; '), # map(lambda x: x.split('@')[-1], # filter(lambda x: '@' in x, text.split() # ) # ) # ) # ) # # print(r) import random # Vytvoříme list, který bude obsahovat všechny žolíkové karty. deck = [ suit + ' ' + str(number) for suit in ['Clubs', 'Diamonds', 'Hearts', 'Spades'] for number in ['Ace']+list(range(2, 11))+['Jack', 'Queen', 'King'] ] random.shuffle(deck) print(deck)
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
19