blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
4a8dc097c4a732ae274d4cd50fbfc6751d30f4b0
vishhy/Python
/lnr_regression.py
1,112
3.546875
4
import matplotlib.pyplot as plt import numpy as np from sklearn import datasets, linear_model from sklearn.metrics import mean_squared_error # it is linear model diabetes= datasets.load_diabetes() # ['data', 'target', 'frame', 'DESCR', 'feature_names', 'data_filename', 'target_filename']) # print(diabetes.DESCR) diabetes_X = diabetes.data # [:, np.newaxis, 2] diabetes_X_train = diabetes_X[:-30] diabetes_X_test = diabetes_X[-30:] diabetes_Y_train = diabetes.target[:-30] diabetes_Y_test = diabetes.target[-30:] # xaxis feature yaxis label model = linear_model.LinearRegression() model.fit(diabetes_X_train, diabetes_Y_train) diabetes_Y_predicted = model.predict(diabetes_X_test) print('Mean squared error is: ', mean_squared_error(diabetes_Y_test, diabetes_Y_predicted)) print("Weights: ", model.coef_) print("Intercept: ", model.intercept_) # plt.scatter(diabetes_X_test, diabetes_Y_test) # plt.plot(diabetes_X_test, diabetes_Y_predicted) # plt.show() # Mean squared error is: 3035.0601152912695 # Weights: [941.43097333] # Intercept: 153.39713623331698
8454ff017dca54ea14ea3180e092b9258a62c88b
EmirVelazquez/thisIsTheWay
/numbers.py
358
3.6875
4
# This grabs a module to access more math functions from python from math import * # Common examples of working with number datatypes and common functions first_num = -5 print(str(first_num) + " comes after 4.") print(abs(first_num)) print(pow(3, 2)) print(max(5, 2)) print(min(10, 1)) print(round(3.646)) print(floor(3.5)) print(ceil(3.7)) print(sqrt(36))
dbdad667b9583aa440e780bcd20897d5ac7e8baa
GitContainer/Pythonista-1
/算法2/bubblesort.py
269
3.796875
4
l = [5,6,0,-1,3,-6,12,1] def bubblesort(l): for i in range(len(l)-1): for j in range(len(l)-i-1): if l[j]>l[j+1]: l[j], l[j+1] = l[j+1], l[j] return l print(bubblesort(l)) # 没什么坑,注意 j 要减 去 i, i要减去 1
53846c764935a95d32cdc39d51fb6414649a10d4
awarbler/awarbler.github.io
/cse210/week04/soloWork/hiloTest.py
1,867
4.28125
4
import random """HILO BASIC 1 1.2 """ # get computer to pick random number 1-100 and have user guess number # also get the count of how many times user guessed # create an array of guesses and then append the guesses by the player number # then display well and print the % of guess using the length of the guesses # then print out here are your guesses and print the list # initialize a list guesses and make it empty to hold player_num(or user)guesses guesses = [] # initialize cpu_num to equal random. randint to guess # from 1 - 100 cpu_num = random.randint(1,100) # initialize player_num to accept input of a integer between 1-100 player_num = int(input("enter a number between 1-100: ")) #append guesses to the guesses list do it everytime the player guesses so add it to the while loop guesses.append(player_num) # check if player number is correct # count the player_number guesses #start loop while player_num != cpu_num: # while player_num is not equal to cpu_num if player_num > cpu_num: # if the number is too high print("too high") # print too high else: # else print("too low") # print too low player_num = int(input("Enter a number between1 -100: ")) # input the next guess ask player to enter a new number guesses.append(player_num) # add to list of guesses else: # else print("well done") # print well done print("it took you %i guesses." % len(guesses)) # print it took you percent of guesses calculate length of guesses print("here are your guesses: ") # print out all guesses print(guesses)
c9019603a65fb9b95d2bedab61c152c578e7857c
lddsjy/leetcode
/python/fibonacci.py
748
3.640625
4
# -*- coding:utf-8 -*- class Solution: def jumpFloor(self, n): if n == 1: return 1 if n < 1: return None id = 1 a = 1 b = 1 while id < n: id +=1 c = a+b a = b b = c return c s = Solution() print(s.jumpFloor(4)) # class Solution: # def Fibonacci(self, n): # if n == 0: # return 0 # if n == 1: # return 1 # if n < 0: # return None # id = 1 # a = 0 # b = 1 # while id < n: # id +=1 # c = a+b # a = b # b = c # return c # # s = Solution() # print(s.Fibonacci(-1)) #
a934db1c245a19dd6a54e009849c39d99e94bd21
andrericca/Testevape
/Cópia de hello.py
528
3.65625
4
#!/usr/bin/python a = input("Quantidade total de VG?: ") b = input("Quantidade total de PG?: ") c = input("Tamanho de cada frasco?: ") d = input("Porcentagem da essencia?: ") e = input("Porcentagem de vg?: ") f = input("Porcentagem de pg?: ") vgml = c * e / 100 eml = c * d / 100 pgml = c * f / 100 - eml print 'VG=', vgml, 'ml ' print 'PG=', pgml, 'ml' print 'Essencia=', eml, 'ml' assert isinstance(b, object) if a >= b: frasco = a / vgml else: frasco = b / pgml print 'Numero de frascos que voce fara=', frasco,
652599653a79a0f252a9fea6ec4b7786753c5029
murayama333/python2020
/02_oop/tr/src/27_exception/ex_tr7.py
419
3.640625
4
class MyRequiredError(Exception): pass class MyLengthError(Exception): pass def validate(value, length): if len(value) == 0: raise MyRequiredError() if len(value) > length: raise MyLengthError() try: value = input("Input: ") validate(value, 5) print(value) except MyRequiredError as e: print("MyRequiredError") except MyLengthError as e: print("MyLengthError")
19be3dbb7b1aef57fd4bf07ffae4ba409faa9927
gerardogtn/SistemasInteligentes
/01-MarsExplorer/sample.py
762
3.515625
4
from drawable import Drawable from positionable import Positionable import random class Sample(Drawable, Positionable): SIZE = 10 COLOR = 'green' def __init__(self, x, y): super().__init__(x, y, self.SIZE) def draw(self, canvas): canvas.create_oval(self.x - self.SIZE / 2, self.y - self.SIZE / 2, self.x + self.SIZE / 2, self.y + self.SIZE / 2, fill= self.COLOR) @staticmethod def random(num, width, height, world): samples = [] while len(samples) < num: x = random.randint(0, width) y = random.randint(0, height) sample = Sample(x, y) if (world.fits(sample)): samples.append(sample) return samples
098076350a6b0e8b9538642e33e8924b8f87a60b
AnujVijjan/Youtube
/tutorial54.py
474
3.828125
4
class Father: surname = "xyz" def __init__(self): self.father_name = "xyz" class Mother: def __init__(self): self.mother_name = "abc" class Child(Father, Mother): def __init__(self): self.child_name = "pqr" def diplay(self): # print(self.father_name) # print(self.mother_name) # print(self.child_name) print(self.surname) father = Father() mother = Mother() child = Child() child.diplay()
23ab7f0444c31f072bf2fd3bf377dfa6dd4406ea
VityasZV/Python-tasks
/5 semestr/homework-7/DungeonMap.py
1,510
3.78125
4
from collections import defaultdict def tunnels_from_input(): tunnels = defaultdict(set) a_to_b = input().split(" ") while len(a_to_b) != 1: tunnels[a_to_b[0]].add(a_to_b[1]) tunnels[a_to_b[1]].add(a_to_b[0]) a_to_b = input().split(" ") beg = a_to_b[0] en = input() return [beg, en, tunnels] def check(dungeons, en): res = True if en in dungeons else False return res def way_check(tunnels, begin, ending): # dungeons is just begin all_dungeons = set(tunnels.keys()) new_dungeons = tunnels[begin] old_dungeons = {begin} if check(new_dungeons.union(old_dungeons), ending): return True else: un = old_dungeons.union(new_dungeons) while un != old_dungeons: old_dungeons = un save = new_dungeons l = list() for el in save: app = list(i for i in tunnels[el]) l = l + app new_dungeons = set(l).difference(old_dungeons) if check(new_dungeons, ending): return True un = old_dungeons.union(new_dungeons) return False def is_way_exist(beg_end_tunnels): begin = beg_end_tunnels[0] ending = beg_end_tunnels[1] tunnels = beg_end_tunnels[2] if tunnels[begin] == set() or tunnels[ending] == set(): return "NO" res = way_check(tunnels, begin, ending) answer = "YES" if res else "NO" return answer print(is_way_exist(tunnels_from_input()))
5d0b4675d65b7ca1817031f6261e48291b467e74
22zagiva/Module-a
/moda_challenge.py
358
4.03125
4
for i in range(10): print("Hello, Python!") #----------------------------------------- for x in range(10): print(x) #----------------------------------------- for b in range(1, 11): print(b) #----------------------------------------- for c in range(2, 21, 2): print(c) #----------------------------------------- for w in range(1, 11): print(w**2)
7bee0b702d1cfe4e474ea16865cda8b9af546135
aysegulkrms/SummerPythonCourse
/Week1/01_Hello_World.py
427
4.375
4
# Printing First Hello World with double quotes print("Hello World") # I am writing a single line comment # Printing Hello World with single quotes print('Hello World') # Print out your name with the Print function print("My name is Cemil Koc") print("Hi, Python") """ I can add multiple line comments by using triple quotes I can write as many lines I want """ ''' I can add multiple line comments by using triple quotes '''
5e8cfdae143f882adc017fbf529627cedc301533
Kawser-nerd/CLCDSA
/Source Codes/AtCoder/arc002/B/4414718.py
267
3.578125
4
from datetime import date,timedelta y,m,d=map(int,input().split("/"))#??????? dt=date(year=y,month=m,day=d)#?????date????? while dt.year/dt.month%dt.day:#?????????????? dt+=timedelta(days=1)#???????????????????????? #print(dt) print(dt.strftime("%Y/%m/%d"))
f07cd326f1a6cc86d96716b09b1e3fdc5f4ee1a9
aayushrai/Project_Eulers_solution
/problem 9.py
286
3.640625
4
def abc(): for a in range(0,500): for b in range(0, 500): for c in range(0, 500): if a<b<c: if a+b+c == 1000: if a**2+b**2 == c**2: return a,b,c a,b,c =abc() print(a*b*c)
155ffecfc68a5c96a5427b259ff583695fe8b7b4
stuart727/edx
/edx600x/L06_Objects/more_operations_on_lists.py
1,190
4.21875
4
import string f ="lalala" print list(f) print f.split(" ") print [x for x in f] '''changing collection while iterating over elements''' '''remove an element''' elems = ['a', 'b', 'c'] for e in elems: print e elems.remove(e) print 'A',elems # MISSING element b # when you remove the 'a' from elems, the remaining elements slide # down the list. The list is now ['b', 'c']. Now 'b' is at # index 0, and 'c' is at index 1. Since the next iteration is going # to look at index 1 (which is the 'c' element), the 'b' gets # skipped entirely! elems = ['a', 'b', 'c'] elems_copy = elems[:] for item in elems_copy: elems.remove(item) print 'B',elems ''' append an element''' # elems = ['a', 'b', 'c'] # for e in elems: # print e # elems.append(e) # print 'C',elems # results in an infinite loop!!! elems = ['a', 'b', 'c'] elems_copy = [] for item in elems: elems_copy.append(item) print 'D',elems_copy elems = ['a', 'b', 'c'] elems_copy = elems[:] for item in elems_copy: elems.append(item) print 'E',elems
d8bfa1037e47e75c32bda0478751f63f69e31ae5
gptix/Graphs
/projects/graph/graph.py
5,845
3.875
4
from util import Stack from util import Queue """In the file graph.py, implement a Graph class that supports the API in the example below. In particular, this means there should be a field vertices that contains a dictionary mapping vertex labels to edges. For example: { '0': {'1', '3'}, '1': {'0'}, '2': set(), '3': {'0'} } This represents a graph with four vertices and two total (bidirectional) edges. The vertex '2' has no edges, while '0' is connected to both '1' and '3'. You should also create add_vertex and add_edge methods that add the specified entities to the graph. To test your implementation, instantiate an empty graph and then try to run the following: """ class Graph(): """A graph stored as a dictionary mapping labels to sets of edges.""" def __init__(self): self.vertices = {} # a dict def add_vertex(self, vertex_id): self.vertices[vertex_id] = set() # a set within the dict def add_edge(self, vertex_id, other_node): # if not vertex_id in self.vertices: # raise Exception(f"No 'from' vertex with value {vertex_label}") self.vertices[vertex_id].add(other_node) def get_neighbors(self, vertex_label): return self.vertices[vertex_label] def bft(self, node): """Breadth-first traversal of graph.""" q = Queue() q.enqueue(node) visited = set() while q.size() > 0: current_node = q.dequeue() if current_node not in visited: visited.add(current_node) neighbors = self.get_neighbors(current_node) for n in neighbors: q.enqueue(n) for v in visited: print(f'{v}') def dft(self, node): """Depth-first traversal of graph.""" s = Stack() s.push(node) visited = [] while s.size() > 0: current_node = s.pop() if current_node not in visited: # print(current_node) visited.append(current_node) # print(visited) neighbors = self.get_neighbors(current_node) for n in neighbors: s.push(n) for v in visited: print(f'{v}') def dft_recursive(self, node, visited=set()): """Use recursion to do DFT.""" print(node) visited.add(node) neighbors = self.get_neighbors(node) for n in neighbors: if n not in visited: self.dft_recursive(n, visited) def bfs(self, start, seek): """Breadth-first search, returning the shortest path to the target.""" q = Queue() visited = set() path = [start] # print(path) q.enqueue(path) while q.size() > 0: # print(visited) # print(q.size()) current_path = q.dequeue() # print(current_path) current_node = current_path[-1] # print(current_node) if current_node == seek: return current_path if current_node not in visited: visited.add(current_node) neighbors = self.get_neighbors(current_node) for n in neighbors: path_copy = current_path[:] # print(path_copy) path_copy.append(n) # print(path_copy) q.enqueue(path_copy) def dfs(self, start, seek): """Depth-first search, returning the shortest path to the target.""" s = Stack() visited = set() path = [start] # print(path) s.push(path) while s.size() > 0: # print(visited) # print(q.size()) current_path = s.pop() # print(current_path) current_node = current_path[-1] # print(current_node) if current_node == seek: return current_path if current_node not in visited: visited.add(current_node) neighbors = self.get_neighbors(current_node) for n in neighbors: path_copy = current_path[:] # print(path_copy) path_copy.append(n) # print(path_copy) s.push(path_copy) def dfs_recursive(self, vertex, seek, path=[], visited=set()): """Use recursion to do search and return a path.""" # keep track of nodes we have visited. visited.add(vertex) # Test to see if vertex is what we are seeking. # This is a halting case. if vertex == seek: return path if len(path) == 0: path.append(vertex) neighbors = self.get_neighbors(vertex) for n in neighbors: # If we have not yet visited the neighbor, recurse. if n not in visited: result = self.dfs_recursive(n, seek, path + [n], visited) # if recursion returns a path, pass that path back 'up'. # This is a second halting case. if result is not None: return result if __name__ == '__main__': graph = Graph() # Instantiate your graph graph.add_vertex(1) graph.add_vertex(2) graph.add_vertex(3) graph.add_vertex(4) graph.add_vertex(5) graph.add_vertex(6) graph.add_vertex(7) graph.add_edge(5, 3) graph.add_edge(6, 3) graph.add_edge(7, 1) graph.add_edge(4, 7) graph.add_edge(1, 2) graph.add_edge(7, 6) graph.add_edge(2, 4) graph.add_edge(3, 5) graph.add_edge(2, 3) graph.add_edge(4, 6) # # graph.dfs_recursive(1,6)
534eb82acda7a7f67c995ff6b51979a648bf2a74
HidoiOokami/Projects-Python
/POO/data.py
865
4.15625
4
class Data: # Contrutor nome magico __init__ def __init__(self, dia = 3, mes = 7, ano = 1997): self.dia = dia self.mes = mes self.ano = ano #Metodo especial que converte para str #self objeto que esta sendo usado nesse momento e um this def __str__(self): # metodo magico return f'{self.dia}\{self.mes}\{self.ano}' #Instancia data = Data(5, 12, 2019) # posso ou não passar os dias dataUm = Data() dataDois = Data(mes=12) #modificando só o mes # Não a necessidade de definir atributos # na classe o python deixa eu manipular dados # que não foram indexados como atributos da classe #data.dia = 5 #data.mes = 12 #data.ano = 2019 # Chamando de forma implicita ele ira procurar o __str__ print(data) # por ser um metodo suportado por todos os obj do py não preciso chamalo print(dataUm) print(dataDois)
bb0d09b70817dd7a9caf8c78d93c51ebac45ab79
sahanavandayar/150_PythonCourse
/a3FINAL.py
14,175
3.6875
4
# Important variables: # movie_db: list of 4-tuples (imported from movies.py) # pa_list: list of pattern-action pairs (queries) # pattern - strings with % and _ (not consecutive) # action - return list of strings # THINGS TO ASK THE MOVIE CHAT BOT: # what movies were made in _ (must be date, because we don't have location) # what movies were made between _ and _ # what movies were made before _ # what movies were made after _ # who directed % # who was the director of % # what movies were directed by % # who acted in % # when was % made # in what movies did % appear # bye # Include the movie database, named movie_db from movies import movie_db from match import match from typing import List, Tuple, Callable, Any # The projection functions, that give us access to certain parts of a "movie" (a tuple) def get_title(movie: Tuple[str, str, int, List[str]]) -> str: return movie[0] def get_director(movie: Tuple[str, str, int, List[str]]) -> str: return movie[1] def get_year(movie: Tuple[str, str, int, List[str]]) -> int: return movie[2] def get_actors(movie: Tuple[str, str, int, List[str]]) -> List[str]: return movie[3] ##print("movie_db[0] is: " + str(movie_db)) ##print("the director is: " +str(movie_db[0][1])) ##print(get_director(movie_db[0])) # Below are a set of actions. Each takes a list argument and returns a list of answers # according to the action and the argument. It is important that each function returns a # list of the answer(s) and not just the answer itself. def title_by_year(matches: List[str]) -> List[str]: """Finds all movies made in the passed in year Args: matches - a list of 1 string, just the year. Note that this year is passed as a string and should be converted to an int Returns: a list of movie titles made in the passed in year """ return[get_title(i) for i in movie_db if get_year(i) == int(matches[0])] ## year = int(matches[0]) ## def movie_made_in_year(movie: Tuple[str,str,int,List[str]])-> bool: ## return year == get_year(movie) ## ## listofMovies = filter(movie_made_in_year, movie_db) ## listofTitles = map(get_title,listofMovies) ## return list(listofTitles) ##assert title_by_year(["1974"]) == ['amarcord','chinatown'],"failed title_by_year test" ##assert title_by_year(["1972"]) == ['the godfather'],"failed title_by_year test" def title_by_year_range(matches: List[str]) -> List[str]: """Finds all movies made in the passed in year range Args: matches - a list of 2 strings, the year beginning the range and the year ending the range. For example, to get movies from 1991-1994 matches would look like this - ["1991", "1994"] Note that these years are passed as strings and should be converted to ints. Returns: a list of movie titles made during those years, inclusive (meaning if you pass in ["1991", "1994"] you will get movies made in 1991, 1992, 1993 & 1994) """ return [get_title(i)for i in movie_db if get_year(i) in list(range(int(matches[0]),int(matches[1])+1))] def title_before_year(matches: List[str]) -> List[str]: """Finds all movies made before the passed in year Args: matches - a list of 1 string, just the year. Note that this year is passed as a string and should be converted to an int Returns: a list of movie titles made before the passed in year, exclusive (meaning if you pass in 1992 you won't get any movies made that year, only before) """ return [get_title(i) for i in movie_db if get_year(i) < int(matches[0])] def title_after_year(matches: List[str]) -> List[str]: """Finds all movies made after the passed in year Args: matches - a list of 1 string, just the year. Note that this year is passed as a string and should be converted to an int Returns: a list of movie titles made after the passed in year, exclusive (meaning if you pass in 1992 you won't get any movies made that year, only after) """ return[get_title(i) for i in movie_db if get_year(i) > int(matches[0])] def director_by_title(matches: List[str]) -> List[str]: """Finds director of movie based on title Args: matches - a list of 1 string, just the title Returns: a list of 1 string, the director of the movie """ return[get_director(i) for i in movie_db if get_title(i) == matches[0]] def title_by_director(matches: List[str]) -> List[str]: """Finds movies directed by the passed in director Args: matches - a list of 1 string, just the director Returns: a list of movies titles directed by the passed in director """ return[get_title(i) for i in movie_db if get_director(i) == matches[0]] def actors_by_title(matches: List[str]) -> List[str]: """Finds actors who acted in the passed in movie title Args: matches - a list of 1 string, just the movie title Returns: a list of actors who acted in the passed in title """ #list comprehension isn't going to work: bc it's putting a list in a list for i in movie_db: if get_title(i) == matches[0]: return get_actors(i) def year_by_title(matches: List[str]) -> List[int]: """Finds year of passed in movie title Args: matches - a list of 1 string, just the movie title Returns: a list of one item (an int), the year that the movie was made """ return[get_year(i) for i in movie_db if get_title(i) == matches[0]] def title_by_actor(matches: List[str]) -> List[str]: """Finds titles of all movies that the given actor was in Args: matches - a list of 1 string, just the actor Returns: a list of movie titles that the actor acted in """ return[get_title(i) for i in movie_db if matches[0] in get_actors(i)] #new actors by year def actors_by_year(matches:List[int])-> List[str]: """Finds all actors in movies from a specific year Args: matches - a list of one item[int] the year that the movie was made Returns: a list of actors who acted in movies released that year """ for i in movie_db: if get_year(i) == int(matches[0]): print(get_actors(i)) return get_actors(i) # dummy argument is ignored and doesn't matter def bye_action(dummy: List[str]) -> None: raise KeyboardInterrupt # The pattern-action list for the natural language query system A list of tuples of # pattern and action It must be declared here, after all of the function definitions pa_list: List[Tuple[List[str], Callable[[List[str]], List[Any]]]] = [ (str.split("what movies were made in _"), title_by_year), (str.split("what movies were made between _ and _"), title_by_year_range), (str.split("what movies were made before _"), title_before_year), (str.split("what movies were made after _"), title_after_year), # note there are two valid patterns here two different ways to ask for the director # of a movie (str.split("who directed %"), director_by_title), (str.split("who was the director of %"), director_by_title), (str.split("what movies were directed by %"), title_by_director), (str.split("who acted in %"), actors_by_title), (str.split("when was % made"), year_by_title), (str.split("in what movies did % appear"), title_by_actor), (["bye"], bye_action), ] def search_pa_list(src: List[str]) -> List[str]: """Takes source, finds matching pattern and calls corresponding action. If it finds a match but has no answers it returns ["No answers"]. If it finds no match it returns ["I don't understand"]. Args: source - a phrase represented as a list of words (strings) Returns: a list of answers. Will be ["I don't understand"] if it finds no matches and ["No answers"] if it finds a match but no answers """ num_matches = 0 result: List[str] = [] for (pattern,function) in pa_list: if match(pattern,src) != None: num_matches += 1 result = function(match(pattern,src)) if num_matches == 0: return ["I don't understand"] elif result == []: return["No answers"] else: return result #for each pattern, action pair in pa_list # try to match - call match with that pattern and the source(src) # save the results from match, in x # if we matched: # increment num_matches # set the result to the results of calling the associated action function # function, passing it the result from match, x #if #elif #else #you have access to num matches and access to result def query_loop() -> None: """The simple query loop. The try/except structure is to catch Ctrl-C or Ctrl-D characters and exit gracefully. """ print("Welcome to the movie database!\n") while True: try: print() query = input("Your query? ").replace("?", "").lower().split() answers = search_pa_list(query) for ans in answers: print(ans) except (KeyboardInterrupt, EOFError): break print("\nSo long!\n") # uncomment the following line once you've written all of your code and are ready to try # it out. Before running the following line, you should make sure that your code passes # the existing asserts. #query_loop() ##if __name__ == "__main__": ## assert sorted(title_by_year(["1974"])) == sorted(["amarcord", "chinatown"]), "failed title_by_year test" ## assert sorted(title_by_year(["1960"])) == sorted(["spartacus"]), "failed title_by_year test" #I wrote this one ## assert sorted(title_by_year(["1952"])) == sorted(["othello","an american in paris"]), "failed title_by_year test" #I wrote this one ## ## assert sorted(title_by_year_range(["1970", "1972"])) == sorted(["the godfather", "johnny got his gun"]), "failed title_by_year_range test" ## assert sorted(title_by_year_range(["1972", "1973"])) == sorted(["the godfather","the day of the jackal","the exorcist"]), "failed title_by_year_range test" ## assert sorted(title_before_year(["1950"])) == sorted(["casablanca", "citizen kane", "gone with the wind", "metropolis"]), "failed title_before_year test" ## assert sorted(title_after_year(["1990"])) == sorted(["boyz n the hood", "dead again", "the crying game", "flirting", "malcolm x"]), "failed title_after_year test" ## assert sorted(director_by_title(["jaws"])) == sorted(["steven spielberg"]), "failed director_by_title test" ## assert sorted(title_by_director(["steven spielberg"])) == sorted(["jaws"]), "failed title_by_director test" ## print(sorted(actors_by_title(["jaws"]))) ## assert sorted(actors_by_title(["jaws"])) == sorted([ ## "roy scheider", ## "robert shaw", ## "richard dreyfuss", ## "lorraine gary", ## "murray hamilton",]), "failed actors_by_title test" ## assert sorted(year_by_title(["jaws"])) == sorted( ## [1975] ## ), "failed year_by_title test" ## assert sorted(year_by_title(["iceman"])) == sorted([1984]), "failed year_by_title test" #I wrote this one ## assert sorted(title_by_actor(["orson welles"])) == sorted( ## ["citizen kane", "othello"] ## ), "failed title_by_actor test" ## ## assert sorted(search_pa_list(["hi", "there"])) == sorted( ## ["I don't understand"] ## ), "failed search_pa_list test 1" ## assert sorted(search_pa_list(["who", "directed", "jaws"])) == sorted( ## ["steven spielberg"] ## ), "failed search_pa_list test 2" ## assert sorted(search_pa_list(["who", "ran", "jaws"])) == sorted( ## ["I don't understand"] ## ), "failed search_pa_list test 2" ## assert sorted(search_pa_list(["who", "directed", "dead again"])) == sorted( ## ["kenneth branagh"] ## ), "failed search_pa_list test 2" ## assert sorted( ## search_pa_list(["what", "movies", "were", "made", "in", "2020"]) ## ) == sorted(["No answers"]), "failed search_pa_list test 3" ## assert sorted( ## search_pa_list(["what", "movies", "were", "made", "in", "1900"]) ## ) == sorted(["No answers"]), "failed search_pa_list test 3" ## assert sorted( ## search_pa_list(["what", "movies", "were", "made", "in", "1700"]) ## ) == sorted(["No answers"]), "failed search_pa_list test 3" ## assert sorted(search_pa_list(["who", "directed", "a star is born"])) == sorted( ## ["george cuckor"] ## ), "failed search_pa_list test 2" ## assert sorted(search_pa_list(["who", "directed", "after the rehearsal"])) == sorted( ## ["ingmar bergman"] ## ), "failed search_pa_list test 2" ## assert sorted(search_pa_list(["who", "acted", "in", "a star is born"])) == sorted(['judy garland', 'james mason', 'jack carson', 'tommy noonan', 'charles bickford']) ## ## ## ###_____________________________________________actors_by_year ## assert sorted(actors_by_year(["1926"])) == sorted(["alfred abel","gustay frohlich","brigitte helm","rudolf kleinrogge","heinrich george"]), "failed actors_by_year_range test" ## ## assert isinstance(title_by_year(["1974"]), list), "title_by_year not returning a list" ## assert isinstance(title_by_year_range(["1970", "1972"]), list), "title_by_year_range not returning a list" ## assert isinstance(title_before_year(["1950"]), list), "title_before_year not returning a list" ## assert isinstance(title_after_year(["1990"]), list), "title_after_year not returning a list" ## assert isinstance(director_by_title(["jaws"]), list), "director_by_title not returning a list" ## assert isinstance(title_by_director(["steven spielberg"]), list), "title_by_director not returning a list" ## assert isinstance(actors_by_title(["jaws"]), list), "actors_by_title not returning a list" ## assert isinstance(year_by_title(["jaws"]), list), "year_by_title not returning a list" ## assert isinstance(title_by_actor(["orson welles"]), list), "title_by_actor not returning a list" # print("All tests passed!")
be6dd8523e6f758ece23e131d890641613f71406
tcandzq/LeetCode
/HashTable/BrickWall.py
1,503
3.828125
4
# -*- coding: utf-8 -*- # @File : BrickWall.py # @Date : 2020-03-09 # @Author : tc """ 题号 554. 砖墙 你的面前有一堵方形的、由多行砖块组成的砖墙。 这些砖块高度相同但是宽度不同。你现在要画一条自顶向下的、穿过最少砖块的垂线。 砖墙由行的列表表示。 每一行都是一个代表从左至右每块砖的宽度的整数列表。 如果你画的线只是从砖块的边缘经过,就不算穿过这块砖。你需要找出怎样画才能使这条线穿过的砖块数量最少,并且返回穿过的砖块数量。 你不能沿着墙的两个垂直边缘之一画线,这样显然是没有穿过一块砖的。 示例: 输入: [[1,2,2,1], [3,1,2], [1,3,2], [2,4], [3,1,2], [1,3,1,1]] 输出: 2 解释: 提示: 每一行砖块的宽度之和应该相等,并且不能超过 INT_MAX。 每一行砖块的数量在 [1,10,000] 范围内, 墙的高度在 [1,10,000] 范围内, 总的砖块数量不超过 20,000。 参考:https://leetcode.com/problems/brick-wall/discuss/101726/Clear-Python-Solution """ from typing import List import collections class Solution: def leastBricks(self, wall: List[List[int]]) -> int: d = collections.defaultdict(int) for line in wall: i = 0 for brick in line[:-1]: i += brick d[i] += 1 # print len(wall), d return len(wall) - max(d.values(), default=0)
d61d5b6b6b0a4e95ba7406814414d2d069961695
silhuzz/Engeto-Project-2-
/main.py
6,333
3.96875
4
#PISKVORKY 2.0 # by Tomas S def zadani_hrace(): while True: pole = input("Vyber si velikost hracího pole.\nVelikost musí být mezi 3 - 100") if not pole.isdecimal(): print("Zadej celé číslo") continue if not (int(pole) < 3) and not (int(pole) > 100): nakolik = int(input("Chceš hrát na 3 nebo 5 výherných?")) if nakolik > int(pole): print("Máš moc malé hrací pole na to.") continue if (nakolik == 3) or (nakolik == 5): print(pole, nakolik) return pole, nakolik else: print("Zadej bud 3 nebo 5!") continue else: print("Zadej číslo mezi 3 až 100. (např 5, 10, 12 atd.") continue def matice_puvodni_stav(pole, matice): for i in range(0, len(matice), pole): rozdeleni = matice[i:i + pole] print("|".join(rozdeleni)) radky = "- " * (pole) print(radky) def vykresli_matici(pole, matice): for i in range(0, len(matice), pole): rozdeleni = matice[i:i + pole] print("|".join(rozdeleni)) radky = "- " * (pole) print(radky) def zadani_pozice(pole, matice, symbol): while True: text = "" if symbol == 1: symbol = "o" elif symbol == 2: symbol = "x" pozice = input("Hráč |" + symbol + "| zadej pozici mezi 1 až " + str(pole * pole)) if pozice.isdecimal(): if int(pozice) >= 1 and int(pozice) <= pole * pole: pozice = int(pozice) - 1 if ("x" in matice[pozice]) or ("o" in matice[pozice]): print("Takhle piškvorky nefungujou, zvol jiné pole.") else: matice[pozice] = symbol return matice else: print("Zadej celé číslo mezi 1 až " + str(pole * pole)) continue def vyhra_radky(pole, matice, nakolik): hrac1 = ["x"] * nakolik hrac2 = ["o"] * nakolik for i in range(0, len(matice), pole): rozdeleni = matice[i:i + pole] if (''.join(hrac1) in ''.join(rozdeleni)): print("Vyhrál hráč 1! Gratulace!") return True elif (''.join(hrac2) in ''.join(rozdeleni)): print("Vyhrál hráč 2! Gratulace!") return True def vyhra_sloupce(pole, matice, nakolik): hrac1 = ["x"] * nakolik hrac2 = ["o"] * nakolik zacatek = 0 while zacatek < pole: rozdeleni = matice[zacatek::pole] if (''.join(hrac1) in ''.join(rozdeleni)): print("Vyhrál hráč 1! Gratulace!") return True elif (''.join(hrac2) in ''.join(rozdeleni)): print("Vyhrál hráč 2! Gratulace!") return True else: zacatek += 1 def vyhra_diagonal1(pole, matice, nakolik): if nakolik == 3: zacatek = 2 konec = (pole * 2) elif nakolik == 5: zacatek = 4 konec = ((pole - nakolik) * (nakolik) + 20) # dospel jsem k tomu matematicky, # nejnizsi mozny konecny index je 20+1 kde pole je 5x5 a hraje se na 5 vyhernych, # pri kazdem dalsi zvetseni hraciho pole dojde k navýšenní posledního indexu o 5 counter = 1 skok = nakolik - 1 hops = (pole - nakolik) + 1 skip = pole - 1 seznam_diagonal1 = [] for i in range(len(matice)): if (i % hops == 0) and (i != 0): zacatek += skok counter += skok bonbon = matice[zacatek:((konec) + counter):skip] seznam_diagonal1.append(bonbon) zacatek += 1 counter += 1 hrac1 = ["x"] * nakolik hrac2 = ["o"] * nakolik for z in seznam_diagonal1: if hrac1 == z: print("Vyhrál hráč 1! Gratulace!") return True elif hrac2 == z: print("Vyhrál hráč 2! Gratulace!") return True def vyhra_diagonal2(pole, matice, nakolik): if nakolik == 3: konec = (pole * 2) + 2 elif nakolik == 5: konec = ((pole * 4) + 4) counter = 1 skok = nakolik - 1 hops = (pole - nakolik) + 1 skip = pole + 1 zacatek = 0 seznam_diagonal2 = [] for i in range(len(matice)): if (i % hops == 0) and (i != 0): zacatek += skok counter += skok bonbon = matice[zacatek:((konec) + counter):skip] seznam_diagonal2.append(bonbon) zacatek += 1 counter += 1 hrac1 = ["x"] * nakolik hrac2 = ["o"] * nakolik for z in seznam_diagonal2: if hrac1 == z: print("Vyhrál hráč 1! Gratulace!") return True elif hrac2 == z: print("Vyhrál hráč 2! Gratulace!") return True def main(): intro = """===========================\nWelcome to Tic Tac Toe\n GAME RULES:\n Each player can place one mark per turn your selected grid\n The WINNER is who succeeds in placing three of their marks in a\n * horizontal,\n * vertical or\n * diagonal row\n ===========================""" print(intro) user_info = zadani_hrace() pole = int(user_info[0]) nakolik = int(user_info[1]) matice = [" "] * pole * pole game_on = True tah = 1 matice_puvodni_stav(pole, matice) while game_on: symbol = 2 if tah % 2 == 0 else 1 matice = zadani_pozice(pole, matice, symbol) if (vyhra_radky(pole, matice, nakolik) or vyhra_sloupce(pole, matice, nakolik) or vyhra_diagonal1(pole, matice, nakolik) or vyhra_diagonal2(pole, matice, nakolik)): game_on = False elif (tah == pole * pole): game_on = False rozhodnuti = input("Nikdo nevyhrál, chcete hrát znovu? Napiš: Y/N").lower() if rozhodnuti == "y": game_on = False main() elif rozhodnuti == "n": game_on = False print("Díky za hru") break else: print("Zadej Y pro pokračovaní a N pro konec.") continue vykresli_matici(pole, matice) tah += 1 if __name__ == "__main__": main()
ff32bffbe4b9f85b7da15b3b9bc4e5a8dc1c9d7d
bestyuan/Time-Series-Forecasting-With-LSTMs
/DataVisualization.py
373
3.546875
4
import pandas as pd from matplotlib import pyplot dataset = pd.read_csv('pollution.csv', header = 0, index_col = 0) values = dataset.values groups = [0, 1, 2, 3, 4, 5, 6, 7] i = 1 pyplot.figure() for group in groups: pyplot.subplot(len(groups),1,i) pyplot.plot(values[:,group]) pyplot.title(dataset.columns[group], y=0.5, loc = 'right') i+=1 pyplot.show()
5a0d28005a7e8153746748532848aafbe243f47e
logancrocker/interview-toolkit
/code/queue/queue.py
421
3.75
4
class Queue: def __init__(self): self.queue = [] def isEmpty(self): return len(self.queue) == 0 def add(self, data): self.queue.append(data) def remove(self): if (not len(self.queue) == 0): self.queue.pop(0) else: print("Empty queue!") def peek(self): if (not len(self.queue) == 0): return self.queue[0] else: print("Empty queue!")
5394b0578e81dfc09d109fa035c58427d1b6e2b6
Gerrydh/Project-2018
/Python Scripts/Min & Max Sepal Lengths.py
796
3.875
4
# Ger Hanlon, 02.04.2018 # This code returns the min and max value of the sepal lenghts, Column(0). #https://stackoverflow.com/questions/46281738 with open("Iris data2.csv") as file: # open, then close the Iris Dataset file lines = file.read().split("\n") #Read each line and split each line num_list = [] # only numbers for line in lines: # reach each line by line try: item = line.split(",")[0] #Choose 1st column which is seperated by a comma num_list.append(float(item)) #Try to analyise each value to ensure it is a number except: pass #If it can't parse, the string is not a number print("The smallest Sepal Length is : ", min(num_list)) #Prints the minimum value print("The tallest Sepal Length is : ", max(num_list)) # Prints the maximum value
e3211950e94767d9813875958e5dc0a5764c6f44
PeravitK/PSIT
/WEEK3/[Midterm] Donut.py
587
3.734375
4
"""donut""" def donut(): '''eiei''' var_a = int(input()) var_b = int(input()) var_c = int(input()) var_d = int(input()) if var_c > 0: ans = var_d//(var_b+var_c) if var_d - (var_b+var_c)*ans < var_b: price = ((var_a*var_b)*ans)+(var_d-((var_b+var_c)*ans))*var_a print(price, var_b+var_c+var_d-(var_b+var_c)) elif var_d - (var_b+var_c) >= var_b: price = ((ans+1)*var_b)*var_a print(price, (ans+1)*(var_b+var_c)) elif var_c == 0: print(var_d*var_a, var_d) donut()
45e2461e92a689b81291644b1c76672b6e9985f3
guam68/class_iguana
/Code/Daniel/python/lab11-simple_calculator.py
386
3.859375
4
from math import * print('-' * 50 + '\nType "done" to quit\n' + '-' * 50 ) while True: try: expression = input('\nEnter a math expression using [+, -, *, /] operators: ') if expression == 'done': break answer = eval(expression, {'__builtins__': None}) print(answer) except: print('\nInvalid expression\n')
b021c4ff2248e7b1cadbf07baf77b09dadb5ca04
krnets/codewars-practice
/5kyu/Find the Partition with Maximum Product Value/index.py
2,676
3.84375
4
""" 5kyu - Find the Partition with Maximum Product Value You are given a certain integer, n, n > 0. You have to search the partition or partitions, of n, with maximum product value. Let'see the case for n = 8. Partition Product [8] 8 [7, 1] 7 [6, 2] 12 [6, 1, 1] 6 [5, 3] 15 [5, 2, 1] 10 [5, 1, 1, 1] 5 [4, 4] 16 [4, 3, 1] 12 [4, 2, 2] 16 [4, 2, 1, 1] 8 [4, 1, 1, 1, 1] 4 [3, 3, 2] 18 <---- partition with maximum product value [3, 3, 1, 1] 9 [3, 2, 2, 1] 12 [3, 2, 1, 1, 1] 6 [3, 1, 1, 1, 1, 1] 3 [2, 2, 2, 2] 16 [2, 2, 2, 1, 1] 8 [2, 2, 1, 1, 1, 1] 4 [2, 1, 1, 1, 1, 1, 1] 2 [1, 1, 1, 1, 1, 1, 1, 1] 1 So our needed function will work in that way for Python and Ruby: find_part_max_prod(8) == [[3, 3, 2], 18] For javascript findPartMaxProd(8) --> [[3, 3, 2], 18] If there are more than one partition with maximum product value, the function should output the patitions in a length sorted way. Python and Ruby find_part_max_prod(10) == [[4, 3, 3], [3, 3, 2, 2], 36] Javascript findPartMaxProd(10) --> [[4, 3, 3], [3, 3, 2, 2], 36] """ from operator import mul from functools import reduce from collections import defaultdict # def partitions(n, I=1): # yield [n] # for i in range(I, n//2 + 1): # for p in partitions(n-i, i): # yield p + [i] def partitions(n, k=1): yield [n] for i in range(k, n//2 + 1): for p in partitions(n-i, i): yield p + [i] # def find_part_max_prod(n): # parts = list(partitions(n)) # products = [[x, reduce(mul, x)] for x in parts] # max_prod_val = max(products, key=lambda x: x[1])[1] # res = list(filter(lambda x: x[1] == max_prod_val, products)) # if len(res) >= 2: # return sorted([x[0] for x in res], key=len) + [res[0][1]] # return res[0] def find_part_max_prod(n): prods = defaultdict(list) for p in partitions(n): prods[reduce(mul, p)].append(p) mpv = max(prods.keys()) return sorted(prods[mpv], key=len) + [mpv] # def find_part_max_prod(n): # prods = defaultdict(list) # for p in partitions(n): # prods[reduce(mul, p)].append(p) # k, v = max(prods.items()) # # return [*v[::-1], k] # return [*reversed(v), k] q = find_part_max_prod(8), [[3, 3, 2], 18] q q = find_part_max_prod(10), [[4, 3, 3], [3, 3, 2, 2], 36] q
8988890c2e21561e3f08e729a8dc6c07d4678fcf
cnspaulding/PFB_problemsets
/PythonPS7/ps7q1.py
284
3.703125
4
#!/usr/bin/env python3 import re poem_file = open('Python_07_nobody.txt', 'r') poem= poem_file.read() found = re.findall(r'Nobody', poem) #print(found) for found in re.finditer(r'Nobody', poem): occur = found.group(0) position = found.start(0)+1 print(occur, position)
1ce7d67781fdc92c37badfc30dd0d46c46087ce0
mingweihe/leetcode
/_1057_Campus_Bikes.py
1,508
3.578125
4
import heapq class Solution(object): def assignBikes(self, workers, bikes): """ :type workers: List[List[int]] :type bikes: List[List[int]] :rtype: List[int] """ # Approach 2 Bucket Sort Algorithm, time O(m*n) dists = [[] for _ in xrange(2001)] for i, w in enumerate(workers): for j, b in enumerate(bikes): d = abs(w[0] - b[0]) + abs(w[1] - b[1]) dists[d].append([i, j]) res = [-1] * len(workers) assigned_bikes = set() for x in dists: for i, j in x: if res[i] == -1 and j not in assigned_bikes: res[i] = j assigned_bikes.add(j) return res # Approach 1 Priority Queue, time O(m*n*log(m)) # hq, w2b = [], collections.defaultdict(list) # for i, (wx, wy) in enumerate(workers): # for j, (bx, by) in enumerate(bikes): # dis = abs(wx-bx) + abs(wy-by) # w2b[i].append([dis, i, j]) # w2b[i].sort(reverse=True) # heapq.heappush(hq, w2b[i].pop()) # res = [0]*len(workers) # assigned_bikes = set() # while len(assigned_bikes) < len(workers): # _, i, j = heapq.heappop(hq) # if j not in assigned_bikes: # assigned_bikes.add(j) # res[i] = j # else: # heapq.heappush(hq, w2b[i].pop()) # return res
8882d09d9c1b34b07ad5b56931c85f996e358476
matheusschuetz/AulasPython
/17-Aula17/exercicio/exercicio2.py
1,187
4.09375
4
# 1 - Faça um menu interativo que tenha: Cadastro da banda, cadastro # do album, cadastro da musica, Sair. # O menu deve ser executado até que se escolha a opção sair. # Cada opção deve ser mostrada # quando selecionado a opção sair, deverá aparecer na tela as # informações das banda cadastradas, # albuns e musicas. lista_banda = [] lista_album = [] lista_musica = [] menu = ''' ############################################################################# Cadastro Faixas ############################################################################# 1 - Cadastro banda 2 - Cadastro album 3 - Cadastro musica 4 - sair Digite a opção: ''' while True: opcao = input(menu) if opcao == '1': lista_banda.append(input('Digite o nome da banda: ')) elif opcao == '2': lista_album.append(input('Digite o nome da album: ')) elif opcao == '3': lista_musica.append(input('Digite o nome da musica: ')) elif opcao == '4': print(f'lista de banda: {lista_banda}\nlista de album: {lista_album}\nlista de musica: {lista_musica}') break else: print('opção invalida')
bd0e0bc07201db9f2611c051b9e80e39f92d3e0d
tudennis/LeetCode---kamyu104-11-24-2015
/Python/reordered-power-of-2.py
870
3.765625
4
# Time: O((logn)^2) = O(1) due to n is a 32-bit number # Space: O(logn) = O(1) # Starting with a positive integer N, # we reorder the digits in any order (including the original order) # such that the leading digit is not zero. # # Return true if and only if we can do this in a way # such that the resulting number is a power of 2. # # Example 1: # # Input: 1 # Output: true # Example 2: # # Input: 10 # Output: false # Example 3: # # Input: 16 # Output: true # Example 4: # # Input: 24 # Output: false # Example 5: # # Input: 46 # Output: true # # Note: # - 1 <= N <= 10^9 import collections class Solution(object): def reorderedPowerOf2(self, N): """ :type N: int :rtype: bool """ count = collections.Counter(str(N)) return any(count == collections.Counter(str(1 << i)) for i in xrange(31))
3e00a53218a5bec14326413929bf0ce342e05134
Simran-02/Bootcamp-project-
/3.py
829
3.765625
4
#Add salting and iterartion to your hashes. #ans:- import uuid import hashlib def hash-password(password): salt=uuid.uuid4().hex return hashlib.sha256(salt.encode()+password .encode()).hexdigest()+':'+salt def check-password d(hashed-password,user-password): password,salt=hashed-password.split(':') return password== hashlib.sha256(salt.encode()+user-password.encode()).hexdigest() new-pass=input('please enter a password:') hashed-password=hash-password(new-pass) print('the string to store in the db is :'+hashed-password) old-pass=input('now please enter the password again to check:') if check-password( hashed-password,old-pass): print('you entered the right password') else: print('i am sorry but the password does not match')
5ca27e6b0ef870ec25424c828a7a69aa8de7de38
Frankiee/leetcode
/math/963_minimum_area_rectangle_ii.py
2,174
3.515625
4
# [Classic, Rectangle] # https://leetcode.com/problems/minimum-area-rectangle-ii/ # 963. Minimum Area Rectangle II # History: # Facebook # 1. # Mar 6, 2020 # Given a set of points in the xy-plane, determine the minimum area of any rectangle formed from # these points, with sides not necessarily parallel to the x and y axes. # # If there isn't any rectangle, return 0. # # # # Example 1: # # # # Input: [[1,2],[2,1],[1,0],[0,1]] # Output: 2.00000 # Explanation: The minimum area rectangle occurs at [1,2],[2,1],[1,0],[0,1], with an area of 2. # Example 2: # # # # Input: [[0,1],[2,1],[1,1],[1,0],[2,0]] # Output: 1.00000 # Explanation: The minimum area rectangle occurs at [1,0],[1,1],[2,1],[2,0], with an area of 1. # Example 3: # # # # Input: [[0,3],[1,2],[3,1],[1,3],[2,1]] # Output: 0 # Explanation: There is no possible rectangle to form from these points. # Example 4: # # # # Input: [[3,1],[1,1],[0,1],[2,1],[3,3],[3,2],[0,2],[2,3]] # Output: 2.00000 # Explanation: The minimum area rectangle occurs at [2,1],[2,3],[3,3],[3,1], with an area of 2. # # # Note: # # 1 <= points.length <= 50 # 0 <= points[i][0] <= 40000 # 0 <= points[i][1] <= 40000 # All points are distinct. # Answers within 10^-5 of the actual value will be accepted as correct. from collections import defaultdict class Solution(object): def minAreaFreeRect(self, points): """ :type points: List[List[int]] :rtype: float """ points = [complex(*z) for z in points] points_indices = defaultdict(list) ret = float('inf') for i in range(len(points)): for j in range(i + 1, len(points)): p1, p2 = points[i], points[j] center = (p1 + p2) / 2 redius = abs(center - p1) points_indices[(center, redius)].append(p1) for (center, redius), groups in points_indices.iteritems(): for i in range(len(groups)): for j in range(i + 1, len(groups)): p1, p2 = groups[i], groups[j] ret = min(ret, abs(p1 - p2) * abs(p1 - (2 * center - p2))) return ret if ret != float('inf') else 0
3346c37a5c2348d3a3effb03ba090493187320c9
archived-user/Numpy-Tutorial-SciPyConf-2016
/exercises/wind_statistics/wind_statistics_completed.py
3,933
4.125
4
# Copyright 2016 Enthought, Inc. All Rights Reserved """ Wind Statistics ---------------- Topics: Using array methods over different axes, fancy indexing. 1. The data in 'wind.data' has the following format:: 61 1 1 15.04 14.96 13.17 9.29 13.96 9.87 13.67 10.25 10.83 12.58 18.50 15.04 61 1 2 14.71 16.88 10.83 6.50 12.62 7.67 11.50 10.04 9.79 9.67 17.54 13.83 61 1 3 18.50 16.88 12.33 10.13 11.17 6.17 11.25 8.04 8.50 7.67 12.75 12.71 The first three columns are year, month and day. The remaining 12 columns are average windspeeds in knots at 12 locations in Ireland on that day. Use the 'loadtxt' function from numpy to read the data into an array. 2. Calculate the min, max and mean windspeeds and standard deviation of the windspeeds over all the locations and all the times (a single set of numbers for the entire dataset). 3. Calculate the min, max and mean windspeeds and standard deviations of the windspeeds at each location over all the days (a different set of numbers for each location) 4. Calculate the min, max and mean windspeed and standard deviations of the windspeeds across all the locations at each day (a different set of numbers for each day) 5. Find the location which has the greatest windspeed on each day (an integer column number for each day). 6. Find the year, month and day on which the greatest windspeed was recorded. 7. Find the average windspeed in January for each location. You should be able to perform all of these operations without using a for loop or other looping construct. Bonus ~~~~~ 1. Calculate the mean windspeed for each month in the dataset. Treat January 1961 and January 1962 as *different* months. (hint: first find a way to create an identifier unique for each month. The second step might require a for loop.) 2. Calculate the min, max and mean windspeeds and standard deviations of the windspeeds across all locations for each week (assume that the first week starts on January 1 1961) for the first 52 weeks. This can be done without any for loop. Bonus Bonus ~~~~~~~~~~~ Calculate the mean windspeed for each month without using a for loop. (Hint: look at `searchsorted` and `add.reduceat`.) Notes ~~~~~ These data were analyzed in detail in the following article: Haslett, J. and Raftery, A. E. (1989). Space-time Modelling with Long-memory Dependence: Assessing Ireland's Wind Power Resource (with Discussion). Applied Statistics 38, 1-50. See :ref:`wind-statistics-solution`. """ from numpy import loadtxt YEAR = 0 MONTH = 1 DAY = 2 # 1. read data into array wind = loadtxt('wind.data') #print wind.shape # 2. calculate min, max, mean, std of wind data wind_data = wind[:,3:] #print wind_data.shape print 'min of all data:', wind_data.min() print 'max of all data:', wind_data.max() print 'mean of all data:', wind_data.mean() print 'std of all data:', wind_data.std() print # 3. calculate stats at each location print 'min of locations:', wind_data.min(axis=0) print 'max of locations:', wind_data.max(axis=0) print 'mean of locations:', wind_data.mean(axis=0) print 'std of locations:', wind_data.std(axis=0) print # 4. calculate stats of each day across all locations print 'min of day', wind_data.min(axis=1) print 'max of day:', wind_data.max(axis=1) print 'mean of day:', wind_data.mean(axis=1) print 'std of day:', wind_data.std(axis=1) print # 5. location with greatest windspeed each day print 'locations with max wind per day:', wind_data.argmax(axis=1) print # 6. year, month, day of max windspeed across all data max_day = wind_data.max(axis=1) index_max = max_day.argmax() print 'date of greatest wind in history:', wind[index_max,:3] print # 7. average at each location in january index_jan = wind[:,1] == 1 jan_wind = wind_data[index_jan] #print jan_wind.shape print 'january avg at each locations:', jan_wind.mean(axis=0) print
8beebd284d4bfb1f318da07454481b7998a0b18f
bruceewmesmo/python-mundo-03
/ex074.py
293
3.921875
4
# EXERCICIO 074 - from random import randint num = (randint(1,10),randint(1,10),randint(1,10),randint(1,10),randint(1,10)) print('Os valores sorteados foram:', end= ' ') for n in num: print(f'{n}', end = ' ') print(f'\n O maior número sorteado foi {max(num)} e o menor {min(num)}')
78572132e86875c8fce575d9a0874515bf131f4b
susyhaga/Challanges-Python
/Frauenloop/Tip_calculator/tip_calculator.py
416
3.84375
4
guest = 2 bill = 80 tipPercentage = 10 def calculator(): percentage_x = bill * tipPercentage / 100 print(percentage_x) tip_x = percentage_x / guest print(tip_x) bill_division = bill / guest print(bill_division) total = bill_division + tip_x print( f'Each guest needs to pay {total} euros and The amount of tip for each guest is {tip_x}.') return (total) calculator()
32343a1b93d85debc90b8b779fd607f630c8387e
superSeanLin/Algorithms-and-Structures
/29_Divide_Two_Integers/29_Divide_Two_Integers.py
786
3.609375
4
class Solution: ## may use Euclidean algorithm(辗转相除) to calculate greatest common divisor def divide(self, dividend, divisor): """ :type dividend: int :type divisor: int :rtype: int """ negative = 1 if dividend * divisor < 0: # different sign negative = -1 # make same sigb divisor = abs(divisor) dividend = abs(dividend) quotient = 0 while dividend >= divisor: temp, count = divisor, 1 while dividend >= temp: # multiply-like; Note: also for exp dividend -= temp temp += temp quotient += count count += count return min(max(negative * quotient, -2**31), 2**31-1)
c603d54cd7c9852ade76502c97afd531b0ea8924
msanchezzg/AdventOfCode
/AdventOfCode2019/day12/day12-1.py
2,592
3.65625
4
class Luna: def __init__(self): self.velocidad = Velocidad() self.posicion = Posicion() def __repr__(self): s = 'pos= <' s += 'x=' + str(self.posicion.x) + ', ' s += 'y=' + str(self.posicion.y) + ', ' s += 'z=' + str(self.posicion.z) + '>, vel= <' s += 'x=' + str(self.velocidad.x) + ', ' s += 'y=' + str(self.velocidad.y) + ', ' s += 'z=' + str(self.velocidad.z) + '>' return s @property def posicion(self): return self.__posicion @posicion.setter def posicion(self, posicion): self.__posicion = posicion def energiaCin(self): return abs(self.velocidad.x) + abs(self.velocidad.y) + abs(self.velocidad.z) def energiaPot(self): return abs(self.posicion.x) + abs(self.posicion.y) + abs(self.posicion.z) def energiaTotal(self): return self.energiaPot() * self.energiaCin() def cambiarVelocidad(self, luna): if (luna.posicion.x > self.posicion.x): self.velocidad.x += 1 elif (luna.posicion.x < self.posicion.x): self.velocidad.x -= 1 if (luna.posicion.y > self.posicion.y): self.velocidad.y += 1 elif (luna.posicion.y < self.posicion.y): self.velocidad.y -= 1 if (luna.posicion.z > self.posicion.z): self.velocidad.z += 1 elif (luna.posicion.z < self.posicion.z): self.velocidad.z -= 1 def cambiarPosicion(self): self.posicion.x += self.velocidad.x self.posicion.y += self.velocidad.y self.posicion.z += self.velocidad.z class Velocidad: def __init__(self, x=0, y=0, z=0): self.x = x self.y = y self.z = z class Posicion: def __init__(self, x=0, y=0, z=0): self.x = x self.y = y self.z = z ###########main with open('in.txt', 'r') as f: lines = f.read().split('\n') lunas = [] iteraciones = 1000 for i in lines: pos = i[:-1].split(',') x, y, z = [int(x.split('=')[1]) for x in pos] luna = Luna() luna.posicion = Posicion(x, y, z) lunas.append(luna) with open('out1.txt', 'w+') as f: for i in range(iteraciones): for l in lunas: for l2 in lunas: l.cambiarVelocidad(l2) for l in lunas: l.cambiarPosicion() f.write('iteracion ' + str(i+1) + '\n') for l in lunas: f.write('\t' + str(l) + '\n') energia = sum([l.energiaTotal() for l in lunas]) f.write('\nEnergía total: ' + str(energia))
18c77c2867fcacaae590f44c735446831f2360d1
mjburgess/public-notes
/python-notes/14.Extra/ExerciseX-PEP8.py
863
4.4375
4
# CHAPTER: PEP8 # OBJECTIVE: Complete the following questions. # PROBLEM: Revise this file and apply PEP8 guidelines; do not change the logic. # TIME: 15m class Person: def __init__(self, first_name): self.first_name = first_name def get_name(self): return self._format(self.firstname) def _format(self, string): return string.upper() def people(message='Making People'): ''' Make a list of sherlocks and watsons -- each of type Person. ''' sherlock = Person('Sherlock') watson = Person('Watson') print(message) return [ sherlock, watson, sherlock, watson, sherlock, watson, sherlock, watson, sherlock, watson, sherlock, watson ] list_of_people = Person() for person in list_of_people: print(person.get_name()) ''' OUTPUT (14.Extra/ExerciseX-PEP8.py): '''
a87179fcbcc0c67b3e41ad4e28e30190f190072f
mknotts623/client_search
/db_functions.py
1,938
3.8125
4
import sqlite3 conn = sqlite3.connect('client_data.db') c = conn.cursor() def create_table(): # need to get ALL parameters later c.execute('PRAGMA foreign_keys = ON;') c.execute('CREATE TABLE IF NOT EXISTS clients(' 'client_name TEXT PRIMARY KEY,' 'email TEXT NOT NULL, ' 'income INTEGER NOT NULL)') c.execute('CREATE TABLE IF NOT EXISTS tags(' 'tag_name TEXT PRIMARY KEY)') c.execute('CREATE TABLE IF NOT EXISTS client_tags(' 'client TEXT NOT NULL, ' 'tag TEXT NOT NULL,' 'FOREIGN KEY(client) REFERENCES client(client_name), ' 'FOREIGN KEY(tag) REFERENCES tags(tag_name));') #won't crash if client is already in database def enter_client(name, email, income): c.execute("SELECT client_name FROM clients WHERE client_name = ?", (name,)) exists = c.fetchone() if exists: print("Client already exists") else: c.execute("INSERT INTO clients(client_name, email, income) VALUES(?,?,?)", (name, email, income)) conn.commit() def enter_tag (tag_name): #won't crash if tag is already in database c.execute("SELECT tag_name from tags WHERE tag_name = ?", (tag_name,)) exists = c.fetchone() if exists: print("Tag already exists") else: c.execute("INSERT INTO tags(tag_name) VALUES(?)", (tag_name,)) conn.commit() def enter_client_tag(client, tag): #not really sure if I'm doing this right... c.execute("SELECT client, tag FROM client_tags " "WHERE client = ? AND tag = ?", (client, tag)) exists = c.fetchone() if exists: print(client + " has already been associated with " + tag + ".") else: c.execute("INSERT INTO client_tags(client, tag) VALUES(?,?)", client, tag) conn.commit()
a01ae760263715cf870040d7e9e8a96e38e458be
SpencerNinja/practice-coding
/Python/CS1400and1410/2019 03 01 Yahtzee.py
1,109
4.03125
4
# Yahtzee Simulation # Spencer Hurd # Instructions # Write a function called Yahtzee_Simulation() # Simulate rolling 6 dice 1 million times # Keep track of the number of the computer rolls a yahtzee # probability of getting yahtzee=6*5*4*3*2*1 # return the number of wins divided by the number of tries # no print statements # Write a function called main() w no parameters # This function calls the Yahtzee_Simulation function 10 times and prints the result of each simulation # Print the mathematical result: print(6/(6**5)) def Yahtzee_Simulation(): a=random.randint(1,6) b=random.randint(1,6) c=random.randint(1,6) d=random.randint(1,6) e=random.randint(1,6) f=random.randint(1,6) for i in range(): rollout=(a+b+c+d+e+f)*1,000,000 return rollout def main(): min=1 max=6 def test(): count=numberOfRolls while numberOfRolls >= count and count >0: print(random.randint(min,max)) count=count -1 def test2(): total=0 for i in range(): total+=random.randint(1,6) return total
8545ad67add5b9cf6b48b0508459506c824eb4c9
danieltshibangu/Mini-projects
/recursion1and2.py
696
4.0625
4
# Python code to demonstrate printing # pattern of numbers def foo1( n ): if n == 2: return 1 else: return 3 * foo1( n - 1 ) ''' Recursive calls, foo1(5) foo1(5) == 9 * 3 = 27 foo1(4) == 3 * 3 = 9 foo1(3) == 3 * 1 = 3 foo1(2) == 1 ''' def foo2( n ): if n > 0: print( n, end='' ) foo2( n-1 ) ''' Recursive calls, foo2(5) foo2(5) prints 5 foo2(4) prints 4 foo2(3) prints 3 foo2(2) prints 2 foo2(1) prints 1 Output: 54321 ''' if __name__ == '__main__': print( "foo1:", foo1( 5 ) )
6a8806df67796f9a5ca19a6e442a8900e25798f7
sathwikmatcha/project-euler
/#48.py
1,120
3.578125
4
# -*- coding: utf-8 -*- """ Created on Wed Jul 1 15:33:58 2020 @author: Sathwik Matcha """ def factorial(n): if n < 0: return 0 elif n == 0 or n == 1: return 1 else: fact = 1 while(n > 1): fact *= n n -= 1 return fact def C(n,r): return factorial(n)//(factorial(n-r)*factorial(r)) def rem(a,b,base): r=a-b factor=pow(a,r) main=pow(b,10) cnt=9 sum0=0 while(cnt>=0): f=factor*C(b,b-cnt)*main//pow(b,10-cnt) f1=int(f%base) if(f1==0): f=0 sum0+=f cnt-=1 continue else: sum0+=f cnt-=1 continue ans=sum0 return int(ans) base=pow(10,10) N0=10405071317 i=11 ans1=N0 while(i<=1000): if(i%10==0): i+=1 continue else: b=(i//10)*10 ans2=rem(i,b,base) print("ans2= ",ans2) ans1+=ans2 ans1=ans1 print("ans1= ",ans1) i+=1 continue print("") print("") print("") print("") print("") print("") print(ans1%base)
49a2e7a3d570ccbbb1ff55396b8d12f09a5a81ce
AlexGalhardo/Learning-Python
/YouTube Ignorancia Zero/Arquivos/52 - Arquivos II: Bytes e For loops/Jogo.py
6,873
3.734375
4
""" Jogo simples de ataque e cura """ #importa o modulo random import random def Salvar(player_vida, player_sp, inimigos): """ Função usada para salvar o jogo """ pass def CarregaJogo(): """ Função que carrega um jogo """ pass def main(): """ Função Principal do Jogo """ print("BATALHA INJUSTA") #Preiro vemos se o usuário quer carregar ou iniciar um novo jogo opção = SelecionaOpção() #Chamamos a função apropriada de acordo com sua escolha if opção.startswith('n'): player_vida, player_sp, inimigos = NovoJogo() else: player_vida, player_sp, inimigos = CarregaJogo() #Enquanto essa variável for True estaremos rodando o jogo jogando = True while jogando: #Nosso loop do jogo imprimeInfoPlayer(player_vida, player_sp) #pedimos para o player escolher o que fazer atk = oqueFazer() #se ele escolher atacar, devemos: if atk.startswith('a'): Atacar(inimigos) player_vida, player_sp, jogando = RealizaOperações(player_vida, player_sp, inimigos) #caso contrário ele escolheu curar elif atk.startswith('c'): #só podemos curar se o sp do player for maior do que 10 if player_sp >= 10: player_vida, player_sp = Curar(player_vida, player_sp) #se o player tiver menos de 10 de sp else: #imprimimos que o player nao pode se curar print("Sp insuficiente!") player_vida, player_sp, jogando = RealizaOperações(player_vida, player_sp, inimigos) #se o player escolhar salvar elif atk.startswith('s'): Salvar(player_vida, player_sp, inimigos) #Se o player desistir else: #Nós dizemos que a variável jogando é falsa jogando = False def SelecionaOpção(): """ Recebe uma entrada válida sobre o que o usuário quer fazer """ while True: opção = input("Deseja carregar um jogo (c) ou iniciar um novo jogo(n)?\n").lower() if opção.startswith('n') or opção.startswith('c'): return opção else: print("Opção inválida, digite novamente.") def NovoJogo(): """ Cria um novo jogo """ #vida padrao de um inimigo inimigo_vida = 50 inimigos = criaInimigos(inimigo_vida) return 500, 100, inimigos def criaInimigos(inimigo_vida): """ Função que criará uma lista de n inimigos selecionada pelo usuário """ #determina o número de inimigos n = int(input("Digite o número de inimigos:\n")) #vetor que armazena todos os inimigos inimigos = [] #adcionamos ao vetor um vetor com 2 componentes: #o número do inimigo e sua vida for i in range(n): inimigos.append([i+1,inimigo_vida]) return inimigos def imprimeInfoPlayer(HP, SP): """ Imprime a vida e o sp do player na tela """ #Imprimimos na tela a vida print("Vida:", HP) #e o sp do player print("SP:", SP) def oqueFazer(): """ Função que garente que o usuário digitará uma opção válida """ while True: escolha = input("Deseja atacar (a), curar (c), salvar(s), ou desistir(d)?\n").lower() if not escolha.isalpha(): print("Digite apenas letras.") elif not (escolha.startswith('a') or escolha.startswith('c') or escolha.startswith('s') or escolha.startswith('d')): print("Digite uma opção válida") else: return escolha def Atacar(inimigos): """ Função realiza operações relacionadas a escolha do player em atacar """ #escolher aleatoriamente um inimigo para ser atacado selecionado = random.choice(inimigos) #determinar o dano causado dano = random.randint(10, 15) #imprimir essas informações para o usuário print("Causou %i de dano ao inimigo %i!"%(dano, selecionado[0])) #diminuir da vida do inimigo o dano selecionado[1] -= dano #se a vida do inimigo for zerada, devemos: if selecionado[1] <= 0: #dizer que o inimigo morreu print("Inimigo %i morreu!"%selecionado[0]) #e remover esse inimigo da lista de inimigos inimigos.remove(selecionado) def Curar(player_vida, player_sp): """ Função realiza operações relacionadas a escolha do player em curar """ #escolhemos um valor aleatório para a cura cura = random.randint(10, 15) #imprimimos quanto o player recebeu de cura print("Você recebeu %i de vida!"%cura) #adcionamos isso a vida do player player_vida += cura #e diminuimos em 10 o sp do player player_sp -= 10 return player_vida, player_sp def RealizaOperações(player_vida, player_sp, inimigos): """ Realiza os calculos e ataques depois do player ter escolhido uma ação """ player_vida = AtaqueInimigo(player_vida, inimigos) #depois devemos aumentar o sp do player if player_sp < 100: #aumentamos em 3 toda rodada player_sp += 3 #mas o player nunca pode ter mais de 100 de sp if player_sp > 100: player_sp = 100 #depois verificamos se o jogo acabou jogando = VerificaSeAcabou(player_vida, inimigos) return player_vida, player_sp, jogando def AtaqueInimigo(player_vida, inimigos): #depois disso é a vez dos inimigos atacarem for inimigo in inimigos: #escolhemos se o inimigo vai acertar ou errar #o inimigo tem 75% de chance de acertar acertou = bool(random.choice([1,1,1,0])) #se ele acertar, devemos: if acertou: #escolher um dano causado ao player dano = random.randint(1, 3) #imprimir a msg do dano print("Inimigo %i causou %i de dano!"%(inimigo[0], dano)) #diminuir a vida do player player_vida -= dano #caso contrário else: #devemos informar que o inimigo errou print("Inimigo %i errou o ataque!"%inimigo[0]) return player_vida def VerificaSeAcabou(player_vida, inimigos): """ Verifica se o jogo acabou, observando a vida do player e o número de inimigos """ #se a vida do player for < 0 ele perdeu if player_vida <= 0: print("Perdeu o jogo!") return False #se o número de inimigos for zero ele venceu if len(inimigos) == 0: print("Parabens você ganhou o jogo!") return False return True main()
d889543a31e3a3071202afbb04b55e5d2df9a48d
aniruddhamurali/Project-Euler
/src/Python/Problem41.py
1,201
3.71875
4
import math import itertools def isprime(n): """Checks number (n) for primality, and returns True of False.""" n = abs(n) if n < 2: return False if n == 2: return True if not n % 1 == 0: return False if n % 2 == 0: return False for x in range(3, round(math.sqrt(n)) + 1, 2): if n % x == 0: return False return True def pandigital_prime(): maxpandigitalprime = 1 fourDigitPermutations = list(itertools.permutations([1,2,3,4],4)) sevenDigitPermutations = list(itertools.permutations([1,2,3,4,5,6,7],7)) for fourDigitTuple in fourDigitPermutations: fourDigitList = list(fourDigitTuple) num = '' for i in fourDigitList: num = num + str(i) if isprime(int(num)) == True: maxpandigitalprime = int(num) for sevenDigitTuple in sevenDigitPermutations: sevenDigitList = list(sevenDigitTuple) num = '' for i in sevenDigitList: num = num + str(i) if isprime(int(num)) == True: maxpandigitalprime = int(num) return maxpandigitalprime # The answer is 7652413
a4fd327e609889ed1667efcd7e490191bac65b01
97cool-vikas/Interviewbit
/Python3/Arrays/Bucketing/Maximum Consecutive Gap.py
757
3.78125
4
''' Given an unsorted array, find the maximum difference between the successive elements in its sorted form. Try to solve it in linear time/space. Example : Input : [1, 10, 5] Output : 5 Return 0 if the array contains less than 2 elements. You may assume that all the elements in the array are non-negative integers and fit in the 32-bit signed integer range. You may also assume that the difference will not overflow. ''' class Solution: # @param A : tuple of integers # @return an integer def maximumGap(self, A): A = list(A) A.sort() ans = 0 if len(A)<2: return 0 for j in range(len(A)-1): if(A[j+1]-A[j]>ans): ans = A[j+1]-A[j] return ans
89548131b010ebc9a7e2fba774af1861f51a951c
mentalcic/lpthw
/ex29_study_drill.py
1,884
3.984375
4
# Study Drill 4. # Can you put other Boolean expressions from Exercise 27 in the if-statement? # Try it. ################### print("\n\nExample 1:\n") a1 = True b1 = 1 != 0 and 2 == 1 print("Printing value of a1:", a1) print("Printing value of b1:", b1) if a1 != b1: print(f"{a1} is not equal to {b1}!") if a1 == b1: print(f"{a1} is equal to {b1}!") ################### print("\n\nExample 2:\n") a2 = "chunky" == "bacon" and (not (3 == 4 or 3 == 3)) b2 = 3 == 3 and (not ("testing" == "testing" or "Python" == "Fun")) print("Printing value of a2:", a2) print("Printing value of b2:", b2) if a2 != b2: print(f"{a2} is not equal to {b2}!") if a2 == b2: print(f"{a2} is equal to {b2}!") ################### print("\n\nExample 3:\n") # define variables # define a procedure to nest some if statements # and create a self loop like in main function from ex23 # execute the procedure to process the variables # Next step is to # - ask user to input numbers a3 and b3 # - ask for the increment # - ask for True of False a3 = 10 b3 = 14 c3 = True # Try with c3 = False :) print(f"Value a3 = {a3}") print(f"Value b3 = {b3}") print(f"Value c3 = {c3}") print("\n") def compare_variables(a3, b3, c3): if a3 < b3: print(f"{a3} is less than {b3}.") if a3 == b3: print(f"{a3} is equal to {b3}.") if a3 > b3: print(f"{a3} is greater than {b3}.") if c3 != (a3 == b3): print(f"{not c3}! I do not comply! Move! On with it!") if c3 == (a3 == b3): print(f"{not c3}, I agree with this!") return print(f"Values are a3 = {a3} and b3 = {b3}. Value c3 = {c3} now looks important.") print("Adding more value to the first one") a3 += 1 print(f"Values are a3 = {a3} and b3 = {b3}. Do not pay attention to value c3 = {c3}") return compare_variables(a3, b3, c3) compare_variables(a3, b3, c3)
f9e9329b0efe777fe2ce07ffc8e0c7cfa3c165d7
mvpfreddy7/python01
/Assignments/assignment_3.3_Freddy_Sanchez.py
267
4.34375
4
#assignment_3.3 gpa = raw_input("enter your GPA:") gpa = float(gpa) if gpa < 0.0 or gpa > 1.0: print "value out of range" elif gpa >= 0.9: print "A" elif gpa >= 0.8: print "B" elif gpa >= 0.7: print "C" elif gpa >= 0.6: print "D" elif gpa < 0.6: print "F"
e2967c3c1d551f7c929b16071d1645feca3ea03c
IronE-G-G/algorithm
/leetcode/340lengthOfLongestSubstringKDistinct.py
1,332
3.5
4
""" 340 至多包含k个不同字符的最长子串 给定一个字符串 s ,找出 至多 包含 k 个不同字符的最长子串 T。 示例 1: 输入: s = "eceba", k = 2 输出: 3 解释: 则 T 为 "ece",所以长度为 3。 示例 2: 输入: s = "aa", k = 1 输出: 2 解释: 则 T 为 "aa",所以长度为 2。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/longest-substring-with-at-most-k-distinct-characters 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ class Solution(object): def lengthOfLongestSubstringKDistinct(self, s, k): """ :type s: str :type k: int :rtype: int """ N = len(s) max_len = 0 counter = 0 lookup = dict() left, right = 0, 0 while right < N: if s[right] not in lookup: lookup[s[right]] = 0 counter += 1 lookup[s[right]] += 1 right += 1 while counter > k: if lookup[s[left]] == 1: counter -= 1 lookup.pop(s[left]) else: lookup[s[left]] -= 1 left += 1 max_len = max(max_len, right - left) return max_len
f75b769d78a1c1436f9054cbaaa5a3f39e46f85a
medaey/bts-sio-public
/01_Algorithme/012_python/2021-10-21_listeBis.py
937
4.25
4
# Tableaux - Listes en python # Liste : ensemble d'elements de types quelconques # Creation d'une liste vide # 2 methodes maliste1 = [] maliste2 = list(); # Creation d'une liste non vide maListe3 = ['Bonjour', 3.14, 45, 'A', True] # Taille d'une liste fonction len() print("taille de la liste maliste3: ", len(maListe3)) print(maListe3) for i in range(0, len(maListe3)): print(maListe3[i]) if maListe3[i] == 45 : print("Trouve") # Ajouter un element a la liste : fonction append print(maliste1) maliste1.append("salut") maliste1.append(8) print(maliste1) # Enlever un element de la liste fonction remove # en specifiant l'element a supprimer maListe3.remove(3.14) print(maListe3) # Enlever un element de la liste fonction delete ou del # en specifiant son indice dans la liste del maListe3[1] print(maListe3) maListe4 = [1,2,3] maliste1.append(maListe4) print(maliste1)
18868c724ba1655e0b9fc82014dd7e5453380822
lmb633/leetcode
/98isValidBST.py
2,001
3.84375
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def isValidBST(self, root): result, _, _ = self.isvalid(root) return result def isvalid(self, root): if root is None: return True, None, None if root.left is None and root.right is None: return True, root.val, root.val left, left_min, left_max = self.isvalid(root.left) right, right_min, right_max = self.isvalid(root.right) flag = True if left_max and left_max >= root.val: flag = False if right_min and right_min <= root.val: flag = False return left and right and flag, left_min if left_min is not None else root.val, right_max if right_max is not None else root.val class Solution2(object): def isValidBST(self, root): if root is None: return True stack = [] last = float('-inf') while True: while root is not None: stack.append(root) root = root.left root = stack.pop() # print(root.val, last) if root.val <= last: return False last = root.val root = root.right if not stack and root is None: return True class Solution3(object): def isValidBST(self, root): result = self.isvalid(root, float('-inf'), float('inf')) return result def isvalid(self, root, lower, higher): if root is None: return True if higher <= root.val or root.val <= lower: return False if not self.isvalid(root.left, lower, root.val): return False if not self.isvalid(root.right, root.val, higher): return False return True
0eb5cbf11d3e2ee30d125685752dfa78519f9805
Rohitguptashaw/My-first-games-and-codes
/count substrings in a string.py
206
3.609375
4
def abc(str1,str2): cont=0 for i in range(len(str1)): if(str1[i:i+len(str2)]==str2): cont+=1 return cont str1=input("string1") str2=input("sub") q=abc(str1,str2) print(q)
87671e2d65148179d961a58f841533b4777c6f15
MarioCioara/PEP21G01
/modul4/modul4_1.py
2,495
3.71875
4
#dictionare # my_dict = { # 'key1': 'value1', # 1: '1', # None: print, # (1,2): 'list' # # } # for key in my_dict.keys(): # print('keys: ',key) # print() # for value in my_dict.values(): # print('values: ',value) # for key, value in my_dict.items(): # print(key, value) #Vrem sa aflam magazinul cu cele mai bune preturi # shop1 = {'mere': 10, 'pere': 15, 'prune': 6, 'ananas': 20} #produs : pret # shop2 = {'mere': 11, 'pere': 15, 'prune': 6} #produs : pret # shop3 = {'mere': 10, 'pere': 16, 'prune': 7, 'papaya': 25} #produs : pret # # need_to_buy = {'mere': 2, 'pere': 3, 'prune': 6} #produs : cantitate # # available_shops = {'a': shop1, 'b': shop2, 'c': shop3} # # def best_buy(available_shops,need_to_buy): # min_price = None # nume_magazin='' # for shop_name,content in available_shops.items(): # suma1 = 0 # for product,quantity in need_to_buy.items(): # suma1 = content.get(product) * quantity # # print('Suma partiala in',shop_name,'=',suma1) # if min_price is None or min_price > suma1: # min_price=suma1 # nume_magazin = shop_name # # # print(min_price) # print(nume_magazin) # best_buy(available_shops=available_shops,need_to_buy=need_to_buy) #------------------------------------------------------------------------------------------ # def down(nr): # nr = nr - 1 # if nr>0: # return down(nr) # else: # return nr # # print(down(10)) #---------------------------------------------------------------------- #Flat list recursiv # data = [1, [2, [3]], 4, [5, [6]], 7, [8, [9]]] # # # def flatten_list(complex_list): # flat_list = [] # for obj_primary in complex_list: # if(type(obj_primary) == list): # result = flatten_list(obj_primary ) # flat_list.extend(result) # else: # flat_list.append(obj_primary) # # return flat_list # # final_list = flatten_list(data) # print('Final list is: ',final_list) #------------------------------------------------------------------------------ #Return a list with the names that have the sum of the number > 50 my_dict = {'Ana': 762399332,'Adi': 723432145,'Bogdan': 750567987} def return_name(dict): lista = [] for nume,nr in dict.items(): s = 0 for cifra in str(nr): s = s + int(cifra) if (s > 50): lista.append(nume) return lista print(return_name(my_dict))
9451ae5b2018d7fa40c0b5d27d654325899e28ef
brookeclouston/Sudoku
/build_graph.py
3,834
3.828125
4
""" Author: Brooke Clouston Date Created: August 24 2019 Creates and displays a sudoku board. """ import random class Graph: """ Class: Graph Creates and displays a sudoku board. """ def __init__(self): """ Function: __init__ Initializes empty game board. """ self.board = [["x", "x", "x", "x", "x", "x", "x", "x", "x"], ["x", "x", "x", "x", "x", "x", "x", "x", "x"], ["x", "x", "x", "x", "x", "x", "x", "x", "x"], ["x", "x", "x", "x", "x", "x", "x", "x", "x"], ["x", "x", "x", "x", "x", "x", "x", "x", "x"], ["x", "x", "x", "x", "x", "x", "x", "x", "x"], ["x", "x", "x", "x", "x", "x", "x", "x", "x"], ["x", "x", "x", "x", "x", "x", "x", "x", "x"], ["x", "x", "x", "x", "x", "x", "x", "x", "x"]] def build_table(self): """ Function: build_table Generates a random number of spaces to fill and creates board. """ spaces_to_fill = random.randint(5, 50) # this could be config to add difficultly level print("SPACES TO FILL: ", spaces_to_fill) while spaces_to_fill > 0: row = random.randint(0, 8) col = random.randint(0, 8) element = self.board[row][col] if element != "x": continue num = random.randint(1, 9) if not self.validate(num, row, col): continue self.board[row][col] = num spaces_to_fill -= 1 return self.board def validate(self, num, row, col): """ Function: validate Convience function to validate row, column and squares. """ if self.check_row(num, row) and \ self.check_column(num, col) and self.check_square(num, row, col): return True return False def check_row(self, num, row): """ Function: check_row Validates rows. """ if num in self.board[row]: return False return True def check_column(self, num, col): """ Function: check_column Validates columns. """ for row in self.board: if row[col] == num: return False return True def check_square(self, num, row, col): """ Function: check_square Validates square by separating rows. """ if row <= 2: return self.square_list(col, num, self.board[0], self.board[1], self.board[2]) if 2 < row <= 5: return self.square_list(col, num, self.board[3], self.board[4], self.board[5]) if row > 5: return self.square_list(col, num, self.board[6], self.board[7], self.board[8]) def square_list(self, col, num, row1, row2, row3): """ Function: square_list Validates squares by building a list out of columns found in rows. """ if col <= 2: square_list = row1[0:3] + row2[0:3] + row3[0:3] elif 3 <= col <= 5: square_list = row1[3:6] + row2[3:6] + row3[3:6] elif col > 5: square_list = row1[6:9] + row2[6:9] + row3[6:9] if num in square_list: return False return True def display(self): """ Function: display Displays the current board. """ row_count = 0 for row in self.board: col_count = 1 if row_count in [3, 6]: print("\n- - - - - - - - - - -") else: print() row_count += 1 for element in range(9): if col_count in [3, 6]: print(row[element], end=" | ") else: print(row[element], end=" ") col_count += 1
8a2368590945c5748d7423751ae5f7ba3558db2f
musawakiliML/Project-Euler-Challenge
/Even Fibonacci Numbers.py
1,087
4.09375
4
''' Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. ''' def Fibonacci_even_valued_terms(n): f = [0, 1] even_values = 0 for i in range(2, n+1): #f.append(f[i-1] + f[i-2]) if (f(i-1) + f(i-2)) % 2 == 0: even_values = even_values + (f(i-1) + f(i-2)) return even_values print(Fibonacci_even_valued_terms(20)) ''' def Fibonacci_even(n): even_values = 0 if n < 0: print("Invalid input!") elif n == 0: return 0 elif n == 1: return 1 else: j = 0 while j < n: #if (Fibonacci_even(i-1) + Fibonacci_even(i-2)) % 2 == 0: #even_values = even_values + (Fibonacci_even(i-1) + Fibonacci_even(i-2)) (Fibonacci_even(n-1) + Fibonacci_even(n-2) j += 1 Fibonacci_even(10) '''
44e6ade8aef823230be98d86773057614536dac5
ganqzz/sandbox_py
/testing/parametrized_tests/test_tennis_unittest.py
630
3.75
4
import unittest from tennis import score_tennis class TennisTest(unittest.TestCase): def test_score_tennis(self): test_cases = [ (0, 0, "Love-All"), (1, 1, "Fifteen-All"), (2, 2, "Thirty-All"), (2, 1, "Thirty-Fifteen"), (3, 1, "Forty-Fifteen"), (4, 1, "Win for Player 1"), ] for player1_points, player2_points, expected_score in test_cases: with self.subTest(f"{player1_points}, {player2_points} -> {expected_score}"): self.assertEqual(expected_score, score_tennis(player1_points, player2_points))
8c209f0a80f85c8f016910a3dc88bddb77387305
Torisels/pipr
/pipr5_6/music.py
2,072
3.609375
4
import time import datetime class Artist: def __init__(self, first_name, last_name, nickname, albums=None, songs=None): self.first_name = first_name self.last_name = last_name self.nickname = nickname self.albums = albums self.songs = songs class Album: def __init__(self, title, publication_date, songs): self.title = title self.publication_date = publication_date self.songs = songs def __len__(self): return self.total_time() def total_time(self): total_time = sum([s.time for s in self.songs], datetime.timedelta()) hours, minutes, seconds = self.split_time_delta(total_time) return f"Total time of album is: {hours:02}:{minutes:02}:{seconds:02} (HH:mm:ss)" @staticmethod def split_time_delta(time_delta): """ :param time_delta: Length of sum as a timedelta object :type time_delta: datetime.timedelta :rtype: tuple(int,int,int) """ minutes, seconds = divmod(time_delta.seconds + time_delta.days * 86400, 60) hours, minutes = divmod(minutes, 60) return hours, minutes, seconds def play(self, first_song_index=0): for song_index in range(first_song_index, len(self.songs)): self.songs[song_index].play() class Song: def __init__(self, title, time): """ :param title: Title of the song. :type title: str :param length: Length of song as a time object :type length: datetime.timedelta """ self.title = title self.time = time def play(self): print(f"The {self.title} is playing na na na for {self.time}") time.sleep(3) s1 = Song("Przekorny los", datetime.timedelta(minutes=3, seconds=2)) s2 = Song("Nie daj sie", datetime.timedelta(minutes=2, seconds=10)) s3 = Song("Lalala", datetime.timedelta(minutes=1, seconds=10)) album = Album("Przeboje polskiej muzyki", datetime.datetime(day=2, month=11, year=2000), [s1, s2, s3]) album.play(1) print(album.total_time())
08c6a71851ce62d88021710ee2c40859411f7de8
Luke-Beausoleil/ICS3U-Unit4-06-Python-RGB_values
/rgb_values.py
523
4.28125
4
#!/usr/bin/env python3 # Created by: Luke Beausoleil # Created on: May 2021 # This program returns all possible RGB values def main(): # this function outputs the RGB values # variables red = 0 green = 0 blue = 0 # process & output for red in range(256): for green in range(256): for blue in range(256): print("RGB({0}, {1}, {2})".format(red, green, blue)) blue += 1 green += 1 red += 1 if __name__ == "__main__": main()
417fec87ee612ce9218b2a5686a502cd0461a84f
azewierzejew/IPP-male-zadanie-testy
/src/chooseCommentToEOFVariant.py
1,007
3.578125
4
#!/usr/bin/python3 from shutil import copyfile from os import getcwd cwd = getcwd() info = ''' Choose out when there's comment without newline (ends with EOF): error - there should be error message printed (cause line without newline) nothing - nothing should be printed (cause it's a comment) Please write your decision (error/nothing): ''' decision = input(info) while decision != "error" and decision != "nothing": decision = input("Please write 'error' or 'nothing': ") print("You choose: " + decision) def copyfileverbose(src, dst): print("Copying " + src + " to " + dst) copyfile(src, dst) if decision == "error": copyfileverbose(cwd + "/storage/end5.errorvariant.out", cwd + "/end5.decided.out") copyfileverbose(cwd + "/storage/end5.errorvariant.err", cwd + "/end5.decided.err") if decision == "nothing": copyfileverbose(cwd + "/storage/end5.noerrorvariant.out", cwd + "/end5.decided.out") copyfileverbose(cwd + "/storage/end5.noerrorvariant.err", cwd + "/end5.decided.err") print()
7d0e03984c3487726420d25da0e8fef5e9ec8be1
naitikshukla/practice
/sample_problems/Fredo and Array Update.py
537
3.75
4
num='15' #input 1 array = "1 2 3 4 5 6 7 8 9 10 89 21 27 98 56 23 12 23 43 98 198 22210" #input 2 array = [int(i) for i in array.split()] #convert to list in integer num = int(num) #cast integer sm = sum(array) #Find sum #print("sum is",sm) print("result is",int(sm/num)+1) #final result
7ee55c8aa1a0e4b79530f09ac7eb95309f16cb26
S-pl1ng/python-web-scraping
/re_assgn.py
404
3.796875
4
#This assignment involves using Regular Expressions (RegEx) to extract and sum all numbers from a given file import re file = open(r"C:\Users\Hp\python_web_course\actual_data.txt") total=0 for line in file: line=line.rstrip() num_list = re.findall("[0-9]+", line) if len(num_list)>0: for i in range(len(num_list)): total+=int(num_list[i]) print("Total sum is: ", total)
0dbfc386fdd5f9e34e8918315aefef921940eadc
greenfox-zerda-lasers/hvaradi
/week-03/day-3/pirate.py
839
3.859375
4
# create a pirate class # it should have 2 methods # drink_rum() # hows_goin_mate() # if the drink_rum was called at least 5 times: # hows_goin_mate should return "Arrrr!" # "Nothin'" otherwise class Pirate(): def __init__(self, name, age, hair): self.alcohol=0 self.name=name self.age=age self.hair=hair def drink_rum(self, alcohol): self.alcohol = self.alcohol + alcohol def describe(self): print("His name is:", self.name, "Age is:", self.age, "Hair is like:", self.hair) def hows_goin_mate(self): if self.alcohol >= 5: print("Arrrr!") else: print("Nothing!") joe=Pirate("Joe",46,"redhead") print(joe.alcohol) joe.hows_goin_mate() joe.drink_rum(6) joe.hows_goin_mate() # print(joe.alcohol) # joe.drink_rum(4) # joe.describe()
08c46ef56d05d1d908a47b8d632ae1e7e8074fbb
tushargoyal02/python
/10.py
337
4.09375
4
#! /usr/bin/python3 a=input("enter a number") b=input("enter b number") def name(a,b): # here a=hello and b=world # so var2 will be helloworld here var2=a+b print(var2,"<-- this is inside") # whille return var2(helloworld) return var2 print(name(a,b)) # here print is helloworld var2=a print("outside",var2) #output -> hello
bb7f07e4c921c723da11a3719cb9475db4d828d7
Shakirsadiq6/Basic-Python-Programs
/Basics_upto_loops/Loops/series.py
264
3.78125
4
'''Add first seven terms of 1/1! + 2/2! + 3/3! + ...''' __author__ = "Shakir Sadiq" SUM = 0 for i in range(1,8): FACTORIAL = 1 for j in range(1,i+1): FACTORIAL *= j division = i/FACTORIAL SUM += division print("Sum of First Seven Terms=", SUM)
e4a04e3d952f4bbad3029dcdcdf7d074a2f52670
weshao/LeetCode
/96.不同的二叉搜索树.py
1,676
3.5
4
# # @lc app=leetcode.cn id=96 lang=python3 # # [96] 不同的二叉搜索树 # # https://leetcode-cn.com/problems/unique-binary-search-trees/description/ # # algorithms # Medium (69.24%) # Likes: 934 # Dislikes: 0 # Total Accepted: 98.1K # Total Submissions: 141.8K # Testcase Example: '3' # # 给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种? # # 示例: # # 输入: 3 # 输出: 5 # 解释: # 给定 n = 3, 一共有 5 种不同结构的二叉搜索树: # # ⁠ 1 3 3 2 1 # ⁠ \ / / / \ \ # ⁠ 3 2 1 1 3 2 # ⁠ / / \ \ # ⁠ 2 1 2 3 # # # @lc code=start # class Solution: # def numTrees(self, n: int) -> int: # if not n: return 0 # dp = [1 for _ in range(n+1)] # for i in range(2, n+1): # _sum = 0 # for j in range(i): # _sum += dp[j] * dp[i-j-1] # dp[i] = _sum # return dp[n] class Solution: def numTrees(self, n: int) -> int: if not n: return 0 dp = [0 for i in range(n+1)] def dfs(n): if n <= 1: return 1 if dp[n]: return dp[n] else: count = 0 for i in range(1, n+1): leftCount = dfs(i-1) rightCount = dfs(n-i) count += (leftCount * rightCount) dp[n] = count return count return dfs(n) # @lc code=end so = Solution() ans = so.numTrees(3) print(ans)
f79757553d52dfd984ce02d5afd10842f25de626
Fondamenti18/fondamenti-di-programmazione
/students/761660/homework01/program01.py
1,325
3.71875
4
''' Si definiscono divisori propri di un numero tutti i suoi divisori tranne l'uno e il numero stesso. Scrivere una funzione modi(ls,k) che, presa una lista ls di interi ed un intero non negativo k: 1) cancella dalla lista ls gli interi che non hanno esattamente k divisori propri 2) restituisce una seconda lista che contiene i soli numeri primi di ls. NOTA: un numero maggiore di 1 e' primo se ha 0 divisori propri. ad esempio per ls = [121, 4, 37, 441, 7, 16] modi(ls,3) restituisce la lista con i numeri primi [37,7] mentre al termine della funzione si avra' che la lista ls=[16] Per altri esempi vedere il file grade.txt ATTENZIONE: NON USATE LETTERE ACCENTATE. ATTENZIONE: Se il grader non termina entro 30 secondi il punteggio dell'esercizio e' zero. ''' l1=[] ls=[] def primi (a): b=2 if ((b**(a-1))% a)==1: return True return False def modi(ls,k): lp=[] for i in ls: b=i if primi(b)==True: lp+=[b] ls.remove(b) l1=ls[:] for e in l1: conta=0 for d in range(2,e,1): if(e%d==0): conta+=1 if(conta>k): ls.remove(e) break if((e in ls) and (conta<k or conta>k)): ls.remove(e) return lp
f009e2fc2448e512e03b65cd463749515db12bfe
dreamgonfly/py-ng-ml
/machine-learning-ex1/ex1/ex1.py
4,118
4.0625
4
## Machine Learning Online Class - Exercise 1: Linear Regression # Instructions # ------------ # # This file contains code that helps you get started on the # linear exercise. You will need to complete the following functions # in this exericse: # # warmUpExercise.py # plotData.py # gradientDescent.py # computeCost.py # gradientDescentMulti.py # computeCostMulti.py # featureNormalize.py # normalEqn.py # # For this exercise, you will not need to change any code in this file, # or any other files other than those mentioned above. # # x refers to the population size in 10,000s # y refers to the profit in $10,000s # ## Initialization from numpy import * from matplotlib.pyplot import * from mpl_toolkits.mplot3d import axes3d, Axes3D from warmUpExercise import warmUpExercise from plotData import plotData from computeCost import computeCost from gradientDescent import gradientDescent # is there any equivalent to "clear all; close all; clc"? ## ==================== Part 1: Basic Function ==================== # Complete warmUpExercise.py print('Running warmUpExercise ... ') print('5x5 Identity Matrix: ') print(warmUpExercise()) print('Program paused. Press enter to continue.') input() ## ======================= Part 2: Plotting ======================= print('Plotting Data ...') data = loadtxt('./ex1data1.txt', delimiter=',') X = data[:, 0]; y = data[:, 1] m = len(y) # number of training examples # Plot Data # Note: You have to complete the code in plotData.py firstPlot = plotData(X, y) firstPlot.show() print('Program paused. Press enter to continue.') input() ## =================== Part 3: Gradient descent =================== print('Running Gradient Descent ...') X = column_stack((ones(m), data[:,0])) # Add a column of ones to x theta = zeros(2) # initialize fitting parameters # Some gradient descent settings iterations = 1500 alpha = 0.01 # compute and display initial cost print(computeCost(X, y, theta)) # run gradient descent theta, J_history = gradientDescent(X, y, theta, alpha, iterations) #pdb.set_trace() # print theta to screen print('Theta found by gradient descent: ',) print('%f %f ' % (theta[0], theta[1])) # Plot the linear fit hold(True) # keep previous plot visible plot(X[:,1], X.dot(theta), '-') legend(('Training data', 'Linear regression')) firstPlot.show() # not sure how to avoid overlaying any more plots on this figure - call figure()? # Predict values for population sizes of 35,000 and 70,000 predict1 = array([1, 3.5]).dot(theta) #pdb.set_trace() print('For population = 35,000, we predict a profit of %f' % (predict1 * 10000)) predict2 = array([1, 7]).dot(theta) print('For population = 70,000, we predict a profit of %f' % (predict2 * 10000)) print('Program paused. Press enter to continue.') input() ## ============= Part 4: Visualizing J(theta_0, theta_1) ============= print('Visualizing J(theta_0, theta_1) ...') # Grid over which we will calculate J theta0_vals = linspace(-10, 10, 100) theta1_vals = linspace(-1, 4, 100) # initialize J_vals to a matrix of 0's J_vals = zeros((len(theta0_vals), len(theta1_vals))) # Fill out J_vals for i in range(len(theta0_vals)): for j in range(len(theta1_vals)): t = array((theta0_vals[i], theta1_vals[j])) J_vals[i][j] = computeCost(X, y, t) # Because of the way meshgrids and mplot3d work, we need to transpose # J_vals before plotting the surface, or else the axes will be flipped J_vals = J_vals.T # Surface plot fig = figure() ax = Axes3D(fig) #pdb.set_trace() sX, sY = meshgrid(theta0_vals, theta1_vals) ax.plot_surface(sX, sY, J_vals, rstride=3, cstride=3, cmap=cm.jet, linewidth=0) xlabel('$\\theta_0$') ylabel('$\\theta_1$') fig.show() # Contour plot fig = figure() # Plot J_vals as 20 contours spaced logarithmically between 0.01 and 1000 contour(sX, sY, J_vals, logspace(-2, 2, 20)) xlabel('$\\theta_0$') ylabel('$\\theta_1$') hold(True) plot(theta[0], theta[1], 'rx', markersize=10, linewidth=2) fig.show() print('Program paused. Press enter to continue. Note figures will disappear when Python process ends.') input()
3f35bb52c28eddd26b14847e2111afb2a0ed62fe
sunilsm7/python_exercises
/Python_practice/practice_01/sentenceAbrevation.py
1,586
4.3125
4
""" Write a python function which accepts a sentence and converts it into an abbreviated sentence to be sent as SMS and returns the abbreviated sentence. Rules to follow while shortening: A. Spaces are to be retained as is, i.e. even multiple spaces are to be retained. B. Each word should be encoded separately - If a word has only vowels then retain the word as is. - If a word has a consonant (at least 1 ) then retain only those consonants. Example: Input 1 : I love India Output 1 : I lv nd Input 2 : MSD says I love cricket and tennis too Output 2 : MSD sys I lv crckt nd tnns t Input 3 : I will not repeat mistakes Output 3: I wll nt rpt mstks """ """ Solution: 1. Split the sentence based on a single space to create a list of words. 2. Individually check if each word is made of only vowels or not. 3. If No, then remove the vowels, we can use regulat expressions to do that. re.sub(r'<the_pattern>','<replaced_with','<the_string>') replace the pattern in first argument with the second argument. 4. Join them back to form the sentence. """ import re def is_all_vowels(word): count = 0 for item in word: if item in ['a','A','e','E','i','I','o','O','u','U']: count += 1 if count == len(word): return True else: return False def compress(msg): words_list = msg.split(' ') # this returns the spaces for i in range(0, len(words_list)): word = words_list[i] if not is_all_vowels(word): words_list[i] = re.sub(r"[aAeEiIoOuU]","", word) print(words_list) return " ".join(words_list) print(compress("I will not repeat mistakes"))
683145a8cef1f4a7c8147c43732b62069accd123
Harisha-1990/PythonCoding
/38_tuple.py
234
4.21875
4
my_tuple = (1,2,3,4,5) print(my_tuple[1]) # just like a list we can access tuple through index print(5 in my_tuple) user ={ (1,2):[1,2,3] #we're trying to use tuple inside dictionary ,'greet':'hello' ,'age':20 } print(user[(1,2)])
cc16aa75d6e7f41724db2b8961f45de632e033c0
FreedomPeace/python
/basicKnowledge/02DataType.py
252
3.921875
4
a = 3 print(a) print(type(a)) a = 3.22 print(type) print(type(a)) a = True # bool类型两个值 True False print(type(a)) # str类型 a = "i am a it programmer" print(type(a)) # 多行字符串 a = """ dog cat sheep """ print(a) print(type(a))
f1c98bb1103fbfce19d8700d1a2ef5c5bd3af542
acacivare12/Mock-Atm3-
/auth.py
3,247
4.03125
4
#register # - first name, last name, password, email # - generate user account #login # - account number & password #bank operations #Initializing the system import random import validation import database from getpass import getpass def init(): print("Welcome to bankPhP") haveAccount = int(input("Do you have an account with us: 1 (yes) 2 (no) \n")) if(haveAccount == 1): login() elif(haveAccount ==2): register() else: print("You have selected invalid option") init() def login(): print("****** Login *****") accountNumberFromUser = input("What is your account number? \n") isValidAccountNumber= validation.accountNumberValidation(accountNumberFromUser) if isValidAccountNumber: password = getpass("What is your password \n ") user = database.authenticate_user(accountNumberFromUser, password) if user: database.user_auth_session(accountNumberFromUser, user) bankOperation(user, accountNumberFromUser) print("Invalid account or password") login() else: print("Account Number Invalid: check that you have up to 10 digits and only integers") init() def register(): print(" ******Register ******") email = input("What is your email address? \n") first_name = input("What is your first name? \n") last_name = input("What is your last name? \n") password = getpass("Create a password for yourself \n") accountNumber =generateAccountNumber() isUserCreated = database.create(accountNumber, email, first_name, last_name, password) if isUserCreated: print("Your Account Has been created") print("== ==== ===== ===== ===") print("Your account number is: %d" % accountNumber) print("Make sure you keep it safe") print("== ==== ===== ===== ===") login() else: print("something went wrong, please try again") register() print("Your Account Has Been Created") login() def bankOperation(user, accountNumberFromUser): print("Welcome %s %s" % (user[0], user [1])) selectedOption = int(input("what would you like to do? (1) deposit (2) withdrawal (3) Logout (4) Exit \n")) if(selectedOption == 1): depositOperation() elif(selectedOption == 2): withdrawalOperation() elif(selectedOption == 3): logout(accountNumberFromUser) elif(selectedOption == 4): exit() else: print("Invalid option selected") bankOperation(user, accountNumberFromUser) def withdrawalOperation(): print("withdrawal") def depositOperation(): print("Deposit Operations") def generateAccountNumber(): return random.randrange(1111111111,9999999999) def setCurrentBalance(userDetails, balance): userDetails[4] = balance def getCurrentBalance(userDetails): return userDetails[4] def logout(accountNumberFromUser): database.delete_auth_session(accountNumberFromUser) login() #### ACTUAL BANKING SYSTEM #### init()
871e0ddb474c299d725b8416378552bad60219eb
2020rkessler/main-folder
/functions/code-a-long.py
916
3.8125
4
# reading: https://www.codementor.io/kaushikpal/user-defined-functions-in-python-8s7wyc8k2 # built in functions print('hello, I am a function') print(len('hello')) # user defined functions # create a function called find_me() # args1 = arr of ints # arg2 = one number you are looking for # output = 1.) true or false # 2.) print the index value of where that int is def find_me(arr, num): for val in arr: if val == num: print('True') return(True) else: print('False') return(False) # call the method lotto = [24,2123,123,342,345,457,345,24,234,3457,6687,2] ans = find_me(lotto, 2) # required and default arguments def dog(woof, bork='borking so loud'): print(woof,bork) dog('woofwoof') # variable number of arguments def cat(*maths): ans = 1 for x in maths: ans = ans * x print(ans) cat(10,10,10) cat(10)
accd556e0a28cbbb36bf29a59ec23399746bad7e
xiangcao/Leetcode
/python_leetcode_2020/Python_Leetcode_2020/67_add_binary.py
1,272
3.671875
4
""" Given two binary strings, return their sum (also a binary string). The input strings are both non-empty and contains only characters 1 or 0. Constraints: Each string consists only of '0' or '1' characters. 1 <= a.length, b.length <= 10^4 Each string is either "0" or doesn't contain any leading zero. """ class Solution: def addBinary(self, a: str, b: str) -> str: result=[] A = list(a) B = list(b) carry = 0 while A or B or carry: if A: carry += int(A.pop()) if B: carry += int(B.pop()) result.append(str(carry % 2)) carry //= 2 return "".join(result[::-1]) # Round 2 class Solution: def addBinary(self, a: str, b: str) -> str: p1, p2 = len(a)-1, len(b)-1 carry = 0 result = [] while p1 >= 0 or p2 >= 0: value1 = int(a[p1]) if p1 >= 0 else 0 value2 = int(b[p2]) if p2 >= 0 else 0 value = value1 + value2 + carry carry = value // 2 value = value % 2 result.append(value) p1 -= 1 p2 -= 1 if carry > 0: result.append(carry) return "".join(map(str, result[::-1]))
3d6b9f8f450b9d9a53b9a3587a0d8bfe37a49f0a
ShiroOYuki/Leetcode
/Python/94/main.py
723
3.796875
4
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right # Question request:Binary Tree Inorder Traversal(left,root,right) class Solution: def inorderTraversal(self, root: TreeNode): if not root: return if not root.left and not root.right: return [root.val] self.ans = [] def find(node): if not node: return find(node.left) # left first self.ans.append(node.val) # than root find(node.right) # last right find(root) return self.ans """main.py 2 3 1 1,3 2,3 2,1 """
b907c60a2c7ec2e249de8417bd0f649116133d06
kumailn/Algorithms
/Python/Kth_Smallest_Element_in_a_BST.py
833
3.890625
4
# Question: Given the root node of a tree, find the nth smallest element in the tree # Solution: Traverse in order iteratively and keep track of the nth smallest element # Difficulty: Easy def kthSmallest(self, root: TreeNode, k: int) -> int: stack = [] val = None # Iterative in order travesal, keep track of K while (stack or root) and k != 0: while root: stack += [root] root = root.left # Every time we pop something from the stack we know that it's ordered # so subtract 1 from k and set out value to be that nodes value root = stack.pop() k -= 1 val = root.val # Shift node to its right child normally root = root.right return val
6957be286171d7047773134d979048c8b3375a13
Manishthakur1297/Card-Game
/Card_Game_Tests.py
1,923
3.609375
4
import unittest from .Card_Game import Game class MyTestCase(unittest.TestCase): def setUp(self): self.card = Game(4) def test_Condition1_WHEN_ALL_SAME(self): self.card.players = [['A', '7', 'J'], ['2', 'K', '6'], ['6', '9', 'A'], ['5', '5', '5']] self.assertEqual(self.card.winner()+1, 4, "Should be Player 4") def test_Condition2_WHEN_SEQUENCE_IS_THERE(self): self.card.players = [['A', '3', '2'], ['2', 'K', '6'], ['6', '9', 'A'], ['5', '5', '6']] self.assertEqual(self.card.winner()+1, 1, "Should be Player 1") def test_Condition3_WHEN_PAIRS_EQUAL(self): self.card.players = [['A', '4', '2'], ['K', 'K', '6'], ['6', '9', 'A'], ['5', '9', '6']] self.assertEqual(self.card.winner()+1, 2, "Should be Player 2") def test_Condition4_MAXIMUM_SUM_CARDS(self): self.card.players = [['A', '4', '2'], ['K', '2', '6'], ['6', '9', 'J'], ['5', '9', '6']] self.assertEqual(self.card.winner()+1, 3, "Should be Player 3") def test_Condition1_POSITIVE(self): player = ['A', 'A', 'A'] self.assertTrue(self.card.condition1(player)) def test_Condition1_NEGATIVE(self): player = ['A', '4', '2'] self.assertFalse(self.card.condition1(player)) def test_Condition2_POSITIVE(self): player = ['A', '2', '3'] self.assertTrue(self.card.condition2(player)) def test_Condition2_NEGATIVE(self): player = ['A', '4', '2'] self.assertFalse(self.card.condition2(player)) def test_Condition3_POSITIVE(self): player = ['A', 'A', '2'] self.assertTrue(self.card.condition3(player)) def test_Condition3_NEGATIVE(self): player = ['A', '3', '2'] self.assertFalse(self.card.condition3(player)) if __name__ == '__main__': unittest.main()
02a127f12fadce6caa83a161f0ddf6f02b00a84a
naffi192123/Python_Programming_CDAC
/Day1/2-aera_of_circle.py
223
4.3125
4
radius = int(input("Enter the radius: ")) pi = 3.14 if radius <= 0: print("invalid input") else: area = pi*(radius**2) perimeter = 2*pi*radius print("Area of circle is: ", area) print("Perimeter of circle is", perimeter)
3f8e211951fdd7afa36dbba5de54ae62befdf24c
JenZhen/LC
/lc_ladder/company/amzn/oa/Partition_Labels.py
1,223
4
4
#! /usr/local/bin/python3 # https://leetcode.com/problems/partition-labels/ # Example # A string S of lowercase letters is given. We want to partition this string into as many parts as possible # so that each letter appears in at most one part, and return a list of integers representing the size of these parts. # # Example 1: # Input: S = "ababcbacadefegdehijhklij" # Output: [9,7,8] # Explanation: # The partition is "ababcbaca", "defegde", "hijhklij". # This is a partition so that each letter appears in at most one part. # A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts. # Note: # # S will have length in range [1, 500]. # S will consist of lowercase letters ('a' to 'z') only. """ Algo: D.S.: Solution: 有意思 Corner cases: """ class Solution: def partitionLabels(self, S: str) -> List[int]: last = {c: i for i, c in enumerate(S)} res = [] curmax, curstart = 0, 0 for i, c in enumerate(S): curmax = max(curmax, last[c]) if curmax == i: res.append(i - curstart + 1) curstart = i + 1 return res # Test Cases if __name__ == "__main__": solution = Solution()
a51c0fca9a194b149626d8dacc1acc3ec3a45e33
MaximOksiuta/for-dz
/dz8/1.py
1,285
3.625
4
import datetime class Date: def __init__(self, date): self.date = date @classmethod def splitter(cls, date): return list(map(int, date.split('-'))) @staticmethod def validation(date): data = date[2] d = datetime.date.today() date[2] = d.year if data > d.year else 2000 if data < 2000 else data data = date[1] if date[2] == d.year: date[1] = 1 if data < 1 else d.month if data > d.month else data else: date[1] = 1 if data < 1 else 12 if data > 12 else data data = date[0] if date[2] == d.year and date[1] == d.month: date[0] = 1 if data < 1 else d.day if data > d.day else data elif [1, 3, 5, 7, 8, 10, 12].count(date[1]): date[0] = 1 if data < 1 else 31 if data > 31 else data elif [4, 6, 9, 11].count(date[1]): date[0] = 1 if data < 1 else 30 if data > 30 else data else: date[0] = 1 if data < 1 else ((28 if date[2] % 4 else 29) if data > (28 if date[2] % 4 else 29) else data) return date cl = Date(input('Введите дату в формате дд-мм-гггг: ')) result = cl.validation(cl.splitter(cl.date)) print(datetime.date(result[2], result[1], result[0]))
7bfddd5e86844a9a1b79d3675b4a412aec7e88f1
tanran-cn/arithmetic-data_structure-py
/practice/Sum3.py
2,126
3.78125
4
# _*_ coding: utf-8 _*_ # 2019/3/28 16:01 __auther__ = "tanran" """ 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。 注意:答案中不可以包含重复的三元组。 例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4], 满足要求的三元组集合为: [ [-1, 0, 1], [-1, -1, 2] ] """ class Solution: def threeSum(self, nums: list) -> list: result_list = [] for i in range(len(nums)): temp_num = nums[i] temp_list1 =nums[i+1:] for n in range(len(temp_list1)): temp_num2 = temp_list1[n] temp_list2 = temp_list1[n+1:] target = 0 - (temp_num + temp_num2) if target in temp_list2: temp_result = [ temp_num, temp_num2, target ] result_list.append(temp_result) res_list = [] for res in result_list: res.sort() if res in res_list: pass else: res_list.append(res) return res_list class Solution2: def threeSum(self, nums: list) -> list: nums.sort() res = [] for i in range(len(nums)): if i == 0 or nums[i] > nums[i - 1]: l = i + 1 r = len(nums) - 1 while l < r: s = nums[i] + nums[l] + nums[r] if s == 0: res.append([nums[i], nums[l], nums[r]]) l += 1 r -= 1 while l < r and nums[l] == nums[l - 1]: l += 1 while r > l and nums[r] == nums[r + 1]: r -= 1 elif s > 0: r -= 1 else: l += 1 return res s = Solution() s.threeSum([-1,0,1,2,-1,-4])
4237818115065574102271c16c031ffca4dbd8d3
GauriShrimali/Detect-Humans
/detectHuman.py
436
3.65625
4
#PROBLEM STATEMENT 10 #Input: A image contains a human or no human #Output: Prediction if the image contains a human or not import cv2 import imutils det = cv2.HOGDescriptor() det.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector()) image = cv2.imread('img.jpeg') (area, _) = det.detectMultiScale(image) if len(area) == 0: print("Image does not contain any humans!") else: print("Image does contain humans!")
8f0a836523a87dba09a2ca96745a75f1381494cf
Lorenzoksouza/DesafioKoper
/conversor.py
3,643
3.796875
4
from num2words import num2words from tkinter import * def numero_para_extenso(num_inicial="0"): """ Funçâo que converte numeros para seu formato por extenso com a entrada de um numero :param num_inicial: Double :return num_extenso: String """ LANG = 'pt-BR' if num_inicial != '': if num_inicial.find(",") != -1: num_inicial = num_inicial.replace(",", ".") # Verificação do input para ver se é numerico try: var = float(num_inicial) except ValueError: return ("Isso não é um número") # Identificação de casas decimais if num_inicial.find(".") != -1: # Divisão do numero em antes e depois da virgula num_dividido = num_inicial.split(".") num_principal = int(num_dividido[0]) num_decimal = int(num_dividido[1]) else: num_principal = int(num_inicial) num_decimal = 0 # inicialização da variavel que vai guardar numero por extenso num_extenso = "" # Verificação da primeira parte do número if num_principal != 0: num_extenso = num2words(num_principal, lang=LANG) if num_principal == 1: num_extenso = num_extenso + " real" if num_principal > 1: num_extenso = num_extenso + " reais" # Verificação da sugunda parte do número if num_decimal != 0: if num_principal > 0: num_extenso = num_extenso + " e " num_extenso = num_extenso + num2words(num_decimal, lang=LANG) if num_decimal == 1: num_extenso = num_extenso + " centavo" if num_decimal > 1: num_extenso = num_extenso + " centavos" # Retorno do numero ja com as nomenclaturas return num_extenso # Classe para uma tela simples para melhor visualização e utilização class Application: def __init__(self, master=None): self.fontePadrao = ("Arial", "10") self.primeiroContainer = Frame(master) self.primeiroContainer["pady"] = 10 self.primeiroContainer.pack() self.segundoContainer = Frame(master) self.segundoContainer["padx"] = 20 self.segundoContainer.pack() self.terceiroContainer = Frame(master) self.terceiroContainer["padx"] = 20 self.terceiroContainer.pack() self.quartoContainer = Frame(master) self.quartoContainer["pady"] = 20 self.quartoContainer.pack() self.titulo = Label(self.primeiroContainer, text="Conversor de numero para extenso") self.titulo["font"] = ("Arial", "10", "bold") self.titulo.pack() self.numeroLabel = Label(self.segundoContainer, text="Numero", font=self.fontePadrao) self.numeroLabel.pack(side=LEFT) self.numero = Entry(self.segundoContainer) self.numero["width"] = 30 self.numero["font"] = self.fontePadrao self.numero.pack(side=LEFT) self.converter = Button(self.quartoContainer) self.converter["text"] = "Converter" self.converter["font"] = ("Calibri", "8") self.converter["width"] = 12 self.converter["command"] = self.converter_numero self.converter.pack() self.mensagem = Label(self.quartoContainer, text="", font=self.fontePadrao) self.mensagem.pack() def converter_numero(self): num = self.numero.get() num_extenso = numero_para_extenso(num) self.mensagem["text"] = num_extenso root = Tk() Application(root) root.mainloop()
8ec5c6d699c0c7f29e326a10f694608fbb29feaf
Takeda1/pythonPrograms
/src/ericjb/aiprojects/hw6/linalg_hw6.py
813
3.6875
4
""" A short script that will contain solutions to numpy exercises for CS444 HW6. """ import numpy as np # Declare numpy arrays here... A = np.array([[ 2, -5, 1], [ 1, 4, 5], [ 2, -1, 6]]) B = np.array([[ 1, 2, 3], [ 3, 4, -1]]) y = np.array([[ 2], [-4], [ 1]]) z = np.array([[-15], [ -8], [-22]]) # Print out the result of computations... print "BA:\n",np.dot(B,A) print "\nAB':\n",np.dot(A,B.T) print "\nAy:",np.dot(A,y) print "\ny'z:",np.dot(y.T,z) print "\nyz':\n",np.dot(y,z.T) print "\nx:", np.dot(np.linalg.inv(A),z) # Practice looping and slicing... print "\nPrinting rows of A:" for row in A: print row print "\nPrinting columns of A:" for i in range(0, len(A)): print A[:,i]
74887db1eea7edc9bb59fb5ed1159316da82f87a
drsagitn/algorithm-datastructure-python
/algorithms/reversed_linked_list.py
983
3.921875
4
""" Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL """ class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseList1(self, head: ListNode) -> ListNode: if head is None or head.next is None: return head n = head prev = None _next = None while n: _next = n.next n.next = prev prev = n n = _next return prev def reverseList(self, head: ListNode) -> ListNode: if head is None or head.next is None: return head rhead = self.reverseList(head.next) head.next.next = head head.next = None return rhead s = Solution() node = ListNode(1) node.next = ListNode(2) node.next.next = ListNode(3) node.next.next.next = ListNode(4) node.next.next.next.next = ListNode(5) s.reverseList(node)
d1c18b8a9475bbf36ca814e6688e8f8beff5b40b
ningpop/Algorithm-Study
/06_이인규/week4/11050.py
236
3.703125
4
def factory(num,result): if num <= 1: return result return factory(num-1,result*num) n, k = map(int,input().split()) up = factory(n,1) down1 = factory(n-k,1) down2 = factory(k,1) print(int(up/(down1*down2)))
8fd3293d1aa45c419c19ed7057929378b2a02f9d
byAbaddon/Book-Introduction-to-Programming-with----JavaScript____and____Python
/Pyrhon - Introduction to Programming/7.1. Complex Loops/13. Fibonacci.py
99
3.609375
4
fib = int(input()) f1, f2 = 1, 1 for i in range(fib): f1 += f2 f1, f2 = f2, f1 print(f1)
a5480cd7a228418eef3052ead47446d2bd0af32a
Srinjana/CC_practice
/MISC/TCS NQT/minty.py
1,343
3.625
4
# Problem statement: # It was one of the places, where people need to get their provisions only through fair price(“ration”) shops. As the elder had domestic and official work to attend to, their wards were asked to buy the items from these shops. Needless to say, there was a long queue of boys and girls. To minimize the tedium of standing in the serpentine queue, the kids were given mints. I went to the last boy in the queue and asked him how many mints he has. He said that the number of mints he has is one less than the sum of all the mints of kids standing before him in the queue. So I went to the penultimate kid to know how many mints she has. # She said that if I add all the mints of kids before her and subtract one from it, the result equals the mints she has. It seemed to be a uniform response from everyone. So, I went to the boy at the head of the queue consoling myself that he would not give the same response as others. He said, “I have four mints”. # Given the number of first kid’s mints(n) and the length(len) of the queue as input, write a program to display the total number of mints with all the kids. # constraints: # 2 < n < 10 # 1 < len < 20 # Input # 1: # 4 2 # Output: # 7 mints, length = map(int, input().split()) for i in range(1, length): nxt = mints - 1 mints += nxt print(mints)
58c46a76f3153c9d97c843897a3c04e20f822fb7
JakubR12/cds-visual
/src/assignment-1.py
1,926
3.75
4
#!/usr/bin/env python """ Load image, find height and width, save output Parameters: path: str <path-to-image-dir> outfile: str <filename-to-save-results> Usage: assignment1.py --image <path-to-image> Example: $ python assignment1.py --path data/img --outfile results.csv ## Task - Save csv showing height and width of every image in a directory """ import os from pathlib import Path import argparse # Define main function def main(): # Initialise ArgumentParser class ap = argparse.ArgumentParser() # CLI parameters ap.add_argument("-i", "--path", required=True, help="Path to data folder") ap.add_argument("-o", "--outfile", required=True, help="Output filename") # Parse arguments args = vars(ap.parse_args()) # Output filename out_file_name = args["outfile"] # Create directory called out, if it doesn't exist if not os.path.exists("out"): os.mkdir("out") # Output filepath outfile = os.path.join("out", out_file_name) # Create column headers column_headers = "filename,height, width" # Write column headers to file with open(outfile, "a", encoding="utf-8") as headers: # add newling after string headers.write(column_headers + "\n") # Create explicit filepath variable filenames = Path(args["path"]).glob("*.jpg") # Iterate over images for image in filenames: # load image image = cv2.imread(image) (height, width, channels) = image.shape # Get novel name name = os.path.split(novel)[1] # Formatted string out_string = f"{name}, {height}, {width}" # Append to output file using with open() with open(outfile, "a", encoding="utf-8") as results: # add newling after string results.write(out_string+"\n") # Define behaviour when called from command line if __name__=="__main__": main()
62ea153c8a1167728642fa25359003fcc0a3571e
wattaihei/ProgrammingContest
/AtCoder/ABC-D/157probD.py
1,527
3.8125
4
class UnionFind(): # 作りたい要素数nで初期化 def __init__(self, n): self.n = n self.root = [-1]*(n+1) self.rnk = [0]*(n+1) # ノードxのrootノードを見つける def Find_Root(self, x): if(self.root[x] < 0): return x else: self.root[x] = self.Find_Root(self.root[x]) return self.root[x] # 木の併合、入力は併合したい各ノード def Unite(self, x, y): x = self.Find_Root(x) y = self.Find_Root(y) if(x == y): return elif(self.rnk[x] > self.rnk[y]): self.root[x] += self.root[y] self.root[y] = x else: self.root[y] += self.root[x] self.root[x] = y if(self.rnk[x] == self.rnk[y]): self.rnk[y] += 1 def isSameGroup(self, x, y): return self.Find_Root(x) == self.Find_Root(y) # ノードxが属する木のサイズ def Count(self, x): return -self.root[self.Find_Root(x)] import sys input = sys.stdin.readline N, M, K = map(int, input().split()) AB = [list(map(int, input().split())) for _ in range(M)] CD = [list(map(int, input().split())) for _ in range(K)] P = [1]*(N+1) uni = UnionFind(N+1) for a, b in AB: P[a] += 1 P[b] += 1 uni.Unite(a, b) ans = [] for n in range(1, N+1): ans.append(uni.Count(n)-P[n]) for c, d in CD: if uni.isSameGroup(c, d): ans[c-1] -= 1 ans[d-1] -= 1 print(*ans)
48d4829e7da323d5810191291ad6a5f1e4c75bde
alabarym/Python3.7-learning
/get_sqrt.py
416
3.984375
4
import math def get_square_roots(number): sqrt_values = [] if number == 0: sqrt_values.append(0) return sqrt_values elif number < 0: return sqrt_values elif number > 0: sqrt_values.append(-math.sqrt(number)) sqrt_values.append(math.sqrt(number)) return sqrt_values print (get_square_roots(-1)) print(get_square_roots(0)) print(get_square_roots(25))
abb0644da7bf431ba81658c35af31206c83eb2f6
cdjasonj/Leetcode-python
/反转从m到n的链表,请使用一趟扫描完成反转.py
1,409
4.09375
4
''' 反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。 说明: 1 ≤ m ≤ n ≤ 链表长度。 示例: 输入: 1->2->3->4->5->NULL, m = 2, n = 4 输出: 1->4->3->2->5->NULL 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/reverse-linked-list-ii 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' #超了 # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode: num = 1 p = head while p: if num == m - 1: # 第一个节点的前一个节点当成头 new_head = p elif num == n: new_head.next = p # 最后节点接上n后面的节点 else: p = p.next num += 1 p = head while p: if num >= m and num <= n: # 遍历到需要逆序的位置 pr = p.next p.next = new_head.next new_head.next = p p = pr num += 1 else: p = p.next num += 1 return head #关键在,怎么在一趟里面即找到要开始的节点,和剩下的节点的头节点 。
0780a48a2aa71410803dda82f23d45dba41add07
DatBiscuit/Projects_and_ChallengeProblems
/Projects/Challenge_Problems/Swap_Variables/sv.py
311
3.96875
4
v1 = 1 v2 = 2 #Your code goes here (Answer provided): v3 = v1 v1 = v2 v2 = v3 print(v1) print(v2) #OR v1 = 1 v2 = 2 #Your code goes here (Answer provided): v3 = v1 v4 = v2 v2 = v3 v1 = v4 print(v1) print(v2) #OR v1 = 1 v2 = 2 #Your code goes here (Answer provided): v1, v2 = v2, v1 print(v1) print(v2)
02b29b2ba0c29de84adf3553dd72202bfffe7bda
JeterG/Post-Programming-Practice
/CodingBat/Python/Warmup_2/array_count9.py
247
3.78125
4
#Given an array of ints, return the number of 9's in the array. def array_count9(nums): if (9 in nums)==False: return 0 else: count=0 for i in nums: if i==9: count+=1 return count
aef9d362fb85529544fdda4a2e23a4a599796896
FloMko/advent2017
/day3/circle.py
1,232
3.875
4
def neighbors(matrix, i=0, j=0, offset=0): """find sum of neighbor""" num = matrix[i-1+offset][j-1+offset] + matrix[i-1+offset][j+offset] + \ matrix[i-1+offset][j+1+offset] + matrix[i+offset][j+1+offset] + \ matrix[i+offset][j-1+offset] + matrix[i+1+offset][j-1+offset] + \ matrix[i+1+offset][j+offset] + matrix[i+1+offset][j+1+offset] return(num) def set_node(matrix, i=0, j=0, offset=0): """set node to sum of neighbor""" matrix[i+offset][j+offset] = neighbors(matrix, 0, 0, 0) return matrix def findway(): size = 60 matrix = [[0 for _ in range(size)] for _ in range(size)] offset = size//2 + 1 num = 1 target = 289326 matrix[offset][offset] = num i = 0 j = 0 step_x = True step = 1 n = 1 step_size = 1 while num <= target: if step_x: i += step else: j += step n -= 1 if n == 0: if not step_x: step = -step step_size += 1 step_x = not step_x n = step_size num = neighbors(matrix, i, j, offset) matrix[i+offset][j+offset] = num return num if __name__ == '__main__': findway()
1b733650922767a03670a581d19ef4bf8e07194f
lallmanish90/coltSteelePythonCourse
/https_requests/requests_module.py
325
3.5
4
""" **requests module ** -lets us make HTTP request from our Python code! -installed using pip -usedful fro webscraping/crawling, grabbing data from other APIs, etc - """ import requests url = "http://google.com" response = requests.get(url) print(f"your request to {url} came back w/ status code {response.status_code}")
b7e863fbd50670c02040cc926029f6fcc5a38cbe
amitjain17/FSDP2019
/DAY2/h2.py
521
4.1875
4
# -*- coding: utf-8 -*- """ Created on Wed May 8 16:03:53 2019 @author: NITS """ def leap(yr): #create function if yr%4 == 0 and yr%100 !=0 or yr%400 ==0: #if the number is divided by 4 and 400 than the number is leap year print ("year is leap year") return True else: #number is not leap year print("year is not leap year") return False year = int(input("Enter the year")) #enter the number for checking the leap year or not leap(year)
de8aaa2419023d53df3883debc2e7be39343c828
CarlosWillian/python
/exercicios/ex 011 a 020/ex012.py
178
3.765625
4
print('Descontão pra você') n1 = float(input('Digite o preço da sua compra: R$ ')) print('O valor a pagar com seus 5% de descontos aplicados é: R$ {:.2f}'.format(n1*0.95))
28be6543781556ee7b0b7af64eef83ddd78a8c30
JerinPaulS/Python-Programs
/ALlElementsInBST.py
1,729
3.9375
4
''' 1305. All Elements in Two Binary Search Trees Given two binary search trees root1 and root2, return a list containing all the integers from both trees sorted in ascending order. Example 1: Input: root1 = [2,1,4], root2 = [1,0,3] Output: [0,1,1,2,3,4] Example 2: Input: root1 = [1,null,8], root2 = [8,1] Output: [1,1,8,8] Constraints: The number of nodes in each tree is in the range [0, 5000]. -105 <= Node.val <= 105 ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]: list1 = [] list2 = [] result = [] def dfs(node, curr): if node is None: return dfs(node.left, curr) curr.append(node.val) dfs(node.right, curr) return curr if root1 is not None: list1 = dfs(root1, []) if root2 is not None: list2 = dfs(root2, []) ptr1, ptr2 = 0, 0 if len(list1) == 0: return list2 if len(list2) == 0: return list1 while ptr1 < len(list1) and ptr2 < len(list2): if list1[ptr1] < list2[ptr2]: result.append(list1[ptr1]) ptr1 += 1 else: result.append(list2[ptr2]) ptr2 += 1 while ptr1 < len(list1): result.append(list1[ptr1]) ptr1 += 1 while ptr2 < len(list2): result.append(list2[ptr2]) ptr2 += 1 return result
97606ee8f5f901138b652e2abac9a5e989a29804
lucasoliveiraprofissional/Cursos-Python
/Curso em Video/desafio086b.py
766
4.375
4
'''Crie um programa que crie uma matriz de dimensão 3x3 e preencha com valores lidos pelo teclado. No final, mostre a matriz na tela, com a formatação correta.''' '''Fiz a versão b pois quis ver o que na dele não estava igual ao meu, pois o meu segundo meu raciocinio está certo, porém não funciona.''' matriz= [[0, 0, 0], [0, 0, 0], [0, 0, 0]] for l in range(0, 3): for c in range(0, 3): matriz[l][c]= int(input(f'Digite um valor para [{l}, {c}]: ')) for l in range(0 ,3): for c in range(0, 3): print(f'[{matriz[l][c]:^5}]', end='') print() '''Para que a matriz não fique desalinhada se digitarmos números muito grandes e número muito pequenos, houve a perfumaria, de centralizar no print como iria aparecer o dado.'''
c9aff1967a82faa6f477aed11bbc7deb8ce96efb
hofmanng/algoritmos-faccat
/prog117.py
411
3.984375
4
# # Faca um programa que peca dois numeros, base e expoente, calcule e # mostre o primeiro numero elevado ao segundo numero. Nao utilize a # funcao de potencia da linguagem. # # Declaracao de variaveis e entrada de dados base = int(input("Insira a base: ")) exp = int(input("Insira o expoente: ")) mult = 1 # Processamento for n in range(1, exp + 1): mult = mult * base # Saida de dados print mult
ca6779bcc9a445cfece9272cc3c17d3f34a90931
aalicav/Exercicios_Python
/ex068.py
429
3.765625
4
from random import choice resultado = choice(['PAR','IMPAR']) c = 0 while True: escolha = str(input('Escolha [Par ou impar]:')).upper().strip() if 'PARIMPAR' not in escolha: escolha = str(input('Escolha [Par ou impar]:')).upper().strip() if escolha != resultado: print(f'Você perdeu, mas ganhou {c} vezes consecutivas!') break else: c += 1 print('Parabéns!Você ganhou')