blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
928b5dff4ec62b05392a631621827969339d1c52
choijaehoon1/programmers_level
/src/test18.py
558
3.59375
4
def solution(a, b): answer = '' num = 0 weeks = ["FRI","SAT","SUN","MON","TUE","WED","THU"] for i in range(1,a): if i == 1 or i == 3 or i == 5 or i == 7 or i == 8 or i == 10 or i == 12: num += 31 elif i == 4 or i == 6 or i == 9 or i == 11: num += 30 else: num += 29 num += b-1 # 24일이 몇번째 날인지 알아야 하므로 일은 1부터 시작이므로 1에다가 b-1인 23을 더해줘야함 res = num % 7 answer = weeks[res] return answer
88f281e6043d7fe2100e2ccdbebb43216bca31f3
esierra8/website_blocker
/website_blocker.py
2,017
3.703125
4
#This is a website blocker, what it does is it goes to your conf files in your system # in this case in windows. You will have to schedule a task in the background that # will check the time and depending on the time (working hours) it will edit the file # and will add the specify websites in the list of links to the block websites. And # thanks to that you won't be able to access the website. #Esteban Sierra #07/12/17 # import time from datetime import datetime as dt #Declaring global variables #temp_path is used as a temporary path to test the file change temp_path = 'hosts' #real path for the file host_path = r'C:\Windows\System32\drivers\etc\hosts' redirect = '127.0.0.1' #The list if links to block website_links = ['www.facebook.com', 'www.tumblr.com', 'facebook.com', 'tumblr.com'] #Infinite loop while True: #Checking for the date and time to see if I want to block the websites #If(RIGHT NOW (dt.now()) is between 8 am and 4 pm) Change the file if dt(dt.now.year, dt.now().month, dt.now().day, 8) < dt.now() < dt.now(dt.now().year, dt.now().month, dt.now().day, 16): print('Working hours...') with open(temp_path, 'r+') as file: content = file.read() for website in website_links: if website in content: pass else: file.write(redirect + ' ' + website + '\n') #Else rewrite every line of the document that does not contain the links. #In other words, rewrite without links to block. else: with open(temp_path, 'r+') as file: content = file.readline() file.seek(0) for line in content: #If there is no website link from the list of website links #in this line of document. Rewrite it, else don't. if not any(website in line for website in website_links): file.write(line) file.truncate() print('Fun hours...') time.sleep(5)
3f30367856c26d1630674216d03c8bf153c3225f
zzylydx/source
/面向过程_02_01/小练习1.py
765
3.984375
4
#!/usr/bin/env python3 # coding utf-8 ''' 练习1 编写一个 学生类,产生一堆学生对象 要求 有一个计算器(属性),统计总共实例了多少对象 ''' class Student: school = 'luffycity' count = 0 def __init__(self,name,age,sex): self.Name = name self.Age = age self.Sex = sex # self.count = self.count + 1 Student.count += 1 def learn(self): print('%s is learing' %self.Name) stu1 = Student('alex','male',38) # 调用类 创建对象 stu2 = Student('jingxing','female',78) stu3 = Student('egon','male',18) # Student.count # stu1.count # stu2.count # stu3.count print(Student.count) print(stu1.count) print(stu2.count) print(stu1.__dict__) print(stu2.__dict__)
403e807b8ddee54bdbcf64a7106fb61acde48cd7
K-G-1/python-practice
/function+file/function.py
548
3.9375
4
#coding=UTF_8 ##函数与文件操作例程 # from sys import argv script , input_file=argv def print_all(f): print f.read() def rewind(f): f.seek(0) def print_one_line(line,f): for line in range(1,line): f.readline() line = line + 1 print line,f.readline() print "Now,we will print the whole file:" txt = open(input_file) txt.encoding = 'utf-8' print_all(txt) print "Now,we will print one line." current_line = input("which line do you want print? ") rewind(txt) print_one_line(current_line,txt) print txt.encoding txt.close()
5843c7ecd033183c91625c70db76f79030eacd34
EduardoAlbert/python-for-data-analysis
/Dictionaries/Dictionary.py
1,146
4.125
4
"""filme = {'titulo': 'Star Wars', 'ano': 1977, 'diretor': 'George Lucas'} print(filme.values()) print(filme.keys()) print(filme.items()) for value in filme.values(): print(value) for key, value in filme.items(): print(f'O {key} é {value}') """ """locadora = [{'titulo': 'Star Wars', 'ano': 1977, 'diretor': 'George Lucas'}, {'titulo': 'Avengers', 'ano': 2012, 'diretor': 'Joss Whedon'}, {'titulo': 'Matrix', 'ano': 1999, 'diretor': 'Wachowski'}] print(locadora[2]['titulo']) """ """pessoas = {'nome': 'Eduardo', 'sexo': 'M', 'idade': 18} print(f'{pessoas["nome"]}') """ """Brasil = list() estado1 = {'uf': 'Rio de Janeiro', 'sigla': 'RJ'} estado2 = {'uf': 'São Paulo', 'sigla': 'SP'} Brasil.append(estado1) Brasil.append(estado2) print(Brasil[1]['sigla']) """ estado = dict() brasil = list() for i in range(0, 3): estado['uf'] = str(input('Unidade Federativa: ')) estado['sigla'] = str(input('Sigla de Estado: ')) brasil.append(estado.copy()) print(brasil) for estados in brasil: for key, value in estados.items(): print(f'O campo {key} tem valor {value}.') print()
1a6cc4175a4e0a04f7c55ef7558bfb0865f8a309
junyaoshi/iGibson
/igibson/scenes/scene_base.py
2,220
3.578125
4
class Scene(object): """ Base class for all Scene objects Contains the base functionalities and the functions that all derived classes need to implement """ def __init__(self): self.build_graph = False # Indicates if a graph for shortest path has been built self.floor_body_ids = [] # List of ids of the floor_heights def load(self): """ Load the scene into pybullet The elements to load may include: floor, building, objects, etc :return: A list of pybullet ids of elements composing the scene, including floors, buildings and objects """ raise NotImplementedError() def get_random_floor(self): """ Sample a random floor among all existing floor_heights in the scene While Gibson v1 scenes can have several floor_heights, the EmptyScene, StadiumScene and scenes from iGibson have only a single floor :return: An integer between 0 and NumberOfFloors-1 """ return 0 def get_random_point(self, floor=None): """ Sample a random valid location in the given floor :param floor: integer indicating the floor, or None if randomly sampled :return: A tuple of random floor and random valid point (3D) in that floor """ raise NotImplementedError() def get_shortest_path(self, floor, source_world, target_world, entire_path=False): """ Query the shortest path between two points in the given floor :param floor: Floor to compute shortest path in :param source_world: Initial location in world reference frame :param target_world: Target location in world reference frame :param entire_path: Flag indicating if the function should return the entire shortest path or not :return: Tuple of path (if indicated) as a list of points, and geodesic distance (lenght of the path) """ raise NotImplementedError() def get_floor_height(self, floor=0): """ Get the height of the given floor :param floor: Integer identifying the floor :return: Height of the given floor """ del floor return 0.0
479013b825b71c328d9ed7b5773ea6a08f78d412
CarlosGiovannyG/Curso_Python
/Calcular_Poblacion.py
1,770
3.6875
4
year = 2022 a = 25 b = 18.9 while a > b: a = a+(a*0.02) b = b+(b*0.03) year += 1 print("El pais B superara a A en el año: " + str(year)) """def poblacion(pA, pB): anio = 2022 while pA > pB: pA += pA*0.02 pB += pB*0.03 anio += 1 return print("Año: ", anio, "\nTotal población A: ", pA, "\nTotal poblacion B: ", pB) pobA = 25e6 pobB = 18.9e6 poblacion(pobA, pobB)""" """SEGUNDO numero1 = int(input('Ingresa un valor: \n')) while numero1 != 1: if numero1 % 2 == 0: print(numero1,"",numero1//2) else: print(numero1," ",numero1 * 3 + 1) numero1 = int(input('Ingresa un valor: \n'))""" """PRIMERO numero = int(input('Ingresa un valor: \n')) while numero > 0: cuadrado = numero * numero print('El cuadrado es:',cuadrado) numero = int(input('Ingresa un valor: \n'))""" """ def factorial(n): if n == 0 or n == 1: return 1 aux = 1 for i in range(n, 0, -1): aux = aux * i return aux n = int(input("Ingresa un valor maximo 10: \n ")) for i in range(1, n + 1): print(i, factorial(i), end=" \n")""" """ flag = True aux = 0 while flag: print(aux) aux += 1 if aux == 11: flag = False else: print('Sirvió') AREA DE UN RECTANGULO ES A * B _______________*************************____________________________ import math def areaRectangulo(a,b): resultado = a * b return resultado def areaCirculo(r): return math.pi * r**2 a = int(input('Ingresa altura: \n')) b = int(input('Ingresa base: \n')) r = int(input('Ingresa radio: \n')) area1 = areaRectangulo(a,b) area2 = areaRectangulo(b,a) area3 = int(areaCirculo(r)) areaTotal = area1 + area2 + area3 print(areaTotal) """
72776a6633e80fcc4e69d79889f4c91ebaca39d3
lo1gr/medical_document_clustering
/embeddings/TFIDF.py
1,694
3.75
4
from sklearn.feature_extraction.text import TfidfVectorizer import pandas as pd import numpy as np # website to look @ for potential info: https://www.freecodecamp.org/news/how-to-process-textual-data-using-tf-idf-in-python-cd2bbc0a94a3/ # what does tokenizer do and do we need it? # on processing nouns def perform_tfidf(df_col): vectorizer = TfidfVectorizer() response = vectorizer.fit_transform((df_col)) feature_names_en = np.array(vectorizer.get_feature_names()) df_tfidf = pd.DataFrame(response.todense(), columns=feature_names_en) return df_tfidf def get_weight(doc_no): # extract the column of the doc you want return (df_tfidf.T.iloc[:,doc_no]) def weighted_sum(doc_no,vec= vectors): W=get_weight(doc_no) #vectors = get_embedding(np.array(W.index)) # is it shape(1) or shape(0)? for word in range(vec.shape[0]): # multiply weight by embedding, same shape as embedding vec[word] = np.array(W)[word]*vec[word] # now sum all the words in the document sum_all = (vec.sum(axis=1))/(np.array(W).sum()) return sum_all abstracts = pd.read_csv('data/abstracts_preproc.csv') df_tfidf = perform_tfidf(abstracts.nouns_lemmatized_text) df_tfidf.shape # words in row, docs in col # 29108, 6909 # for the embeddings we have: vectors and output_format print(vectors) # 6909 rows (docs), 300 cols print(output_format) get_weight(0) vectors[0] vectors.shape[0] W = get_weight(doc_no) # vectors = get_embedding(np.array(W.index)) for word in range(6909): # multiply weight by embedding, same shape as embedding # x vectors[word] what ???? 300 columns? vectors[word] = np.array(W)[word] * vectors[word][]
6ad6e49a50d8e9051095c42179c27b18131f316b
odora/CodesNotes
/Python_100_examples/example3.py
1,294
4.125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2019/1/26 22:29 @Author : cai examples come from http://www.runoob.com/python/python-exercise-example3.html """ # ============== Example 3 ====================================== # 一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少? # =============================================================== def perfect_square(): for i in range(1, 85): if 168 % i == 0: j = 168 / i; if i > j and (i + j) % 2 == 0 and (i - j) % 2 == 0: m = (i + j) / 2 n = (i - j) / 2 x = n * n - 100 print(x) def perfect_square2(): ''' 列表推导式 :return: ''' [print(m ** 2 - 100, end=',') for m in range(1, 169) for n in range(1, 169) if (n ** 2 - m ** 2) == 168] def perfect_square2_loop(): ''' for 循环形式 :return: ''' for m in range(1, 169): for n in range(1, 169): if (n ** 2 - m ** 2) == 168: print(m ** 2 - 100, end=',') if __name__ == '__main__': perfect_square() perfect_square2() print('\n') perfect_square2_loop()
ebb9529c30a0e7f84ca40222f52ff4e97ff9fd4b
TheAkshrCompany/Python
/Fibonacci.py
461
4.21875
4
############################################## # code By Harsh Tiwari # code for Fibonacci in python ################################################## def Fibonacci(p): fab=[0,1] a=0 b=1 if p<=0: return print("Enter the valid number") if p==1: return fab.pop(0) for i in range(p-2): c=a+b a=b b=c fab.append(c) return fab a=int(input("Enter number of output required")) print(Fibonacci(a))
5980f2ce5a05ade82d0c2c80692a32ce6b3bc55c
whiz-Tuhin/Competitve
/Hackerrank/University Codesprint/seperate_numbers.py
984
3.796875
4
def check_forward(prev,remain): if(len(remain) == 0): return 1 if(len(remain) >= 1 and remain[0] == '0'): return 0 a = -1 # taking -1 as intializing value pos = -1 flag = -1 for i in range(1,(len(remain)+1)): a = int(str(remain[:i])) if(a == prev+1): flag = 1 pos = i break if(flag == 1): return check_forward(a,remain[pos:]) def beautiful_numbers(num): for i in range(1,((len((num))/2)+1)): #print "****" prev = int((num[:i])) remain = num[i:] if(check_forward(prev,remain) == 1): return prev if __name__ == "__main__": q = int(input()) for i in range(q): num = (raw_input()) # num = list(str(num)) # typecasting it into a list in order to play with digits final = beautiful_numbers(num) if(final): print ("YES" + " " + str(final)) else: print("NO")
f673da68371d83e5c5a7fa95004eccfd3a6c2a93
martinjakopec/euler
/eul10.py
267
3.59375
4
import math zbroj = 0 def is_prime(x): output = True for i in range(2, int(math.sqrt(x) + 1)): if x % i == 0: output = False return output for i in range(2,2000001): if is_prime(i): zbroj += i print(zbroj)
29826ebc9ff45905e7dc57200e34694f04732a0e
rejithry/class
/algo2_misc/optimize.py
12,857
3.6875
4
# Do Not Repeat Repeated Work # # Focus: Units 5 and 6: Interpreting and Optimization # # # In class we studied many approaches to optimizing away redundant # computation. For example, "X * 0" can be replaced with "0", because we # know in advance that the result will always be 0. However, even if we do # not know the answer in advance, we can sometimes save work. Consider this # program fragment: # # x = a + b + c; # y = 2; # z = a + b + c; # # Even though we do not know what "a + b + c" will be, there is no reason # for us to compute it twice! We can replace the program with: # # x = a + b + c; # y = 2; # z = x; # works since "x = a + b + c;" above # # and neither a nor b nor c has been changed since # # ... and always compute the same answer. This family of optimizations is # sometimes called "common expression elimination" -- the subexpression # "a+b+c" was common to two places in the code, so we eliminated it in one. # # In this problem we will only consider a special case of this # optimization. If we see the assignment statement: # # var1 = right_hand_side ; # # Then all subsequent assignment statements: # # var2 = right_hand_side ; # # can be replaced with "var2 = var1 ;" provided that the "right_hand_side"s # match exactly and provided that none of the variables involved in # "right_hand_Side" have changed. For example, this program cannot be # optimized in this way: # # x = a + b + c; # b = 2; # z = a + b + c; # # Even though the right-hand-sides are exact matches, the value of b has # changed in the interim so, to be safe, we have to recompute "a + b + c" and # cannot replace "z = a + b + c" with "z = x". # # For this problem we will use the abstract syntax tree format from our # JavaScript interpreter. Your procedure will be given a list of statements # and should return an optimized list of statements (using the optimization # above). However, you will *only* be given statement of the form: # # ("assign", variable_name, rhs_expression) # # No other types of statements (e.g., "if-then" statements) will be passed # to your procedure. Similarly, the rhs_expression will *only* contain # expressions of these three (nested) form: # # ("binop", exp, operator, exp) # ("number", number) # ("identifier", variable_name) # # No other types of expressions (e.g., function calls) will appear. # # Write a procedure "optimize()" that takes a list of statements (again, # only assignment statements) as input and returns a new list of optimized # statements that compute the same value but avoid recomputing # whole right-hand-side expressions. (If there are multiple equivalent # optimizations, return whichever you like.) # # Hint: x = y + z makes anything involving y and z un-available, and # then makes y + z available (and stored in variable x). def optimize(ast): op_ast = ast[:] for stmt_num in range(0,len(ast)): var_list = [] stmt = ast[stmt_num] var_list = get_var_list(stmt[2]) #print var_list for i in range(stmt_num + 1, len(ast)): n_stmt = ast[i] if n_stmt[1] in var_list and not(n_stmt[2][0] == 'identifier' and n_stmt[2][1] == n_stmt[1]) : break; if n_stmt[2] == stmt[2]: op_ast[i] = (op_ast[i][0],op_ast[i][1],('identifier',stmt[1])) return op_ast def get_var_list(stmt): if stmt[0] == 'identifier': return [stmt[1]] elif stmt[0] == 'binop': return get_var_list(stmt[1]) + get_var_list(stmt[3]) else: return [] # We have included some testing code to help you check your work. Since # this is the final exam, you will definitely want to add your own tests. example1 = [ \ ("assign", "x", ("binop", ("identifier","a"), "+", ("identifier","b"))) , ("assign", "y", ("number", 2)) , ("assign", "z", ("binop", ("identifier","a"), "+", ("identifier","b"))) , ] answer1 = [ \ ("assign", "x", ("binop", ("identifier","a"), "+", ("identifier","b"))) , ("assign", "y", ("number", 2)) , ("assign", "z", ("identifier", "x")) , ] print (optimize(example1)) == answer1 example2 = [ \ ("assign", "x", ("binop", ("identifier","a"), "+", ("identifier","b"))) , ("assign", "a", ("number", 2)) , ("assign", "z", ("binop", ("identifier","a"), "+", ("identifier","b"))) , ] print (optimize(example2)) == example2 example3 = [ \ ("assign", "x", ("binop", ("identifier","a"), "+", ("identifier","b"))) , ("assign", "y", ("binop", ("identifier","a"), "+", ("identifier","b"))) , ("assign", "x", ("number", 2)) , ("assign", "z", ("binop", ("identifier","a"), "+", ("identifier","b"))) , ] answer3 = [ \ ("assign", "x", ("binop", ("identifier","a"), "+", ("identifier","b"))) , ("assign", "y", ("identifier", "x")) , ("assign", "x", ("number", 2)) , ("assign", "z", ("identifier", "y")) , # cannot be "= x" ] print (optimize(example3)) == answer3 example4 = [ \ ("assign", "x", ("binop", ("identifier","a"), "+", ("identifier","b"))) , ("assign", "y", ("binop", ("identifier","b"), "+", ("identifier","c"))) , ("assign", "z", ("binop", ("identifier","c"), "+", ("identifier","d"))) , ("assign", "b", ("binop", ("identifier","c"), "+", ("identifier","d"))) , ("assign", "z", ("number", 5)) , ("assign", "p", ("binop", ("identifier","a"), "+", ("identifier","b"))) , ("assign", "q", ("binop", ("identifier","b"), "+", ("identifier","c"))) , ("assign", "r", ("binop", ("identifier","c"), "+", ("identifier","d"))) , ] answer4 = [ \ ("assign", "x", ("binop", ("identifier","a"), "+", ("identifier","b"))) , ("assign", "y", ("binop", ("identifier","b"), "+", ("identifier","c"))) , ("assign", "z", ("binop", ("identifier","c"), "+", ("identifier","d"))) , ("assign", "b", ("identifier", "z")) , ("assign", "z", ("number", 5)) , ("assign", "p", ("binop", ("identifier","a"), "+", ("identifier","b"))) , ("assign", "q", ("binop", ("identifier","b"), "+", ("identifier","c"))) , ("assign", "r", ("identifier", "b")) , ] print optimize(example4) == answer4 example4 = [ ('assign', 'x', ('binop', ('identifier', 'a'), '+', ('identifier', 'b'))), ('assign', 'a', ('identifier', 'a')), ('assign', 'y', ('binop', ('identifier', 'a'), '+', ('identifier', 'b'))), ] answer4 = [ ('assign', 'x', ('binop', ('identifier', 'a'), '+', ('identifier', 'b'))), ('assign', 'a', ('identifier', 'a')), ('assign', 'y', ('identifier', 'x')), ] print optimize(example4) == answer4 example1 = [('assign', 'x', ('binop', ('binop', ('identifier', 'a'), '+', ('identifier', 'b')), '+', ('identifier', 'c'))), ('assign', 'y', ("number", 2)), ('assign', 'z', ('binop', ('binop', ('identifier', 'a'), '+', ('identifier', 'b')), '+', ('identifier', 'c')))] answer1 = [('assign', 'x', ('binop', ('binop', ('identifier', 'a'), '+', ('identifier', 'b')), '+', ('identifier', 'c'))), ('assign', 'y', ("number", 2)), ('assign', 'z', ('identifier', 'x'))] print optimize(example1) == answer1 # x = a + e + b + c; # e = 2; # z = a + e + b + c; # example2 = [('assign', 'x', ('binop', ('binop', ('binop', ('identifier', 'a'), '+', ('identifier', 'e')), '+', ('identifier', 'b')), '+', ('identifier', 'c'))), ('assign', 'e', ("number", 2)), ('assign', 'z', ('binop', ('binop', ('binop', ('identifier', 'a'), '+', ('identifier', 'e')), '+', ('identifier', 'b')), '+', ('identifier', 'c')))] answer2 = [('assign', 'x', ('binop', ('binop', ('binop', ('identifier', 'a'), '+', ('identifier', 'e')), '+', ('identifier', 'b')), '+', ('identifier', 'c'))), ('assign', 'e', ("number", 2)), ('assign', 'z', ('binop', ('binop', ('binop', ('identifier', 'a'), '+', ('identifier', 'e')), '+', ('identifier', 'b')), '+', ('identifier', 'c')))] print optimize(example2) == answer2 example4a = [\ ("assign", "x", ("binop", ("identifier","a"), "+", ("identifier","b"))) , ("assign", "y", ("binop", ("identifier","x"), "+", ("identifier","c"))) , ("assign", "z", ("binop", ("binop", ("identifier","a"), "+", ("identifier","b")), "+", ("identifier","c"))) , ] answer4a = [\ ("assign", "x", ("binop", ("identifier","a"), "+", ("identifier","b"))) , ("assign", "y", ("binop", ("identifier","x"), "+", ("identifier","c"))) , ("assign", "z", ("identifier", "y")) , ] print optimize(example4a) == answer4a print optimize(example4a) # x = a + e + b + c; # e = 2; # z = a + e + b + c; # example4b = [ \ ('assign', 'x', ('binop', ('binop', ('binop', ('identifier', 'a'), '+', ('identifier', 'e')), '+', ('identifier', 'b')), '+', ('identifier', 'c'))), ('assign', 'e', ("number", 2)), ('assign', 'z', ('binop', ('binop', ('binop', ('identifier', 'a'), '+', ('identifier', 'e')), '+', ('identifier', 'b')), '+', ('identifier', 'c'))), ] answer4b = [ \ ('assign', 'x', ('binop', ('binop', ('binop', ('identifier', 'a'), '+', ('identifier', 'e')), '+', ('identifier', 'b')), '+', ('identifier', 'c'))), ('assign', 'e', ("number", 2)), ('assign', 'z', ('binop', ('binop', ('binop', ('identifier', 'a'), '+', ('identifier', 'e')), '+', ('identifier', 'b')), '+', ('identifier', 'c'))) ] print optimize(example4b) == answer4b # x = a + e + b + c; # y = e; # z = a + e + b + c; # example4c = [ \ ('assign', 'x', ('binop', ('binop', ('binop', ('identifier', 'a'), '+', ('identifier', 'e')), '+', ('identifier', 'b')), '+', ('identifier', 'c'))), ('assign', 'y', ("identifier", 'e')), ('assign', 'z', ('binop', ('binop', ('binop', ('identifier', 'a'), '+', ('identifier', 'e')), '+', ('identifier', 'b')), '+', ('identifier', 'c'))), ] answer4c = [ \ ('assign', 'x', ('binop', ('binop', ('binop', ('identifier', 'a'), '+', ('identifier', 'e')), '+', ('identifier', 'b')), '+', ('identifier', 'c'))), ('assign', 'y', ("identifier", 'e')), ('assign', 'z', ("identifier", 'x')) ] print optimize(example4c) == answer4c example5 = [\ ("assign", "a", ("identifier", "b")) , ("assign", "a", ("identifier", "a")) , ] #Some people might believe that a = a should be optimized away. Well, it should practically. But #this is not allowed under the rules given in the assignment. a = a is not a "subsequent" assignment #statement for 'a'. answer5 = [\ ("assign", "a", ("identifier", "b")) , ("assign", "a", ("identifier", "a")) , ] print optimize(example5) == answer5 # self-assign # x = x + z + 1; # y = x + z + 1; example6 = [\ ("assign", "x", ("binop", ("identifier","x"), "+", ("binop", ("identifier","z"), "+", ("number","1")))), ("assign", "y", ("binop", ("identifier","x"), "+", ("binop", ("identifier","z"), "+", ("number","1")))) ] # Some people might think that y = x would be a correct optimization, and I think they would be technically right. # But I have seen people say this shouldn't be optimized. I would appreciate help with reasoning here. answer6 = [\ ("assign", "x", ("binop", ("identifier","x"), "+", ("binop", ("identifier","z"), "+", ("number","1")))), ("assign", "y", ("binop", ("identifier","x"), "+", ("binop", ("identifier","z"), "+", ("number","1")))) ] print optimize(example6) == answer6 print optimize(example6) example7 = [ \ ("assign", "x", ("binop", ("identifier","a"), "+", ("identifier","b"))) , ("assign", "y", ("number", 2)) , ("assign", "d", ("number", 2)) , ("assign", "z", ("binop", ("identifier","a"), "+", ("identifier","b"))) , ] # This one is a still in debate to me. Some people say that d = 2 is replaced with d = y. And that is what I have put # in the answer below. However, I still am not 100% convinced that this should be the case. # 7-6 states: # # If we see the assignment statement: # # var1 = right_hand_side ; # # Then all subsequent assignment statements: # # var2 = right_hand_side ; # # can be replaced with "var2 = var1 ;" provided that the "right_hand_side"s # match exactly and provided that none of the variables involved in # "right_hand_Side" have changed. # # Notice the key phrase --- "provided that none of the VARIABLES involved in "right_hand_Side" have changed.". And certainly, the constant number 2 IS NOT a variable. # I would appreciate official reasoning and/or response on this one. answer7 = [ \ ("assign", "x", ("binop", ("identifier","a"), "+", ("identifier","b"))) , ("assign", "y", ("number", 2)) , ("assign", "d", ("identifier", "y")) , ("assign", "z", ("identifier", "x")) , ] print optimize(example7) == answer7
484ac1f17bfaff13f0c0543c124b208e222a9548
ashar-sarwar/python-works
/python_assignment/practice 1.py
105
3.71875
4
dict = {'Name': 'Zabra'} print ("Value :" ,dict.get('Age',8)+1) print ("Value :" ,dict.get('Age',8)+1)
f0e27f5e5e5e409a19dfbfe931e0125932a8f678
thakursc1-zz/IMDB-Movie-DataBase
/Btree.py
6,688
3.796875
4
### Class movie make a set of storage options as below class movie: def __init__(self,title,ID,year,rating): self.title=title self.id=ID self.year=year self.rating=rating def printmovie(self): print self.title ,"(",self.year,")" print "imdb id :",self.id print "rating :",self.rating ### Class Tree Node Makes an node for the tree using movie class at payload class TreeNode: def __init__(self,id,val,year,rating=None,left=None,right=None,parent=None): self.key=val self.payload= movie(val,id,year,rating) #### uses movie class self.leftchild=left self.rightchild=right self.parent=parent def hasLeftChild(self): return self.leftchild def hasRightChild(self): return self.rightchild def isLeftChild(self): return self.parent.leftchild==self and self.parent def isRightChild(self): return self.parent.rightchild==self and self.parent def isRoot(self): return not self.parent def isleaf(self): return not (self.rightchild or self.leftchild) def hasAnyChildren(self): return self.rightchild or self.leftchild def hasBothChilren(self): return self.rightchild and self.leftchild def replaceNodeData(self,ID,value,year,rating,lc,rc): self.key = value self.payload = movie(value,ID,year,rating) self.leftChild = lc self.rightChild = rc if self.hasLeftChild(): self.leftChild.parent = self if self.hasRightChild(): self.rightChild.parent = self class BinarySearchTree: def __init__(self): self.root = None self.size = 0 def length(self): return self.size def __len__(self): return self.size def put(self,key,val,year,rating): if self.root: val = val.lower() self._put(id,val,year,rating,self.root) else: val = val.lower() self.root=TreeNode(id,val,year,rating) self.size = self.size + 1 def _put(self,id,val,year,rating,currentnode): if val<currentnode.key: if currentnode.hasLeftChild(): self._put(id,val,year,rating,currentnode.leftchild) else: currentnode.leftchild = TreeNode(id,val,year,rating,None,None,currentnode) elif val==currentnode.key: if id<currentnode.payload.id: if currentnode.hasLeftChild(): self._put(id,val,year,rating,currentnode.leftchild) else: currentnode.leftchild = TreeNode(id,val,year,rating,None,None,currentnode) else: if currentnode.hasRightChild(): self._put(id,val,year,rating,currentnode.rightchild) else: currentnode.rightchild = TreeNode(id,val,year,rating,None,None,currentnode) else: if currentnode.hasRightChild(): self._put(id,val,year,rating,currentnode.rightchild) else: currentnode.rightchild = TreeNode(id,val,year,rating,None,None,currentnode) def get(self,val): if self.root: res = self._get(val,self.root) if res: return res.payload else: return None else: return None def _get(self,val,currentnode): if not currentnode: return None elif currentnode.key==val: return currentnode elif val<currentnode.key: return self._get(val,currentnode.leftchild) else: return self._get(val,currentnode.rightchild) def __getitem__(self,val): return self.get(val.lower()) def pre_tree(self): self.root.payload.printmovie() print " LEFT SUBTREE Begins........" if self.root.hasLeftChild: self._pre_node(self.root.leftchild) print 500*"*" print " Right SUBTREE Begins.......\n" if self.root.hasRightChild: self._pre_node(self.root.rightchild) return def _pre_node(self,node): if not node: return else: node.payload.printmovie() print "------------(",node.parent.payload.title,")" if node.hasLeftChild: self._pre_node(node.leftchild) if node.hasRightChild: self._pre_node(node.rightchild) else:return def in_tree(self): print " LEFT SUBTREE Begins........" if self.root.hasLeftChild: self._in_node(self.root.leftchild) print 50*'/' self.root.payload.printmovie() print 50*'/' print " Right SUBTREE Begins.......\n" if self.root.hasRightChild: self._in_node(self.root.rightchild) def _in_node(self,node): if not node: return else: if node.hasLeftChild: self._in_node(node.leftchild) node.payload.printmovie() print "------------(",node.parent.payload.title,")" if node.hasRightChild: self._in_node(node.rightchild) else:return def post_tree(self): print " LEFT SUBTREE Begins........" if self.root.hasLeftChild: self._post_node(self.root.leftchild) print 50*'/' print 50*'/' print " Right SUBTREE Begins.......\n" if self.root.hasRightChild: self._post_node(self.root.rightchild) print 50*'-' self.root.payload.printmovie() def _post_node(self,node): if not node: return else: if node.hasLeftChild: self._post_node(node.leftchild) if node.hasRightChild: self._post_node(node.rightchild) node.payload.printmovie() print "------------(",node.parent.payload.title,")" return ############# Creates a tree using Nodes.txt My_Movie_BTree = BinarySearchTree() file = open("Nodes.txt",'r') temp = file.read().splitlines() file.close() length = len(temp) i=0 while i<length: val = temp[i].lower() i=i+1 id = temp[i] i=i+1 year = temp[i] i=i+1 rating = temp[i] i=i+1 My_Movie_BTree.put(id,val,year,rating) #generates binarysearch tree in less than 0.5 secs# #My_Movie_BTree.pre_tree()#Time needed is only for printin #k = My_Movie_BTree["mehmood"]'''
8c9dabece40f2b10a4b539b2dc281e06afc12cc9
daisyang/data_structure_and_algorithm
/Findstring.py
1,626
4.28125
4
# Given a sorted array of valings which is interspersed with empty valings, write a method to find the location of a given valing. # Example: find 'ball' in ['at', '', '', '', 'ball', '', '', 'car', '', '', 'dad', '', ''] will return 4 # Example: find 'ballcar' in ['at', '', '', '', '', 'ball', 'car', '', '', 'dad', '', ''] will return -1 def Stringlocation(l,left,right,val): if val is None: return -1 if left > right: return -1 mid = int(left+right)/2 print "mid" , mid, l[mid] while l[mid]=='' and mid<right: mid+=1 if mid == right: while l[mid]=='' and mid >left: mid-=1 print "change mid to" , mid,l[mid] if l[mid]=='': return -1 if val == l[mid]: return mid elif val < l[mid]: print "checking " ,left,mid-1 return Stringlocation(l,left,mid-1,val) else: print "checking " ,mid+1,right return Stringlocation(l,mid+1,right,val) #iterative def Stringlocation2(l,val): first = 0 last = len(l)-1 while (first<=last): while first <=last and l[last]=='': last-=1 if (first > last): return -1 mid = (first+last)/2 print "mid:" , mid while (l[mid] ==''): #since last is larger than mid and last has a value, so mid won't go out of the array mid+=1 print "change mid to " , mid, l[mid] if l[mid]==val: return mid if val < l[mid]: last = mid-1 else: first = mid+1 return -1 def main(): l=['at', 'az', '', '', 'ball', '', '', 'car', '', '', 'dad', '', 'g'] l=['at', '','','', 'g'] # index = Stringlocation(l,0,len(l)-1,'c') index = Stringlocation2(['at','','','v','c'],'at') print "answer :" ,index if __name__ == '__main__': main()
3dd7dad24bc72f6550bcbb693891a2d0825d5f0a
yuangaonyc/project_euler
/problem_10.py
200
3.703125
4
num = 2 sm =0 def is_prime(num): for i in range(2, int(num ** 0.5)+1): if num % i == 0: return False return True while num < 2000000: if is_prime(num): sm += num print(num, sm) num += 1
d63ea9d2621c86e359e529485f33dbf1ce56903b
cosmunsoftwares/django-boilerplate
/project_name/core/utils.py
4,918
3.765625
4
class CPF(object): INVALID_CPFS = ['00000000000', '11111111111', '22222222222', '33333333333', '44444444444', '55555555555', '66666666666', '77777777777', '88888888888', '99999999999'] def __init__(self, cpf): self.cpf = cpf def validate_size(self): cpf = self.cleaning() if bool(cpf and (len(cpf) > 11 or len(cpf) < 11)): return False return True def validate(self): cpf = self.cleaning() if self.validate_size() and cpf not in self.INVALID_CPFS: digit_1 = 0 digit_2 = 0 i = 0 while i < 10: digit_1 = (digit_1 + (int(cpf[i]) * (11-i-1))) % 11 if i < 9 else digit_1 digit_2 = (digit_2 + (int(cpf[i]) * (11-i))) % 11 i += 1 return ((int(cpf[9]) == (11 - digit_1 if digit_1 > 1 else 0)) and (int(cpf[10]) == (11 - digit_2 if digit_2 > 1 else 0))) return False def cleaning(self): return self.cpf.replace('.', '').replace('-', '') if self.cpf else '' def format(self): return '%s.%s.%s-%s' % (self.cpf[0:3], self.cpf[3:6], self.cpf[6:9], self.cpf[9:11]) if self.cpf else '' class ZipCode(object): def __init__(self, zip_code): """ Class to interact with zip_code brazilian numbers """ self.zip_code = zip_code def format(self): return '%s-%s' % (self.zip_code[0:5], self.zip_code[5:8]) if self.zip_code else '' def cleaning(self): return self.zip_code.replace('-', '') if self.zip_code else '' class Phone(object): def __init__(self, phone): self.phone = phone def cleaning(self): if self.phone: phone = self.phone.replace('(', '') phone = phone.replace(')', '') phone = phone.replace('-', '') phone = phone.replace(' ', '') phone = phone.replace('.', '') phone = phone.replace('+', '') return phone return '' def format(self): if self.phone: if len(self.phone) == 8: return '%s.%s' % (self.phone[0:4], self.phone[4:8]) if len(self.phone) == 9: return '%s %s.%s' % (self.phone[0:1], self.phone[1:5], self.phone[5:9]) if len(self.phone) == 10: return '%s %s.%s' % (self.phone[0:2], self.phone[2:6], self.phone[6:10]) if len(self.phone) == 11: return '%s %s%s.%s' % (self.phone[0:2], self.phone[2:3], self.phone[3:7], self.phone[7:11]) if len(self.phone) == 13: return '+%s (%s) %s %s.%s' % ( self.phone[0:2], self.phone[2:4], self.phone[4:5], self.phone[5:9], self.phone[9:13] ) return '' class CNPJ(object): def __init__(self, cnpj): """ Class to interact with cnpj brazilian numbers """ self.cnpj = cnpj def calculating_digit(self, result): result = result % 11 if result < 2: digit = 0 else: digit = 11 - result return str(digit) def calculating_first_digit(self): one_validation_list = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2] result = 0 pos = 0 for number in self.cnpj: try: one_validation_list[pos] except IndexError: break result += int(number) * int(one_validation_list[pos]) pos += 1 return self.calculating_digit(result) def calculating_second_digit(self): two_validation_list = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2] result = 0 pos = 0 for number in self.cnpj: try: two_validation_list[pos] except IndexError: break result += int(number) * int(two_validation_list[pos]) pos += 1 return self.calculating_digit(result) def validate(self): """ Method to validate brazilian cnpjs """ self.cnpj = self.cleaning() if len(self.cnpj) != 14: return False checkers = self.cnpj[-2:] digit_one = self.calculating_first_digit() digit_two = self.calculating_second_digit() return bool(checkers == digit_one + digit_two) def cleaning(self): if self.cnpj: return self.cnpj.replace('-', '').replace('.', '').replace('/', '') return '' def format(self): """ Method to format cnpj numbers. """ if self.cnpj: return '%s.%s.%s/%s-%s' % (self.cnpj[0:2], self.cnpj[2:5], self.cnpj[5:8], self.cnpj[8:12], self.cnpj[12:14]) return ''
630dd6b75782bdf5917ecd82ccc77bbfd472aabe
KimTaeHyun-GIT/Study
/응용해서 만든거/if문.py
541
3.9375
4
case = int(input('password : ')) if case==3102: print("Password Correct") select = int(input('Enter the number : ')) if select == 1: print("You Enter the 1") elif select == 2: print("You Enter the 2") elif select == 1023: print("New Password Detected") new_password = int(input('Enter the Number : ')) if new_password == 456 : print("□") elif case==4001: print("Welcome Owner") select = int(input('Enter the number : ')) if select == 1 : print("You Enter the 391") else : print("Failed")
882252c363a58130788252a86cda11106a9b4e58
gnramos/CIC-APC
/src/exemplos/03_Fluxo/02_Repeticao/04-do-while.py
580
4.0625
4
# -*- coding: utf-8 -*- # @package: 04-do-while.py # @author: Guilherme N. Ramos (gnramos@unb.br) # @disciplina: Algoritmos e Programação de Computadores # # Em Python, não há o laço de repetição DO-WHILE. Mas o # comportamento pode ser replicado da seguinte forma: # # while True: # # iteração # # if criterio_de_parada: # break N = 10 print('do-while(i < %d)' % N) print('\t', end=' ') i = 0 # Inicialização do critério de parada. while True: print(i, end=' ') i += 1 # Atualização da condição de parada. if i >= N: break print()
f00d55a500396e25fa3c9a09e50dca32cd556476
4roses41/COM404
/PracticeTCA/Question1/Q1.py
138
3.84375
4
Question = input("What happens when the last petal falls? ") print(Question) print("My dear Bella when the last petal falls " + Question)
213b337206746cd05b2ef42c4d743ee122bcc710
rmcclorey/pythonTest
/Text.py
790
4.09375
4
#enter string returns reversed string def reverseString(str): return str [::-1] print reverseString("Hello World") #enter single word string returns pig latin form def pigLatin(str): return str[1:]+str[0]+"ay" print pigLatin("Hello") #enter string returns how many vowels present def vowelCounter(str): vowels = ["a","e","i","o","u"] counter = 0 for char in str: if char in vowels: counter += 1 return counter print vowelCounter("Hello World") #enter string returns if palindrome or not def palindromeChecker(str): if str == str[::-1]: return "True" else: return "False" print palindromeChecker("racecar") print palindromeChecker("Hello World") #enter string returns the amount of characters def wordCounter(str): return len(str) print wordCounter("Hello World")
f97fff24bd34a40427c0edd48673aaf254af6106
zzy1120716/my-nine-chapter
/catagory/BinaryTree/0072-construct-binary-tree-from-inorder-and-postorder-traversal.py
1,109
4.21875
4
""" 72. 中序遍历和后序遍历树构造二叉树 根据中序遍历和后序遍历树构造二叉树 样例 给出树的中序遍历: [1,2,3] 和后序遍历: [1,3,2] 返回如下的树: 2 / \ 1 3 注意事项 你可以假设树中不存在相同数值的节点 """ # Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None class Solution: """ @param inorder: A list of integers that inorder traversal of a tree @param postorder: A list of integers that postorder traversal of a tree @return: Root of a tree """ def buildTree(self, inorder, postorder): # write your code here if not inorder: return root = TreeNode(postorder[-1]) root_pos = inorder.index(postorder[-1]) root.left = self.buildTree(inorder[:root_pos], postorder[:root_pos]) root.right = self.buildTree(inorder[root_pos + 1:], postorder[root_pos:-1]) return root if __name__ == '__main__': print(Solution().buildTree([1, 2, 3], [1, 3, 2]))
3ed312280bd16c883d4ce7391cb92b61cc935d62
rafaelperazzo/programacao-web
/moodledata/vpl_data/139/usersdata/237/61911/submittedfiles/diagonaldominante.py
274
3.6875
4
# -*- coding: utf-8 -*- import numpy as np a=int(imput("Digite o numero de linhas: ")) b=int(imput("Digite o numero de colunas: ")) n=np.zeros((a,b)) for i in range(0,n.shape[0],1): for j in range(0,n.shape[1],1): n[i,j]=float(imput("Digite o termo: ")) print(n)
d0a3fadf4f55ef02ce05658661bfba397ba8d15e
sirdaybat/aoc
/2016/16.py
389
3.5
4
import sys def invert(s): return "".join("0" if c == "1" else "1" for c in s) state = sys.argv[1].strip() target_length = int(sys.argv[2]) while len(state) < target_length: state = state + "0" + invert(reversed(state)) state = state[:target_length] while len(state) % 2 == 0: cs = "" for i in range(0, len(state), 2): cs += "01"[state[i] == state[i+1]] state = cs print state
2bd989281d719d81e4e6844db156cc4820ebc8a0
gudbrandsc/RSA-Public-Key-Cryptosystem
/rsa-homework.py
2,965
4.28125
4
import random # src: https://www.rookieslab.com/posts/how-to-find-multiplicative-inverse-of-a-number-modulo-m-in-python-cpp def multiplicative_inverse(e, phi): for i in range(0, phi): if (e*i) % phi == 1: return i return -1 def gcd(a, b): while b != 0: a, b = b, a % b return a # Check if a number is a prime def is_prime(num): if num == 2: # corner case return True if num < 2 or num % 2 == 0: return False for n in range(3, int(num**0.5)+2, 2): if num % n == 0: return False return True # Read input from console and make sure the number is prime def read_prime_input(message): loop = True num = 0 while loop: num = int(input(message)) loop = not is_prime(num) if loop: print("Not a prime number, try again..") return num # To read about the logic, see: # https://www.tutorialspoint.com/cryptography_with_python/cryptography_with_python_understanding_rsa_algorithm.htm def generate_keypairs(p, q): n = p * q phi = (p-1) * (q-1) #Choose an integer e such that e and phi(n) are coprime e = random.randrange(1, phi) #Use Euclid's Algorithm to verify that e and phi(n) are comprime # https://en.wikipedia.org/wiki/RSA_(cryptosystem)#Key_generation g = gcd(e, phi) while g != 1: e = random.randrange(1, phi) g = gcd(e, phi) #Use Extended Euclid's Algorithm to generate the private key d = multiplicative_inverse(e,phi) #Public key is (e, n) and private key is (d, n) return ((e, n), (d, n)) def encrypt_message(publickey, message_text): # Get e and n from publickey e, n = publickey #For each letter of the message get the Unicode code and follow math from ref in method desc encrypt = [(ord(char) ** e) % n for char in message_text] #Return the array of bytes return encrypt def decrypt_message(pk, encryptedtext): #Unpack the key into its components key, n = pk #Generate the plaintext based on the ciphertext and key using a^b mod m plain = [chr((char ** key) % n) for char in encryptedtext] #Return the array of bytes as a string return "".join(plain) if __name__ == '__main__': print ("--------------- RSA Encrypter/ Decrypter --------------- ") p = read_prime_input("Enter a prime number:") q = read_prime_input("Enter a another (different) prime number:") print ("Generating your public and private keypairs...") public_key, private_key = generate_keypairs(p, q) print ("Your public key is ", public_key ," and your private key is ", private_key) message = input("Enter a message to encrypt with your private key: ") encrypted_msg = encrypt_message(private_key, message) print ("Encrypted message: ") print (''.join(map(lambda x: str(x), encrypted_msg))) print ("Decrypted message using with public key: ", public_key ," . . .") print (decrypt_message(public_key, encrypted_msg))
c05864e31397d9eea7f7d31a86e1b6be07055627
cmosguy/kaggle-hash-code-traffic-signal
/traffic/street.py
1,466
3.703125
4
# Define class of street for keeping properties and methods class Street: def __init__(self, start_int, end_int, name, time_used): self.start_int = start_int self.end_int = end_int self.name = name self.time_used = time_used self.queue = [] # Append new car driving on this street def add_queue(self, car_name, isInit): if isInit: self.queue.append({car_name: self.time_used}) else: self.queue.append({car_name: 1}) # Update cars position on this street def update_cars_move(self, cars, isGreenLight): update_car = None # Remove car that reached the destination if len(self.queue) > 0: if cars[list(self.queue[0].keys())[0]].current_street == -1: self.queue.pop(0) # Update other cars on street for i, car in enumerate(self.queue): car_name = list(car.keys())[0] if cars[car_name].new_street_flag == False: car_time_used = list(car.values())[0] if isGreenLight: if car_time_used >= self.time_used and i == 0: self.queue.remove(car) update_car = car_name else: car[car_name] = car[car_name] + 1 else: car[car_name] = car[car_name] + 1 return update_car
b0255ae776c0a82e42aefe7afa9c88b631d0f50b
kmustyxl/DSA_final_fighting
/NowCoder/Array_Sort/HeapSort_EXAM_Mid_number.py
3,643
4.0625
4
def Mid_number(arr): ''' 随时获取数据流中的中位数 首先,需要建立一个大根堆和一个小根堆。 实时保证大根堆和小根堆的平衡,数量差值不能大于1 大根堆存放数组中较小的部分,则堆顶就是较小部分的最大值 小根堆存放数组中较大的部分,则堆顶就是较大部分的最小值 :param arr: :return: ''' if arr is None: return Big_heap = [] #建立大根堆 Small_heap = [] #建立小根堆 mid_num_arr = [] Big_heap.append(arr[0]) #首先将第一个数放在大根堆中 for i in range(1,len(arr)): if Big_heap[0] >= arr[i]: #如果数据流吐出的数字小于大根堆堆顶,则放入大根推 Big_heap.append(arr[i]) BigHeapinsert(Big_heap, len(Big_heap)-1) #调整大根堆结构,恢复大根堆结构 else: Small_heap.append(arr[i]) #如果数据流吐出的数字大于大根堆堆顶,则放入小根推 SmallHeapinsert(Small_heap, len(Small_heap)-1) #调整小根堆结构,恢复小根堆结构 if len(Big_heap) - len(Small_heap) >= 2: #判断大小根堆规模差值是否大于1 swap(Big_heap, 0, len(Big_heap)-1) #如果大根堆超,则将大根堆堆顶弹出 heapsize = len(Big_heap)-1 #策略为:将堆顶与最后一个数交换位置 BigHeapify(Big_heap,0,heapsize) #在heapsize范围上恢复大根堆 remove_data = Big_heap.pop() #将弹出的堆顶数据放到小根堆 Small_heap.append(remove_data) SmallHeapinsert(Small_heap, len(Small_heap) - 1) elif len(Small_heap) - len(Big_heap) >= 2: #小根堆的处理与大根堆同理 swap(Small_heap, 0, len(Small_heap)-1) heapsize = len(Small_heap) - 1 SmallHeapify(Small_heap, 0, heapsize) remove_data = Small_heap.pop() Big_heap.append(remove_data) BigHeapinsert(Big_heap, len(Big_heap)-1) if len(Big_heap) == len(Small_heap): mid_num = (Big_heap[0] + Small_heap[0]) / 2.0 elif len(Big_heap) - len(Small_heap) == 1: mid_num = Big_heap[0] elif len(Big_heap) - len(Small_heap) == -1: mid_num = Small_heap[0] mid_num_arr.append(mid_num) return mid_num_arr def swap(arr, index1, index2): temp = arr[index1] arr[index1] = arr[index2] arr[index2] = temp def BigHeapinsert(arr, index): #大根堆插入新的数据,并与父代依次比较,找到合适位置 while arr[index] > arr[int((index-1)/2)]: swap(arr, index, int((index-1)/2)) index = int((index-1)/2) def SmallHeapinsert(arr,index): while arr[index] < arr[int((index-1)/2)]: swap(arr, index, int((index-1)/2)) index = int((index-1)/2) def BigHeapify(arr, index, heapsize): #大根堆的调整是将最后的子代和栈顶交换位置,此时‘临时栈顶’小于后代 left = 2 * index + 1 #因次需要依次比较子代找到合适位置 while left < heapsize: if left + 1 < heapsize and arr[left+1] > arr[left]: lagest = left + 1 else: lagest = left swap(arr, index, lagest) index = lagest left = 2 * index + 1 def SmallHeapify(arr, index, heapsize): left = 2 * index + 1 while left < heapsize: if left + 1 < heapsize and arr[left+1] < arr[left]: least = left + 1 else: least = left swap(arr, index, least) index = least left = 2 * index + 1
903a96a00dae3cce6ebe2eeba508da57b38f4a0a
darkblaro/Python-code-samples
/myPower.py
99
3.609375
4
def myPow(a,b): while b-1>0: a=a<<1 b=b-1 return a print(myPow(2,8))
14760827f09dfb12f8e2f894000367c1b2ee2577
radhikagarg03/Python-project
/Assignment/Assignment8.py
1,912
3.6875
4
#Q1. class Circle(): def __init__(self,radius): self.radius = radius def getArea(self): return 3.14*self.radius*self.radius def getCircumference(self): return self.radius*2*3.14 obj1=Circle(10) print(obj1.getArea()) print(obj2.getCircumference()) #Q2. class Student(): def __init__(self,name,roll): self.name = name self.roll= roll def display(self): print self.name print self.roll obj2=Student("radhika",23) obj3=Student("tushar",22) obj2.display() obj3.display() #Q3. class Temprature(): def convertFahrenhiet(self,celsius): return (celsius*(9/5))+32 def convertCelsius(self,farenhiet): return (farenhiet-32)*(5/9) #Q4. class MovieDetails: def __init__(self,name,a_name,year,rate): self.name = name self.a_name = a_name self.year = year self.rate = rate def display(self): print("\nMovie Name : ",self.name) print("Artist Name : ",self.a_name) print("Year of release : ",self.year) print("Rating : ",self.rate) def update(self): print("Update Details") self.name = input("Update Movie Name : ") self.a_name = input("Update Artist Name : ") self.year = input("Update year of release : ") self.rate = input("Update rating : ") obj4 = MovieDetails("Baaghi2","Tiger","2018","9") obj4.display() obj4.update() obj4.display() #Q5 class Expenditure: def __init__(self,exp1,sav1): self.exp1 = exp1 self.sav1 = sav1 def display(self): print("\nExpenditure : ",self.exp1) print("Savings : ",self.sav1) def calculateSalary(self): return self.sav1 + self.exp1 def displaySalary(self): print("Total Salary : ",self.calculateSalary()) ob7 = Expenditure(400000,250000) ob7.display() ob7.displaySalary()
5c3db748af8f46ed2921b79889d8e4106c7b4f46
Farazzaidi22/CG_lab02
/image_histo_rgb.py
669
3.875
4
import numpy as np import cv2 as cv from matplotlib import pyplot as plt #uint8 is an unsigned 8-bit integer that can represent values 0..255 #numpy uint8 will wrap. For example, 235+30 = 9 #img = np.zeros((200,200), np.uint8) img =cv.imread("lena.jpg") cv.imshow("img", img) #splitting img in RGB b,r,g = cv.split(img) cv.imshow("b", b) cv.imshow("g", g) cv.imshow("r", r) #hist(array, no of pixels, range of those pixels) #ravel is used for flattening a 2D array into 1D plt.hist(img.ravel(), 256, [0,256]) plt.hist(b.ravel(), 256, [0,256]) plt.hist(g.ravel(), 256, [0,256]) plt.hist(r.ravel(), 256, [0,256]) plt.show() cv.waitKey(0) cv.destroyAllWindows()
cef4204c3131566960b2cffb00031012c9cfab5a
marshallhumble/Coding_Challenges
/Code_Eval/Moderate/RemoveCharacters/RemoveCharacters.py3
320
3.796875
4
#!/usr/bin/env python from sys import argv with open(argv[1], 'r') as f: cases = f.read().strip().splitlines() for item in cases: text, letters = item.split(',') text = text.split() for c in letters: for t in text: text[text.index(t)] = t.replace(c, '') print(' '.join(text))
d3c9556ac2879c7afdffd951708bc6089b45d36a
chang-1/BrownUniversity
/CSCI1420/hw02/models.py
3,519
3.546875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' This file contains the Linear Regression Regressor Brown CS142, Spring 2020 ''' import random import numpy as np def l2_loss(predictions, Y): ''' Computes L2 loss (sum squared loss) between true values, Y, and predictions. @params: Y: A 1D Numpy array with real values (float64) predictions: A 1D Numpy array of the same size of Y @return: L2 loss using predictions for Y. ''' #calculate squared loss loss = (predictions-Y)**2 return loss.sum() class LinearRegression: ''' LinearRegression model that minimizes squared error using either stochastic gradient descent or matrix inversion. ''' def __init__(self, n_features): ''' @attrs: n_features: the number of features in the regression problem weights: The weights of the linear regression model. ''' self.n_features = n_features + 1 # An extra feature added for the bias value self.weights = np.zeros(n_features + 1) def train(self, X, Y): ''' Trains the LinearRegression model weights using either stochastic gradient descent or matrix inversion. @params: X: 2D Numpy array where each row contains an example, padded by 1 column for the bias Y: 1D Numpy array containing the corresponding values for each example @return: None ''' self.train_solver(X, Y) def train_solver(self, X, Y): ''' Trains the LinearRegression model by finding the optimal set of weights using matrix inversion. @params: X: 2D Numpy array where each row contains an example, padded by 1 column for the bias Y: 1D Numpy array containing the corresponding values for each example @return: None ''' temp = np.matmul(X.transpose(),X) temp = np.linalg.pinv(temp) temp = np.matmul(temp, X.transpose()) self.weights = np.matmul(temp, Y) def predict(self, X): ''' Returns predictions of the model on a set of examples X. @params: X: a 2D Numpy array where each row contains an example, padded by 1 column for the bias @return: A 1D Numpy array with one element for each row in X containing the predicted value. ''' predictions = np.matmul(X, self.weights) return predictions def loss(self, X, Y): ''' Returns the total squared error on some dataset (X, Y). @params: X: 2D Numpy array where each row contains an example, padded by 1 column for the bias Y: 1D Numpy array containing the corresponding values for each example @return: A float number which is the squared error of the model on the dataset ''' predictions = self.predict(X) return l2_loss(predictions, Y) def average_loss(self, X, Y): ''' Returns the mean squared error on some dataset (X, Y). MSE = Total squared error/# of examples @params: X: 2D Numpy array where each row contains an example, padded by 1 column for the bias Y: 1D Numpy array containing the corresponding values for each example @return: A float number which is the mean squared error of the model on the dataset ''' return self.loss(X, Y)/X.shape[0]
f5feda0c8976345dc5e11b6e67b76692f8e443ff
ojhaanshu87/LeetCode
/39_combination_sum.py
1,787
3.953125
4
''' Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order. The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different. It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input. Example 1: Input: candidates = [2,3,6,7], target = 7 Output: [[2,2,3],[7]] Explanation: 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate, and 7 = 7. These are the only two combinations. Example 2: Input: candidates = [2,3,5], target = 8 Output: [[2,2,2,2],[2,3,3],[3,5]] Example 3: Input: candidates = [2], target = 1 Output: [] Example 4: Input: candidates = [1], target = 1 Output: [[1]] Example 5: Input: candidates = [1], target = 2 Output: [[1,1]] ''' class Solution(object): def find(self, candidate_index, combination, candidates, target, solutions): current_sum = sum(combination) if current_sum == target: solutions.append(combination[:]) return for next_index in range(candidate_index, len(candidates)): if current_sum + candidates[candidate_index] > target: return combination.append(candidates[next_index]) self.find(next_index, combination, candidates, target, solutions) combination.pop() return solutions def combinationSum(self, candidates, target): candidates.sort() return self.find(0, [], candidates, target, [])
556f8101ee3f1be7137d02d807ad4a86d3cd1827
jwhite007/python-practice
/practice_modules/string_compression.py
638
3.890625
4
#! /usr/bin/env python def compr_str(string): compr_str = '' count = 0 # import pdb; pdb.set_trace() for i in string: if compr_str == '': compr_str = i count += 1 elif compr_str[len(compr_str) - 1] == i: count += 1 else: compr_str = compr_str + str(count) + i count = 1 compr_str = compr_str + str(count) if len(compr_str) == len(string) * 2: return string else: return compr_str if __name__ == '__main__': print compr_str('aabbbcccc') print compr_str('aabbbccccddddd') print compr_str('abcd')
2e02823e4c94a2c272c70d9a428f2ed7c93b1bbc
machevera/pytest
/parametros2.py
1,254
3.640625
4
#sys.argv is the list of command-line arguments. #sys.argv ES UNA LISTA #uso de la libreria getopt (get options) #python parametros2.py -i archivo1.xls -o archivo1.sql #python parametros2.py --ifile=archivo1.xls --ofile=archivo1.sql #imports import sys import getopt #funciones def p(mensaje): print("\n--"+mensaje+"--") p('** PARAMETROS DE LA LINEA DE COMANDOS (con gestion de opciones) **') p('cantidad de parametros') print(str(len(sys.argv))) p("carga de opciones (lista)") #python parametros2.py -i archivo1.xls -o archivo1.sql #python parametros2.py --ifile=archivo1.xls --ofile=archivo1.sql try: #sys.argv[1:] es la lista de opciones opciones,argumentos=getopt.getopt(sys.argv[1:],"hi:o:",["ifile=","ofile="]) except getopt.GetoptError: print ("parametros2.py -i <archivo entrada> -o <archivo salida>") sys.exit(0) p('lista de opciones') print(opciones) p('lista de argumentos') print(argumentos) p('gestion de opciones y argumentos') for opcion,argumento in opciones: print(f"el valor de la opcion {opcion} es {argumento}") if opcion in ("-i","--ifile"): print(f"el archivo de entrada es {argumento}") elif opcion in ("-o","--ofile"): print(f"el archivo de salida es {argumento}")
5e14397a2248c2ecfd54df6cd5834798645ee385
cantseemy/py
/Project_5_4.py
503
3.921875
4
#! /usr/bin/env python3 import math print("a * x^2 + b * x + c = 0 ") a = int(input("a = ")) if a == 0: while a == 0: a = int(input("a = ")) continue b = int(input("b = ")) c = int(input("c = ")) d = b**2-4*a*c if d == 0: x = -1*b/2*a print("D = 0, Коренем рівняня є : ",x) elif d < 0: print("D < 0, Коренів немає") else: x1 = (-1*b+math.sqrt(d))/(2*a) x2 = (-1*b-math.sqrt(d))/(2*a) print("D > 0, Корені рівняння : ","x1 = ",x1,"|","x2 = ",x2)
6bc6c76ccb57b66e093bf27de8c978151f7510b4
DouglasCarvalhoPereira/Interact-OS-PYTHON
/M7/csv_to_html.py
2,568
3.765625
4
#!/usr/bin/env python3 import sys import csv import os def process_csv(csv_file): """#Transforma o CSV em uma lista de listas""" print("Processando {}".format(csv_file)) with open(csv_file, "r") as datafile: data = list(csv.reader(datafile)) return data def data_to_html(title, data): """Transforma a lista tabela HTML""" # HTML Header html_content = """ <html> <head> <style> table { width: 25%; font-family: arial, sans-serif; border-collapse: collapse; } tr:nth-child(odd) { background-color: #dddddd; } td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; } </style> </head> <body> """ html_content += "<h2>{}</h2><table>".format(title) #Adiciona cada linha de dados como uma linha da tabela #A primeria linha é tratada separadamente por ser especial for i, row in enumerate(data): html_content += "<tr>" for column in row: if i == 0: html_content += "<th>{}</th>".format(column) else: html_content += "<td>{}</td>".format(column) html_content += "</tr>" html_content += "</tr>" html_content += """</tr></table></body></html>""" return html_content def write_html_file(html_string, html_file): #Saber se o arquivo HTML que estamos escrevendo existe ou não if os.path.exists(html_file): print("{} Esse arquivo já existe!") with open(html_file, 'w') as htmlfile: htmlfile.write(html_string) print("Tabela {} criada com sucesso.".format(html_file)) def main(): """Verifica todos os argumentos e chama a função de processamento""" #Verifica se os arquivos da linha de comando estão incluídos if len(sys.argv) < 3: print("ERROR: Argumento de linha de comando não encontrado!") print("Saindo do programa...") sys.exit(1) csv_file = sys.argv[1] html_file = sys.argv[2] # Verifica se está incluído o arquivo com as extenções if ".csv" not in csv_file: print("Arquivo CSV não encontrado") print("Saindo do sistema!") sys.exit(1) if not os.path.exists(csv_file): print("Caminho para o arquivo {} inexistente".format(csv_file)) print("Saino do sistema!") sys.exit(1) data = process_csv(csv_file) title = os.path.splitext(os.path.basename(csv_file))[0].replace("_", " ").title() html_string = data_to_html(title, data) write_html_file(html_string, html_file) if __name__ =="__main__": main()
7a9d5f6c20d34fe36f7a3ad9db70f9ebff1d80d8
jaruwitteng/6230401856-oop-labs
/jaruwit-6230401856-lab3/Problem 1.py
127
3.9375
4
total = 0 digit = 0 while total <= 200: digit = digit + 1 total += digit ** 2 print("the final total is", total)
c58130d67d4734cdc1bbb1d25dd83f244c699d62
tinasoady/detect_error
/PARITE.py
535
3.578125
4
#!/usr/bin/env python3 def getParity(n): parity = 0 while n: parity = ~parity n = n & (n - 1) return parity def parityimp(binArray): res=[] for i in binArray: if getParity(i): b = bin(i) b = b[2:] res.append("1" + b) else: b = bin(i) b = b[2:] res.append("0" + b) return res def paritypair(binArray): res=[] for i in binArray: if getParity(i): b = bin(i) b = b[2:] res.append("0" + b) else: b = bin(i) b = b[2:] res.append("1" + b) return res
d51a9d75672357869c8afa8f637fe9394cf76cb7
13548029769/Aline-game-python-
/code/alien.py
1,196
3.515625
4
import pygame from pygame.sprite import Sprite class Aline(Sprite): """a class representative aline""" def __init__(self,ai_settings,screen): """init aline setting and initialization""" super().__init__() self.screen = screen self.ai_settings = ai_settings #loading alien image and setting its attribute self.image = pygame.image.load("images/alien.bmp") self.rect = self.image.get_rect() self.rect.x = self.rect.width self.rect.y = self.rect.height # setting alien accurate position self.x = float(self.rect.x) def blitme(self): """draw alien at specific position""" self.screen.blit(self.image,self.rect) def update(self): """move right and left aliens""" self.x += (self.ai_settings.alien_speed_factor * self.ai_settings.fleet_direction) self.rect.x = self.x def check_edges(self): """if alien at the edge of screen""" screen_rect = self.screen.get_rect() if self.rect.right >= screen_rect.right: return True elif self.rect.left <= screen_rect.left: return True
c8ce2b31c7ee91626c1f2ea3a863be8ea9101b85
3chrisprosise/pythonUtil
/Util1.py
6,897
3.890625
4
# -*- encoding:utf-8 -*- from math import pi import string # # 整数除法 // # print(3//2) # 结果为 1 # #序列相加 # list1 = [1, 2, 3] # list2 = [4, 5, 6] # print(list1+list2) # #创建空列表 # squence = [None]*10 # print(squence) # 判断成员 # date = ['Mon', 'Tue', 'Ths', 'Wen'] # print('Mon' in date) # True # print('Wen' in date) # False # print(len(date)) # 3 获取长度 # numbers = [22, 33, 44] # print(max(date)) # 返回Tue 这里是如何判断的? # print(max(numbers)) # 返回44 max对不同内容的处理 # # 列表元素删除 # date = ['Mon', 'Tue', 'Ths'] # del date[2] # print(date) # print(len(date)) # 删除元素后列表长度改变 # # 分片赋值 # numbers = [1, 5] # num = [2, 3, 4] # numbers[1:1] = num # print(numbers) # 这里直接将num插入到numbers中间 # print(len(numbers)) # print(numbers[1:4]) # numbers[1:4] = [] # print(numbers) # print(len(numbers)) # 空列表不占位 # # 列表方法 # numbers = [1, 2, 3] # numbers.append(4) # numbers.append(4) # numbers.append(4) # numbers.append(4) # print(numbers) # print(numbers.count(4)) # 统计4出现的次数 # # a = [1, 2, 3] # b = [4, 5, 6] # a.extend(b) # print(a) #利用列表拓展原有列表 # # location = numbers.index(4) # print(location) # 只显示4 第一次出现的位置 # # numbers.insert(4, 'ok') # print(numbers) # 在某个元素第一次出现的位置后方插入新的对象 # # numbers.pop(3) # 移除列表中某一个元素 默认为最后一个, 参数为元素的位置 # print(numbers) # # numbers.remove('ok') # 移除列表中某个元素,参数为这个元素 # print(numbers) # # numbers.reverse() # 列表中元素反序存放 # print(numbers) # # # numbers.insert('ok') # numbers.sort() # print(numbers) # 改变原列表的排列顺序,按照一定的顺序,不是数字的排序会出错,而且sort函数不返回值 # # after = sorted(numbers) # sorted()可以用来获取副本 # print(after) # # # 元组 # source = (1, 2, 3) # print(source) #创建元组 # # # 仅仅包含一个元素的元组 # print((3,)) # 这里的逗号非常重要 # 将列表转换为元组 # source = tuple([1, 2, 3]) # print(source) # # # 元组和列表的区别 1 元组可以在影射中当作键使用 # # 字符串操作 # fromat = "Pi with three decimals: %.3f" # print(fromat % pi) # # print('%x' % 42) # x 16进制 # print('%f' % pi) # print('%10f' % pi) # print('%10.2f' % pi) # print('%.2f' % pi) # print('%010f' % pi) # 用0 填充空位 # print('%-020.2f' % pi) # print(string.digits) # 0-9 字符串 # print(string.ascii_letters) # 所有大写和小写的字符 # print(string.ascii_lowercase) # 所有小写字符 # print(string.ascii_uppercase) # 所有大写字符 # print(string.printable) # print(string.punctuation) # 所有标点字符串 # str = ' This is a very long String ' # location = str.find('is') # in只能用来查找单个字符,find可以查找一串字符 # print(location) # 返回最左段索引,没有则返回-1 # # seq = ['1', '2', '3', '4', '5', '6'] # sep = '+'.join(seq) # print(sep) # join 可以使用字符来连接字典中的元素 # str = str.lower() # 转变为小写的字符串 # str = str.replace('is', 'is not') # 替换字符串的内容 # str = str.strip() # 去除字符串两边的空格 # # print(str) # 字典操作 # d = dict(name='Chris', age=20) # 创建字典 # print(len(d)) # del d['name'] # print(len(d)) # 删除键同样会释放空间 # print('age' in d) # 查询字典中的键 # print('My age is %d' % d['age']) # 字典格式化字符串 # # d.clear() # 清空字典 # p = d.copy() # 创建一个新的字典,内容与之前的内容相同 # p = d.fromkeys(['age', 'name', 'action']) # print(p) # 创建一个新的字典 # #print(d['name']) # 这里会报错,因为没有name对应的值 # print(d.get('name')) # 这里找不到键对应的值时候会返回None ,不会触发程序异常 # print(d.items()) # 将字典所有项以列表的形式返回 # print(d.__iter__()) # __iter__() 方法返回对象本身 # d['name'] = 'Chris' # print(d) # d.pop('name') # 删除了字典中对应的项 # print(d) # print(d.keys()) # 返回字典中的所有键 # d['name'] = 'Chris' # d['action'] = 'run' # d['eat'] = 'apple' # d.popitem() # print(d) # 随即删除一个项,经过验证确实是随即的。。。。。 # d.setdefault('speak', 'loudly') # # 如果没有对应的值,则创建一个健值,如果有,则返回对应键的值 # d.update({'name': 'Tom'}) # 覆盖或者添加对应的键值 # print(d) # key, value = d.popitem() # popitem() 随即删除项 # print(key) # print(value) # 链式赋值 # z= 3 # x=y=z # # # # 等价与 # print(x) # print(y) # # 这里的x与y共享一个地址?是的 # x = 4 # print(y) # print(False==False) #True # print(False=={}) #False # print(False==0) # True # print(False=='') # False # print(False==None) # False # print(False==()) # False # # 解释器会将以下的表达式看作假值 # # print(bool(False)) # False # print(bool({}))# False # print(bool([]))# False # print(bool(()))# False # print(bool(None))# False # # print(bool(''))# False # # print(bool(0))# False # z = 3 # p = 3 # x = z # y = p # print(x is y) # is 运算符的结果有时不可测 ,少用 # # print([2, 3, 4] < [1, 7, 8]) # False # print([2, 3, 4] < [2, 7, 8]) # True # # # 比较符号 < > <= >= 都是依照排列顺序比较的 # # number = 7 # # 这种表达式可以简化 # if 0 <= number <= 7: # print('ok') # 列表推导式 # list = [x*x for x in range(10)] # 这种循环返回一个列表 # print(list) # list = [(x, y) for x in range(10) for y in range(10)] # 共81 个点 ,相当于两个for循环嵌套 # print(list) # del 可以用来删除无用对象 # 动态创建命名空间 py 3.0 不适用 # from math import sqrt # scope = {} # exec('sqrt = 1 in scope') # print(sqrt) # print(scope['sqrt']) def add(x,y): ''' 两个数字的求和 :param x: 一个数字 :param y: 另一个数字 :return: 求和 ''' return x + y print(callable(add)) # 判断函数是否可以调用 # help(add) # 函数的说明是存储在 .__doc__ 属性中的,在python 的内建函数help中可以查看这些函数的说明 # 两个变量引用同一个列表的时候其实是同时引用一个列表 list1 = ['one', 'two', 'three'] # list2 = list1 # list2[0] = 'apple' # 这个操作会改变list1 list2 = list1[:] list2[0] = 'apple' # list2 获取了list1 的一个副本,并没有功共用一个列表 print(list1) a=1 b=2 c=3 d=4 e=5 f=6 def lookuppara(*para): return para # 这里返回的是一个元组 def lookuppara2(**para): return para # 这里返回的是一个列表 两个 * 与一个 * 的区别 print(lookuppara(a, b, c, d, e, f)) print(lookuppara2(a=1, b=2, c=3, d=4, e=5, f=6))
4d363fcd447d53d36f9cfd4d2c6f851a69f94aa2
simranbarve/Queue
/CircularQueue.py
1,419
3.96875
4
class CircularQueue: def __init__(self, queue_size = 7): self.queue_size = queue_size self.queue = [None] * queue_size self.front = -1 self.rear = -1 '''checks if the stack is empty (used in enqueue and dequeue methods)''' def isempty(self): '''if the rear pointer and front pointer are bith minus 1 the queue is empty''' if (self.rear == -1) and (self.front == -1): return True else: return False def isfull(self): if (self.rear + 1) % self.queue_size == self.front: return True else: return False def add_item(self, value): if not self.isfull(): if self.isempty(): self.front = 0 self.rear = 0 self.queue[self.rear] = value else: self.rear = (self.rear + 1) % self.queue_size self.queue[self.rear] = value return True return False def remove_item(self): if not self.isempty(): self.queue[self.front] = None if self.front == self.rear: self.front = -1 self.rear = -1 else: self.front = (self.front + 1) % self.queue_size return True return False def printing(self): print(self.queue) return True
0cc98572b5f49820af23e97891796e033515bb62
SusmoyBarman1/Python-OOP
/3. updateData.py
767
4.0625
4
class Human(): def __init__(self): self.name = 'susmoy' self.age = 24 def updateName(self, name): self.name = name def updateAge(self, age): self.age = age man1 = Human() man2 = Human() ''' print(f'\nName of 1st person: {man1.name}') print(f'Age of 1st person: {man1.age}') print(f'Name of 2nd person: {man2.name}') print(f'Age of 2nd person: {man2.age}\n') print('\nUpdating the name of 2nd person\n') man2.updateName('Nipa') man2.updateAge(22) print(f'\nName of 1st person: {man1.name}') print(f'Age of 1st person: {man1.age}') print(f'Name of 2nd person: {man2.name}') print(f'Age of 2nd person: {man2.age}\n') ''' print('Compare objects by their name') if man1.name == man2.name: print('Same person')
9cf1f63c0387d1241ff810d847e5b64624fdf5c4
ash-xyz/CompetitiveProgramming
/Kattis/Datum/date.py
255
3.9375
4
from datetime import date days = [ 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', ] day, month = map(int, input().split()) day_of_week = date(2009, month, day) print(days[day_of_week.weekday()])
b1ad89ac90fb83bc0be425247240d132e6650996
thebazman1998/School-Projects
/Grade 10/Unit 1/Bp_U1_Assignment5/Bp_U1_Assignment5_V4.py
1,795
4.1875
4
""" Name: Basil Class: ICS201-01 Date: 10/02/14 Assignment 5 """ #Imports libraries import math, random #Asks user for a number and saves it to variable a a = input("Enter a number") print "Rounded down integer", math.floor(a) print "Rounded up integer", math.ceil(a) """ 1. The math.floor() command tells it to round down to the nearest float, the math.ceil() command tells it to round up to the nearest float 2. It has to be a number, not a string 3. The return value is a floating point number """ ################################################################################ #Asks for two numbers and saves them to variables a and b a = input("Enter a number") b = input("Enter another number") #Prints absolute value of both numbers print "The absolute value of the first number is", math.fabs(a) print "The absolute value of the second number is", math.fabs(b) #Prints the numbers converted to radians print "The first number, in radians is:", math.radians(a) print "The second number, in radians is:", math.radians(b) ################################################################################ import random #Asks user for two numbers and stores them in variables a & b a = input("Enter a number") b = input("Enter another number") #Prints a random integer between the two numbers given print random.randint(a, b) #Prints a random float between 0.0 and 1.0 print random.random() #Prints a float between the two parameters print random.uniform(a, b) """ 1. What do they do? They find random integers and floats in between given numbers 2. What data type does the parameter have to be? An integer or a float 3. What data type is the return value? An integer or float """ ################################################################################
e959cdde65daf61cd19e655fec9b7ddd65ffbe6a
annechen112995/ShakespeareSonnet
/src/dictionaries.py
3,955
3.71875
4
from shakespeare_processing import * BORDER = "===============================================================" def load_file(filename): ''' Given a filename, load the file and return list of sentences deliminated by '\n' ''' raw_text = open(filename).read() return raw_text def import_syllables(): ''' Returns a dictionary of words to syllables. Syllables: list of strings in the form of '1' or 'E1' where the number represent the number of syllables and 'E' represent that it is only that number of syllables if the word appears at end of line ''' filename = 'data/Syllable_dictionary.txt' raw_text = load_file(filename) text_list = raw_text.strip().split('\n') syllables = {} for line in text_list: sep = line.split(' ') word = sep[0] info = sep[1:] syllables[word] = info return syllables def generate_rhyme_dict(): ''' Constructs a rhyme_to_word dictionary and a word_to_rhyme dictionary ''' filename = 'data/shakespeare.txt' raw_text = open(filename).read() text_list = raw_text.strip().split('\n') # Preprocessing text_list = remove_int(text_list) text_list = remove_empty(text_list) text_list = lowercase(text_list) text_list = remove_punctuation(text_list) new_text = '\n'.join(text_list) # Separate into sonnets sonnets = separate_sonnets(new_text) # Initialize dictionary rhyme_to_word = {} word_to_rhyme = {} # Rhyming pattern of Shakespean Sonnet pattern_14 = [(0, 2), (1, 3), (4, 6), (5, 7), (8, 10), (9, 11), (12, 13)] pattern_12 = [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10, 11)] for i, sonnet in enumerate(sonnets): lines = sonnet.split('\n') print("Sonnet {}".format(i)) print("Number of lines: {}".format(len(lines))) if len(lines) == 14: pattern = pattern_14 else: pattern = pattern_12 for (i, j) in pattern: print(BORDER) print(lines[i]) print(lines[j]) print(BORDER) last_word_i = lines[i].split(' ')[-1] last_word_j = lines[j].split(' ')[-1] rhyme_i = None rhyme_j = None # Check if words are in the dictionary if last_word_i in word_to_rhyme: rhyme_i = word_to_rhyme[last_word_i] if last_word_j in word_to_rhyme: rhyme_j = word_to_rhyme[last_word_j] # If both words have not been in dictionary, create new rhyme if rhyme_i is None and rhyme_j is None: keys = list(rhyme_to_word.keys()) if keys == []: rhyme = 0 else: rhyme = max(keys) + 1 rhyme_to_word[rhyme] = [last_word_j, last_word_i] word_to_rhyme[last_word_i] = rhyme word_to_rhyme[last_word_j] = rhyme # if word j is in dictionary, add i to j's rhyme elif rhyme_i is None: word_to_rhyme[last_word_i] = rhyme_j rhyme_to_word[rhyme_j].append(last_word_i) # if word i is in dictionary, add j to i's rhyme elif rhyme_j is None: word_to_rhyme[last_word_j] = rhyme_i rhyme_to_word[rhyme_i].append(last_word_j) # if separate rhymes, combine elif rhyme_i != rhyme_j: list_words_i = rhyme_to_word[rhyme_i] list_words_j = rhyme_to_word[rhyme_j] combine = list_words_i + list_words_j rhyme_to_word[rhyme_i] = combine for word in list_words_j: word_to_rhyme[word] = rhyme_i del rhyme_to_word[rhyme_j] return rhyme_to_word, word_to_rhyme if __name__ == '__main__': (rtw, wtr) = generate_rhyme_dict()
119985c0fb5b36a51360003131436ae029d50346
Akash-kakkar/Python-DS
/Day9/PyDS_Day9.py
1,012
4.09375
4
#When does operation between two uneven ndarray support in numpy and how? # '''If the arrays have different shapes, then the element-by-element operation is not possible. But, in real-world applications, you will rarely come across arrays that have the same shape. So Numpy also provides the ability to do arithmetic operations on arrays with different shapes. That ability is called broadcasting. Although you can do arithmetic operations on arrays with wide-ranging shapes, there are a few limitations. So, it helps us to know the broadcasting rules before we look at a few examples. In general, you can do arithmetic operations between two arrays of different shapes, if: The size of each dimension is the same, or The size of one of the dimensions is one And you can use these rules to perform operations even between a ten-dimensional array and a two-dimensional array. The dimensionality of the arrays does not matter.''' import numpy as np A = np.arange(4) B = np.arange(12).reshape(3, 4) A + B
c62db5dc47eb08c3ffd5eedc616aec6158e21abc
gabrielajachs/courses
/Python Developer/Lesson120.py
493
3.546875
4
class PlayerCharacter: membership = True def __init__(self, name, age): self.name = name self.age = age def shout(self): print(f"My name is {self.name}") @classmethod def adding_things(cls, num1, num2): return cls('Teddy', num1 + num2) @staticmethod def adding_things(cls, num1, num2): return cls('Teddy', num1 + num2) #player1 = PlayerCharacter("Tom", 20) player3 = PlayerCharacter.adding_things(2,3) print(player3.age)
5c6dc02a8e551831b04c88e664c6e0e1b2e0596e
thewchan/python_oneliner
/ch3/numpy_assoc2.py
693
3.890625
4
"""NumPy association analysis example. Here we would like to find the two items that were purchased most often together. """ import numpy as np # Row is customer shopping basket # row = [course 1, course 2, ebook 1, ebook 2] # value 1 indicates that an item was bought. basket = np.array([[0, 1, 1, 0], [0, 0, 0, 1], [1, 1, 0, 0], [0, 1, 1, 1], [1, 1, 1, 0], [0, 1, 1, 0], [1, 1, 0, 1], [1, 1, 1, 1]]) # One-liner copurchases = [(i, j, np.sum(basket[:, i] + basket[:, j] == 2)) for i in range(4) for j in range(i + 1, 4)] print(copurchases)
34e44753e83b11bf76982057445277012dd1b3ba
akshat14714/IT-Practice
/labs/lab-7/gibberish.py
347
3.640625
4
inputfile = open("encrypted.txt","r") file = open("decrypted.txt","w") def decrypt(): string = inputfile.read() string = "".join(string.split('#')) string = "".join(string.split('\n')) string = "".join(string.split(' ')) ans = "" for i in string: ans += chr(ord(i) - 20) file.write(ans) decrypt() file.close()
c77d4a0c8ce00e0d7d83844e7092c69c0be08020
captainmoha/MITx-6.00.1x
/Week 3/Objects/applyToEach.py
628
3.984375
4
# using functions as first class objects # apply to each function takes a function and applies # it to a list lista = [1,2,3,4,5] listb = [6,1,2,7,9] def applyToEach(L,recurFact): for i in range(len(L)): L[i] = recurFact(L[i]) return L # factorial with recursion def recurFact(n): if n == 0: return 1 # handling zero factorial if n == 1: # base case return n return n * recurFact(n-1) # recursive step lista = [1,2,3,4,5] listb = [6,1,2,7,9] print applyToEach(lista,recurFact) x = map(max,lista,listb) print "mapping list to min " + str(x)
ceb29017310ac5582c500582312dd40a42f29b0d
mukeshk/python-learning
/hacker-rank/Strings/find-a-string.py
798
4.1875
4
""" In this challenge, the user enters a string and a substring. You have to print the number of times that the substring occurs in the given string. String traversal will take place from left to right, not from right to left. Output Format Output the integer number indicating the total number of occurrences of the substring in the original string. Sample Input ABCDCDC CDC Sample Output 2 """ def count_substring(string, sub_string): count_rec=0 for i in range(0, len(string)): substr = string[i:i+len(sub_string)] if substr == sub_string: count_rec = count_rec+1 return count_rec if __name__ == '__main__': string = raw_input().strip() sub_string = raw_input().strip() count = count_substring(string, sub_string) print count
835ccc9a5580665c8b950b0b205e97b5cb0a5320
katesolovei/python
/numbers.py
708
3.75
4
#Дано целое, положительное, трёхзначное число. Например: 123, 867, 374. Необходимо его перевернуть. #Например, если ввели число 123, то должно получиться на выходе ЧИСЛО 321. ВАЖНО! Работать только с числами. #Строки, оператор IF и циклы использовать НЕЛЬЗЯ! number = int(input("Input *** number\n")) res = list() res.append(number//100) number = number - res[0]*100 res.append(number//10) number = number - res[1]*10 res.append(number) new_res = res[-1]*100 + res[-2]*10 +res[-3] print(new_res)
352e9aacde6bd81540203ef3a9917ab4f0661361
caicono/PythonStartUp
/ex1.py
615
4
4
# -*- coding: utf-8 -*- ## ex1 print "Hello, world!" print "Hello again" print "你好!" ## ex2 print "I will count my chickens:" print "hens:", 25+ 30/6 print "Roosters:",100-25*3%4 print "is it true that 3+2<5-7?", 3+2<5-7 #print 3+2<5-7 ## ex3 varibles cars = 100 space_in_a_car = 4.0 drivers = 30 passengers = 90 cars_not_driven = cars - drivers cars_driven = drivers carpool_capacity = cars_driven*space_in_a_car print "There are ",cars,"cars available" print "There will be", cars_driven, "cars driven today" print "Hey %s there." % "you" print "%s" % " what is persentage?"
1d27acceacc19bc44d5b71216e3cf5da20b55205
Ahmed-AG/python_tricks
/14-iterables.py
907
3.953125
4
def treat_as_iterable(iterable_var): print(iterable_var) first_pass = [] for v in iterable_var: first_pass.append(v) print("\tFirst Pass", first_pass) print("\tSecond pass", [v for v in iterable_var]) print() #lists_exist = [1, 2, 3] #treat_as_iterable(lists_exist) #range_generates = range(5) #treat_as_iterable(range_generates) #reverse_generates = reversed(range(10)) #treat_as_iterable(reverse_generates) #map_generates = map(lambda x: x**2, range(5)) #treat_as_iterable(map_generates) #zip_generates = zip(range(5), range(5, 10)) #treat_as_iterable(zip_generates) #comprehensions_exist = [x for x in zip(range(5), range(5, 10))] #treat_as_iterable(comprehensions_exist) #Example 2: #items = [ "one","two","three","four" ] #iterator = iter(items) #print(iterator) #print(next(iterator)) #print(next(iterator)) #print(next(iterator)) #print(next(iterator)) #print(next(iterator))
9726003d9e990bfcf4d657b0e557c351f8056267
theByteCoder/CorePython
/List_Comprehension.py
570
3.890625
4
word = "coding is great" # old method my_list = [] for letter in word: my_list.append(letter) print(my_list) # comprehension method my_list = [letter for letter in word] print(my_list) # comprehension method my_list = [num for num in range(1, 100)] print(my_list) # comprehension method - add conditions my_list = [num for num in range(1, 100) if num % 2 == 0] print(my_list) def add_suffix(each_letter): return f'{each_letter} suffix' chars = [] each_name = [add_suffix(each_letter) for each_letter in word] print(each_name)
6405b712be71faf4dbd9b6215aca6787a800a4d0
dodecatheon/UW-Python
/winter2012/week04/print_time.py
230
3.59375
4
#!/usr/bin/env python import time import datetime def date_time(): return datetime.datetime.now() if __name__ == "__main__": print "Here is the time: %s" % time.time() print "and again: %s" % datetime.datetime.now()
9dac90a81abe3269786a86052cfb246a79ed98e0
JZillifro/python-projects
/A5/assignment5.py
5,718
3.921875
4
"""Implement a class called TreeDict that supports operators the same way as a dict. TreeDict should be implemented using the binarysearchtree module I have provided (you can download it from canvas in the same folder as this file). You need to make sure you support the following operations with the same semantics as a normal Python dict: * td[key] * td[key] = value * key in td * td.get(key) * td.get(key, default) * td.update(iterable_of_pairs_or_dict_or_TreeDict) * len(td) * for key in td: pass * for key, value in td.items(): pass * A constructor: TreeDict(iterable_of_pairs_or_dict_or_TreeDict) Iteration should be in key order, this should be pretty easy to do just by traversing the tree using an in-order traversal. None of the iterator methods should make a copy of any of the data in the TreeDict. You should only implement in-order traversal once and use that implementation for both kinds of traversal. You should support a constructor which takes the same arguments as update and creates a TreeDict with just those values. There is an easy way to do this in just a couple of lines using your existing update method. For each operation, make sure it does the same thing as a dict and you handle errors by throwing the same type of exception as would be thrown by a dict. However unlike dict your implementation will not support None as a key and you should throw an appropriate exception if None is used as a key. Look at the available built in exceptions and pick the most appropriate one you find. Most of these methods will be very short (just a couple of lines of code), a couple will be a bit more complicated. However all the hard work should already be handled by the binarysearchtree module. It looks like a lot of operations, but it shouldn't actually take that long. Many of the operations are quite similar as well. Do not reimplement anything in the binarysearchtree module or copy code from it. You should not need to. For this assignment I expect you will have to use at least the following things you have learned: * Raising exceptions * Catching exceptions * Implementing magic methods * Generators using yield (and you will need to look up "yield from" in the Python documentation) * Type checks * Default values/optional arguments You will also need to read code which I think will help you learn to think in and use Python. To reiterate some of the things you should be aware of to avoid losing points: * None of the iterator methods should make a copy of any of the data in the TreeDict. * You should only implement in-order traversal once and it should be recursive (it's so much easier that way). * Do not reimplement anything in the binarysearchtree module or copy code from it. * There are easy ways to implement all the required operations. If your implementation of a method is long you may want to think if there is a simpler way. Links: * https://docs.python.org/3.5/library/stdtypes.html#dict * http://en.wikipedia.org/wiki/Binary_search_tree#Traversal * https://docs.python.org/3.5/reference/expressions.html#yieldexpr """ from binarysearchtree import Node class TreeDict: def __init__(self, args = dict()): self.root = Node() self.size = 0 self.update(args) def update(self, args): # self.root = Node() # self.size = 0 for e in args: if e is not None: if type(e) is tuple: a = e[0] b = e[1] else: a = e b = args[e] self.root.insert(a, b) self.size += 1 else: raise KeyError("None is not a valid key") # if type(args) is dict: # print("HEY") # for e in args: # self.root.insert(e, args[e]) # self.size += 1 # elif type(args) is TreeDict: # print("HO") # for e in args: # if e != None: # self.root.insert(e, args[e]) # elif iter(args): # temp = iter(args) # if (sum(1 for e in temp)%2) == 0: # temp = iter(args) # for a,b in temp: # self.root.insert(a, b) # else: # raise ValueError("Iter, but not of pairs") # else: # raise ValueError("bad type") def __getitem__(self, key): if type(self.root.key) != type(key): raise KeyError(".*"+key+".*") try: temp = self.root.lookup(key) return temp.value except ValueError: return None def __setitem__(self, key, value): try: temp = self.root.lookup(key) temp.value = value except ValueError: if self.__contains__(key): self.size -= 1 self.root.insert(key, value) self.size += 1 def __contains__(self, item): try: self.root.lookup(item) except ValueError: return False return True def get(self, key, default=None): if key in self: return self[key] return default def __len__(self): return self.size def __iter__(self): yield from in_order(self.root) def items(self): # result = () # for e in self: # result.__add__(tuple((e, self[e]))) # return result return [(e, self[e]) for e in self] def in_order(cur_node): if cur_node is not None: yield from in_order(cur_node.left) yield cur_node.key yield from in_order(cur_node.right)
f5f36950d2cf34fb2b5e4d03f64b40a3226102bc
nitinworkshere/algos
/algos/tree/BST/SymmetricTree.py
556
3.90625
4
class Node: def __init__(self, val): self.val = val self.right = None self.left = None def symetric_tree(root1, root2): if not root1 and not root2: return True if root1 and root2: return root1.val == root2.val and symetric_tree(root1.left, root2.right) and symetric_tree(root1.right, root2.left) root = Node(1) root.left = Node(2) root.right = Node(2) root.left.right = Node(4) root.left.left = Node(3) root.right.right = Node(3) root.right.left = Node(4) print(symetric_tree(root.left, root.right))
b075c9a8b26b25603439618a88bef44eaac6a43b
itwasntzak/game_helper
/dice.py
225
3.6875
4
import random def dice(): diceRoll = random.randrange(1, 7, 1) return(diceRoll) def diceRoll(): userChoice = int(input()) rollResult = [dice() for value in range(userChoice)] print(rollResult)
3120f9b6ffe60e4676082d187f95259b27fad0f8
junaidwahid/Implementation-of-UNET-Convolutional-Networks-for-Biomedical-Image-Segmentation
/helper_functions.py
1,318
3.703125
4
from torchvision.utils import make_grid import matplotlib.pyplot as plt def show_tensor_images(image_tensor, num_images=25, size=(1, 28, 28)): ''' Function for visualizing images: Given a tensor of images, number of images, and size per image, plots and prints the images in an uniform grid. ''' # image_shifted = (image_tensor + 1) / 2 image_shifted = image_tensor image_unflat = image_shifted.detach().cpu().view(-1, *size) image_grid = make_grid(image_unflat[:num_images], nrow=4) plt.imshow(image_grid.permute(1, 2, 0).squeeze()) plt.show() def crop(image, new_shape): """ Function for cropping an image tensor: Given an image tensor and the new shape, crops to the center pixels. Parameters: image: image tensor of shape (batch size, channels, height, width) new_shape: a torch.Size object with the shape you want x to have """ middle_height = image.shape[2] // 2 middle_width = image.shape[3] // 2 starting_height = middle_height - new_shape[2] // 2 final_height = starting_height + new_shape[2] starting_width = middle_width - new_shape[3] // 2 final_width = starting_width + new_shape[3] cropped_image = image[:, :, starting_height:final_height, starting_width:final_width] return cropped_image
95fad8bdfd32aa98bcdf6c7ee62b0e4fff7bbe0c
spunos/project_euler
/problem12.py
1,104
3.75
4
# The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: # 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... # Let us list the factors of the first seven triangle numbers: # 1: 1 # 3: 1, 3 # 6: 1, 2, 3, 6 # 10: 1,2,5,10 # 15: 1,3,5,15 # 21: 1,3,7,21 # 28: 1,2,4,7,14,28 # We can see that 28 is the first triangle number to have over five divisors. # What is the value of the first triangle number to have over five hundred divisors? import math, timeit start = timeit.default_timer() def divs(n): facs = 0 for i in range(1, math.ceil(math.sqrt(n))): if (n % i == 0): facs += 2 if (i * i == n): # adjust when i is a perfect square facs -= 1 return facs t = 1 for i in range(2,100000): t += i numdivs = divs(t) if numdivs > 500: print(t, ": ", numdivs) break end = timeit.default_timer() print("time: {0:.2f}".format(end - start))
2a3afe09c8e5a1386fb691ad6eabece6fbf901f5
Jcabanas268/PRG105
/chapter_practice/chapter7/ch_7_7.1_students_grades/student_grades_program.py
2,004
4.125
4
# Program to input student name & grade, print two dimensional list, write list to grade.txt def main(): # define main() function try: # try statement num_students = int(input('Enter the number of students: ')) # input for student quantity student_grades = [] # initialize list for student and grade for student in range(num_students): # for statement to append name & grade to student_grades list name = input('Enter student name: ') # input student name grade = input('Enter student\'s final letter grade: ') # input student grade student_grades.append([name, grade]) # append name and grade to student_grade list print(student_grades) # output student & grade two dimensional list file_doc = open('grades.txt', 'w') # open to write grades.txt for line in student_grades: # for statement to write student_grades list to grade.txt line_out = "'" + line[0] + "', '" + line[1] + "'\n" # value to format line for txt document file_doc.write(line_out) # write line_out value to grade.txt file_doc.close() # close grade.txt document except Exception as error: # exception to print error, resume main() print("Error: ", error) # output error message print() main() # resume main() main() # call main() function
6b91af2520471f23ef8afdbbfca301fd7126830a
marciocg/arvore_digital
/arvore_digital.py
2,293
3.5625
4
import time, string # Define uma classe com a estrutura de nó da árvore digital, usando dicionário class ArvNode: filho = {} fimpalavra = False def __init__(self): self.filho = {} self.fimpalavra = False self.contador = 0 raiz = ArvNode() # cria nó raiz vazio def insere(palavra): atual = raiz for i in range(len(palavra)): if palavra[i] not in atual.filho: # procura cada letra da palavra node = ArvNode() # cria nó vazio atual.filho[palavra[i]] = node # insere o nó no filho else: node = atual.filho[palavra[i]] # vincula o filho ao nó atual = node atual.fimpalavra = True atual.contador += 1 def busca(palavra,raiz): atual = raiz for i in range(len(palavra)): if palavra[i] not in atual.filho: return {palavra : "- palavra não encontrada"} else: node = atual.filho[palavra[i]] atual = node return {palavra + " encontrada" : atual.fimpalavra,"Qt. de ocorrências" : atual.contador} iniciots = time.process_time() print("Lendo a base...") base = open("dracula.txt","r+",encoding="utf8") texto = base.read() #print(texto) texto = texto.translate((str.maketrans("","", string.punctuation))) palavras = texto.split() print("Calculando o nro. de palavras") print("Nro. de palavras: " + str(len(palavras))) print(">>TEMPO 1: "+str(time.process_time() - iniciots)) criats = time.process_time() print("Criando a estrutura de dados...") for palavra in palavras: insere(palavra) print("Árvore digital criada com sucesso.") print(">>TEMPO 2: "+str(time.process_time() - criats)) inpbusca = 0 while inpbusca != '': inpbusca = input("Palavra para busca (ENTER p/ sair): ") buscats = time.process_time() if inpbusca != '': print('>>TEMPO 3 TS inicio da busca:', buscats) print(busca(inpbusca,raiz)) print(">>TEMPO 4: "+str(time.process_time() - buscats)) else: print("Programa encerrado.") """ insere("ABA") insere("OBA") insere("ABEL") insere("ABERTO") insere("ABRIR") insere("ABRIL") print(busca("ABERTO",raiz)) print(busca("ABRIR",raiz)) print(busca("ABE",raiz)) print(busca("RIR",raiz)) printArv(raiz) """
3cfafaaa65660adae97b6df7e0fc9959c3386a28
ChristineKarimi/Project-euler
/square.py
256
3.796875
4
#sum square difference def main(): # finding sum of the squares. a = sum([i**2 for i in range(101)]) # finding the square of the sum. b = sum(range(101))**2 # Results. print(b - a) if __name__ == '__main__': main()
20b4e82ed2829dddae66d36a6ce911f589c2f239
moontree/leetcode
/version1/483_Smallest_Good_Base.py
1,223
4.15625
4
""" For an integer n, we call k>=2 a good base of n, if all digits of n base k are 1. Now given a string representing n, you should return the smallest good base of n in string format. Example 1: Input: "13" Output: "3" Explanation: 13 base 3 is 111. Example 2: Input: "4681" Output: "8" Explanation: 4681 base 8 is 11111. Example 3: Input: "1000000000000000000" Output: "999999999999999999" Explanation: 1000000000000000000 base 999999999999999999 is 11. """ import math def smallest_good_base(n): """ :type n: str :rtype: str """ n = long(n) max_length = int(math.log(n, 2) + 1) for l in xrange(max_length, 1, -1): k = int(n ** (1.0 / (l - 1))) val = (k ** l - 1) / (k - 1) if val == n: return str(k) return str(n - 1) examples = [ { "n": "13", "res": "3", }, { "n": "4681", "res": "8", }, { "n": "1000000000000000000", "res": "999999999999999999", }, { "n": "2251799813685247", "res": "2", }, { "n": "727004545306745403", "res": "727004545306745402", } ] for example in examples: print "----" print smallest_good_base(example["n"])
c7812d94c29ca1363f279584bddb20a916491cb1
quintanaesc/CYPRobertoQE
/python/libro/problemasresueltos/capitulo2/problema2_1.py
169
3.75
4
N=int(input("Ingrese el numero de sonidos emitidos por el grillo ")) if N>0: T=(N/4)+40 print(f"La temperatura es de {T} grados fahrenheit") print("Fin del programa")
a8a12087a7ae2ecf6d6d5ca1cd0896364d8f4494
pankajdahilkar/RPi_tutorials
/LED interfacing/blinky2.py
605
4
4
import RPi.GPIO as GPIO import time LED = 40 # pin40 print(" ******** LED Blinking using Raspberry Pi 3 ********* ") print(" **** Designed by pankajdahilkar.github.io **** ") GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) # We are accessing GPIOs according to their physical location GPIO.setup(LED, GPIO.OUT) # We have set our LED pin mode to output GPIO.output(LED, GPIO.LOW) # When it will start then LED will be OFF while True: #Compiler will keep on executing this loop (infinite loop GPIO.output(LED, GPIO.HIGH) # led on time.sleep(2) #delay GPIO.output(LED, GPIO.LOW) # led off time.sleep(2)
43224c9b38afade96060132180545248e4d84d94
xarchived/patrix
/patrix/patrix.py
2,118
3.546875
4
def matrix(r, c): return [[0 for _ in range(c)] for _ in range(r)] def shape(mat): r = len(mat) c = len(mat[0]) return r, c def main_diagonal(mat): dia = [] col = 0 for row in mat: dia.append(row[col]) col += 1 return dia def anti_diagonal(mat): dia = [] col = len(mat[0]) - 1 for row in mat: dia.append(row[col]) col -= 1 return dia def windows(mat, r, c): max_row, max_col = shape(mat) i = 0 j = 0 while True: window = matrix(r, c) for row in range(r): for col in range(c): cur_row = row + i cur_col = col + j if cur_row >= max_row or cur_col >= max_col: continue window[row][col] = mat[cur_row][cur_col] yield window if j + c < max_col: j += 1 continue if i + r < max_row: j = 0 i += 1 continue break def clockwise_rotate(mat): r, c = shape(mat) tmp = matrix(r, c) for i in range(r): for j in reversed(range(c)): tmp[i][c - j - 1] = mat[j][i] return tmp def flip(mat): tmp = [] for row in mat: tmp.append(list(reversed(row))) return tmp def orientations(mat): tmp = mat yield tmp tmp = clockwise_rotate(tmp) yield tmp tmp = clockwise_rotate(tmp) yield tmp tmp = clockwise_rotate(tmp) yield tmp tmp = flip(mat) yield tmp tmp = clockwise_rotate(tmp) yield tmp tmp = clockwise_rotate(tmp) yield tmp tmp = clockwise_rotate(tmp) yield tmp def compare(mat1, mat2): r, c = shape(mat1) for i in range(r): for j in range(c): if mat1[i][j] != mat2[i][j]: return False return True def inclusion(mat1, mat2): r, c = shape(mat1) for i in range(r): for j in range(c): if mat1[i][j] == 0: continue if mat1[i][j] != mat2[i][j]: return False return True
0e6f54dbbf8e8e5f561f2495c5a76eaaed3dc0f8
Gokhulnath/Algorithm_lab
/Ex 6/ex6.py
1,012
3.78125
4
def trace_lcs(tab,a,b): i=len(a) j=len(b) lcs=[] while(i>0): if(tab[i][j]==tab[i-1][j]): i=i-1 elif(tab[i][j-1]==tab[i][j]): j=j-1 else: lcs.append(a[i-1]) i=i-1 j=j-1 print("Longest subsequence:",lcs) def longest_subsequence(a,b): tab=[] lcs=[] for i in range(len(a)+1): tab.append([0]*(len(b)+1)) for i in range(1,len(a)+1): for j in range(1,len(b)+1): if(a[i-1]==b[j-1]): tab[i][j]=tab[i-1][j-1]+1 else: tab[i][j]=max(tab[i-1][j],tab[i][j-1]) print("Length of the longest subsequence:",tab[len(a)][len(b)]) trace_lcs(tab,a,b) a=[1,8,2,9,3,4,0] b=[1,67,89,2,90,3,4] longest_subsequence(a,b) """ a=[3,9,80,67] b=[1,2,4,5] Length of the longest subsequence: 0 Longest subsequence: [] a=[1,8,2,9,3,4,0] b=[1,67,89,2,90,3,4] Length of the longest subsequence: 4 Longest subsequence: [4, 3, 2, 1] """
becbefa76ebf883d5d913c4a7c95ddd750867cbc
ernybugi/ACM_ICPC_DOT_NET_PS
/p1011/p1011.py
589
3.53125
4
for test in range(input()): startEnd = map(int, raw_input("").split(" ")) distance = startEnd[1] - startEnd[0] maxStep = 2 result = 2 if distance == 1: print 1 elif distance == 2: print 2 else: distance -= 2 # except first and last 1 step while distance > maxStep: if distance > 2 * maxStep: result += 2 distance -= 2 * maxStep else: result += 1 distance -= maxStep maxStep += 1 result += 1 print result
3164b94d26a9dcd9940e5cb259830ed9772fc603
Jansonboss/LeetCoding_Practice
/DepthFirstSearch/LintCode90_K_SumII.py
954
3.5625
4
# https://github.com/princeton-nlp/SimCSE def kSumII(A, k, target): A = sorted(A) subsets = [] dfs(A, 0, k, target, [], subsets) return subsets def dfs(A, index, k, target, subset, subsets): if len(subset) == k and target == 0: subsets.append(list(subset)) return if k == 0 or target <= 0: return for i in range(index, len(A)): subset.append(A[i]) dfs(A, i + 1, k , target - A[i], subset, subsets) subset.pop() # This is the same thing using k to track # def dfs(self, A, index, k, target, subset, subsets): # if k == 0 and target == 0: # subsets.append(list(subset)) # return # if k == 0 or target <= 0: # return # for i in range(index, len(A)): # subset.append(A[i]) # self.dfs(A, i + 1, k - 1, target - A[i], subset, subsets) # subset.pop() if __name__ == '__main__': print(kSumII([1,2,3,4], k=2, target=5))
8763b7f391a155078b065d7f227e10a73f67e357
jakegerard18/Python-Datastructures-and-Algs
/Stack.py
437
3.828125
4
from LinkedList import LinkedList class Stack: def __init__(self, startingNode): self.size = 0 self.stack = LinkedList(startingNode) def push(self, node): self.stack.addToHead(node) self.size += 1 def pop(self): self.size -= 1 return self.stack.removeHead() def peak(self): return self.stack.getHead() def printStack(self): self.stack.printList()
72f019884e5b5efc5f07e17d2b7556ade1cdc884
newbabyknow/python_practice
/longest_substring.py
454
3.78125
4
# 滑动窗口方法,计算字符串的最长不重复子字符串 def window(s): begin_index = 0 max_long = 0 for i in range(1, len(s)): if s[i] in s[begin_index:i]: max_long = max(max_long, len(s[begin_index:i])) begin_index += s[begin_index:i].index(s[i]) + 1 if max_long == 0: max_long = len(s) return max_long if __name__ == '__main__': a = window('abcaaaabcdfcdc') print(a)
620b07938c9c4e9d25586de86c4c53f8589b07ba
shikhashah2627/LeetCodePractice
/ArrayImpQuestions.py
3,401
3.65625
4
def countTriplets(nums): # nums.sort() n = len(nums) # count = 0 # for i in range(0, n-2): # j = i+1 # while j < n: # if nums[i] + nums[j] in nums: # count += 1 # j += 1 # return count max_val = 0 for i in range(n): max_val = max(max_val, nums[i]) freq = [0 for i in range(max_val + 1)] for i in range(n): freq[nums[i]] += 1 ans = 0 # stores the number of ways for i in range(1, max_val + 1): for j in range(i + 1, max_val - i + 1): ans += freq[i] * freq[j] * freq[i + j] return ans # print(countTriplets([1,3,4,5])) import heapq def mergeTwoArrays(n1,n2): heapq.heapify(n2) for i in n1: heapq.heappush(n2,i) print(n2) # mergeTwoArrays([1,4,6,7,8,9],[2,3,4,5]) # Equilibrium index of an array def Equilibrium(nums): n,i,j = len(nums),0,len(nums)-1 sum1 = sum2 = ans = 0 while i < n and j > 0: if (sum1+nums[i] == sum2 + nums[j]): ans = i+j-1 break sum1+=nums[i] sum2+=nums[j] i+=1 j-=1 return ans # print(Equilibrium([-7, 1, 2,3,-8,-9])) # Python program to find # maximum amount of water that can # be trapped within given set of bars. # Space Complexity : O(1) def findWater(arr,n): # initialize output result = 0 # maximum element on left and right left_max = 0 right_max = 0 # indices to traverse the array lo = 0 hi = n-1 while(lo <= hi): if(arr[lo] < arr[hi]): if(arr[lo] > left_max): # update max in left left_max = arr[lo] else: # water on curr element = max - curr result += left_max - arr[lo] lo+=1 else: if(arr[hi] > right_max): # update right maximum right_max = arr[hi] else: result += right_max - arr[hi] hi-=1 return result # Driver program arr = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1] n = len(arr) # print("Maximum water that can be accumulated is ", # findWater(arr, n)) def sellBuyStock(stocks): j = 0 c = 0 for i in range(1,n): if li[i-1]>li[i] : if i-j>1: print("(",end="") print(j ,i-1,end="") print(")",end=" ") c = 1 j = i else: j+=1 elif (i==(n-1) and li[i]>li[j] and i>j): print("(",end="") print(j, i,end="") print(")",end="") c = 1 if c == 0 : print("No Profit") else: print() t-=1 def largestNumber(nums): """ :type nums: List[int] :rtype: str """ # def mycmp(a, b): # x = a + b # y = b + a # return (x > y) - (x < y) # return str(int("".join(sorted([str(i) for i in nums], reverse=True, key=mycmp)))) nums = sorted([str(n) for n in nums],key = lambda x:x*(32),reverse=True) return "0" if set(nums) == set("0") else "".join(nums) print(largestNumber([3,35,50,55,9]))
da992604e15bf93e45d5ec9f3546b6bf337d705f
herllyc/Leetcode_Daily
/电话号码组合/index.py
332
3.78125
4
def index(digits): tel_dic = {2:'abc',3:'def',4:'ghi',5:'jkl',6:'mno',7:'pqrs',8:'tuv',9:'wxyz'} print(tel_dic[2]) if digits=='': return[''] ls = [''] for i in digits: ls = [x+y for x in ls for y in tel_dic[int(i)]] return ls if __name__ == '__main__': str = '23' print(index(str))
d9ff2b47d4918e770318b705b239c4f7cb14566c
hyun98/python
/알고리즘/수학/소수1.py
477
3.984375
4
def prime_checker(n): if n==1: return 0 else: d=2 while(n!=d): if n%d != 0: d+=1 else: return 0 if n==d: return 1 def the_number_of_prime(arr): count=0 for i in arr: count+=prime_checker(i) print(count) if __name__=="__main__": import sys n = int(input()) arr = list(map(int, sys.stdin.readline().split())) the_number_of_prime(arr)
adee8a69e12f792fc87935562548473902b26750
Zander-M/ICS-Exercise
/state_machine.py
738
3.78125
4
# ope = [ '+', '-', '*', "/"] # while input != "q": # a = input() # if not a.isdigit(): # if a == 'q': # break # elif a == 'c': # a = input() # else: # a = input() # b = input() # if not b.isdigit(): # if b == 'q': # break # elif b == 'c': # b = input() # else: # b = input() # c = input() # if c not in ope: # if c == 'q' # break # elif b == 'c': # b = input() # else: # b = input() # def first_num(a): while not a.isdigit(): a = input() if a == 'q': return False return a def second_num(b): while not b.isdigit(): b = input() if b == 'q': return False elif b == 'c': return True return b def ope(c): while not c.isdigit(): pass return
9d72e153c2f20e8ac8ce55946b4e9d72907bfd6b
jianantian/misc
/_exercises/the_pragmatic_programmers/python/6.py
663
3.765625
4
import arrow def get_input(message=""): while True: raw = input(message) try: res = int(raw) except ValueError: print("Please check your input.") else: break return res age = get_input("What is your current age? ") retire_age = get_input("At what age would you like to retire? ") duration = retire_age - age now = arrow.now().year retire_year = now + duration if duration >= 0: print("You have {} years left until you can retire.".format(duration)) else: print("You retired {} years ago.".format(abs(duration))) print("It's {}, so you retire in {}.".format(now, retire_year))
e57d0a0b857bccfcfa8c209accb3f20e9ff3e03d
splaiser/newbie
/Class/user/user.py
793
3.53125
4
class User(): def __init__(self,first_name,last_name,age,location): self.first = first_name self.last = last_name self.age = age self.location = location self.login_attempts = 0 def describe_user(self): print(f"First name : {self.first.title()}") print(f"Last name : {self.last.title()}") print(f"Age : {self.age}") print(f"Location : {self.location.title()}") def greet_user(self): print(f"Welcome and Hello Dear, {self.first.title()} {self.last.title()}") def increment_login_attempts(self): self.login_attempts += 1 def reset_login_attempts(self): self.login_attempts = 0 def show_login_attempts(self): print (f"Login attempts : {self.login_attempts}")
812afb47347144d757f17e3f5e94104067b65f94
sammorrell/space-exe-python
/code/pythonic/enumerate.py
342
4.1875
4
# Zip combines the two or more arrys into a single # for loop, leting you easily iterate over the values list1 = ['a1', 'a2', 'a3', 'a4', 'a5'] list2 = ['b1', 'b2', 'b3', 'b4', 'b5'] for i, l1 in enumerate(list1): l2 = list2[i] print('{}, {}'.format(l1, l2)) # Will print: # a1, b1 # a2, b2 # a3, b3 # a4, b4 # a5, b5
d3d674d52977eb8577ab092266565fd9f1cec22f
arch123A/luoye
/Tony_study/whiel99乘法表.py
197
3.5
4
def 打印99表(): j=1 while j<=9: i=1 while i<=j: print ( "%d×%d=%d" % (i, j, i * j), end="\t" ) i+=1 j=j+1 print() 打印99表()
607310fa9e365d31019f82dd98750f7f66c54440
Redoxfox/python_algoritmos
/funcion.py
800
4.1875
4
'''Programa para calcular valores de funcion f(x) = x²-13x+30 en intervalo [3,10]''' '''Esta funcion puede ser representada como y = x²-13x+30 ''' #Definicion de variables yi = 0 #Resultado de la funcion en cada punto del intervalo (iniciacion a cero) xi = 3 #Valor de cada punto del intervalo (iniciacion en 3) '''Definición de ciclo condicionado (while) para iterar cada punto de la funcion y al mismo tiempo cumplir con la condicion del intervalo [3,10]''' while(xi >= 2 and xi <= 10): #Implementacion de funcion en lenguaje Python yi = xi*xi - 13*xi + 30 #Impresion de valor de para cada punto del intervalo print('El valor de la funcion f(', xi ,') =(', xi,')²','-13(',xi,') + 30=', yi) #Aumento de valor de xi en 1 para evaluar el siguiente valor xi += 1
0d7ecbaa57a82fe2cbb476f280271c1a8f10cbf9
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/kmsnyde/lesson04/mailroom2.py
2,397
3.578125
4
# -*- coding: utf-8 -*- """ Created on Wed Apr 11 17:38:02 2018 @author: Karl M. Snyder """ #[[fill]align][sign][#][0][minimumwidth][.precision][type] from collections import defaultdict donor_dict = defaultdict(list, {'Karl Stick': [10, 20, 30], 'Kate Stam': [5, 30], 'Christine Goose': [21], 'Matt Hen': [40, 5, 11], 'Zumi Was': [32]}) def menu(): menu_dict = {'1:': 'Send a Thank You', '2:': 'Create a Report', '3:': 'Send letters to everyone', '4:': 'Quit'} for k,v in menu_dict.items(): print(k, v) def thank_you_greeting(): print('{} {}'.format('\nType a user\'s name or "list" to show names.', print())) def donations(): return float(input('Donor Amount: ')) def send_thanks(): thank_you_greeting() # print() input1 = input('-> ') print(' ') if input1 == 'list': for name in list(donor_dict): print(name) else: input2 = donations() donor_dict[input1.title()].append(input2) def create_report(): sum_data = [(k, sum(v), len(v), sum(v)/len(v)) for k,v in donor_dict.items()] sum_data = sorted(sum_data, key=lambda x: x[1], reverse=True) print(sum_data) print('{:<20} {:>20} {:>20} {:>20}'.format('Donor Name', '| Total Given', '| Num Gifts', '| Average Gift')) print('{}'.format('-' * 83)) for line in sum_data: print('{:<20} {:>20.02f} {:>20} {:>20.02f}'.format(*line)) letters = 'Dear {},\n\n\tThank you for your total contributions in the amount of ${}.\n\n\tYou are making a difference in the lives of others.\n\n\t\tSincerely,\n\t\t"Working for America"' def send_letters_all(): for name, value in donor_dict.items(): f = open('Thank_You - {}.txt'.format(name.lower().replace(' ', '_')), 'w') f.write(letters.format(name, sum(value))) print('\nYour letters have been printed to the current directory!') if __name__ == "__main__": user_input = None while user_input != 4: print('\n', 'Please select a number from the following choices:\n') menu() user_input = int(input('Selection: ')) if user_input == 1: send_thanks() elif user_input == 2: create_report() elif user_input == 3: send_letters_all()
e024d268bfe95db8a4a9f339c870f84a4e7663c5
dvdgitman/DevOPS-Project
/SiteChecker.py
533
3.9375
4
import requests def get_url_status(urls): # checks status for each url in list urls # for url in urls: try: r = requests.get(urls) print(urls + "\tStatus: " + str(r.status_code)) # Prints the url and status of the site(Up/Down) except Exception as e: print(urls + " - The url is probably down or isn't written correctly.Make sure to add http or https. ") def main(): url = input("Enter a full URL 'https://yoursite.com': ") get_url_status(url) if __name__ == "__main__": main()
70a17a5e43e6c56302c95e65482557cda4a4678a
geethaninge/PythonCoding
/PythonPgm/SearchUsingDivideAndConqure.py
622
4.15625
4
''' Divide and conqre approach has log n time complexity for binary search string should be in sorted order ''' def binarySearch(list1,key): if len(list1)==0 : return False mid = (len(list1))//2 if key == list1[mid] : return True elif key < list1[mid]: return binarySearch(list1[:mid-1],key) else: return binarySearch(list1[mid+1:],key) list1= [int(x) for x in input("enter elements :").split()] key =int( input("enter search element :")) position =binarySearch(list1.sort(),key) if position : print("the search term is found ") else: print("the search term is not found ")
0d6ec1badb5b143d658e8c150062063c349d5486
srujanprophet/PythonPractice
/Class XII CBSE/1.1.32.py
184
4
4
l = [] n = int(raw_input("Enter n :")) for i in range(n): x = int(raw_input("Enter number : ")) l.append(x) print "Set of Numbers :",l print "Reversed set of Numbers",l[::-1]
a32799b09aa55d659d2af9bb7edbe35bd19e5460
sujal100/sujal100-Probability_and_Random_variable
/exercise_2/code/exercise_2.py
774
3.703125
4
# problem ''' A box contains 4 white balls and 3 red balls. In succession, two balls are randomly selected and removed from the box. Given that the first removed ball is white, the probability that the second removed ball is red is _____ (A) 1/3 (B) 3/7 (C) 1/2 (D) 4/7''' # solution import random def pickBalls(nLoops=1000): Balls = [0]*3+[1]*4 nHits = 0 for _ in range(nLoops): b = random.sample(Balls, 2) while b[1] == 0: # While 2nd ball is red b = random.sample(Balls, 2) if b[0]: # If first ball was white nHits += 1 return float(nHits) / nLoops print('the probability that the second removed ball is red is ',format(pickBalls(1000000))) print('Hence, answer is (C)')
a678eaf1e3f07032d2eaf15e5810d2868d8c0256
jsearfoo/beginner-project-solutions
/Pythagorean Triples Checker.py
1,086
4.25
4
''' Pythagorean Triples A "Pythagorean Triple" is a set of positive integers, a, b and c that fits the rule: a*a + b*b = c*c Here is a list of the first few Pythagorean Triples (3,4,5) (5,12,13) Example: scale 3,4,5 by 2 gives 6,8,10 which should be Pythagorean Triples ''' def PyTriples(a,b,c): asquare=a*a bsquare=b*b csquare=c*c if asquare+bsquare==csquare: print("Yes its a Pythagorean Triple\n") print("{} + {} = {}".format(asquare,bsquare,csquare) ) else: print("Nopes! Its not a Pythagorean Triple") print("{} + {} is not = {}".format(asquare, bsquare, csquare)) def main(): print("Check if a triangle is Pythagorean triples") a = int(input("input first integer a")) b = int(input("input second integer b")) c = int(input("input third integer c")) PyTriples(a, b, c) again=input("Wanna Try again? y/n") if again=='y': main() else: print("Goodbye! Thanks for using this app") if __name__=="__main__": main()
0c288b3da6dab5a1d9b670253e9093a20cc12099
jonatanjmissora/PRACTICE_PYTHON
/PRACTICE_21_AL_25.py
4,008
3.765625
4
"""# escribir un archivo open_file = open('test.txt', 'w') open_file.write('testprimer renglon\n') open_file.write('segundo renglon\n') open_file.write('tercer renglon\n') open_file.close() #otra forma de escribir, mejor syntaxis with open('names.txt', 'w') as open_file: open_file.write('cuarto renglon\n') #leer un archivo y contar los nombres with open('names.txt', 'r') as open_file: all_text = open_file.read() all_text = all_text.split("\n") print(all_text) Darth = 0 Lea = 0 Luke = 0 for s in all_text: if s == "Darth": Darth += 1 elif s == "Lea": Lea += 1 else: Luke += 1 print(Darth, Lea, Luke) # leyendo por renglon Darth = 0 Lea = 0 Luke = 0 with open('names.txt', 'r') as open_file: line = open_file.readline() #chars = list(line) imprime ["D","a","r","t","h","\n"] #line = line.strip() #cada obj de la lista es un renglon while line: line = line.strip() if line == "Darth": Darth += 1 elif line == "Lea": Lea += 1 else: Luke += 1 line = open_file.readline() print(Darth, Lea, Luke) counter_dict = {} with open('names.txt') as f: line = f.readline() while line: line = line.strip() if line in counter_dict: counter_dict[line] += 1 else: counter_dict[line] = 1 line = f.readline() print("directorio: ", counter_dict) #{"Luke":15, "Darth":31, "Lea":54} print(counter_dict["Lea"]) #54 ,valor de Lea for i in counter_dict.items(): #("Luke",15) ("Darth", 31) ("Lea", 54) print(i) # se pueden operar pero como pares juntos for i in counter_dict: # luke Darth Lea "no se pueden operar" print(i) #pero si puedo usar sus nombre para operar sus valores total = 0 for i in counter_dict: total += counter_dict[i] print(total) total = 0 for x, y in counter_dict.items(): # se pueden operar por separado print(x, y) if x == "Lea": print("esta Lea!!") total += int(y) print(total) print("solo keys:", counter_dict.keys(), "no se puede acceder") print("solo values:", counter_dict.values(), "tampoco") print("los pares:", counter_dict.items(), "sirve para iterar") # interseccion de numeros en 2 archivos de texto with open('num1.txt', 'r') as open_file: text1 = open_file.read() text1 = text1.split() print(text1) with open('num2.txt', 'r') as open_file: text2 = open_file.read() text2 = text2.split() print(text2) L = [] for i in text1: if i in text2: L.append(i) print(L) #con funcion pasar sting a integer def arch_a_ints(filename): list_to_return = [] with open(filename) as f: line = f.readline() while line: list_to_return.append(int(line)) line = f.readline() return list_to_return # otra forma de funcion def arch_list_int(filename): with open(filename) as f: f = list(map(x, f.read().split())) return f primes = arch_a_ints('num1.txt') happies = arch_a_ints('num2.txt') overlap = [x for x in primes if x in happies] print(overlap) # que la compu adivine tu numero con busq binaria def guess_num(): tries = 0 start = 0 end = 101 while True: guess = int((start+end)/2) tries += 1 print("pc guess:", guess, " tries:", tries) if guess == N: return tries elif guess > N: print("too high") end = guess else: start = guess print("too low") N = 54 print("yo got it in", guess_num(), "tries")""" # idem pero sin busqueda binaria import random def guess_number(): start = 0 end = 101 tries = 0 while True: guess = random.randint(start, end) print("is", guess, "your number?") tries += 1 answer = input("answer (l=low) (h=high) (y=yes):") if answer == "y": return tries elif answer == "h": end = guess else: start = guess print("you got it in", guess_number(), "try/es")
4be3a56e8cac0e8e1aafea827a6cbf3769be6b05
sankar-vs/Python-and-MySQL
/Numpy/8_Convert_list_tuple_to_array.py
399
4.4375
4
''' @Author: Sankar @Date: 2021-04-14 08:19:25 @Last Modified by: Sankar @Last Modified time: 2021-04-14 08:35:09 @Title : Numpy_Python-8 ''' ''' Write a Python program to convert a list and tuple into arrays. List to array: [1 2 3 4 5 6 7 8] Tuple to array: [[8 4 6] [1 2 3]] ''' import numpy as np list = [1,2,3,4,5,6,7,8] tuple = ((8,4,6),(1,2,3)) print(np.asarray(list)) print(np.asarray(tuple))
cef88cde497da1e8bade740a872f630a72500589
Pedro0901/python3-curso-em-video
/Python 3 - Mundo 2/Scripts Python - Mundo 2/Aula13.py
1,011
4.0625
4
for c in range(0, 6): #Primeiro numero dentro do parentese é onde a contagem começa, o 2º é onde PARA. (Para e nao mostra o numero) print(c) print('-------------DIVISÓRIA-------------') for c in range(6, 0, -1): #O -1 informa que você quer contar do maior para o menor. (De traz pra frente) print(c) print('\nFIM') print('-------------DIVISÓRIA-------------') for c in range(0, 7, 2): #Conta de 0 a 7 pulando de 2 em 2. O 2 informa que você quer pular de 2 em 2. print(c) print('-------------DIVISÓRIA-------------') n = int(input('\nDigite um número: ')) for c in range(0, n+1): print(c) print('-------------DIVISÓRIA-------------') i = int(input('\nInicio: ')) f = int(input('\nFim: ')) p = int(input('\nPasso: ')) for c in range(i, f+1, p): print(c) print('-------------DIVISÓRIA-------------') s = 0 for c in range(0, 4): n = int(input('\nDigite um valor: ')) s += n #Mesma coisa que s = s + n (S recebe S mais N) print('\nO somatório de todos os valores foi: {}'.format(s))
58d8564f83024fdb740fe9a4510b4671b0a97738
ayoubabounakif/HackerRank-Python
/03. Strings/006. String Validators.py
802
4.09375
4
# Problem: https://www.hackerrank.com/challenges/string-validators/problem if __name__ == '__main__': s = input() result = ["False", "False", "False", "False", "False"] for i in s: if i.isalnum(): result[0] = "True" if i.isalpha(): result[1] = "True" if i.isdigit(): result[2] = "True" if i.islower(): result[3] = "True" if i.isupper(): result[4] = "True" print(*result, sep="\n") if __name__ == '__main__': s = input() print(any([char.isalnum() for char in s])) print(any([char.isalpha() for char in s])) print(any([char.isdigit() for char in s])) print(any([char.islower() for char in s])) print(any([char.isupper() for char in s]))
d17839f31e383648f27b00beacb09fb379efdb6f
esau91/Python
/Problems/leetcode/avg_word_len.py
565
4.125
4
#Author: esau91 #Date: 03/04/2021 #Source: leetcode #Description: return the average word len from string def solution(test): words_len = [] test = test.split() if len(test) == 0: print(0) return 0 for word in test: words_len.append(len(word)) print(sum(words_len)/len(words_len)) def main(): solution('hola como estas preguntame algo') solution('uno dos tres cuatro') solution('palabras largas programando corriendo') solution('') solution('holamundo') if __name__ == '__main__': main()
cb50e54c2018b4b9b22f33240cf6f8b8827e9086
naveenramees/py-program
/52.py
90
3.859375
4
y = int(input("Enter the num:")) if y%2 == 0: print "\nEven" if y%2 != 0: print "\nOdd"
5640b6b0d3666f1579b231651d6634b554ae1f46
EachenKuang/LeetCode
/code/674#Longest Continuous Increasing Subsequence.py
517
3.546875
4
# https://leetcode.com/problems/longest-continuous-increasing-subsequence/description/ class Solution: def findLengthOfLCIS(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) < 1: return 0 temp = 1 sum = 1 for i in range(1, len(nums)): if nums[i] > nums[i-1]: sum += 1 if sum > temp: temp = sum else: sum = 1 return temp
afcba87fdca54e36cb4756286e14bf4af7ac6f1b
KanthetiManojSanjay/PythonProjects
/python_tips/operator_overloading_examples.py
1,704
3.828125
4
from functools import total_ordering @total_ordering # to reduce redudancy class Money: def __init__(self, currency, amount): self.currency = currency self.amount = amount def __add__(self, other): return Money(self.currency, self.amount + other.amount) def __sub__(self, other): return Money(self.currency, self.amount - other.amount) def __repr__(self): return repr((self.currency, self.amount)) def __eq__(self, other): return ((self.currency, self.amount) == (other.currency, other.amount)) # def __ne__(self, other): # return ((self.currency, self.amount) != ( # other.currency, other.amount)) # not needed as we already implemented equals method above def __gt__(self, other): return ((self.currency, self.amount) > (other.currency, other.amount)) # If we use total_ordering then eq & any one of other is enough. remaining methods(lt,gt ..etc) need not be explicitly overloaded """ def __lt__(self, other): return ((self.currency, self.amount) < (other.currency, other.amount)) def __ge__(self, other): return ((self.currency, self.amount) >= (other.currency, other.amount)) def __le__(self, other): return ((self.currency, self.amount) <= (other.currency, other.amount)) """ amount1 = Money('EUR', 10) amount2 = Money('EUR', 20) amount3 = Money('EUR', 10) print(amount1 + amount2) print(amount2 - amount1) print(amount1 == amount2) print(amount1 != amount2) print(amount1 == amount3) print(amount1 > amount2) print(amount1 > amount3) print(amount2 > amount3) print(amount1 >= amount2) print(amount1 >= amount3) print(amount2 >= amount3)
371f3ba9f41608e0a4cc4b1ae976defc94cc9f68
jeff-lund/CS199
/Python/Lists/binary.py
566
4.125
4
# Converting a decimal number to a binary number with a divide by 2 algorithm n = int(input("Enter a positve number: ")) if n < 0: print("Invalid number") elif n == 0: print(0) else: binary = [] count = 0 while n > 0: q = n // 2 # quotient is to be carried on to the next iteration r = n % 2 # remainder is the extracted bit binary.append(r) n = q count += 1 # print in reverse to turn into binary number while count > 0: count -= 1 print(binary[count], end='') print()
76644f45c6147d982e67856c627be3c93efe685e
MohammedGhafri/data-structures-and-algorithms-python
/data_structures_and_algorithms/challenges/quick_sort/quick_sort.py
745
3.953125
4
def QuickSort(arr,left,right): if left < right: pi = Partition(arr,left,right) QuickSort(arr, left, pi-1) QuickSort(arr, pi+1, right) return arr def Partition(arr,left,right): i = ( left-1 ) pivot = arr[right] for j in range(left , right): if arr[j] < pivot: i = i+1 arr[i],arr[j] = arr[j],arr[i] swaping=swaper(arr,i,j,right) return swaping def swaper(arr,i,j,right): arr[i+1],arr[right] = arr[right],arr[i+1] return ( i+1 ) if __name__ == "__main__": a=[8,4,23,42,16,15] n = len(a) print(a,'\n') QuickSort(a,0,n-1) print(a)