blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
ffc1682c80e2832036efcca28d793d23926e97a3
tpobst/temp
/ex15.py
1,088
4.0625
4
#import argv from sys from sys import argv #argv wants a filename with the run command (%run C:/Users/Tim/temp/ex15.py C:/Users/Tim/temp/ex15_sample.txt #) #argv unpacks the variables script and filename and filename is assigned the file typed with the run command script, filename = argv #the variable txt is assigned the command to open the variable filename txt = open(filename) #line below prints a line filling in the name of the variable filename print "Here's your file %r:" % filename #line below prints the results of the command read() which is called on the variable txt print txt.read() txt.close() #prints a prompt print "Type the filename again:" #assignes the filename to the variable file_again via the raw_input command and uses a greater than symbol to show where to type file_again = raw_input("> ")#C:/Users/Tim/temp/ex15_sample.txt #assigns the variable txt_again with the command open which is called on the variable file_again txt_again = open(file_again) #prints the results of read() called on the variable txt_again print txt_again.read() txt_again.close()
8c10c922a60bd31d3973f50e06872d10b8bbd449
lizzzcai/leetcode
/python/dynamic_programming/0887_Super_Egg_Drop.py
4,325
3.921875
4
''' 03/06/2020 887. Super Egg Drop - Hard Tag: Dynamic Programming, Binary Search, Math You are given K eggs, and you have access to a building with N floors from 1 to N. Each egg is identical in function, and if an egg breaks, you cannot drop it again. You know that there exists a floor F with 0 <= F <= N such that any egg dropped at a floor higher than F will break, and any egg dropped at or below floor F will not break. Each move, you may take an egg (if you have an unbroken one) and drop it from any floor X (with 1 <= X <= N). Your goal is to know with certainty what the value of F is. What is the minimum number of moves that you need to know with certainty what F is, regardless of the initial value of F? Example 1: Input: K = 1, N = 2 Output: 2 Explanation: Drop the egg from floor 1. If it breaks, we know with certainty that F = 0. Otherwise, drop the egg from floor 2. If it breaks, we know with certainty that F = 1. If it didn't break, then we know with certainty F = 2. Hence, we needed 2 moves in the worst case to know what F is with certainty. Example 2: Input: K = 2, N = 6 Output: 3 Example 3: Input: K = 3, N = 14 Output: 4 Note: 1 <= K <= 100 1 <= N <= 10000 ''' from typing import List # Solution class Solution1: def superEggDrop(self, K: int, N: int) -> int: ''' https://juejin.im/post/5d9ede57518825358b221349 Time O(KNlogN) Space O(KN) ''' memo = {} def dp(k, n): if (k, n) not in memo: if n == 0: ans = 0 elif k == 1: ans = n else: lo, hi = 1, n while lo+1< hi: x = (lo+hi)//2 t1 = dp(k-1, x-1) t2 = dp(k, n-x) if t1 < t2: lo = x elif t1 > t2: hi = x else: lo = hi = x ans = 1 + min((max(dp(k-1, x-1), dp(k, n-x)) for x in (lo, hi))) memo[k, n] = ans return memo[k, n] return dp(K, N) class Solution2: def superEggDrop(self, K: int, N: int) -> int: ''' https://juejin.im/post/5d9ede57518825358b221349 https://leetcode.com/problems/super-egg-drop/discuss/158974/C%2B%2BJavaPython-2D-and-1D-DP-O(KlogN) Time O(KlogN) Space O(KN) The key concept of the original O(KN^2) solution is to try all the floor to get the min-cost min(max(broke, not broke) for every floor) as the answer. Original DP definition: I stand on nth floor and give me k eggs, the minimum times I try is dp[n][k]. This definition means the result of this problem is dp[N][K]. This solution is somehow a reverse thinking: New DP definition: If you give me k egg, let me drop m times, I can try out maximum dp[m][k] floors. Based on this definition, the result is some m, which cases dp[m][K] equals N. The transfer equation is based on the following facts: No matter which floor you try, the egg will only break or not break, if break, go downstairs, if not break, go upstairs. No matter you go up or go down, the num of all the floors is always upstairs + downstairs + the floor you try, which is dp[m][k] = dp[m - 1][k - 1] + dp[m - 1][k] + 1. ''' dp = [[0]*(K+1) for _ in range(N+1)] for m in range(1, N+1): for n in range(1, K+1): dp[m][n] = dp[m-1][n-1] + dp[m-1][n] + 1 if dp[m][n] >= N: return m return dp[N][K] # Unit Test import unittest class TestCase(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_testCase(self): for Sol in [Solution1(), Solution2()]: func = Sol.superEggDrop self.assertEqual(func(2, 6), 3) self.assertEqual(func(3, 14), 4) self.assertEqual(func(1,2), 2) self.assertEqual(func(3, 25), 5) if __name__ == '__main__': unittest.main()
7f6fbfb8c373cbe1e36333e2343bbe99550e1927
dimk00z/summer_yandex_algorithmic_course
/Homework_2/D_More_than_your_neighbors/D_More_than_your_neighbors.py
485
3.515625
4
def count_neighbors(number_list): neighbors_count = 0 for element_position, element in enumerate(number_list[1:-1:]): if (element > number_list[element_position]) \ and (element > number_list[element_position+2]): neighbors_count += 1 return str(neighbors_count) with open('input.txt') as file: number_list = list(map(int, file.read().split())) with open('output.txt', 'w') as file: file.write(count_neighbors(number_list))
3d2d3a46dbe04db8963f89891cfd0c7962ce5e21
hassxa96/Programacion
/EjerciciosPOO/Ejercicio8.py
1,748
3.84375
4
""" Desarrollar un programa que conste de una clase padre Cuenta y dos subclases PlazoFijo y CajaAhorro. Definir los atributos titular y cantidad y un método para imprimir los datos en la clase Cuenta. La clase CajaAhorro tendrá un método para heredar los datos y uno para mostrar la información. La clase PlazoFijo tendrá dos atributos propios, plazo e interés. Tendrá un método para obtener el importe del interés (cantidad*interés/100) y otro método para mostrar la información, datos del titular plazo, interés y total de interés. Crear al menos un objeto de cada subclase. """ class Cuenta(): def __init__ (self, titular, cantidad): self.titular= titular self.cantidad=cantidad def getTitular(self): return self.titular def getCantidad (self): return self.cantidad def setTitular (self,titular): self.titular=titular def setCantidad (self,cantidad): self.cantidad=cantidad def mostrar_datos(self): return "Titular: " + self.titular + " Cantidad: " + str(self.cantidad) class CajaAhorro(Cuenta): def __init__(self, titular, cantidad): super().__init__(titular,cantidad) def imprimir(self): super().mostrar_datos() class PlazoFijo(Cuenta): def __init__(self,titular,cantidad,plazo,interes): super().__init__(titular,cantidad) self.plazo=plazo self.interes=interes def importe_interes(self): total= self.cantidad*self.interes/100 print("El importe del interés es: ", total) def imprimir(self): super().mostrar_datos() self.importe_interes() c1=CajaAhorro("Raul",1000) c1.imprimir() p1=PlazoFijo("Manuel", 200, 3, 10) p1.imprimir()
17b3fab549301f28a5b5fbfc0e631a2589e2d253
maheshagadiyar/newproject
/two functions with argument.py
183
3.546875
4
def div(a,b): return a/b def squareroot(c): return c**(1/2) def square(d): return d*d def cube(e): return e**3 result=cube(square(squareroot(div(45,5)))) print(result)
8f89b898169528e3c644c27b845b795e60dfeedb
RyanFTseng/Projects
/regex/phonenumber regex.py
138
3.84375
4
import re print('enter number') x=input() a=re.match('\d{3}-\d{3}-\d{4}',x) if a == None: print('not found') else: print('found')
d1ce894430d7d2a2972be43f04796755940f97ce
ispastlibrary/Titan
/2015/AST1/vezbovni/Dejan/10.py
294
3.59375
4
lista1 = [1, 2, 3] lista2 = [5, 4, 10] #print(lista[2]) #lista=lista1+lista2 import numpy as np #lista1=np.array([1, 2, 3]) #for i in range(len(lista1)): # print(i) #lista1.insert(2, 93) #print(lista1) #k = 100 #l = 200 #b = 100 #x=np.arange(k, l, b) #print(x) a = np.sin(np.pi/2) print(a)
3141389bb519e9d9e3b739cae0fd5c442d8c872a
jackrapp/python_challenge
/PyPoll/main.py
1,844
3.890625
4
#election data columns: voter ID, county, candidate import os import csv total = 0 winner= 0 candidate_list={} #function for adding name and votes to dictionary def sort_list(name): if name in candidate_list: #find vote count votes = candidate_list[str(name)] #increase vote count by 1 candidate_list[str(name)] = votes + 1 else: #if not found add to list candidate_list[(str(name))] = 1 #get data file election_data = os.path.join("election_data.csv") #read data file with open(election_data, newline = "") as csvfile: votes = csv.reader(csvfile, delimiter = ",") next(votes) for row in votes: sort_list(row[2]) total = total + 1 #find overall winner for name in candidate_list: winner = max(candidate_list[name], winner) if candidate_list[name] == winner: pywinner = name #A complete list of candidates who received votes print('''Election Results ----------------''') print(f"Total Votes: {total}") print("----------------") #percentage calculation for name in candidate_list: print(f"{name}: {'{:.2%}'.format(candidate_list[name]/total)} ({candidate_list[name]})") print("----------------") print(f"Winner: {pywinner}") print("----------------") with open("pypoll_winner.txt", "w") as pypoll_winner: print("Election Results", file = pypoll_winner) print("----------------", file = pypoll_winner) print(f"Total Votes: {total}", file = pypoll_winner) print("----------------", file = pypoll_winner) for name in candidate_list: print(f"{name}: {'{:.2%}'.format(candidate_list[name]/total)} ({candidate_list[name]})", file = pypoll_winner) print("----------------", file = pypoll_winner) print(f"Winner: {pywinner}", file = pypoll_winner) print("----------------", file = pypoll_winner)
de7bc4e69b24263ad4be5f8bf6bc3a05c19996aa
dletk/COMP380-Spring-2018
/openCV_code/inclass_activity_1/mileStone_3.py
580
3.5625
4
import cv2 image = cv2.imread("TestImages/SnowLeo2.jpg") # Draw a cile around the leopard's head cv2.circle(image, (120, 130), 70, (207, 142, 27), thickness=3) # Draw a rectangle over its body cv2.rectangle(image, (190, 100), (530, 300), (0, 0, 120), thickness=cv2.FILLED) # Draw some lines as the tail for i in range(4): cv2.line(image, (530, 120), (530 + 10 * (i + 1), 250), (0, 255, 255), thickness=2) cv2.putText(image, "SnowLeo2.jpg", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255)) cv2.imshow("Image window", image) cv2.waitKey(0)
ced974a774b0623bde93666c8b4306998e4ecda1
ibrahimnagib/Game-of-Life
/Life.py
8,795
4.4375
4
# Life.py # Ibrahim Nagib # In 2422 class Abstract_Cell: """ class Abstract_Cell creates Abstract_Cell objects that can become either a Fredkin_Cell or a Conway_Cell, both are derived from this Parent class """ def __init__(self, symbol): self.symbol = symbol self.live_neighbors = 0 class Conway_Cell(Abstract_Cell): """ class Conway_Cell is derived from the class Abstract_Cell, it defines a Conway_Cell, its symbol is '*' if alive, and '.' if dead. It's status is 1 if alive, and 0 if dead. Int 1 and 0 were used in order to reduce the if statements needed to increment the live neighbors. This way, we will simply add status (1 or 0) to all neighbors regardless. """ def __init__(self, symbol): Abstract_Cell.__init__(self, symbol) self.name = "conway" if symbol == "*": self.status = 1 elif symbol == ".": self.status = 0 class Fredkin_Cell(Abstract_Cell): """ class Fredkin_Cell is derived from the class Abstract_Cell, it defines a Fredkin_Cell, its symbol is its age if alive, and '-' if dead. It's status is 1 if alive, and 0 if dead, similar to Conway_Cell. A Fredkin_Cell becomes a Conway_Cell if it ages past age 2. """ def __init__(self, symbol): Abstract_Cell.__init__(self,symbol) self.name = "fredkin" if symbol == "-": self.status = 0 self.age = 0 else: self.status = 1 self.age = int(symbol) class Wall_Cell(Abstract_Cell): """ class Wall_Cell is derived from the class Abstract_Cell, it defines a Wall_Cell, its symbol is '#' and is always "dead". It's status is always 0 , and therefore will not interupt any of characters on the board, but creates a buffer and eliminates the need for if statements at sides and corners. """ def __init__(self, symbol): Abstract_Cell.__init__(self, symbol) self.name = "wall" self.live_neighbors = 0 self.status = 0 class Life: """ Class Life owns the game of life and creates game objects. It has a board, which is read in using Life's read_board method. It plays each round and prints the boards that are called to be shown. """ def __init__(self,infile): self.board = [] self.rows = 0 self.cols = 0 self.population = 0 #self.infile = open(textfile,"r") self.infile = infile def read_board(self): """ read_board method reads the starting positions of the board, and depending on the symbols it finds, assigns them accordingly to either a Conway_Cell, Fredkin_Cell, or Wall_Cell. """ self.population = 0 self.cols = int(self.infile.readline())+2 self.rows = int(self.infile.readline())+2 self.board = [[Wall_Cell("#") for i in range(self.rows)] for j in range(self.cols)] for i in range(self.cols-2): x = self.infile.readline() for j in range (self.rows-2): if x[j] == "." : cell = Conway_Cell(x[j]) elif x[j] == "*": cell = Conway_Cell(x[j]) self.population += 1 elif x[j] == "-": cell = Fredkin_Cell(x[j]) elif x[j] == "0": cell = Fredkin_Cell(x[j]) self.population += 1 self.board[i+1][j+1] = cell self.infile.readline() """ After read board is called, it prints the board it has read, this board is Generation 0, it also prints the inital population on the board. """ print("Generation = 0 ", "Population = ",self.population) self.show_board() print() def play_round_Fredkin_Cell(self): """ play_round_Fredkin_Cell iterates through the entire board, adding each cell's status (1 or 0) to all of it's neighbors, which for fredkin, are 4. """ for x in self.board: for f in x: f.live_neighbors = 0 for i in range(1, self.cols - 1): for j in range(1, self.rows - 1): status = self.board[i][j].status assert type(status)==int for m in range(i-1 , i +2): self.board[m][j].live_neighbors += status for n in range(j-1 , j +2): self.board[i][n].live_neighbors += status self.board[i][j].live_neighbors -= status def play_round_Conway_Cell(self): """ play_round_Conway_Cell iterates through the entire board, adding each cell's status (1 or 0) to all of it's neighbors, which for conway, are 8 total. """ for x in self.board: for f in x: f.live_neighbors = 0 for i in range(1, self.cols - 1): for j in range(1, self.rows - 1): status = self.board[i][j].status assert type(status)==int for m in range(i - 1, i + 2): for n in range(j - 1, j + 2): self.board[m][n].live_neighbors += status self.board[i][j].live_neighbors -= status def run_conway(self, rounds, shown): gen = 1 assert type(rounds)==int assert type(shown)==int while rounds > 0: self.population = 0 self.play_round_Conway_Cell() self.update_board() if gen % shown == 0: assert type(self.population)==int assert type(gen)==int print("Generation = ",gen , "Population = ", self.population) self.show_board() print() rounds -=1 gen += 1 def run_fredkin(self, rounds, shown): gen = 1 assert type(rounds)==int assert type(shown)==int while rounds > 0: self.population = 0 self.play_round_Fredkin_Cell() self.update_board() if gen % shown == 0: print("Generation = ",gen , "Population = ", self.population) self.show_board() print() rounds -=1 gen += 1 def update_board(self): """ update_board iterates through the board, according to the cell it is on, it checks, its status, and whether its Fredkin_Cell or Conway_Cell. According the their respective rules, it changes the cells from dead to alive, or vise versa. also ages the Fredkin_Cells accordingly. update_board also increments the population of the board accordinly for the next board. """ for x in self.board: for f in x: if f.status == 0: if f.name == "conway": assert type(self.population)==int if f.live_neighbors == 3: f.symbol ="*" f.status = 1 self.population += 1 elif f.name == "fredkin": if f.live_neighbors == 1 or f.live_neighbors == 3 : f.status = 1 f.symbol = str(f.age) self.population += 1 else: f.status = 0 elif f.status == 1: if f.name == "conway": assert type(self.population)==int #assert type(f.status)== 1 if not((f.live_neighbors == 2 or f.live_neighbors == 3)): f.symbol = "." f.status = 0 else: self.population += 1 elif f.name == "fredkin": if f.live_neighbors == 1 or f.live_neighbors == 3: f.status = 1 f.age += 1 if f.age <= 2: f.symbol = str(f.age) self.population += 1 else: self.board.replace(f, Conway_Cell("*")) else: f.status = 0 f.symbol = "-" def show_board(self): """ shows board by printing each array in the 2d array on a new line. Only prints [1:-1] in both the outer and inner arrays. Those indexes are the Wall. """ for s in self.board[1:-1]: print(''.join(x.symbol for x in s[1:-1]))
c04f1a5ea0f0eb58b2f35b6954e87d8f328d3367
EtsuNDmA/stud_tasks
/Python_functions/task_7.py
2,114
3.953125
4
# -*- coding: utf-8 -*- VOWELS = 'a', 'e', 'i', 'o', 'u', 'y' def string_to_groups(string): list_words = string.split() assert len(list_words) == 3, 'String have to consist of exactly 3 words' result = {} for word in list_words: group0 = set() group1 = set() group2 = set() for letter in word: letter = letter.lower() if letter in VOWELS: group0.add(letter) elif 'a' <= letter <= 'm': group1.add(letter) else: group2.add(letter) result[word] = group0, group1, group2 return result def count_items(list_): counter = {'int': 0, 'str': 0} for item in list_: if isinstance(item, int): counter['int'] += 1 elif isinstance(item, str): counter['str'] += 1 else: # Рекурсивно вызываем эту же функцию cnt = count_items(item) counter['int'] += cnt['int'] counter['str'] += cnt['str'] return counter def dict_to_groups(dict_): d1 = {} d2 = {} d3 = {} for key, value in dict_.items(): if isinstance(key, int): d1[key] = value if isinstance(key, str): d2[key] = value else: try: if any([isinstance(key_item, str) for key_item in key]): d2[key] = value except TypeError: pass if isinstance(key, tuple): d3[key] = value return d1, d2, d3 if __name__ == '__main__': print('Task 1 "string_to_groups digits"') string = 'Hello pretty World' print('Input data: {}'.format(string)) print(string_to_groups(string)) print('\nTask 2 "count_items"') list_ = [1, 2, ['abc', 5], (32,), 'zyx'] print('Input data: {}'.format(list_)) print(count_items(list_)) print('\nTask 3 "dict_to_groups"') dict_ = {1: 2, 'abc': 42, (7, 8): 'hello', ('xyz', 55): 'world'} print('Input data: {}'.format(dict_)) print(dict_to_groups(dict_))
517e53b5379a247f2289835692d6a3e37ab785f5
luhu888/python-Demo
/tuple.py
870
4.0625
4
#!/usr/bin/python #-*- coding: UTF-8 -*- __author__ = 'Administrator' ''' classmates=['ha','en','yu','wo','ta'] classmates.insert(1,'luhu') classmates.append('ll') classmates.append('ll') classmates.append('ll') classmates.pop(2) classmates[3]='lll' print classmates list=[12,23,2,34,[1,2,3,4,5,],89,'ll'] #list里面可以嵌套list,可以看成二维数组,或多维数组 print list[4][2] sum=0 for s in[1,2,3,4,5,6,7,8,9,0]: sum=sum+s print sum ''' x=1 #阶乘 for y in range(4): x=x*(y+1) print x ''' import math #游戏的位移 def move(x,y,step,angle=0): nx=x+step*math.cos(angle) ny=y+step*math.sin(angle) return nx,ny print move(100,100,60,math.pi/6)''' ''' def square(x,n=2): #平方函数的扩展 s=1 while n>0: n=n-1 s=s*x return s print square(7,3) print square(7) '''
90fa1697d1f295b92a6a6ed8bb66f744d5cb16b7
NicolasStefanelli/Codex
/c_lib/files.py
5,215
3.859375
4
""" Author:Jarvis Lu Date: 2/27/2020 This file contains the File class. The majority of editing of a file's content happens within the file class """ from .import include from .import function from .import variable from file_io import writer """ Initialization of the File class @param file_path path to the file that this writer class is going to write to @instance function_dict a dictionary to keep all functions so a specifc func can be returned given a func name @instance current_function the last function the user was editing. This is implemented so the user can edit the same function without the need to specify it again @instance writer the writer class this file class uses to modify the actual file @instance include the include class that will host all the different includes needed by this file @instance output the content of this file. Changes will be made to the self.output list then it would be passed to writer to write to file @instance tracker keeps track of everything within the file. Whenever a new object is created it is placed in the tracker depending on its position in the file. When the output is being generated, output will be generated sequencially from the first item in tracker to the last """ class File(object): def __init__(self, file_path): self.function_dict = {} self.current_function = None self.writer = writer.Writer(file_path) self.include = include.Include() self.output = [] self.tracker = [] """ Writes the content of self.output to the file TODO when the file had error output at the very end, it is possible for the writer to miss the end, might need to clear the whole file before writing again """ def write_output(self): self.writer.write(self.output) """ Adds include to output TODO include doesn't work if another include is added later on during the editing process. Includes from the standard c library should be made automatically @param include the name fo the library to be included """ def add_std_include(self, include): self.include.add_std_include(include, self.output, 0) if self.include not in self.tracker: self.tracker.append(self.include) """ Add a function to the file @param func_name name of the function to be added @param return_type type of value the function will return @param func_type is the function a definition or a declaration """ def add_function(self, func_name, return_type, func_type): new_func = function.Function(func_name, return_type) self.function_dict.update({new_func.func_name:new_func}) if(func_type == "definition"): new_func.return_func_definition(self.output, self.return_write_line()) elif(func_type == "declaration"): new_func.return_func_declaration(self.output, self.return_write_line()) self.tracker.append(new_func) self.current_function = new_func """ Add content to the body of a function @param action_type can be either add or modify TODO: implement remove for action type as well @param name can be add for adding content to a line inside a function or modify for change the content of an existing line inside a function or Variable to add a variable inside the function or call to add a call inside the function TODO: implement if_else, for, while and switch statements @param line Use this parameter if a specific item at a line needs to be modified @param func_name this paramter can be used to change a function by its name """ def add_to_function_body(self, action_type, name= None, line= None, value= None, func_name= None): if func_name != None: self.current_function = self.function_dict.get(func_name) elif line != None: line = line - self.return_write_line(self.current_function) original_body_length = self.current_function.return_num_lines() self.current_function.add_to_function_body(action_type, name, line, value) self.current_function.return_modified_func(self.output, self.return_write_line(self.current_function), original_body_length) self.write_output() """ Returns the next line to write to based on what has already been written in to the file. When new information is needs to be added, this function is used to tell the file where to place the new information @param element this parameter can be used to specify a function and the line to write to where the new information is directly below the element """ def return_write_line(self, element= None): if self.tracker: ret = 0 for token in self.tracker: if(element == token): return ret ret += token.return_num_lines() +1 return ret else: return 1
3ee372ca4398acf8e80e8aec9d533273e23241c3
clondon/check_emails
/checkmails.py
2,476
3.90625
4
# Queue and threads in Python # https://www.youtube.com/watch?v=NwH0HvMI4EA # Import Queue module from queue import Queue # Import threading modules import threading # Import time module for using stop watch import time # Net work sockets import socket # email protocols import smtplib # Setup Threading queue print_lock = threading.Lock() # Assign queue funtion to q q = Queue() # A list of none valid email addresses in the file # Job counter count_valid = 0 # Failure queue nonvalid_email = [] # Open my emails list file f = open("emails.txt","r") # This function is where the actual task is done # Function definition def exampleJob(worker): print("Worker function") # This is a dummy task that could be a useful item print("Example Job function", threading.current_thread().name, worker) # this shows the threads in action for learning # This is where we put jobs into the queue def threader(): # Loops while there is something in the queue while True: # This "pops" a jon off the queue. # This could be the job board. worker = q.get() # Call the worker function with the job to be done exampleJob(worker) # When the work is done the thread is closed q.task_done() # This is the factory manager dishing out the work. # We'll have 10 workers for x in range(10): # Adds the threads t = threading.Thread(target = threader) # The target = calls the theading modules # Sets the thread to run in the background t.daemon = False # This starts the work day t.start() # Starts the stops workday start = time.time() # This is the number of tasks to perform # open a file to process # Read file line by line and check whether email is valid for line in f: item = line.strip() # Strips newlines # only add valid emaild addresses if ('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$', item): q.put(item) # put items in the queue else: # Not valid list print("/nNone valid/n", item) non_valid.append(item) print endif: # Adds the threads t = threading.Thread(target = threader) # Sets the thread to run in the background t.daemon = True # This starts the work day t.start() q.join() # Report print(f"Entire job took", time.time() - start, "to check", count_valid, "email addressses") print(nonvalid_email)
0a01d0f7fb97a32864d822ce91db5f501e5850a6
mhunsaker7/lc101
/crypto/helpers.py
733
3.90625
4
import string def alphabet_position(letter): lower_letter = letter.lower() alphabet = "abcdefghijklmnopqrstuvwxyz" return alphabet.index(lower_letter) def rotate_character(char, rot): if str(char) in string.digits: return char elif str(char) in string.punctuation or str(char) in string.digits: return char elif char == char.lower(): alphabet = "abcdefghijklmnopqrstuvwxyz" idx = (alphabet_position(char) + rot) % 26 new_char = alphabet[idx] return new_char elif char == char.upper(): alphabet_upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" idx = (alphabet_position(char) + rot) % 26 new_char = alphabet_upper[idx] return new_char
fbb5785a4eebf34e1d5ee1b00f06361b975796c7
kangli-bionic/Coding
/python_learning/6.00.2x/week1/greedy.py
2,221
4.3125
4
#python3 class item(object): """ creates an instance of class object item """ def __init__(self,name,value,weight): self.name=name self.value=value self.weight=weight def __str__(self): return self.name+' :<'+str(self.value)+','+str(self.weight)+'>' def getName(self): return self.name def getValue(self): return self.value def getCost(self): return self.weight def getDensity(self): return (self.value/self.weight) def BuildMenu(names,values,weights): """ creates and return a menu based on the input :param names: is a list of names of items :param values: is a list of values of items corresponding to the names :param weights: is a list of weights of the items corresponding to the names :return: returns a list of objects items """ menu=[] for i in range(len(names)): menu.append(item(names[i],values[i],weights[i])) return menu def greedy(items,maxcost,keyFunction): result,total_value,total_cost=[],0,0 items_copy=sorted(items,key=keyFunction,reverse=True) for i,thing in enumerate(items_copy): if total_cost+thing.getCost()<=maxcost: result.append(thing) total_value+=thing.getValue() total_cost+=thing.getCost() return (result,total_value,total_cost) def testGreedy(items,constraint,keyFunction): taken,value,cost=greedy(items,constraint,keyFunction) print('Total value of items taken is :'+str(value)) print('Total cost of items taken is :'+str(cost)) for i in taken: print(' ',i) def testGreedys(maxvalue): print('Use greedy by value to allocate',maxvalue,'calories') testGreedy(items,maxvalue,item.getValue) print('\n use greedy by cost to allocate',maxvalue,'calories') testGreedy(items,maxvalue,lambda x: 1/item.getCost(x)) print('\n use greedy by density to allocate',maxvalue,'calories') testGreedy(items,maxvalue,item.getDensity) names=['wine','beer','pizza','burger','fries','cola','apple','donut'] values=[89,90,95,100,90,79,50,10] calories=[123,154,258,354,365,150,95,195] items=BuildMenu(names,values,calories) testGreedys(1000)
d0a00a29547240e8b69018059ea7e13977a50dc1
thorn3r/sudokuSolver
/stripper.py
352
3.53125
4
class Stripper: @staticmethod def strip(fileName): with open(fileName) as f: cont = f.read() cont = cont.strip() #strip out newline chars l = [char for char in cont if '\n' not in char] #convert chars to ints l = [int(c) for c in l] #print(l) return l
f0480d2f5fb8f8557702eef94fb2bfec6ee6b4d6
tarunluthra123/Competitive-Programming
/Leetcode/Validate Binary Search Tree.py
491
3.84375
4
# 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 isValidBST(self, root: TreeNode, minVal = -(1<<32), maxVal = (1<<32)) -> bool: if not root: return True return (minVal < root.val < maxVal) and self.isValidBST(root.left, minVal, root.val) and self.isValidBST(root.right, root.val, maxVal)
b0a88105d8cec9a6334b45b562f74c673bd6dd74
Ming-H/leetcode
/59.spiral-matrix-ii.py
407
3.515625
4
# # @lc app=leetcode id=59 lang=python3 # # [59] Spiral Matrix II # # @lc code=start class Solution: def generateMatrix(self, n: int) -> List[List[int]]: """ !!!!!!!!!!!!!!!!!!!!!!!! """ matrix, l = [], n*n+1 while l > 1: l, r = l - len(matrix), l matrix = [range(l, r)] + list(zip(*matrix[::-1])) return matrix # @lc code=end
ac945bd059d1f034b479695819a469c4dd1ad691
oxnz/sketchbook
/sat/indexedsat.py
2,473
3.703125
4
""" Solve a SAT problem by truth-table enumeration with pruning and unit propagation. Sped up with an index from each variable to the clauses using it. """ ## solve([]) #. {} ## solve([[]]) ## solve([[1]]) #. {1: True} ## solve([[1,-2], [2,-3], [1,3]]) #. {1: True, 2: False, 3: False} import sat from sat import assign def solve(problem): "Return a satisfying assignment for problem, or None if impossible." env = {} index = build_index(problem) return solving(index, env, sat.problem_variables(problem), on_update(problem, env, [])) def solving(index, env, variables, unit_literals): "Try to extend a consistent assignment for problem to a satisfying one." if unit_literals is 'contradiction': return None if not variables: return env if unit_literals: literal, unit_literals = unit_literals[0], unit_literals[1:] v, value = abs(literal), (0 < literal) variables = removed(variables, v) return assume(index, env, variables, unit_literals, v, value) v, variables = variables[0], variables[1:] for value in (False, True): result = assume(index, env, variables, unit_literals, v, value) if result is not None: return result return None def assume(index, env, variables, unit_literals, v, value): env = assign(v, value, env) return solving(index, env, variables, on_update(index.get(v if value else -v, ()), env, unit_literals)) def build_index(problem): index = {} for clause in problem: for literal in clause: index.setdefault(-literal, []).append(clause) return index def on_update(clauses, env, unit_literals): unit_literals = unit_literals[:] for clause in clauses: unknown_literals = [] for literal in clause: value = env.get(abs(literal)) if value is None: unknown_literals.append(literal) elif value == (0 < literal): break # Clause is true else: if not unknown_literals: return 'contradiction' # Clause is false if (len(unknown_literals) == 1 and unknown_literals[0] not in unit_literals): unit_literals.extend(unknown_literals) return unit_literals def removed(xs, x): xs = list(xs) xs.remove(x) return xs
865667c9ac05a7bfaa7bcf0eb7f3b3a698fd1484
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/ethan_nguyen/lesson10/mailroom_fp.py
6,965
3.65625
4
import sys, os import pytest from functools import reduce #create a donor_db as a dict donor_db = {"William Gates, III": [653772.32, 12.50], "Jeff Bezos": [877.33], "Paul Allen": [663.23, 47, 10.50], "Mark Zuckerberg": [1663.23, 4300.87, 10432.0], "Donald Trump": [50000.24, 1002] } prompt = "\n".join(("Welcome to the mail room", "Please choose from below options:", "S - Send a Thank You", "C - Create a Report", "L - Send letters to all donors" "Q - Exit" ">>> ")) def view_donors(): print("\n".join(donor_db)) def quit_program(): print ("Thank you. Bye!") sys.exit(0) # exit the interactive script #function to make sure input name is letters only and longer than 2 characters def validate_name(): while (True): try: input_Name = str(input("Please enter a name > ")) if (len(input_Name) > 2 and input_Name.isalpha()): break else: raise TypeError except TypeError: print("Letters only or longer name, please.") return input_Name #function to make sure input amount is numeric def validate_amount(input_Name=""): while (True): try: input_Amount = input(f"{input_Name} please input amount > ") value = float(input_Amount) break except ValueError: print('Valid amount, please') return value #function to make sure factor is number def validate_factor(): while (True): try: input_Amount = input(f"Please input factor > ") value = int(input_Amount) break except ValueError: print('Valid factor, please') return value def send_thank_you(): input_name = validate_name() while("list" in input_name): for d in sorted(donor_db.keys()): print(d) input_name = validate_name() is_NewDonor = False if input_name not in donor_db: is_NewDonor = True value = validate_amount(input_name) print(create_thank_you_note(input_name, value)) #add Donor if he/she is not in donor_db if is_NewDonor: add_new_donor(input_name, float(value)) else: #select_Donor.append(float(value)) #donor_db[input_Name] = select_Donor update_amount(input_name, float(value)) def create_thank_you_note(name, value): return f'Dear {name}, \n Thank you for your very kind donation of ${value:,.2f} \n \ It will be put to very good use. \n Sincerely, \n -UW' def update_amount(name, amount): """function to update amount given a name""" donor_db[name].append(amount) def add_new_donor(name, amount): """function to add a new donor""" donor_db[name] =[amount] def sort_key(donor): return sum(donor[1]) def get_report(): sort_Donor = sorted(donor_db.items(), key=sort_key, reverse = True) rows = list() for d in sort_Donor: rows.append("{:<25} ${:>12,.2f}{:>22}{:<10}${:>12,.2f}".format(d[0], sum(d[1]), len(d[1]), '',sum(d[1])/len(d[1]))) return rows def display_report(): for r in get_report(): print(r) def create_report(): space='' print(f'Donor Name {space:<15}| Total Given {space:<10}| Num Gifts {space:<9}| Average Gift {space:<19}') print("-"*85) #sort_Donor = sorted(donor_db.items(), key=lambda x: x[1], reverse = True) display_report() def get_letter_text(name, amount): """Get letter text for file content""" return f'Dear {name}, \n Thank you for your very kind donation of ${float(sum(amount)):,.2f} \n \ It will be put to very good use. \n Sincerely, \n -UW' def create_letter(path, letter_name, letter): """Create letter""" with open(f'{path}/{letter_name}.txt', 'w') as f: f.write(letter) def send_letters(): path = os.getcwd() for k,v in donor_db.items(): create_letter(path, k, get_letter_text(k, v)) print("Done!") def test_get_report(): expected = "{:<25} ${:>12,.2f}{:>22}{:<10}${:>12,.2f}".format("Paul Allen", 708.42, 3, '',236.14) result = get_report() assert expected in result def test_get_report_count(): result = get_report() assert len(result) == 5 def test_get_letter_text(): expected = "Dear World, \n Thank you for your very kind donation of $300.00 \n \ It will be put to very good use. \n Sincerely, \n -UW" assert get_letter_text("World", [100, 200]) == expected def test_create_letter(): expected = os.path.join(os.getcwd(), "World.txt") create_letter(os.getcwd(), "World", "Dear World, \n Thank you for your very kind donation of $300.00 \n \ It will be put to very good use. \n Sincerely, \n -UW") assert os.path.isfile(expected) def test_create_thank_you_note(): expected = 'Dear Ethan, \n Thank you for your very kind donation of $10,000.00 \n \ It will be put to very good use. \n Sincerely, \n -UW' assert create_thank_you_note("Ethan", 10000) == expected def test_add_new_donor(): add_new_donor('Ethan', 10000) expected_key, expected_value = "Ethan", [10000] assert expected_key in donor_db and expected_value == donor_db[expected_key] def test_update_amount(): update_amount("Ethan", 100) expected_key, expected_value = "Ethan", [10000, 100] assert expected_key in donor_db and expected_value == donor_db[expected_key] ''' function to return the sum of all donations after mulitpliying by factor ''' def map_reduce(f, l): return reduce((lambda x, y: x + y), map(lambda x: x * f, l)) def test_map_reduce(): test = [0, 2, 3] assert 10 == map_reduce(2, test) ''' function to print the projection with upper and lower limit set by user ''' def challenge(): print("Please input the lower limit:") lower_limit = validate_amount() lower_factor = validate_factor() print("Please input the upper limit:") upper_limit = validate_amount() upper_factor = validate_factor() donor_list = list() for k,v in donor_db.items(): donor_list.extend(v) upper_amount = map_reduce(lower_factor, filter(lambda x: x <=lower_limit, donor_list)) lower_amount = map_reduce(upper_factor, filter(lambda x: x >=upper_limit, donor_list)) print(10 * "-" + " Run Projection " + 10 * "-") print("{} time contributions that ${} or below would be: ${:>12,.2f}".format(upper_factor, upper_limit, upper_amount)) print("{} time contributions that ${} or above would be: ${:>12,.2f}".format(lower_factor, lower_limit, lower_amount)) if __name__ == "__main__": arg_dict = {'S':send_thank_you, 'C':create_report, 'L':send_letters, 'P':challenge} while True: response = input("Please select S for \"Send a Thank You\" C for \"Create a Report\" L for \"Send Letters\" P for \"Run Projection\" or Q to quit >").upper() arg_dict.get(response, quit_program)()
f36e25d2a73a3fffed9c19ae93745ae5b7bb2972
Brycham/205-project
/Crop.py
285
3.515625
4
# Thomas Lopes # 05/12/2018 # This code takes a full path and return the filename def crop(sentence): path = "" for letter in sentence: if(letter == "/"): path = "" else: path += letter return path print(crop("C:/Users/Thomas/205git"))
01c6492a90f3c9588bbd9317405671da2c5b0fa4
udamadu11/Serial_number_tool
/Improve.py
1,011
3.59375
4
import xlsxwriter file_name = input("Enter File name: ex: file.xlsx : ") pattern = input("Enter Pattern: ex: 01H : ") start_number = int(input('Start Number : ex: 4654900 : ')) end_number = int(input('End Number : ex: 4656900 : ')) first_row = input("Enter First Row name : ex: IGT8_0.6M / LED : ") second_row = input("Enter Second Row name : ex : 9W / 3W : ") third_row = input("Enter Third Row name : ex: 6500K / 865 / 830 : ") fourth_row = input("Enter Fourth Row name : ex: E27 / B22 : ") workbook = xlsxwriter.Workbook(file_name) worksheet = workbook.add_worksheet() # number assign as quantity number = end_number j = 0 for i in range(start_number, number+1): my_list = (f"{pattern}{i}") j = (i - start_number) worksheet.write(j, 0, j) worksheet.write(j, 1, first_row) worksheet.write(j, 2, second_row) worksheet.write(j, 3, third_row) worksheet.write(j, 4, fourth_row) worksheet.write(j, 5, "1901") worksheet.write(j, 6, my_list) print(my_list) workbook.close()
74c6107a790191f52d504ca37d29d182e3992e33
sachaBD/engg1300-week1-B-extra-content
/resistor_uncertainty.py
1,866
3.953125
4
import random import matplotlib.pyplot as plt """ Generate the combined series resistance for n resistance with a value resistance and a random tolerance. """ def n_series_resistors(n, resistance, tolerance): total = 0 for i in range(0,n): actualR = resistance * ( 1 - tolerance * (random.random() * 2 - 1)) total += actualR return total """ Generate the combined parralel resistance for n resistance with a value resistance and a random tolerance. """ def n_parralel_resistors(n, resistance, tolerance): total = 0 for i in range(0,n): actualR = resistance * ( 1 - tolerance * (random.random() * 2 - 1)) total += (actualR)**(-1) return (total)**(-1) """ Create a nice graph to visually show the distributions of resistance due to varying combinations. """ def create_graphics(number, resistance, tolerance): # Store many samples for the possible resistor space RT = [] # Generate many samples from resistors of these values for i in range(0, 100000): RT.append(n_series_resistors(number, resistance, tolerance)) # Place into buckets of 0.1 ohms to count occurances binned = {} for r in RT: binned.setdefault(round(r,2) , 0) binned[round(r,2)] += 1 # normalise the occurance function vNormed = [float(i)/sum(binned.values()) for i in binned.values()] print(len(binned), len(vNormed)) plt.title("Series resistance of 10 10 Ohm resistors with tolerance 5%. 10^6 samples.") plt.xlabel("Resistance (Ohms)") plt.ylabel("Occurances grouped to 0.01 Ohms") plt.scatter(binned.keys(), vNormed) plt.ylim([min(vNormed) - max(vNormed) * 0.1, max(vNormed) * 1.1]) plt.show() """ Inputs to the program: """ R1 = 2 R2 = 100 tolerance = 0.05 create_graphics(R1, R2, tolerance)
db736317d33df2c83577cc8156abf08096c6b002
tesera/prelurn
/prelurn/describe.py
2,867
3.53125
4
"""Functions for describing data""" import numpy as np import pandas as pd from collections import OrderedDict def _pandas_describe(df, **kwargs): """ Wrapper to dataFrame.describe with desired default arguments :param df: data frame :param **kwargs: keyword arguments to DataFrame.describe """ return df.describe(include='all', **kwargs).transpose() # TODO: would be a nice thing to cache def basic_type_from_name(name): """ Get basic data type name from dtype :param name: name attribute of dtype - type.name :return: :rtype: """ candidates = {'float': 'numeric', 'int': 'numeric', 'bool': 'boolean', 'datetime': 'timestamp', 'category': 'categorical', 'object': 'categorical'} basic_type = 'unknown' for prefix, val in candidates.items(): if name.startswith(prefix): basic_type = val return basic_type def summarize_types(df): """ Get simple data types for each variable :param df: data frame :return: :rtype: """ types = df.dtypes basic_types = [basic_type_from_name(item.name) for item in types] return basic_types def get_fraction_missing(df): """ Get fraction of observation missing for each variable :param df: data frame :return: missing fractions in order of df columns :rtype: list """ num_rows = df.shape[0] missing_fraction = df.isnull().sum() / num_rows return missing_fraction.values.tolist() def _get_categories_as_str(column, category_sep=','): if column.dtype.name not in ['object', 'category']: return np.nan if column.dtype.name == 'object': column = column.astype('category') cat_list = column.cat.categories.tolist() cat_str = category_sep.join(cat_list) return cat_str def get_unique_categories(df): """ Get unique classes for each variable np.nan if variable is not categorical or string :param df: data frame :return: unique values in data frame :rtype: list """ return [_get_categories_as_str(df[c]) for c in df] def custom_describe(df): """Describe a data frame Function to run the custom describe functions and format data in a shape that can be merged to the result of _pandas_describe, specifically, variables as rows and descriptives as columns. :param df: data frame :return: :rtype: """ types = summarize_types(df) fraction_missing = get_fraction_missing(df) unique_classes = get_unique_categories(df) new_index = df.columns.tolist() data = OrderedDict(type=types, missing_proportion=fraction_missing, categories=unique_classes) describe_df = pd.DataFrame(data, index=new_index) return describe_df
d4150298be286c6105bf705205aa35f3b04f7d63
kenrick90/Regex-Substitution
/Regex Substitution.py
253
3.71875
4
import re dict = {" && ":" AND ", " || ":" OR "} para=[] l = int(input()) for i in range(l): para.append(input()) for line in para: line = str(re.sub(r" &&(?= )"," and",line)) line = re.sub(' \|\|(?= )',' or',line) print(line)
c0fa97c9bce9c9a9a9fcd1c6ca637b5d0cdc42f7
joseph-mutu/Codes-of-Algorithms-and-Data-Structure
/Leetcode/[171]Exceel 表格数字 -- 逆序.py
458
3.703125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-03-05 14:22:53 # @Author : mutudeh (josephmathone@gmail.com) # @Link : ${link} # @Version : $Id$ import os class Solution(object): def titleToNumber(self, s): if not s: return 0 num = 0 mul = 1 for letter in s[::-1]: num += (ord(letter) - ord('A') + 1) * mul mul *= 26 return num s = Solution() print(s.titleToNumber('ZY'))
59aa87cdc16664a874edbc236bf8ae35e3c4de6f
selvatp/CS1XA3
/Lab02/myconvert.py
375
4.3125
4
# myconvert.py # A program to convert Celsius temperatures to Fahrenheit and # prints a table of Celsius temperatures and the Fahrenheit equivalents # every 8 degrees from 0C to 100C # by: Piranaven Selvathayabaran def main(): print("Celsius | Fahrenheit") for i in range(0,101,8): fahrenheit = 9/5 * i + 32 print(i," ",fahrenheit) main()
9b464d06a777eb6f6ffaaf2ec29f821fd984faa8
patrykstefanski/dc-lang
/scripts/gen_matrix.py
266
3.515625
4
import random import sys if len(sys.argv) < 2: print('Usage: {} <N> [SEED]'.format(sys.argv[0])) sys.exit(1) n = int(sys.argv[1]) if len(sys.argv) >= 3: random.seed(sys.argv[2]) print(n) for i in range(2 * n * n): print(random.randint(-1000, 1000))
880313d2f76219c4203d9be285a8b4324e96cd29
Psp29onetwo/python
/zipfunction.py
113
3.8125
4
list1 = [1, 2, 3, 4, 5, 6] list2 = [7, 8, 9, 1, 2, 3] zipped_list = list(zip(list1, list2)) print(zipped_list)
1b293c2199aca78fd775305bd43d86acfe06a0b8
judigunkel/Exercicios-Python
/Mundo 2/ex041.py
679
3.984375
4
""" A Confederação Nacional de Natação precisa de um programa wue leia o ano de nascimento de um atleta e mostre sua categoria, de acordo com a idade: Até 09 anos - Mirim Até 14 anos - Infantil Até 19 anos - Junior Até 25 anos - Sênior Acima - Master """ from datetime import date nasc = int(input('Ano de nascimento: ')) atual = date.today().year idade = atual - nasc print(f'O atleta tem {idade} anos.') if idade <= 9: print('Classificação: MIRIM') elif idade <= 14: print('Classificação: INFANTIL') elif idade <= 19: print('Classificação: JÙNIOR') elif idade <= 25: print('Classificação: SÊNIOR') else: print('Classificação: MASTER')
eaae22fdca519eb39ddca227462fa4185c781a07
accus84/python_bootcamp_28032020
/moje_skrypty/20200523_moje/basic/04_napisy.py
142
3.5625
4
n1 = "Ala" n2 = "kot" print(n1 + " " + n2) # łączenie napisów - konkatenacja print(f"{n1} {n2}") print("{a} {b}".format(a = n1, b = n2))
c5386f3f4a6d663ba98b5115a2ea2702ec96de7e
HarshaRathi/PPL-Assignment
/Assign3/line.py
300
3.828125
4
import turtle class line(): def __init__(self , len = 5): self.__len = len def get_len(self): return self.__len def draw(self): t = turtle.Turtle() t.forward(self.__len) l = line(400) print("Length of line = ",l.get_len()) l.draw() turtle.done()
3daf2131c2c05cd19609ac537f49bc56edabb295
Jhancrp/Examen_Final
/Final/Modulo3/banco.py
799
3.578125
4
#Ejercicio 01 mastercard= [51, 52, 53, 54 , 55] american_expres = [34,37] visa = [4] def luhn(ccn): c = [int(x) for x in ccn[::-2]] u2 = [(2*int(y))//10+(2*int(y))%10 for y in ccn[-2::-2]] print(f"numero = {ccn}") return sum(c+u2)%10 == 0 prueba = 49927398716 #con este numero funciona prueba2=549273989816 #no valida la funcion por eso arroja not found apesar de que inicia con 54 numero = input("Ingrese numero: ") #Test if luhn(numero) == True : dig = numero[0] + numero[1] dig = int(dig) if (dig == 34 or dig == 37): print("American express") elif (dig == 51 or dig== 52 or dig == 53 or dig==54 or dig == 55): print("Mastercard") elif int(numero[0]) == 4 : print("Visa") else: print("Not found")
e2db0bfcfdfa9e4bcaea32df1a295b21ba1cca62
ehoney12/comp110-21f-workspace
/exercises/ex03/tar_heels.py
397
3.75
4
"""An exercise in remainders and boolean logic.""" __author__ = "730240245" # Begin your solution here... int1: int = int(input("Enter an int: ")) divis_by_2: int = (int1 % 2) divis_by_7: int = (int1 % 7) if divis_by_2 == 0: if divis_by_7 == 0: print("TAR HEELS") else: print("TAR") else: if divis_by_7 == 0: print("HEELS") else: print("CAROLINA")
d138888489d9c5bfcd5050469cf0b0cde9434f44
Aeternix1/Python-Crash-Course
/Chapter_6/6.4_glossary2.py
543
3.984375
4
#Glossary but without the print statements glossary = { 'loop':'A means to accomplish a process several times', 'if': 'A particular form of boolean', 'list': 'set of values stored sequentially in memory', 'boolean':'a conditional statement', 'style': 'Style is an important part of programming', 'dictionary': 'storing values using a key value pair', 'key' : 'starting term in a glossary', 'value': 'corresponding value to a key', } for key, value in glossary.items(): print(key + ":" + value + "\n")
baee40593ee9a221617eea3e1fe7488713a3c9c0
angel19951/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/models/square.py
2,600
4.125
4
#!/usr/bin/python3 """ This module contains a Square class """ from models.rectangle import Rectangle from models.base import Base class Square(Rectangle): """ Square class """ def __init__(self, size, x=0, y=0, id=None): """ Initializes a square class that inherits from rectangle Args: size (int): size of the square x (int): position in x axis of the square y (int): position in y axis of the square """ super().__init__(size, size, x, y, id) def __str__(self): """ Prints information of a square """ return "[Square] ({:d}) {:d}/{:d} - {:d}".format(self.id, self.x, self.y, self.size) @property def size(self): """ Returns size of the square """ return self.width @size.setter def size(self, value): """ Assings and validates the value of size """ if type(value) is not int: raise TypeError("width must be an integer") elif value < 0: raise ValueError("width must be > 0") else: self.width = value def area(self): """ Returns the area of a square """ return self.size * self.size def display(self): """ Prints str rep of a square """ for y_skip in range(self.y): print() spaces = " " * self.x for row in range(self.size): print(spaces, end="") for col in range(self.size): print("#", end="") print() def update(self, *args, **kwargs): """ Updates the value of the square using args """ if len(args): for key, arg in enumerate(args): if arg == 0: self.id = arg elif arg == 1: self.size = arg elif arg == 2: self.x = arg elif arg == 3: self.y = arg else: if "id" in kwargs: self.id = kwargs["id"] if "size" in kwargs: self.size = kwargs["size"] if "x" in kwargs: self.x = kwargs["x"] if "y" in kwargs: self.y = kwargs["y"] def to_dictionary(self): """ Return dict representation of a class """ square = Square(self.id, self.size, self.x, self.y) return dict(square.__dict__)
df81954a358fa3139677a07b150494e005fb8c81
ariadnei/rkiapp
/site_ver/7.py
3,691
3.734375
4
''' 7. Образовать слова от слов в скобках и ставить в пропуски ''' def main(level): import app.exc.functions as fun import app.exc.formation as form task_name = 7 task = 'Вставьте в пропуски (1) - ({}) слова, образованные от слов в скобках. Поставьте эти слова в правильную форму.\n{}' #TODO: добавить заполненный пример text = fun.reading('text') #print(text) sents = fun.sts(text) #print(sents) tokens = fun.tkns(sents) #print(tokens) text_tokens = fun.text_tokens(tokens) #print(text_tokens) w_in_sent = [] # список всех подходящих слов в предложениях for sent in tokens: w_for_sent = [] # список подходящих в предложении; пустой, если ничего for token in sent: if fun.check_min(token.lem, level) and token.lem in form.vocab: w_for_sent.append(token) # добавляем срзу весь токен w_in_sent.append(w_for_sent) #print(w_in_sent) w_list = fun.rand_one(w_in_sent) #print(w_list) suit_n = '' # проверяем, есть ли хоть одно реальное слово в w_list, или все '' for e in w_list: suit_n += e if not suit_n: # ни в одном предложении ни нашлось ни одного подходящего слова print('К сожалению, в тексте нет ни одного предложения, подходящего для создания упражнения. Попробуйте выбрать уровень выше или просто подобрать другой текст.') else: new_tokens = [] # пойдёт в задание key_tokens = [] # пойдёт в ключи k = 0 # счётчик номеров for i, sent in enumerate(tokens): # заменяем на пропуски if w_list[i]: # есть токен на замену k += 1 root_word = form.vocab[w_list[i].lem] #print(w_list[i].text, root_word) new_token = fun.Token('({})______({})'.format(k, root_word)) # делаем новым токеном то же слово с подчёркиванием #print(new_token.text) new_sent = sent[:w_list[i].num] + [new_token] + sent[w_list[i].num+1:] new_tokens.append(new_sent) key_token = '({}) {}'.format(k, w_list[i].text) key_tokens.append(key_token) else: new_tokens.append(sent) #print(fun.text_tokens(new_tokens)) #print() #print(key_tokens) task_sents = fun.join_toks(new_tokens) #print(task_sents) task_text = ' '.join(task_sents) #print(task_text) key_text = '\n'.join(key_tokens) #print(key_text) # форматируем тексты задания и ключей task_text = task.format(k, task_text) key_text = task.format(k, key_text) # записываем задание и ключи fun.writing(task_text, task_name) fun.writing_key(key_text, task_name) # выводим на сайт site_task_text = task_text.replace('\n', '<br>') print(site_task_text, "<br><br><br>") print("Ответы:<br>") site_key_text = '<br>'.join(key_tokens) print(site_key_text)
86810068371413cc41f0e544739323a3755e25f6
aurel1212/Sp2018-Online
/students/alex_skrn/Lesson06Activity/calculator/subtracter.py
328
3.8125
4
#!/usr/bin/env python3 """This module provides a subtraction operator.""" class Subtracter(object): """Provide a class for subtracting one number from the other.""" @staticmethod def calc(operand_1, operand_2): """Take two operands and subtract one from the other.""" return operand_1 - operand_2
fc3cb94fadf7a82391b1adb0da5334c9dcc15bf9
Dmitrygold70/rted-myPythonWork
/Day07/classes/example01/point4.py
783
3.765625
4
class Point: count = 0 def __init__(self, x=0, y=0): self.x = x self.y = y Point.count += 1 def __del__(self): Point.count -= 1 def show(self): print("({}, {})".format(self.x, self.y)) if __name__ == '__main__': p1 = Point(10, 20) p1.show() print("there are", Point.count, "points") p2 = Point(44, 55) p2.show() print("there are", Point.count, "points") p3 = p2 print("there are", Point.count, "points") del p1 print("there are", Point.count, "points") del p2 print("there are", Point.count, "points") del p3 print("there are", Point.count, "points") points = [ Point(1, 1), Point(2, 2), Point(30, 40) ] print(len(points))
2a570809d7d1e04c9e354ab775f1ceeb31a0b447
chintanaprabhu/leetcode
/Python3-Solutions/Sort Colors.py
786
3.65625
4
class Solution: def sortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ rightOfZero = currIndex = 0 leftOfTwo = len(nums)-1 while currIndex <= leftOfTwo: if(nums[currIndex] == 0): nums[rightOfZero], nums[currIndex] = nums[currIndex], nums[rightOfZero] rightOfZero += 1 currIndex += 1 continue if(nums[currIndex] == 2): nums[leftOfTwo], nums[currIndex] = nums[currIndex], nums[leftOfTwo] leftOfTwo -= 1 continue currIndex += 1 Sort Colors
4c333d550d39e1c71024f88b9360b57983343e83
qqmadeinchina/myhomeocde
/homework_zero_class/lesson16/单例模式-times_1.py
2,069
3.640625
4
#!D:\Program Files\Anaconda3 # -*- coding: utf-8 -*- # @Time : 2020/8/8 13:54 # @Author : 老萝卜 # @File : 单例模式-times_1.py # @Software: PyCharm Community Edition # 单例模式是设计模式的一种 # 单例模式 保证系统中的一个类只有一个实例, class Person: pass p1 = Person() p2 = Person() print(p1) print(p2) # <__main__.Person object at 0x00000000021E97F0> # <__main__.Person object at 0x000000000258E0F0> # 1 谁创建了对象? class Person: def __init__(self): print('初始化方法....') # 未执行 p1 = Person() print("p11=",p1) # 初始化方法.... class Person: def __new__(cls, *args, **kwargs): print(123) def __init__(self): print('初始化方法....') # 未执行 p1 = Person() # 123 class Person: def __init__(self): print('初始化方法....') # 未执行 def __new__(cls, *args, **kwargs): print(123) p1 = Person() # 123 # object有一个new方法来创建对象 # 创建对象之后,才可以执行 __init__(self),进行初始化 # 2. 对象的执行顺序 class Person: def __new__(cls, *args, **kwargs): print(123) obj = object.__new__(cls) # 创建了一个对象 return obj def __init__(self): print('创建完对象之后再初始化....') p1 = Person() # 3. class Person: # 私有变量 _instance = None def __new__(cls, *args, **kwargs): print(123) if Person._instance is None: obj = object.__new__(cls) # 创建了一个对象 Person._instance = obj # 将这个对象赋值给类的私有变量_instance return Person._instance def __init__(self): print('创建完对象之后再初始化....') p1 = Person() p2 = Person() p3 = Person() print(id(p1),id(p2),id(p3)) # 123 # 123 # 123 # 创建完对象之后再初始化.... # 123 # 创建完对象之后再初始化.... # 123 # 创建完对象之后再初始化.... # 123 # 创建完对象之后再初始化.... # 39626232 39626232 39626232
94e8bd8c6c398ac43b896752fe2e2624499b91af
samuellly/dojo_assignment_file
/dojo_python/fundamentals/star.py
1,031
3.734375
4
x = [4, 6, 1, 3, 5, 7, 25] def print_Stars(arr): for i in arr: print i * "*" print_Stars(x) #2nd Star assignment x = [4, "Tom", 1, "Michael", 5, 7, "Jimmy Smith"] def print_Stars(arr): for i in range(len(arr)): if isinstance(arr[i], int): print arr[i] * "*" elif isinstance(arr[i], str): print arr[i][0].lower() * len(arr[i]) print_Stars(x) #answer # Part I # x = [4,6,1,3,5,7,25] # def draw_starsI(num_list): # for num in num_list: # output = '' # for i in range(num): # output += '*' # print output # # draw_starsI(x) # # # Part II # y = [4,'Tom',1,'Michael',5,7,'Jimmy Smith'] # def draw_stars2(my_list): # for item in my_list: # output = '' # if type(item) is int: # for i in range(item): # output += '*' # elif type(item) is str: # first_letter = item[0].lower() # for i in range(len(item)): # output += first_letter # print output # # draw_stars2(y)
ab7f13c776fb4e0b8346b5f7d1dafae9ad3a901f
924235317/leetcode
/114_flatten_binary_tree_to_linked_list.py
876
3.84375
4
from treenode import * def flatten(root: TreeNode) -> None: def flattenCore(root): if root and not root.left and not root.right: return root if root.left and root.right: tmp = root.right t = flattenCore(root.left) root.right = root.left t.right = tmp root.left = None return flattenCore(tmp) elif root.left: t = flattenCore(root.left) root.right = root.left root.left = None return t elif root.right: root.left = None return flattenCore(root.right) if not roort: return None t = flattenCore(root) t.right = None if __name__ == "__main__": l = [1,2,3,4,5] root = list2treenode(l) print_treenode(root) flatten(root) print_treenode(root)
a70b0d9eb2e191f7c3638443ffe5eae6fb57fc11
HLNN/leetcode
/src/0540-single-element-in-a-sorted-array/single-element-in-a-sorted-array.py
636
3.671875
4
# You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. # # Return the single element that appears only once. # # Your solution must run in O(log n) time and O(1) space. # #   # Example 1: # Input: nums = [1,1,2,3,3,4,4,8,8] # Output: 2 # Example 2: # Input: nums = [3,3,7,7,10,11,11] # Output: 10 # #   # Constraints: # # # 1 <= nums.length <= 105 # 0 <= nums[i] <= 105 # # class Solution: def singleNonDuplicate(self, nums: List[int]) -> int: res = 0 for n in nums: res ^= n return res
99617d7d030c6a612adfa9b3e82dc1efefb315d7
thezencode/project_euler
/problem3.py
644
3.734375
4
import math import time def is_prime(n): for x in range(2, int(math.sqrt(n)) + 1): if n % x == 0: return False return True def return_prime_factors(a_number): factors = [a_number] while True: if is_prime(factors[0]): break for i in range(2, int(factors[0])): if factors[0] % i == 0: factors[0] = factors[0] / i factors.append(i) break return int(max(factors)) start = time.time() print(return_prime_factors(600851475143)) end = time.time() print(f"This program takes {end - start} seconds to run.")
13c2e648a216e168c2c062d21dec4311e6a5ecac
yiyang7/warfarin-bandit
/src/visualize.py
3,034
3.765625
4
""" Helper methods for visualizing simulation results """ import numpy as np import matplotlib.pyplot as plt def plot_regret(reward_histories, plot_legend, plot_bound=False, drop_k=0): """ Plots regret vs. t reward_history: array of reward_history arrays plot_legend: legend for the plotted curve (string) plot_bound: whether to plot the max/min bound drop_k: drop the largest and smallest 'drop_k' records when averaging and plotting """ regret = 0 - np.array(reward_histories) N, T = regret.shape # N simulation runs; T steps per run assert N > 2 * drop_k cumulative_regret = np.cumsum(regret, axis=1) cumulative_regret.sort(axis=0) cumulative_regret = cumulative_regret[drop_k:N-drop_k,:] average = np.mean(cumulative_regret, axis=0) t_axis = np.arange(1, T+1) if plot_bound: lower, upper = cumulative_regret[0,:], cumulative_regret[-1,:] plt.fill_between(t_axis, lower, upper, alpha=0.2, color='gray') plt.plot(t_axis, average, label=plot_legend) def plot_incorrect_fraction(reward_histories, plot_legend, plot_bound=False, drop_k=0): """ Plots regret/t vs. t (i.e. fraction of incorrect decisions) reward_history: array of reward_history arrays plot_legend: legend for the plotted curve (string) plot_bound: whether to plot the max/min bound drop_k: drop the largest and smallest 'drop_k' records when averaging and plotting """ regret = 0 - np.array(reward_histories) # value 1 corresponds to incorrect decision N, T = regret.shape # N simulation runs; T steps per run assert N > 2 * drop_k cumulative_regret = np.cumsum(regret, axis=1) incorrect_fraction = cumulative_regret / np.arange(1, T+1) incorrect_fraction.sort(axis=0) incorrect_fraction = incorrect_fraction[drop_k:N-drop_k,:] average = np.mean(incorrect_fraction, axis=0) t_axis = np.arange(1, T+1) if plot_bound: lower, upper = incorrect_fraction[0,:], incorrect_fraction[-1,:] plt.fill_between(t_axis, lower, upper, alpha=0.2, color='gray') plt.plot(t_axis, average, label=plot_legend) def plot_validation_accuracy(val_step_history, val_accuracy_histories, plot_legend, plot_bound=False, drop_k=0): """ Plots cross validation accuracy vs. t plot_legend: legend for the plotted curve (string) plot_bound: whether to plot the max/min bound drop_k: drop the largest and smallest 'drop_k' records when averaging and plotting """ N = len(val_accuracy_histories) assert N > 2 * drop_k accuracy = np.array(val_accuracy_histories) accuracy.sort(axis=0) accuracy = accuracy[drop_k:N-drop_k,:] average = np.mean(accuracy, axis=0) if plot_bound: lower, upper = accuracy[0,:], accuracy[-1,:] plt.fill_between(val_step_history, lower, upper, alpha=0.2, color='gray') plt.plot(val_step_history, average, label=plot_legend)
522a655c0bd5d237ef7a681f13928cf5f01bfee6
yongxuUSTC/leetcode_my
/median_of_two_sorted_arrays.py
3,338
3.5625
4
class Solution(object): def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ ###method1: #nums3=[] #i=0 #j=0 #while(i<len(nums1) and j < len(nums2)): # if (nums1[i] <= nums2[j]): # nums3.append(nums1[i]) # i += 1 # else: # nums3.append(nums2[j]) # j += 1 # #while(i<len(nums1)): # nums3.append(nums1[i]) # i += 1 # #while(j<len(nums2)): # nums3.append(nums2[j]) # j += 1 # #if (len(nums3)%2==1): # return nums3[len(nums3)//2] #else: # return (nums3[len(nums3)//2-1]+nums3[len(nums3)//2])*0.5 ####################################################################################################################### ###method2: #to search the average median in a binary search method, as it asks for log(m+n), for log(m+n): binary search or binary search tree #idea: to find the i-th and j-th element in the begining of the right half in the merged n+m array, so if i, then j=half-j, half=(n+m)/2 m=len(nums1) # assume shorter one, or swap it n=len(nums2) # assume longer one, or swap it if m >n: nums1, nums2, n, m =nums2, nums1, m, n #special cases: if m==0 and n != 0: # one of them is empty if n%2==1: return nums2[n//2] else: return (nums2[n//2-1] + nums2[n//2])*0.5 elif m==0 and n==0: # both of them are empty return None #half=(n+m)/2 ### or (m+n+1)//2 ??? ###bug half=(n+m+1)/2 #i=m//2 #the index in n for the 1st or 2nd index in the whole sorted right half #j=half-i # the index in m for the 1st or 2nd index in the whole sorted right half iMin=0 # only traverse on the m array, so the j in n array can be decided as above, so the time complexity is log(m) iMax=m while iMin <= iMax: i=(iMin+iMax)//2 j=half-i if i<m and nums2[j-1] > nums1[i]: ### [0, j-1] should be all smaller than i, i and j is not comparable, i is too small iMin=i+1 elif i>0 and nums1[i-1] > nums2[j]: ### [0, i-1] should be all smaller than j, i and j is not comparable, i is too large iMax=i-1 else: if i==0: ## all i is larger than all j maxleft=nums2[j-1] ### i==0. so j=half-0=half elif j==0: # i=half-0=half=(n+m)/2, maxleft=nums1[i-1] else: ### nums2[j-1] < nums1[i] or nums1[i-1] < nums2[j], i and j in the middle maxleft=max(nums2[j-1], nums1[i-1]) if i==m: minright=nums2[j] elif j == n: minright=nums1[i] else: minright=min(nums1[i],nums2[j]) if (m+n)%2 == 0: return (minright+maxleft)*0.5 else: return maxleft
e36ad46bc89127df55ef3f64b21d206834500fbd
dhirensr/Ctci-problems-python
/leetocde/bstfromPreorder.py
1,636
3.859375
4
import queue class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def bstFromPreorder(preorder,inorder,start,end): if len(preorder)==0: return None elif (start > end): return None elif( start ==end): root = TreeNode(inorder[start]) return root search_array = inorder[start:end] index= None # print(start,end,action) for i in preorder: if(i in search_array): root = TreeNode(i) preorder.remove(i) index = inorder.index(i) #print(index,preorder) break if(index!=None): root.left = bstFromPreorder(preorder,inorder,start,index-1) root.right = bstFromPreorder(preorder,inorder,index+1,end) return root else: return None root = bstFromPreorder([4,2],[2,4],0,1) result = [root.val] q = queue.Queue() q.put(root) while not q.empty(): val = q.get() if val.left != None or val.right != None: if(val.left != None): q.put(val.left) result.append(val.left.val) else: result.append(None) if(val.right != None): q.put(val.right) result.append(val.right.val) else: result.append(None) print(result) def bstFromPreorder(preorder): inorder = sorted(preorder) if not preorder: return None root = TreeNode(preorder[0]) idx = inorder.index(preorder[0]) root.left = self.bstFromPreorder(preorder[1:idx + 1]) root.right = self.bstFromPreorder(preorder[idx + 1:]) return root
9a6dcffb3b8c7af0fb2f8b774a0e36d8ee18fc53
jingyiZhang123/leetcode_practice
/array/remove_duplicated_from_sorted_array2_80.py
1,230
4.03125
4
""" Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? For example, Given sorted array nums = [1,1,1,2,2,3], Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length. """ class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 result = 1 record_index = 1 record_num = nums[0] record_len = 1 data_len = len(nums) for i in range(1, data_len): if nums[i] > record_num: record_num = nums[i] nums[record_index] = nums[i] record_index += 1 result += 1 record_len = 1 elif nums[i] == record_num: if record_len < 2: nums[record_index] = nums[i] record_len += 1 record_index += 1 result += 1 return result L = [1,1,1,1,3,3] result = Solution().removeDuplicates(L) print(result, L)
0a470515f9aa9cc918eb85ebee38f9607377bcc7
DrishtiSabhaya/ParkingManagementSystem
/Training/parking_color.py
2,002
3.578125
4
#Building the CNN #importing libraries from keras.models import Sequential from keras.layers import Convolution2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense from PIL import Image #Initializing CNN classifier = Sequential() #Color version #Step-1 Convolution conv_layer_1 = Convolution2D(32, 3, 3, input_shape=(32, 32, 3), activation="relu") classifier.add(conv_layer_1) #Step-2 pooling classifier.add(MaxPooling2D(pool_size=(2,2))) #Adding second conv layer conv_layer_2 = Convolution2D(32, 3, 3, input_shape=(32, 32, 3), activation="relu") classifier.add(conv_layer_2) classifier.add(MaxPooling2D(pool_size=(2,2))) #Step-3 Flattening classifier.add(Flatten()) #Step-4 Full Connection classifier.add(Dense(output_dim = 128, activation="relu")) classifier.add(Dense(output_dim = 1, activation="sigmoid")) #Compiling the CNN classifier.compile(optimizer="adam", loss="binary_crossentropy", metrics=['accuracy']) #Fitting the CNN to dataset from keras_preprocessing.image import ImageDataGenerator train_datagen = ImageDataGenerator( rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True) test_datagen = ImageDataGenerator(rescale=1./255) training_set = train_datagen.flow_from_directory('dataset/training', target_size=(32, 32), batch_size=32, class_mode='binary') test_set = test_datagen.flow_from_directory( 'dataset/test', target_size=(32, 32), batch_size=32, class_mode='binary') from PIL import Image classifier.fit_generator( training_set, steps_per_epoch=300, epochs=30, validation_data=test_set, validation_steps=2930) classifier.save("models/parking_color_32.h5")
a923848e72d3cc98e73c5df962003cf868f53c68
HamedSanaei/CloudProject
/DataCenterTopologies/Switch.py
1,077
3.515625
4
# this is an object oriented way but is not completed class Switch: # class level attributes #firstOutput: Switch = Switch(10) # self means compiler prepare currnet instance as a value for the called method # constructor method def __init__(self, number, stype): # instance level attributes # using property self.__number = number self.stype = stype def __str__(self) -> str: return f"this is switch number:({self.number}) with type:({self.stype})" # define a class method @classmethod def factoryMethod(cls) -> Switch: return cls(0, "core") @property def stype(self): return self.__stype @stype.setter def stype(self, stype: str): self.__stype = stype # A readonly property @property def number(self): return self.__number @property def connectedSwithes(self): return self.__connectedSwithes @connectedSwithes.setter def connectedSwithes(self, switchList: list): self.__connectedSwithes = switchList
8c3c264b352fb9dab27208dd526e647446e7c4ae
mdilauro39/ifdytn210
/sistemagestioninstituto/original/pais_view.py
2,380
3.5
4
# -*- coding: utf-8 *-* class PaisView: def __init__(self): self.tab1 = " " self.tab2 = " " * 2 self.tab3 = " " * 3 self.txt_opt = "%sElija una opción: " % self.tab2 self.txt_nombre = "%sPaís: " % self.tab3 self.txt_apellido = "%sAbreviatura: " % self.tab3 self.txt_id = "%sID de país: " % self.tab3 pass def mostrar_menu(self): """Vista del menú de opciones""" menu = """ Menú del Gestor de Países (1) Crear un país (2) Ver listado de países (3) Editar un país (4) Eliminar un país (0) Salir """ print menu opcion = raw_input(self.txt_opt) return opcion def crear_pais(self): """Vista del formulario para crear nuevo país""" print """ CREAR UN NUEVO PAÍS """ nombre = raw_input(self.txt_nombre) apellido = raw_input(self.txt_apellido) return (nombre, apellido) def confirmar_creacion(self): """Vista de confirmación de creación de nuevo país""" print """ País creado con éxito! """ def listar_paises(self, listado): """Vista para el listado de países""" print """ LISTADO DE PAÍSES: """ for row in listado: id = row[0] pais = row[1] abbr = row[2] print "%s[%d] %s (%s)" % (self.tab3, id, pais, abbr) def editar_pais(self, listado): """Vista del formulario para editar un país""" self.listar_paises(listado) print "\n\n" id = raw_input(self.txt_id) print "\n" pais = raw_input(self.txt_pais) abbr = raw_input(self.txt_abbr) return (id, pais, abbr) def confirmar_editar_pais(self): """Vista de confirmación de edición""" print """ País editado correctamente. """ def eliminar_pais(self, listado): """Vista de formulario para eliminar país""" self.listar_paises(listado) print "\n\n" id = raw_input(self.txt_id) print "\n" return id def confirmar_eliminar_pais(self): """Vista de cofirmación eliminar país""" print """ País eliminado correctamente. """
dc30ad813259a9a771356b6a409f2bc995fa123c
donhuvy/fluent-python
/02-array-seq/bisect_grade.py
404
3.546875
4
''' Ref: https://docs.python.org/3/library/bisect.html ''' import bisect def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'): # bisect.biset_left would be the wrong one to use here :) i = bisect.bisect(breakpoints, score) return grades[i] if __name__ == "__main__": scores = [33, 99, 77, 70, 89, 90, 100] for score in scores: print(f"{score} -> {grade(score)}")
f5d82c152bdf7445bd7a1f7bf0c500f92e2b601f
kmzn128/CCI_Python
/CCI_1/CCI_10/10_1_2.py
607
3.75
4
def _insert(li, el, l, r): if(r-l < 0): return if(r-l == 0): if(li[l] > el): li.insert(l,el) else: #if(l == len(li)): # li.append(el) #else: li.insert(l+1, el) mid = l + (r-l)//2 if(el < li[mid]): _insert(li,el,l,mid-1) else: _insert(li,el,mid+1,r) def insert_another_array(a, b): left = 0 for elem_b in b: right = len(a)-1 _insert(a, elem_b, left, right) a = [2,4,8,14,26,35,46,78,90,100] b = [23,34,45,56,67,200] insert_another_array(a, b) print(a)
4172c269bbae488c99dacff5fdd3f1c393a06314
nixonpj/leetcode
/Number of 1 Bits.py
629
3.734375
4
""" Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). Constraints: The input must be a binary string of length 32. Follow up: If this function is called many times, how would you optimize it? """ class Solution: def hammingWeight(self, n: int) -> int: one_count = 0 i = 1 n = abs(n) while n: x = (n % 2 ** i) one_count += bool(x) print(n, 2 ** i, x, one_count) n = n - x i += 1 return one_count s = Solution() print(s.hammingWeight(15))
bbb4c8f0789e09408fe7b233ac52191926c940ed
tushargoyal02/pyautogui_repo
/basic_cmd.py
699
3.59375
4
# SOME COMMAN COMMAND FOR FUTURE import pyautogui # move the cursor left right up to the point according to current location ''' - up and bottom (-x mean to the left, -y mean to the up) # Click mouse button -> pyautogui.rightClick() -> pyautogui.doubleClick() -> pyautogui.click(button='right', click=2, interval=0.1) - denote the type of click, number of time click and interval of click # Drag and drop of mouse -> pyautogui.moveTo(x,y,duartion=1) -> pyautogui.mouseDown(button='left') -> pyautogui.moveTo(x2,y2, duration=2) -> pyautogui.mouseUp(button='left') OR -> pyautogui.moveTo(x2,y2, duration=2) -> pyautogui.dragTo(x2,y2, duration=2) ''' pyautogui.move(380,115)
201aa841324e1b0cbbf30b8d9378de0acf6a0dda
williamf1/Maths-Cheating-Device
/pover-of.py
1,410
4.0625
4
import time #hi #start print(""" o o o o o o o o o o o o o o o o o o o o o o o o o o o o (for the power of) """) #login needspassword=True while needspassword==True: #username/password input username=raw_input("username:") password=raw_input("password:") #userpass codes if username!="m c d" or password!="m c d": print(" ") print ("incorrect username/password") else: needspassword=False #introduction print(" ") print("welcome to the maths cheating device (for the power of) ") print(" ") #how to time.sleep(1) print("follow the instructions to get your answers") print(" ") #contact time.sleep(1) print("if you need help contact:ken.faulkner.gh@gmail.com") print(" ") time.sleep(1) #input for calculator base=raw_input("base number?") power=raw_input("to the power of") #waiting to give answers print("calculating. ") time.sleep(0.5) print("calculating.. ") time.sleep(0.5) print("calculating... ") time.sleep(0.5) print("calculating. ") time.sleep(0.5) print("calculating.. ") time.sleep(0.5) print("calculating... ") time.sleep(1) print("finished") time.sleep(1) #calculator answer=int(base) for x in range(int(power)-1) : answer=answer*int(base) print("answer"+str(answer))
d8a782bf78cbb1db7a6dd77ddf3376495deb9411
bkyileo/algorithm-practice
/python/Combination Sum II.py
1,334
3.8125
4
# coding=utf-8 __author__ = 'BK' ''' Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. Each number in C may only be used once in the combination. Note: All numbers (including target) will be positive integers. Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak). The solution set must not contain duplicate combinations. For example, given candidate set 10,1,2,7,6,1,5 and target 8, A solution set is: [1, 7] [1, 2, 5] [2, 6] [1, 1, 6] Subscribe to see which companies asked this question ''' class Solution(object): def helper(self,cand,target,re,temp): if target==0: if temp not in re: re.append(temp) return for i,num in enumerate(cand): if num <= target: self.helper(cand[i+1:],target-num,re,temp+[num]) def combinationSum2(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ candidates.sort() re=[] temp=[] self.helper(candidates,target,re,temp) return re cand = [10,1,2,7,6,1,5] target = 8 solu=Solution() print solu.combinationSum2(cand,target)
17c8262752f9ebccdd3275d32e7f1b3dbe477372
rafaelgama/Curso_Python
/Udemy/Secao3/aula68.py
1,070
4.09375
4
# Zip - Unindo iteráveis # Zip_longest - Itertools from itertools import zip_longest, count # O Zip une os Iteraveis com a mesma quantidade descartando o que sobra. #Exemplos de ZIP cidades = ['São Paulo','Belo horizonte','Salvador','Campinas'] estados = ['SP','MG','BA'] cid_est = zip(cidades, estados) print(cid_est) # transformar em lista de novo #print(list(cid_est)) for valor in cid_est: print(valor) print('-=-' * 20) # O Zip_longest une os Iteraveis mesmo que não tenha a mesma quantidade #Exemplos de Zip_longest """cid = ['São Paulo','Belo horizonte','Salvador','Campinas'] est = ['SP','MG','BA'] cidest = zip_longest(cid, est, fillvalue='Estado') #fillvalue é utilizado para preencher os que são vazios. print(cidest) for val in cidest: print(val) print('-=-' * 20)""" #Exemplos de Zip com count ind = count() cid = ['São Paulo','Belo horizonte','Salvador','Campinas'] est = ['SP','MG','BA'] cidest = zip(ind, est, cid) #fillvalue é utilizado para preencher os que são vazios. print(cidest) for val in cidest: print(val)
ffa082853669da04b93d0afd82004fcc1441973a
moontasirabtahee/Problem-Solving
/Leetcode/1389. Create Target Array in the Given Order.py
327
3.625
4
from typing import List class Solution: def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]: target_array = [] for n, i in zip(nums, index): target_array.insert(i, n) return target_array sol = Solution() print(sol.createTargetArray([1,2,3,4,0], [0,1,2,3,0]))
19b60d8ad9343d5698d10530cdaa7595d9defa8a
bluejok3/TADEJ_Louis_M1RES
/Python_M1.py
15,002
3.96875
4
#TD1 #!/usr/bin/env python # coding: utf-8 # In[1]: x = 5 y = 10 z = 7 print ( x + y - z ) # In[3]: a = "je suis" b = "un beau" c = "gosse" print (a, b, c) # In[5]: print ( 10000 > 1) print ( 1==1) print (1 < 0) # In[3]: prenom = "Louis " nom = "Tadej" nom_complet = prenom + nom print (nom_complet) i= 0 while i <= 100: print('L T') i = i+1 # In[4]: a = input ("salut bg c'est quoi ton prénom ? ") b = int (input("tu m'as l'air jeune et dynamique, t'as quel age ? ")) # In[9]: Celsius = int (input("Entrez la température Celsius: ")) Farhenheit= 9/5 * Celsius + 32 print ("Température: ", Celsius, "Farhenheit = ", Farhenheit, " F") Farhenheit = int(input("Rentre la température en farhenheit: ")) Celsius = (Farhenheit-32)*5/9 print ("Temperature: ", Farhenheit, "Celsius =", Celsius, " C") # In[10]: A=input('Entrer une valeur de verite pour A: (entrer False ou True)') B=input('Entrer une valeur de verite pour B: (entrer False ou True)') C=input('Entrer une valeur de verite pour C: (entrer False ou True)') expression_bol=input('Entrer une expression Bolenne avec des "non", "ou", "et", et des parentheses:') expression_bol.replace('non', 'not') expression_bol.replace('et', 'and') expression_bol.replace('ou', 'or') print (bool(expression_bol)) # In[ ]: #TD2 #!/usr/bin/env python # coding: utf-8 # In[1]: # Exercice 1 | questions 1 et 2 c = "X44bf38j23jdjgfjh737nei47" c_num = "" c_alpha = "" for caracters in c: if str.isdigit(caracters) == True: c_num += caracters else: c_alpha += caracters print(c_num, c_alpha) # In[2]: # Exercice 1 | question 3 str_find = "j23" c.find(str_find) if c.find(str_find) != -1: new_c = c.replace(str_find, "j24") print(new_c) # In[3]: # Exercice 1 | question 4 list = ["f","3","7"] for string in list: first = c.find(string) print(first) print("\n") # In[4]: # Exercice 2 question 1 (a,b et c) texte = "We introduce here the Python language" compteur = 0 for lettre in texte: compteur += 1 if compteur == len(texte): print("good") else: print("not good") # Sans compter les espaces compteur_lettre = 0 for lettre in texte: if lettre == " ": pass else: compteur_lettre += 1 print(compteur_lettre) # Compter les mots dans la variable texte mots = len(texte.split()) print(mots) # In[5]: # Exercice 2 question 2 # Cela est toujours viable puisque le module split est utilisé texte2 = "We introduce here the Python language. To learn more about the language, consider going through the excellent tutorial https://docs.python.org/ tutorial. Dedicated books are also available, such as http://www.diveintopython.net/." mots = len(texte2.split()) print(mots) # In[6]: # Exo 3 | 1-2 n = input("Entrer des mots separes par un espace : ") user_list = n.split() list_triee = sorted(user_list) print(list_triee) # In[17]: # exercice 4 questions 1 à 3 Couleurs = ["Pique", "Trefle", "Carreau", "Coeur"] valeurs = [2, 3, 4, 5, 6, 7, 8, 9, 10, "valet", "dame", "roi", "as"] deck = [] for C in Couleurs: for v in valeurs: card = str(v) + " " + str(C) deck.append(card) #print(deck) from random import shuffle shuffle(deck) print(deck) joueur1 = [] joueur2 = [] joueur3 = [] joueur4 = [] for index in range(13): joueur1.append(deck[index]) joueur2.append(deck[index + 1]) joueur3.append(deck[index + 2]) joueur4.append(deck[index + 3]) print(" J1 = " + str(joueur1)) print(" J2 = " + str(joueur2)) print(" J3 = " + str(joueur3)) print(" J4 = " + str(joueur4)) # In[29]: # exercice 5 question 1 et 2 with open("diamonds.csv", "r") as f: diamants=f.readlines() diamants[10].split(",") # In[31]: #exercice 5 question 3 with open("diamonds.csv", "r")as f: diamants_100=f.readlines() diamants_100[:20] # In[47]: #exercice 5 question 4 with open("diamonds.csv", "r")as f: diamants_prix=f.readlines(100000) num_columns = len(5) diamonds.csv(5) diamants_prix[:20] # In[5]: #exercice 6 question 1 infoEleves = input("Entrer prenom, nom et matricule étudiant séparés par un espace : ") list = infoEleves.split(" ") lepie= tuple(list) print(lepie) main_list = [] # In[6]: #exercice 6 question 2 et 3 while True: choix = input("Entrer prénom, nom et matricule étudiant séparés par un espace : (FIN pour finir) ") if choix == "FIN": break else: list = choix.split(" ") matricule = tuple(list) main_list.append(matricule) for etudiant in main_list: print(etudiant[0]) # In[7]: #exercice 7 questions 1 à 3 fr_en = { "jardin": "garden", "voiture": "car", "soleil": "sun", "cerveau": "brain" } for cle, valeur in fr_en.items(): if cle == "cerveau": print(valeur) else: pass # In[8]: #exercice 7 question 4 en_fr = {} for cle, valeur in fr_en.items(): en_fr[valeur] = cle # assigne cette cle avec cette valeur print(en_fr) # In[10]: #exercice 7 question 5 if "brain" in (en_fr): # par défaut dans les clés pour values .values print("la traduction est ici") # In[12]: #exercice 7 question 6 for cle, values in en_fr.items(): if en_fr[cle] == "cerveau": print("clé = " + cle, "valeur = " + values) # In[13]: #exercice 7 question 7 à 10 new = { "jardin": ["garden", "Garten"], "voiture": ["car", "Wagen"], "soleil": ["sun", "Sonne"], "cerveau": ["brain", "Gehirn"], "chemin" : ["path", "Pfad"] } for cle, values in new.items(): if cle == "chemin": print ("la deuxième traducion du mot chemin est : " + values[1]) del new["chemin"] print(new) # In[17]: #exercice 8 questions 1 et 2 etudiant = {} while True: choix = input("Entrer le prénom, nom et matricule étudiant séparés par un espace : (FIN pour finir) ") if choix == "FIN": break else: list = choix.split(" ") lepie = tuple(list) count = 0 for cle in etudiant.keys(): if lepie[1] in cle: count += 1 if count > 0: new_key = montuple[1] + str(count) etudiant[new_key] = lepie else: etudiant[lepie[1]] = lepie print(etudiant) # In[18]: #exercice 8 question 3 for keys in etudiant.keys(): print("Nom étudiant : " + keys) # In[19]: #exercice 8 question 4 if "Obama" in (etudiant): print(etudiant["Obama"]) # In[20]: #exercice 8 question 5 for cle, values in etudiant.items(): if values[2] == "12345678": print("cle " + str(cle), "valeur " + str(values)) # In[ ]: #TD3 #!/usr/bin/env python # coding: utf-8 # In[7]: # Exercice 1 | question 1 def exo1_1(): utilisateur = int(input("Entrer un nombre à multiplier : ")) for x in range(1,6): print(utilisateur*x) # Exercice 1 | question 2 def exo1_2(): user = int(input("Entrer un nombre à multiplier : ")) for x in range(1, 11): print(utilisateur*x, end=" ") # Exercice 1 | question 3 def exo1_3(): user = int(input("Entrer un nombre à trouver sa table : ")) for x in range(utilisateur): print("Table de", int(x) + 1, ":") for i in range(1, 11): print((x+1)*i,) # Exercice 1 | question 4 def exo1_4(): user = int(input("Entrer un nombre à afficher en asterisk : ")) for x in range(utilisateur): print("*" * (x+1)) # Exercice 1 | question 5 def exo1_5(): user = int(input("Entrer un nombre à afficher en asterisk : ")) for x in range(utilisateur): print(" " * ((user-1)-x) + ("* " * (x+1))) # In[2]: # Exercice 2 | question 1 def exo2_1(): jours = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] mois = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] mj = [] longueur = len(jours) - len(mois) if longueur == 0: for x in range(len(jours)): mj.append((mois[x], jours[x])) else: print("can't do it") return mj mj = exo2_1() # Le laisser sinon l'exo exo2 question 2() n'a pas la variable mj # print(mj) si on veut display mj # Exercice 2 | question 2 def exo2_2(): annee = [] for month in mj: for x in range(month[1]): annee.append((str(x+1)) + " " + month[0]) return annee annee = exo2_2() # Le laisser sinon exo2_3() n'a pas la variable annee # print(annee) si on veut display annee # Exercice 2 | question 3 def exo2_3(): annee2 = [] jours_semaine = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] for jour in range(365): annee2.append(jours_semaine[jour%len(jours_semaine)] + " " + annee[jour]) return annee2 annee2 = exo2_3() #print(annee2) # si on veut display annee2 # Exercice 2 | questions 4 et 5 def exo2_4_5(): dico = {} jours_semaine = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] for jour in range(365): dico[annee[jour]] = jours_semaine[jour%len(jours_semaine)] print(dico) print(dico["28 October"]) # exo2_4_5() # In[3]: #exercice 3 question 1 def exo3_1(): liste_notes = [] while len(liste_notes) < 3: user = int(input("Entrer une note : ")) liste_notes.append(user) minimum = min(liste_notes) maximum = max(liste_notes) somme = 0 for notes in liste_notes: somme += int(notes) moyenne = float(somme)/len(liste_notes) print("moyenne " + str(moyenne), "minimum " + str(minimum), "maximum " + str(maximum)) # Exercice 3 | question 2 def exo3_2(): utili = int(input("Entrer le nombre de notes que vous voulez entrer ? ")) liste_notes = [] while len(liste_notes) < utili: user = int(input("Entrer une note : ")) liste_notes.append(user) mini = min(liste_notes) maxi = max(liste_notes) som = 0 for notes in liste_notes: som += int(notes) moy = float(som) / len(liste_notes) print("moyenne " + str(moy), "minimum " + str(mini), "maximum " + str(maxi)) #exercice 3 question 3 def exo3_3(): liste_notes = [] while True: user = input("Entrer une note : (fin pour finir) ") if user == "fin": break else: liste_notes.append(float(user)) mini = min(liste_notes) maxi = max(liste_notes) som = 0 for notes in liste_notes: som += int(notes) moy = float(som) / len(liste_notes) print("moyenne " + str(moy), "minimum " + str(mini), "maximum " + str(maxi)) # In[4]: #Exercice 4 from random import * def exo4(): alea21 = randint(1,100) correct = False while not correct: user = int(input("Devine le nombre entre 1 et 100 ")) if alea21 > user: print("Trop Petit !") elif alea21 < user: print("trop Grand !") elif alea21 == user: break if alea21 == user: rejoue = input ("bien joué mek, on rejoue ? (y or n) ") if rejoue == 'y': exo4() # In[ ]: #TD4 #Exercice 1 question 1 from math import pi; def surf_cercle(r): #variable r pour le rayon return pi(r**2) r = input("saissisez R :") surf_cercle(r) # In[12]: #Exercice 1 question 2 def surf_cercle2(r=1): return pi(r2) # In[14]: #exercice 1 question 3 def vol_boite(L,l,h): #h=hauteur, L=Longueur et l=largueur h=float(input("entrer la hauteur de votre boite :")) L=float(input("entrer la Longueur de votre boite :")) l=float(input("entrer la largueur de votre boite :")) return Llh # In[15]: #exercice 1 question 4 def vol_boite2(x=None,y=None,z=None): #définition des arguments x,y,z et qui par défaut n'ont pas de valeur (soit 'None') if y==None and z==None: #si y et z n'ont pas de valeur (None) return x3 elif z==None: #si z n'a pas de valeur (None) return (x*2)y else: return xyz # In[16]: def remplacement(c1,c2,ch): return ch.replace(c1,c2) # In[17]: def remplacement2(c1=" ",c2="",ch=""): return ch.replace(c1,c2) # In[18]: #exercice 2 def nb_car(chaine): nb_car=0 for car in chaine: if car == " ": pass else: nb_car+=1 return nb_car def nb_mots(chaine): nb_mots=len(chaine.split()) return nb_mots # In[19]: #exercice 3 question 1 def TableMult(n,debut=1,fin=10): for x in range(debut,fin+1): print((nx),end=" ") # In[ ]: #exerice 3 question 2 def TableMult2(n,debut=1,fin=10): if debut>fin : for x in range(debut,fin,-1): print((nx),end=" ") else: for x in range(debut,fin+1): print((nx),end=" ") # In[ ]: #exercice 3 question 3 # In[ ]: #exercice 4 def motus(): from random import randint mots = ["arbre", "grave", "piece", "nuage", "crane", "sonne", "table", "herbe", "ecrou", "mulet"] number = randint(0, len(mots) - 1) random_word = mots[number] word = [] word[:0] = random_word user = [] for x in range(len(word)): user.append("-") print(" ".join(user)) compteur = 0 while True: compteur += 1 if compteur == 11: break else: print("Essai numéro : " + str(compteur)) ask = input("Entrez une lettre : ") for i in range(len(word)): if ask == word[i]: user[i] = word[i] if user == word: print(" ".join(user)) win = input("Bravo! Envie de rejouer ? y/n ") if win == "y": motus() else: exit() else: pass print(" ".join(user)) rejoue = input("Perdu... Voulez-vous rejouer y/n : ") if rejoue == "y": motus() motus() # In[ ]: #exo 6 #!/usr/bin/env python # coding: utf-8 # In[2]: import pandas as pd import numpy as np data = pd.read_csv # In[4]: #Remplacement des valeurs vides par la moyenn data = data.replace('unknown', np.nan) data('prod_cost') = pd.to_numeric(data['prod_cost']) print(data['prod_cost']) data('prod_cost') = data('prod_costr').replace(np.nan, data['prod_cost'].mean()) print(data['prod_cost']) # In[5]: data = pd.read_csv('mover_market_snapshot.csv', sep=";") data('warranty')=pd.to_numeric(data["warranty"].str[0]) print(data('warranty')) # In[6]: data=pd.read_csv('mover_market_snapshot.csv', sep=";") data.product_type= pd.Categorical(data.product_type) data['product_type']=data.product_type.cat.codes data['product_type']= pd.factorize(data['product_types'])[0] + 1 print(data['product_type']) # In[7]: df = pd.read_csv('mover_market_snapshot.csv', rep=";") df = pd.get_dummies(df.product_type, prefix='product_type') df.head() # In[ ]:
c67a2f09b9e40519ab6ca472d90a351932e49eda
DEADalus9/Test
/Lesson_4/Task_2.py
3,050
3.984375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed May 20 19:14:01 2020 @author: vladislav MATHEMATICAL PENDULUM """ import graphics as gr import math G = 0.1 SIZE_X = 400 SIZE_Y = 400 BALL_RADIUS = 10 window = gr.GraphWin('MATHEMATICAL PENDULUM', SIZE_X, SIZE_Y) # Initial point of pendulum coords = gr.Point(100, 200) # Previous point of pendulum coords_old = gr.Point(100, 200) # Zero point zero_coords = gr.Point(SIZE_X / 2, 0) # Initial velocity of pendulum velocity = gr.Point(0, 0) # Initial acceleration acceleration = gr.Point(0, 0) def sub(point_1, point_2): return gr.Point(point_1.x - point_2.x, point_1.y - point_2.y) def add(point_1, point_2): return gr.Point(point_1.x + point_2.x, point_1.y + point_2.y) def update_velocity(velocity, acceleration): return add(velocity, acceleration) def update_coords(coords, velocity): return add(coords, velocity) length = ((sub(coords, zero_coords).x) ** 2 + (sub(coords, zero_coords).y) ** 2) ** 0.5 print(length) def check_coordinates(coords, zero_coords): """ distance = sub(coords, zero_coords) distance_2 = (distance.x ** 2 + distance.y ** 2) ** 0.5 print('distance =', distance_2) coords = gr.Point(coords.x + distance_2 + length, coords.y + distance_2 + length) """ if coords.x == SIZE_X / 2: coords.y = length elif coords.x < SIZE_X / 2: coords.y = length else: coords.y = length def check_coords(coords, velocity): """ Check colission between Ball and Walls Parameters ---------- coords : Tuple of Int Coordinates of Ball. velocity : Int Velocity of Ball. Returns ------- None. """ if 0 >= coords.y - BALL_RADIUS or coords.y + BALL_RADIUS >= SIZE_Y: velocity.y = -velocity.y if 0 >= coords.x - BALL_RADIUS or coords.x + BALL_RADIUS >= SIZE_X: velocity.x = -velocity.x def update_acceleration(ball_coords, center_coords): accel_x = (ball_coords.x / length) ** 2 * G accel_y = length - ball_coords.y print('acc_x = {} acc_y = {}'.format(accel_x, accel_y)) if ball_coords.x < SIZE_X / 2: return gr.Point(accel_x, -accel_y) elif ball_coords.x == 0: return gr.Point(0, 0) else: return gr.Point(-accel_x , accel_y) ball = gr.Circle(coords, BALL_RADIUS) ball.setFill('blue') ball.draw(window) def cord_line(cords, zero_cords): cord = gr.Line(coords, zero_coords) cord.setWidth(3) cord.draw(window) while True: acceleration = update_acceleration(coords, zero_coords) velocity = update_velocity(velocity, acceleration) coords = update_coords(coords, velocity) #check_coordinates(coords, zero_coords) check_coords(coords, velocity) deltas = sub(coords, coords_old) ball.move(deltas.x, deltas.y) #cord_line(coords, zero_coords) coords_old = gr.Point(coords.x, coords.y)
bfb00704f74b832d5e21bf2956f7a619c4d8e4da
nandhakumarm/InterviewBit
/LinkedList/swapInPairs.py
1,243
3.859375
4
class ListNode(object): def __init__(self,val): self.val=val self.next=None class Solution(object): def printList(self,A): temp=A while temp!=None: print temp.val, temp=temp.next print "done" def swapPairs(self, head): headtemp=ListNode(0) headtemp.next=head if head==None or head.next==None: return head curr=head next_to_curr=curr.next prev_to_curr=headtemp #Solution.printList(self, next_to_curr) head=next_to_curr while curr!=None and curr.next!=None: curr=prev_to_curr.next prev_to_curr.next=None next_to_curr=curr.next temp=curr.next.next next_to_curr.next=None next_to_curr.next=curr curr.next=temp prev_to_curr.next=next_to_curr prev_to_curr=curr curr=temp #next_to_curr=curr.next return head l1=ListNode(1) l1.next=ListNode(2) l1.next.next=ListNode(3) l1.next.next.next=ListNode(4) #l1.next.next.next.next=ListNode(5) sol=Solution() sol.printList(sol.swapPairs(l1)) l2=ListNode(3) sol.printList(sol.swapPairs(l2))
40a544242594dbde0c1fff9007fea7488bf14bc5
libus1204/bigdata2019
/01. Jump to python/chap05/Restaurant_ver_2.py
1,026
3.546875
4
class MyRestaurant_ver_2: def __init__(self, name, type): self.restaurant_name = name self.cuisine_type = type def describe_restaurant(self): print("저희 레스토랑 명칭은 '%s'이고, %s 전문점입니다." %(self.restaurant_name, self.cuisine_type)) print("저희 %s 레스토랑이 오픈했습니다." % self.restaurant_name) def __del__(self): print("%s 레스토랑 문닫습니다." % self.restaurant_name) restaurant=[] for count in range(3): user_input = str(input("레스토랑 이름과 요리 종류를 선택하세요.(공백으로 구분) : ")) user_restaurant = user_input.split(' ') name = user_restaurant[0] type = user_restaurant[1] # restaurant.append(count) # restaurant[count] = MyRestaurant_ver_2(name, type) # restaurant[count].describe_restaurant() restaurant.append(MyRestaurant_ver_2(name, type)) restaurant[count].describe_restaurant() print(restaurant) print("\n저녁 10시가 되었습니다.\n")
23d8a2a2e8bf67696f7c27c36a500f3e6a930f47
andriyl1993/Diploma
/letters.py
574
3.734375
4
# -*- coding: utf-8 -*- UKR_ALPHABET = "абвгдеиіїжзийклмнопрстуфхцчшщьєюяАБВГДИІЇЖЗИЙКЛМНОПРСТУФХЦЧШЩЬЄЮЯ" def ukr_letter(letter): return letter in UKR_ALPHABET def work_ukr_chars(word): for s in word: if not ukr_letter(s): return False return True def get_words(word): res = [] start = 0 for i, s in enumerate(word): if not ukr_letter(s): if len(word[start:i]): res.append(word[start:i]) start = i + 1 if i != start and len(word[start:i]): res.append(word[start:i]) return res
ff9b9d75bfe8cf77665d502ea0c3cd82329994fa
ankitrana1256/LeetcodeSolutions
/Valid Number[ 82.42% ].py
1,225
3.5625
4
# VALIDATE NUMBERS #s = "0e1" #s = "0" #s = "2" #s = "0089" #s = "-0.1" #s = "+3.14" #s = "4." #s = "-.9" #s ="-90E3" #s = "3e+7" #s = "+6e-1" #s = "53.5e93" #s = "-123.456e789" # NON VALIDATE NUMBERS #s = "abc" #s = "1a" #s = "1e" #s = "e3" #s = "99e2.5" #s = "--6" #s = "-+3" #s = "95a54e53" # CODE count = 0 flag = False dot_count = 0 new_no = "" for i in s: if i.isdigit(): flag = False new_no += i count += 1 if i == "-" or i == "+": if flag == False: new_no += i flag = True else: new_no = None break if i == ".": if dot_count < 1: dot_count += 1 new_no += i else: new_no = None break if i.isalpha(): if i == "e" or i == "E": if count >= 1: new_no += i count += 1 else: new_no = None break else: new_no = None break try: if new_no != None: char = float(new_no) print(True) else: char = None print(False) except ValueError: print(False)
6d9269d2dd3aa1b54190e2a9245efb320390e57c
fantasylsc/LeetCode
/Algorithm/Python/25/0023_Merge_k_Sorted_Lists.py
2,376
4
4
''' Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. Example: Input: [ 1->4->5, 1->3->4, 2->6 ] Output: 1->1->2->3->4->4->5->6 ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # 1. brute force 2. using heap 3. merge two lists # brute force class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: nodes = [] for list in lists: while list: nodes.append(list.val) list = list.next dummy = ListNode(0) head = dummy for node in sorted(nodes): head.next = ListNode(node) head = head.next return dummy.next # solution by merging 2 lists class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: def mergeTwo(l1, l2): dummy = ListNode(0) head = dummy while l1 and l2: if l1.val <= l2.val: head.next = l1 l1 = l1.next else: head.next = l2 l2 = l2.next head = head.next if not l1: head.next = l2 if not l2: head.next = l1 return dummy.next # attention n = len(lists) interval = 1 while interval < n: for i in range(0, n - interval, interval * 2): lists[i] = mergeTwo(lists[i], lists[i + interval]) interval *= 2 return lists[0] if n > 0 else None # solution using heap # import heapq # class Solution: # def mergeKLists(self, lists: List[ListNode]) -> ListNode: # q = [] # for l in lists: # while l: # heapq.heappush(q, l.val) # l = l.next # dummy = ListNode(0) # head = dummy # while q: # val = heapq.heappop(q) # head.next = ListNode(val) # head = head.next # return dummy.next
8a00bd639cd42e5d1e5a00bda63699962d624a6d
bestchanges/hello_python
/sessions/4/pavel_shchegolevatykh/conv.py
2,229
4.09375
4
import rates def print_rates(exchange_rates_to_print): print('output:') for rate in exchange_rates_to_print: print(f'{rate[0]} {rate[1]}') def get_rates(): value_to_convert = input('input value to check (e.g. 10 USD): ') processed_value = value_to_convert.split(' ', 1) try: amount = float(processed_value[0]) currency = processed_value[1].upper() except ValueError: print('Input string is not in proper format') exchange_rates = rates.get_exchange_rates(amount, currency) print_rates(exchange_rates) def parse_rate_value(raw_value): currencies = raw_value.split('/', 1) currency_from = currencies[0].upper() currency_to = currencies[1].split('=')[0].upper() try: rate_amount = float(raw_value.split('=', 1)[1]) except ValueError: print('Input string is not in proper format') return {'from': currency_from, 'to': currency_to, 'rate': rate_amount} def convert_to_string(rate_value): return f'{rate_value["from"]}/{rate_value["to"]}={rate_value["rate"]}\n' def add_or_update_rates(): value_to_enter = input('Please enter value to add or update (e.g. USD/EUR=3): ') rate_value = parse_rate_value(value_to_enter) rates.add_or_update_exchange_rate(rate_value) def load_rates(file_name): with open(file_name, "r") as file_handle: content = file_handle.readlines() result = list([parse_rate_value(line.lower().strip()) for line in content]) return result def save_rates(file_name, data): proper_lines = (convert_to_string(item) for item in data) with open(file_name, "w") as file_handle: file_handle.writelines(proper_lines) try: loaded_exchange_data = load_rates('rates.txt') rates.exchange_data = loaded_exchange_data except FileNotFoundError: pass while True: action = input('Please select action (1 - check rates, 2 - add/update rates, anything else to exit): ') if action == '1': get_rates() elif action == '2': add_or_update_rates() else: print('Invalid action, exiting..') break save_rates('rates.txt', rates.exchange_data)
dad555e524a50bed1f6cfa0e801d77276d91a728
ElliotMoffatt/NetworksCoursework
/gvch48_question1.py
8,311
3.875
4
# -*- coding: utf-8 -*- """ Created on Sat Oct 27 15:36:22 2018 @author: gvch48 """ import random import queue import matplotlib.pyplot as plt def make_ring_group_graph(m,k,p,q): #initialize empty grqph ring_group_graph = {} for vertex in range(m*k): ring_group_graph[vertex] = [] for vertex in range(m*k): for other_vertex in range(vertex+1,m*k): groupDiff = (other_vertex % m) - (vertex % m) random_number = random.random() if groupDiff in [-1,0,1,m-1] and random_number < p and other_vertex not in ring_group_graph[vertex]: ring_group_graph[vertex] += [other_vertex] ring_group_graph[other_vertex] += [vertex] elif random_number < q and other_vertex not in ring_group_graph[vertex]: ring_group_graph[vertex] += [other_vertex] ring_group_graph[other_vertex] += [vertex] return ring_group_graph def compute_degrees(graph): """Takes a graph and computes the degrees for the nodes in the graph. Returns a dictionary with the same set of keys (nodes) and the values are the degrees.""" #initialize degrees dictionary with zero values for all vertices degree = {} for vertex in range( len(graph) ): degree[vertex] = 0 #consider each vertex for vertex in range( len(graph) ): for neighbour in graph[vertex]: degree[vertex] += 1 return degree def degree_distribution(graph): """Takes a graph and computes the unnormalized distribution of the degrees of the graph. Returns a dictionary whose keys correspond to degrees of nodes in the graph and values are the number of nodes with that degree. Degrees with no corresponding nodes in the graph are not included in the dictionary.""" #find in_degrees degree = compute_degrees(graph) #initialize dictionary for degree distribution degree_distribution = {} #consider each vertex for vertex in degree: #update degree_distribution if degree[vertex] in degree_distribution: degree_distribution[degree[vertex]] += 1 else: degree_distribution[degree[vertex]] = 1 return degree_distribution def max_dist(graph, source): """finds the distance (the length of the shortest path) from the source to every other vertex in the same component using breadth-first search, and returns the value of the largest distance found""" q = queue.Queue() found = {} distance = {} for vertex in range(len(graph)): found[vertex] = 0 distance[vertex] = -1 max_distance = 0 found[source] = 1 distance[source] = 0 q.put(source) while q.empty() == False: current = q.get() for neighbour in graph[current]: if found[neighbour] == 0: found[neighbour] = 1 distance[neighbour] = distance[current] + 1 max_distance = distance[neighbour] q.put(neighbour) return max_distance def diameter(graph): """returns the diameter of a graph, by finding, for each vertex, the maximum length of a shortest path starting at that vertex, and returning the overall maximum""" distances = [] for vertex in graph: #look at each vertex distances += [max_dist(graph, vertex)] #find the distance to the farthest other vertex return max(distances) #return the maximum value found def local_clustering_coefficient(graph, vertex): """returns ratio of edges to possible edges in neighbourhood of vertex""" edges = 0 #look at each pair of neighbours of vertex for neighbour1 in graph[vertex]: for neighbour2 in graph[vertex]: #look at whether neighbour pair are joined by an edge if (neighbour1 < neighbour2) and (neighbour2 in graph[neighbour1]): edges += 1 #divide number of edges found by number of pairs considered return 2*edges/(len(graph[vertex]) * (len(graph[vertex]) - 1)) def average_clustering_coefficient(graph): sum = 0 for vertex in range(len(graph)): sum += local_clustering_coefficient(graph, vertex) return sum/len(graph) def make_distrib_image(m,k,p): # m= int(input("Number of groups: ")) # k= int(input("Number of vertices per group: ")) # p= float(input("Probability of edge between vertices in same or adjacent group: ")) # print("Computing...") graph = make_ring_group_graph(m,k,p,0.5-p) distrib = degree_distribution(graph) normalized_distribution = {} for degree in distrib: normalized_distribution[degree] = distrib[degree] / (m*k) #create arrays for plotting xdata = [] ydata = [] for degree in distrib: xdata += [degree] ydata += [normalized_distribution[degree]] #plot degree distribution plt.clf() #clears plot plt.xlabel('Degree') plt.ylabel('Normalized Rate') plt.title('Normalized Degree Distribution of Graph (m='+str(m)+', k='+str(k)+', p='+str(p)+')') plt.loglog(xdata, ydata, marker='.', linestyle='None', color='b') plt.savefig('normalized degree distrib '+str(m)+' '+str(k) + ' '+str(p)+' .png',dpi=300) def make_diameter_image(m,k,q,minp,maxp,mult_p, num_of_graphs): #points is number of probabilities to compute diameter for. evenly distributed between minp and maxp xdata = [] ydata = [] p = minp while p <= maxp: print(p) graph = make_ring_group_graph(m,k,p,q) xdata += [p] ydata += [diameter(graph)/(m*k)] p *= mult_p if num_of_graphs > 1: for graph_tracker in range(1,num_of_graphs): print('graph: '+str(graph_tracker+1)) graphYdata = [] for p in xdata: graph = make_ring_group_graph(m,k,p,q) graphYdata += [diameter(graph)/(m*k)] for yValue in range(len(graphYdata)): ydata[yValue] += graphYdata[yValue] ydata = [y/num_of_graphs for y in ydata] plt.clf() #clears plot plt.xlabel('Probability') plt.xlim(max(minp-0.05,0),maxp+0.05) plt.ylabel('Normalised Diameter') plt.title('Average Normalised Diameter over '+str(num_of_graphs)+' Graphs (m='+str(m)+', k='+str(k)+', q='+str(q)+')') plt.plot(xdata,ydata,marker='.', linestyle='None', color='b') plt.savefig('normalised diameter vs probability '+str(m)+' '+str(k)+' '+str(q)+' '+str(num_of_graphs)+' .png',dpi=300) def make_clustering_image(m,k,q,minp,maxp,precision, num_of_graphs): #points is number of probabilities to compute diameter for. evenly distributed between minp and maxp xdata = [] ydata = [] p = minp while p < maxp: graph = make_ring_group_graph(m,k,p,q) avrg_cluster_coeff = average_clustering_coefficient(graph) xdata += [p] ydata += [avrg_cluster_coeff] p += precision xdata += maxp ydata += [average_clustering_coefficient(make_ring_group_graph(m,k,maxp,q))] if num_of_graphs > 1: for graph_tracker in range(1,num_of_graphs): print('graph: '+str(graph_tracker+1)) graphYdata = [] for p in xdata: graph = make_ring_group_graph(m,k,p,q) avrg_cluster_coeff = average_clustering_coefficient(graph) graphYdata += [avrg_cluster_coeff] for yValue in range(len(graphYdata)): ydata[yValue] += graphYdata[yValue] ydata = [y/num_of_graphs for y in ydata] plt.clf() #clears plot plt.xlabel('Probability') plt.xlim(minp-precision,maxp+precision) plt.ylabel('Average Clustering Coefficient') plt.title('Average Clustering coeff over '+str(num_of_graphs)+' Graphs (m='+str(m)+', k='+str(k)+', q='+str(q)+')') plt.plot(xdata,ydata,marker='.', linestyle='None', color='b') plt.savefig('average clustering vs probability '+str(m)+' '+str(k)+' '+str(q)+' '+str(num_of_graphs)+' .png',dpi=300,bbox_inches='tight') ####TEST CODE#### #graph = make_ring_group_graph(4,4,0.3,0.2) print("running: make_diameter_image") make_diameter_image(100,10,1/1000,1/200,1,1.2,5)
f9953dcd1cd11c34076f20712da03c3404553284
kuan1/test-python
/100days/02-计算圆.py
217
3.875
4
''' 输入半径计算周长和面积 ''' import math radius = float(input('请输入半径')) perimeter = 2 * math.pi * radius area = math.pi * radius ** 2 print(f'周长:{perimeter}') print(f'面积:{area}')
f2444ebb4e218320a1592ae70cff14312652348d
chinatsui/DimondDog
/algorithm/exercise/hash_table/first_unique_character_in_string.py
754
3.734375
4
""" LeetCode-387 Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. Examples: s = "leetcode" return 0. s = "loveleetcode", return 2. Note: You may assume the string contain only lowercase letters. """ class Solution: @staticmethod def first_unique_char(s): """ :type s: str :rtype: int """ if not s: return -1 ch_idx_map = dict() for (i, ch) in enumerate(s): if ch not in ch_idx_map: ch_idx_map[ch] = i else: del ch_idx_map[ch] return list(ch_idx_map.values())[0] if ch_idx_map else -1 print(Solution().first_unique_char("loveleetcode"))
7933d6fb9bd3ebc440693853af938faf3b7f50ad
DS-PATIL-2019/Trees-4
/KthSmallest.py
701
3.6875
4
""" The approach here is very simple just do a inorder traversal and store the values in the array and return the kth index from the array. A optimization for this could be to keep the count of k and decrease the value of k at every node traversal and then when your k value hits 0 return the node value. Leetcode - Running Time complexity - O(N) Space Complexity - O(N) """ def kthSmallest(self, root, k): arr = self.inorder(root) return arr[k-1] def inorder(self,root): res = [] if root == None: return res if root: res = self.inorder(root.left) res.append(root.val) res = res + self.inorder(root.right) return res
68ff0eb6eec8ada8ffe8e79c335932a87f4a43d6
DayDreamChaser/OnlineJudge
/PTA/B_level/1094_GoogleRecruit.py
726
3.8125
4
# 1094 谷歌的招聘 # 在这个问题上, 用C/C++ 比python快 4倍, 内存只用python的1/8 import math input_nums = input() L, N = [int(num) for num in input_nums.split(" ")] number = input() #length = L def is_prime_sqrt(N): if N <= 1: return False else: flag = True num = int(math.sqrt(N)) for i in range(2, num+1): if (N % i) == 0: flag = False break return flag # 找N以上的, 如果L小于N就不考虑 flag = 0 for i in range(L - N + 1): cur_num = int(number[i:i+N]) num_string = number[i:i+N] # print(cur_num) if 200236, then 0023 if is_prime_sqrt(cur_num): flag = 1 break if flag == 1: print(num_string) else: print("404")
5aeaa8f455435c223fc073f562771679a4bcc85a
BrunoCerberus/Algoritmo
/Ex85.py
519
3.546875
4
""" Faca um algoritmo (pseudocodigo) que leia um vetor (A) de 10 posicoes. Em seguida, compacte o vetor, retirando os valores 0(zero) e negativos, colocando apenas em um vetor B de 10 posicoes os valores validos de forma consecutiva, as posicoes nao utilizadas devem ficar ao final e com valor 0(zero). """ from random import randint A = [] B = [] x = 0 for i in range(0,10): A.append(randint(-100,100)) print(A) while x < 5: for i in A: if i <= 0: B.append(i) A.remove(i) x+=1 print(A) print(B)
b0252c3660d4a8e8dad10eae7ff89af943a7e71b
S1DAL3X/Python
/EncryptCaesar.py
1,336
3.75
4
#скрипт для шифровки\\дешифровки текста по принципу шифра Цезаря alphavite = list(' abcdefghijklmnopqrstuvwxyz/\!?&,')#33 output = [] def coder(text, key): text = text.lower() for label in text: position = alphavite.index(label) newPos = position + key while newPos > len(alphavite): newPos = newPos - len(alphavite) newLabel = alphavite[newPos] output.append(newLabel) for line in output: print(line, end='') def decoder(text, key): text = text.lower() for label in text: position = alphavite.index(label) newPos = position - key newLabel = alphavite[newPos] output.append(newLabel) for line in output: print(line, end = '') def main(): choice = input('Вы хотите (З)акодировать или (Р)асшифровать текст? ') if choice == 'З': text = input('Введите текст: ') key = int(input('Введите ключ от 0 до 24: ')) coder(text, key) elif choice == 'Р': text = input('Введите текст: ') key = int(input('Введите ключ: ')) decoder(text, key) main() #Created by S1DAL3X
2840c8924380c965bd979fed1a430f116749c51a
rice-apps/petition-app
/controllers/netid2name.py
529
3.71875
4
import urllib2 import json api_key = "" def netid2name(netid): # Get the JSON response from the server api_response_string = urllib2.urlopen("http://api.riceapps.org/api/people?key=" + api_key + "&net_id=" + netid).read() api_response = json.loads(api_response_string) # Do something useful with it if api_response["result"] == "success": students = api_response["people"]["students"] return students[0]['name'] else: print "An error was encountered:", api_response["message"]
856d36caf10689fb73a001cd1d610a7cdade356d
nevilkandathil/coding-questions
/003 Closest Value BST/c_BST.py
1,333
3.84375
4
def findClosestValueInBst(tree, target): return closestValue(tree, target, tree.value) ''' Method 1 Average: time O(log(n))| space O(1) Worst: time O(n) | space O(1) ''' # Using recursion def closestValue(tree, target, closest): currentNode = tree while currentNode is not None: if abs(target - closest) > abs(target - currentNode.value): closest = currentNode.value if currentNode.value > target: currentNode = currentNode.left elif currentNode.value < target: currentNode = currentNode.right else: break return closest ''' Method 2 Average: time O(log(n))| space O(log(n)) Worst: time O(n) | space O(n) ''' # def closestValue(tree, target, closest): # if tree is None: # return closest # if abs(target - closest) > abs(target - tree.value): # closest = tree.value # if target < tree.value: # return closestValue(tree.left , target, closest) # elif target > tree.value: # return closestValue(tree.right, target, closest) # else: # return closest # This is the class of the input tree. Do not edit. class BST: def __init__(self, value): self.value = value self.left = None self.right = None ''' Test by creating any required binary tree '''
93d1a777adff41a8c493fb378f1898866855aec5
whwatkinson/maze
/walls/mk1/simple_wall.py
3,871
3.78125
4
from random import randint, getrandbits, choice from typing import Tuple, List from collections import namedtuple from datetime import datetime WallMeta = namedtuple('WallMeta', [ "vertical", "wall_length", "x", "y", "wall_coords", "is_door", "door_coords" ]) class SimpleWall: def __init__( self, maze_height: int, maze_width: int, number_of_walls: int = 10, max_wall_length: int = 5 ): self.maze_height = maze_height self.maze_width = maze_width self.number_of_walls = number_of_walls self.max_wall_length = max_wall_length # TODO add a check for min number of walls if wift/ height is too small self.walls_meta = self.get_walls_meta() @staticmethod def get_wall_coords( vertical: bool, length: int, x: int, y: int ) -> List[Tuple[int, int]]: """ As it says on the tin :param vertical: Is the wall vertical :param length: The length of the wall :param x: The x coordinate :param y: The y coordinate :return: The coordinates of the wall """ wall_coords = [] for _ in range(length): wall_coords.append((x, y)) if vertical: x += 1 else: y += 1 return wall_coords @staticmethod def narnia(x: int, y: int, wall_length: int, temporal: int) -> bool: """ Is there a door, deterministic with the illusion of randomness :param x: :param y: :param wall_length: :param temporal: :return: """ if wall_length < 3: return False # Combine coords to get unique identifier lucy = (x + y) % 4 edmund = temporal % 8 aslan = True if (lucy == 0 and edmund == 0) else False return aslan def determine_wall_upper_bound( self, vertical: bool, wall_length: int ) -> Tuple[int, int]: if vertical: try: x = randint(1, self.maze_height - wall_length - 1) except ValueError: x = 1 y = randint(1, self.maze_width - 1) else: x = randint(1, self.maze_height - 1) try: y = randint(1, self.maze_width - wall_length - 1) except ValueError: y = 1 return x, y def get_walls_meta(self) -> List[WallMeta]: """ Generates a list of WallMeta tuples :return: A list of wall_metas """ walls_meta = [] # No list comp as need x and y vars for _ in range(self.number_of_walls): # Vertical vertical = bool(getrandbits(1)) # Length of wall wall_length = randint(1, self.max_wall_length) # Wall starting coordinates x, y = self.determine_wall_upper_bound(vertical, wall_length) # Get the wall coordinates wall_coords = self.get_wall_coords(vertical, wall_length, x, y) # Is there a door? If so unlinkely! temporal = datetime.now().second is_door = self.narnia(x, y, wall_length, temporal) # Door coords door_coords = choice(wall_coords) if is_door else None wm = WallMeta( vertical=vertical, wall_length=wall_length, x=x, y=y, wall_coords=wall_coords, is_door=is_door, door_coords=door_coords ) walls_meta.append(wm) return walls_meta def __repr__(self): """The goal is to be unambiguous.""" return f"|SIMPLE_WALL| (number_of_walls: {self.number_of_walls})"
1c88b6c3ed35e1ecea5f6ef50974a2ae34b5d04d
JosephAlonzo/Practicas-Python
/ejerciciosEvaluacion/ejercicio10.py
497
3.890625
4
class Rimas(): def __init__(self, word1, word2): self.word1 = word1 self.word2 = word2 def checkIfRhyme(self): if(self.word1[-3:] == self.word2[-3:]): return "Las palabras riman" elif (self.word1[-2:] == self.word2[-2:]): return "las palabras riman un poco" else: return "No riman" word1= input("Escribe una palabra: ") word2= input("Escribe otra palabra: ") obj = Rimas(word1, word2) print(obj.checkIfRhyme())
a0f7cb00714a7ae715ff7c9119f3384873be63d7
zhanglintc/algorithm
/sort/sort.py
4,070
3.734375
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # -*- mode: python -*- # vi: set ft=python : def timer(func): import functools @functools.wraps(func) def wrapper(*args, **kwargs): import time t1 = time.time() res = func(*args, **kwargs) t2 = time.time() print(f"{func.__name__}: {t2 - t1} secs") return res return wrapper @timer def swap_sort(a): n = len(a) for i in range(n): for j in range(i+1, n): if a[i] > a[j]: a[i], a[j] = a[j], a[i] @timer def bubble_sort(a): n = len(a) for i in range(n): for j in range(n-1-i): if a[j] > a[j+1]: a[j], a[j+1] = a[j+1], a[j] @timer def selection_sort(a): n = len(a) for i in range(n): min_idx = i for j in range(i+1, n): min_idx = min_idx if a[min_idx] < a[j] else j a[i], a[min_idx] = a[min_idx], a[i] @timer def insertion_sort(a): n = len(a) for i in range(n): pre_idx = i - 1 current = a[i] while pre_idx >= 0 and a[pre_idx] > current: a[pre_idx+1] = a[pre_idx] pre_idx -= 1 a[pre_idx+1] = current @timer def shell_sort(a): n = len(a) gap = n // 2 while gap > 0: for i in range(n): pre_idx = i - gap current = a[i] while pre_idx >= 0 and a[pre_idx] > current: a[pre_idx+gap] = a[pre_idx] pre_idx -= gap a[pre_idx+gap] = current gap //= 2 @timer def heap_sort(a): import heapq h = [] for n in a: heapq.heappush(h, n) a.clear() for _ in range(len(h)): n = heapq.heappop(h) a.append(n) @timer def merge_sort(a): def _sort(a): n = len(a) if n <= 1: return a m = n // 2 return _merge(_sort(a[:m]), _sort(a[m:])) def _merge(left, right): res = [] while left and right: if left[0] < right[0]: res.append(left.pop(0)) else: res.append(right.pop(0)) if left: res += left if right: res += right return res res = _sort(a)[:] a.clear() for n in res: a.append(n) @timer def quick_sort(a): def _qsort(a, bl, br): q = [(bl, br)] while q: bl, br = q.pop(0) if bl >= br: continue l, r = bl, br m = l + (r - l) // 2 a[l], a[m] = a[m], a[l] p = a[l] while l < r: while l < r and a[r] >= p: r -= 1 if l < r: a[l] = a[r] l += 1 while l < r and a[l] <= p: l += 1 if l < r: a[r] = a[l] r -= 1 a[l] = p q.append((bl, l-1)) q.append((l+1, br)) _qsort(a, bl=0, br=len(a)-1) @timer def counting_sort(a): # https://mp.weixin.qq.com/s?__biz=MzIxMjE5MTE1Nw==&mid=2653195533&idx=1&sn=02918dc51b07837ce1119f00d7900dbc if not a: return low = min(a) # offset high = max(a) counter = [0] * (high - low + 1) for n in a: counter[n-low] += 1 a.clear() for i in range(len(counter)): a += [i+low] * counter[i] @timer def counting_sort_stable(a): # https://mp.weixin.qq.com/s?__biz=MzIxMjE5MTE1Nw==&mid=2653195533&idx=1&sn=02918dc51b07837ce1119f00d7900dbc if not a: return low = min(a) high = max(a) counter = [0] * (high - low + 1) for n in a: counter[n-low] += 1 for i in range(1, len(counter)): counter[i] += counter[i-1] res = [0] * len(a) for i in range(len(a)-1, -1, -1): counter_idx = a[i] - low res_idx = counter[counter_idx] - 1 res[res_idx] = a[i] counter[counter_idx] -= 1 a.clear() for n in res: a.append(n) counting_sort_stable([1])
b72c2a0c6674a26af3a291aa51b44482b521632d
shuvo14051/python-data-algo
/Problem-solving/HackerRank/HackFest 2020-Cyclic Binary String.py
893
3.6875
4
string = input() li_of_string = [] result = [] if int(string) == 0: print("-1") else: for i in string: li_of_string.append(i) for i in range(len(li_of_string)): number = 0 string2 = '' item = li_of_string.pop() li_of_string.insert(0, item) for i in li_of_string: string2 += i number = int(string2, 2) result.append(number) count = 0 even_item = [] final_result = [] for i in result: if i % 2 == 0: even_item.append(i) count += 1 if count == 0: print("0") else: for i in even_item: d = 0 while i % 2 == 0: i = i // 2 d += 1 final_result.append(d) max = max(final_result) if max > 9: print("-1") else: print(max)
d985a26b5f3d3b53e2d344a54b39d20c42f67ed0
yasiriqbal1/concept-to-clinic-1
/prediction/src/algorithms/evaluation/metrics.py
949
3.546875
4
import numpy as np def get_accuracy(true_positives, true_negatives, false_positives, false_negatives): """ The accuracy is the ability to correctly predict the class of an observation. Args: true_positives: amount of items that have correctly been identifies as positives true_negatives: amount of items that have correctly been identifies as negatives false_positives: amount of items that have wrongly been identifies as positives false_negatives: amount of items that have wrongly been identifies as negatives """ return (true_positives + true_negatives) / (true_positives + true_negatives + false_positives + false_negatives) def logloss(true_label, predicted, eps=1e-15): """ Calculate the logarithmic loss (http://wiki.fast.ai/index.php/Log_Loss) """ p = np.clip(predicted, eps, 1 - eps) if true_label == 1: return -np.log(p) return -np.log(1 - p)
f40c1786ae3658bd586faefd54713fc32ace1625
MilanMolnar/Codecool_SI_week3
/Game statistics reports/part2/printing.py
2,973
3.75
4
from reports2 import get_most_played, sum_sold, get_selling_avg, count_longest_title, get_date_avg, get_game, \ count_grouped_by_genre, get_date_ordered # Printing functions def print_get_most_played(): print("The title of the most played game in the file is:", get_most_played("game_stat.txt") + ".") def print_sum_sold(): print(str(sum_sold("game_stat.txt")), "million copies have been sold total according to the file.") def print_get_selling_avg(): avg_float = get_selling_avg("game_stat.txt") print(str(avg_float) + "is the average selling according to the file.") def print_count_longest_title(): print(count_longest_title("game_stat.txt"), "characters long is the longest title in the file.") def print_get_date_avg(): print(get_date_avg("game_stat.txt"),"is the average of the release dates in the file") def print_get_game(prompt): items = "" title = input(prompt) print_list = [] for i in range(len(get_game("game_stat.txt", title))): print_list.append(str(get_game("game_stat.txt", title)[i])) for item in range(len(print_list)): items += '"' + print_list[item] + '"' + ", " if item + 1 == len(print_list): items = items[:-2] items += "." print(title + "'s data in the file are the following:", items) question = input("Do you want a detailed verison[y/n]") if question in ["y","Y"]: print(title + "'s genre is '"+ print_list[3]+ "' was relased in", print_list[2], "sold over",print_list[1], "million copies and currently owned by:", print_list[4] + ".") else: print("Have a nice day!") def print_count_grouped_by_genre(): print_dic = count_grouped_by_genre("game_stat.txt") for key in print_dic: print(key, "genre has", print_dic[key], "games in the file.") def print_get_date_ordered(): items = "" print_list = [] for i in range(len(get_date_ordered("game_stat.txt"))): print_list.append(str(get_date_ordered("game_stat.txt")[i])) for item in range(len(print_list)): items += '"' + print_list[item] + '"' + ", " if item + 1 == len(print_list): items = items[:-2] items += "." print("The date in which the games were ordered in the file are as follows " + items) print("\n\nWhat is the title of the most played game (i.e. sold the most copies)?") print_get_most_played() print("\n\nHow many copies have been sold total?") print_sum_sold() print("\n\nWhat is the average selling?") print_get_selling_avg() print("\n\nHow many characters long is the longest title?") print_count_longest_title() print("\n\nWhat is the average of the release dates?") print_get_date_avg() print("\n\nWhat properties has a game?") print_get_game("Input the title of the game: ") print("\n\nHow many games are there grouped by genre?") print_count_grouped_by_genre() print("\n\nWhat is the date ordered list of the games?") print_get_date_ordered()
ec08f30607302176b4210dbab6c732821ee9d52d
mattielangford/stats_midterm
/stats_midterm.py
193
3.515625
4
import numpy as np ## To know P(A|B) What is A and B? a = 'Knows the material' b = 'Answered correctly' p_a = 0.60 p_b_a = 0.85 p_b = 1 - 0.15 - 0.20 p_a_b = (p_b_a * p_a) / p_b print(p_a_b)
c69edd2652a8c86769187db8dcb0d948a78918cf
cpeixin/leetcode-bbbbrent
/geekAlgorithm010/Week06/unique-paths-ii.py
2,270
3.703125
4
# coding: utf-8 # Author:Brent # Date :2020/7/16 10:37 PM # Tool :PyCharm # Describe :一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。 # # 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。 # # 现在考虑网格中有障碍物。那么从左上角到右下角将会有多少条不同的路径? # # 来源:力扣(LeetCode) # 链接:https://leetcode-cn.com/problems/unique-paths-ii class Solution(object): def uniquePathsWithObstacles(self, obstacleGrid): """ :type obstacleGrid: List[List[int]] :rtype: int """ m, n = len(obstacleGrid), len(obstacleGrid[0]) for i in range(m): for j in range(n): # 有障碍物 if obstacleGrid[i][j]: obstacleGrid[i][j] = 0 else: # 处理边界问题 if i == j == 0: obstacleGrid[i][j] = 1 else: # 如果 i 为 0,则是第0行,无法获取上层数值,所以只能为同层左边元素的值 up = obstacleGrid[i - 1][j] if i != 0 else 0 # 如果 j 为 0, 则是第0列,无法获取同层左元素,所以只能为同列上层元素的值 left = obstacleGrid[i][j - 1] if j != 0 else 0 obstacleGrid[i][j] = up + left return obstacleGrid[-1][-1] def uniquePathsWithObstacles_1(self, obstacleGrid): m = len(obstacleGrid) n = len(obstacleGrid[0]) if obstacleGrid[0][0]: return 0 dp = [0] * (n + 1) dp[1] = 1 for i in range(1, m + 1): for j in range(1, n + 1): if obstacleGrid[i - 1][j - 1] == 0: dp[j] += dp[j - 1] else: dp[j] = 0 return dp[-1] if __name__ == '__main__': a = [ [0, 0, 0], [0, 1, 0], [0, 0, 0] ] solution = Solution() solution.uniquePathsWithObstacles_1(a)
7a3b13e7497d4ab49ff8cd4b2dff7d1c961010dd
chenxu0602/LeetCode
/305.number-of-islands-ii.py
3,079
3.75
4
# # @lc app=leetcode id=305 lang=python3 # # [305] Number of Islands II # # https://leetcode.com/problems/number-of-islands-ii/description/ # # algorithms # Hard (40.57%) # Likes: 705 # Dislikes: 15 # Total Accepted: 67.8K # Total Submissions: 167.2K # Testcase Example: '3\n3\n[[0,0],[0,1],[1,2],[2,1]]' # # A 2d grid map of m rows and n columns is initially filled with water. We may # perform an addLand operation which turns the water at position (row, col) # into a land. Given a list of positions to operate, count the number of # islands after each addLand operation. An island is surrounded by water and is # formed by connecting adjacent lands horizontally or vertically. You may # assume all four edges of the grid are all surrounded by water. # # Example: # # # Input: m = 3, n = 3, positions = [[0,0], [0,1], [1,2], [2,1]] # Output: [1,1,2,3] # # # Explanation: # # Initially, the 2d grid grid is filled with water. (Assume 0 represents water # and 1 represents land). # # # 0 0 0 # 0 0 0 # 0 0 0 # # # Operation #1: addLand(0, 0) turns the water at grid[0][0] into a land. # # # 1 0 0 # 0 0 0 Number of islands = 1 # 0 0 0 # # # Operation #2: addLand(0, 1) turns the water at grid[0][1] into a land. # # # 1 1 0 # 0 0 0 Number of islands = 1 # 0 0 0 # # # Operation #3: addLand(1, 2) turns the water at grid[1][2] into a land. # # # 1 1 0 # 0 0 1 Number of islands = 2 # 0 0 0 # # # Operation #4: addLand(2, 1) turns the water at grid[2][1] into a land. # # # 1 1 0 # 0 0 1 Number of islands = 3 # 0 1 0 # # # Follow up: # # Can you do it in time complexity O(k log mn), where k is the length of the # positions? # # # @lc code=start class Union: def __init__(self): self.par = {} self.rnk = {} self.siz = {} self.count = 0 def add(self, p): self.par[p] = p self.rnk[p] = 0 self.siz[p] = 1 self.count += 1 def find(self, x): if self.par[x] != x: self.par[x] = self.find(self.par[x]) return self.par[x] def unite(self, x, y): xr, yr = map(self.find, (x, y)) if xr == yr: return if self.rnk[xr] < self.rnk[yr]: xr, yr = yr, xr if self.rnk[xr] == self.rnk[yr]: self.rnk[xr] += 1 self.par[yr] = xr self.siz[xr] += self.siz[yr] self.count -= 1 class Solution: def numIslands2(self, m: int, n: int, positions: List[List[int]]) -> List[int]: # Union Find (aka Disjoint Set) # Time complexity: O(m x n + L) # Space complexity: O(m x n) ans, islands = [], Union() for x, y in positions: if (x, y) in islands.par: ans += ans[-1], continue islands.add((x, y)) for dx, dy in (0, 1), (0, -1), (1, 0), (-1, 0): nx, ny = x + dx, y + dy if (nx, ny) in islands.par: islands.unite((x, y), (nx, ny)) ans += islands.count, return ans # @lc code=end
f824ca7510d775b15a3c8171a7fb18b4721c7e43
umunusb1/PythonMaterial
/python3/07_Functions/009_default_args.py
1,980
4.4375
4
#!/usr/bin/python3 """ Purpose: Functions Demo Function with default arguments """ # def addition(num1, num2): # return num1 + num2 def addition(var1, var2, var3=0): return var1 + var2 + var3 print(f'{addition(10, 20) =}') print(f'{addition(10, 20, 30) =}') # print(dir(addition)) print(f'{addition.__defaults__ =}') # ------------------------------ # def hello(): # print('Hello world!') # hello() # def hello(name): # print(f'Hello {name}') # hello('Python') def hello(name='world!'): print(f'Hello {name}') hello() hello('Python') # ---------------------------- # --------------------------------------------- # def statement_creator(age = 24, name, qualification='B.Tech'): # """ # This is a statement creator function # :param name: mandatory arg # :param age: # :param qualification: # :return: # """ # print(f"{name}'s age is {age}. qualification is {qualification}") # SyntaxError: non-default argument follows default argument # NOTE: default args should be defined at last only def statement_creator(name, age = 24, qualification='B.Tech'): """ This is a statement creator function :param name: mandatory arg :param age: :param qualification: :return: """ print(f"{name}'s age is {age}. qualification is {qualification}") print(f'statement_creator.__defaults__ :{statement_creator.__defaults__}') print(f'statement_creator.__kwdefaults__:{statement_creator.__kwdefaults__}') # statement_creator() # TypeError: statement_creator() missing 1 required positional argument: 'name' statement_creator('Udhay') statement_creator(name='Udhay') print() statement_creator('Udhay', 28) statement_creator(name='Udhay', age=28) print() statement_creator('Udhay', 28, 'M.Tech') statement_creator(name='Udhay', age=28, qualification='M.Tech') statement_creator(28) # statement_creator(age=28) # TypeError: statement_creator() missing 1 required positional argument: 'name'
aa067e050061f56bda08b4749a6e4722fc5a9ae0
rgrishigajra/Competitive-Problems
/leetcode/75. Sort Colors Medium.py
494
3.9375
4
def sortColors(nums) -> None: """ Do not return anything, modify nums in-place instead. """ start = 0 end = len(nums) - 1 idx = 0 while idx <= end: if nums[idx] == 0: nums[idx], nums[start] = nums[start], nums[idx] start += 1 idx += 1 elif nums[idx] == 2: nums[idx], nums[end] = nums[end], nums[idx] end -= 1 else: idx += 1 print(nums) sortColors([2,0,1])
fbf9ec70a4398209d4ad3556c8691ab75d3efeef
asswecanfat/git_place
/杂项/网站检验.py
317
3.5
4
import urllib.request as urr import chardet as c respone = input('请输入URL:') ass = urr.urlopen(respone).read() v = c.detect(ass) if v['encoding'] == 'utf-8': print('该网站编码方式是:' + v['encoding']) elif v['encoding'] == 'GB2312': print('该网站使用的编码是:' + v['encoding'])
5a34d03447c38a292b4595eb553770ccc05b924b
Taoge123/OptimizedLeetcode
/LeetcodeNew/TwoPointers/LC_028_Implement_strStr.py
1,497
4
4
""" Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Example 1: Input: haystack = "hello", needle = "ll" Output: 2 Example 2: Input: haystack = "aaaaa", needle = "bba" Output: -1 """ class Solution1: def strStr(self, haystack, needle): for i in range(len(haystack) - len(needle) + 1): if haystack[i:i + len(needle)] == needle: return i return -1 class SolutionKMP1: def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ if needle == '': return 0 return self.kmp(haystack, needle) def makeNext(self, P): next = [0] * len(P) q = 1 # cursor in P, starting from 1 k = 0 # k is the length of maximum common suffix and prefix while q < len(P): while k > 0 and P[q] != P[k]: k = next[k - 1] if P[q] == P[k]: k += 1 next[q] = k q += 1 return next def kmp(self, T, P): next = self.makeNext(P) i = 0 # cursor in T q = 0 # cursor in P while i < len(T): while q > 0 and P[q] != T[i]: q = next[q - 1] if T[i] == P[q]: q += 1 if q == len(P): return i - len(P) + 1 i += 1 return -1
5879b1d5b0d71cb9a57c9d8e2ee12a2c31821f41
daniel-reich/turbo-robot
/QcswPnY2cAbrfwuWE_17.py
649
4.375
4
""" Create a function that filters out factorials from a list. A factorial is a number that can be represented in the following manner: n! = n * (n-1) * (n-2) * ... * 3 * 2 * 1 Recursively, this can be represented as: n! = n * (n-1)! ### Examples filter_factorials([1, 2, 3, 4, 5, 6, 7]) ➞ [1, 2, 6] filter_factorials([1, 4, 120]) ➞ [1, 120] filter_factorials([8, 9, 10]) ➞ [] ### Notes N/A """ def filter_factorials(numbers): def fact(x): if x == 0: return 1 else: return x*fact(x-1) return [i for i in numbers if i in [fact(j) for j in range(i+1)]]
f9308006515865a750a85d83205066d086fac221
Jeanrain-lee/lab-python
/lec01/ex04.py
687
3.765625
4
""" 연산자(operator) - 할당(assignment): = - 산술 연산: +, -, *, **, /, //, % - 복합 할당 연산: +=, -=, *=, /=, ... - 비교 연산: >, >=, <, <=, ==, != - 논리 연산: and, or, not - identity 연산: is, is not(id() 함수의 리턴값이 같은 지 다른 지) """ x = 1 # 연산자 오른쪽의 값을 연산자 왼쪽의 변수에 저장(할당) # 1 = x print(2 ** 3) # 2 x 2 x 2 print(10 / 3) print(10 // 3) # 정수 나눗셈 몫 print(10 % 3) # 정수 나눗셈 나머지 x = 1 print('x =', x) x += 10 # x = x + 10 print('x =', x) print(1 == 2) print(1 != 2) x = 50 print(0 < x < 100) # x > 0 and x < 100 print(x < 0 or x > 10) # Alt+Enter (마법키)
97153124d7a14a42f6d2d2e8702d6a20aa2f6371
ankitdipto/ImageInfoExtractor
/OCR/python files/OCRengine.py
1,587
3.546875
4
from PIL import Image from PIL import ImageFilter import pytesseract import requests import cv2 import os pytesseract.pytesseract.tesseract_cmd= r"C:\Program Files\Tesseract-OCR\tesseract.exe" def image_preprocess(image): ''' 1)resizing the image so that OCR can prepossess it in a better way 2)converting image to grayscale one can also help us to get a better image input for OCR engine 3)converting image to black & white will also help for better results we will set a threshold so that open CV will make that part of image while which is below that threshold and it will make the part of image black that have intensity greater than that threshold ''' image2 = cv2.resize(image, None, fx=0.25, fy=0.25) gray = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY) adaptive_image = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 75, 15) for i in range(0, adaptive_image.shape[0]): for j in range(0, adaptive_image.shape[1]): adaptive_image[i][j] = abs(adaptive_image[i][j] - 250) return adaptive_image class OCR(): def __init__(self, imagename): self.image = cv2.imread(imagename) #self.pre_image = image_preprocess(self.image) self.new_name = imagename[0:-4]+"_extracted.txt" def extraction(self): text = pytesseract.image_to_string(self.image) path = "C:\\Users\\DELL\\OneDrive\\Desktop\\New folder" fullpath = os.path.join(path, self.new_name) file = open(fullpath, "w") file.write(text) file.close()
8f81baeeab865f930a2a7d388af9625712b91544
agile-course/runmoar
/runmoar/running_calendar/utils.py
329
3.5
4
from datetime import datetime, timedelta def toDate(input_date): return datetime.strptime(input_date, '%Y-%m-%d') def getDateRange(start_date, end_date): dates_to_check = [] while start_date <= end_date: dates_to_check.append(start_date) start_date += timedelta(days=1) return dates_to_check
2d3b15511b9a77a0a0b921055d30914d9dfc48f5
riyag283/Leetcode-July-20-Challenge
/quest12.py
238
3.65625
4
def funct(n): binary = '' while n > 0: if n & 1: binary += '1' else: binary += '0' n >>= 1 return int(binary,2) #binary = '11101' #print(int(binary,2)) print(funct(4294967293))
4011fa3e1467604fe02dbad202d4168b8f3d6a65
Stranger65536/AlgoExpert
/medium/hasSingleCycle/program.py
2,346
4.09375
4
# # Single Cycle Check # You're given an array of integers where each integer represents # a jump of its value in the array. For instance, the integer 2 # represents a jump of two indices forward in the array; the integer # -3 represents a jump of three indices backward in the array. # # If a jump spills past the array's bounds, it wraps over to the # other side. For instance, a jump of -1 at index 0 brings us to the # last index in the array. Similarly, a jump of 1 at the last index # in the array brings us to index 0. # # Write a function that returns a boolean representing whether the # jumps in the array form a single cycle. A single cycle occurs if, # starting at any index in the array and following the jumps, every # element in the array is visited exactly once before landing back # on the starting index. # # Sample Input # array = [2, 3, 1, -4, -4, 2] # Sample Output # true # Hints # Hint 1 # In order to check if the input array has a single cycle, you have to # jump through all of the elements in the array. Could you keep a # counter, jump through elements in the array, and stop once you've # jumped through as many elements as are contained in the array? # # Hint 2 # Assume the input array has length n. If you start at index 0 and # jump through n elements, what are the simplest conditions that you # can check to see if the array doesn't have a single cycle? # # Hint 3 # Given Hint #2, there are 2 conditions that need to be met for the # input array to have a single cycle. First, the starting element (in # this case, the element at index 0) cannot be jumped through more than # once, at the very beginning, so long as you haven't jumped through # all of the other elements in the array. Second, the (n + 1)th element # you jump through, where n is the length of the array, must be the # first element you visited: the element at index 0 in this case. # # Optimal Space & Time Complexity # O(n) time | O(1) space - where n is the length of the input array def hasSingleCycle(array): # Write your code here. nxt = 0 for i in range(len(array)): shift = array[nxt] nxt = nxt + shift if nxt >= 0: nxt = nxt % len(array) else: nxt = -(abs(nxt) % len(array)) if nxt == 0 and i != len(array) - 1: return False return nxt == 0
7413a034468b07278ec678dbea5f712751f15347
m4mayank/ComplexAlgos
/rearrange_array.py
636
3.875
4
#!/usr/local/bin/python3.7 #Rearrange a given array so that Arr[i] becomes Arr[Arr[i]] with O(1) extra space. # #Example: # Input : [1, 0] # Return : [0, 1] #Lets say N = size of the array. Then, following holds true : # 1) All elements in the array are in the range [0, N-1] # 2) N * N does not overflow for a signed integer def arrange(A): for i in range(0, len(A)): A[i] = A[i] + (len(A)*((A[A[i]])%len(A))) for i in range(0, len(A)): A[i] = A[i]//len(A) #A= [1, 2, 7, 0, 9, 3, 6, 8, 5, 4 ] #Answer = [2, 7, 8, 1, 4, 0, 6, 5, 3, 9] A = [3,4,2,1,0] #Answer=[1, 0, 2, 4, 3] arrange(A) print(A)
6b7894b77d9fe77f50df91ce5f8502d6931af1fd
Bajo-presion/3er_Anio_instancia_Marzo
/Estudiantes.py
3,780
3.53125
4
import random from Estadistica import * #CLASE ESTUDIANTE - USADO PARA CREAR BASE DE DATOS # Si bien su atributo tiene el nombre completo, el nombre de clase debe ser sencillo class Estudiante(): # y único para poder acceder a el fácilmente def __init__(self, nombre=None, curso=None, dni= None ): self.nombre = nombre self.curso = curso self.dni = dni # En caso de que hiciera falta - preguntar cuando se toma contacto con ellos def mostrar_datos(self): return "DATOS ESTUDIANTE: " + \ "\nNOMBRE: " + str(self.nombre) + \ " --- \tDNI: " + str(self.dni) + \ "\nCURSO: " + str(self.curso) #GETTERS def getNombre(self): return self.nombre def getDni(self): return self.dni def getCurso(self): return self.curso #SETTERS def setNombre(self, nombre): self.nombre = nombre def setDni(self, dni): self.dni = dni def setCurso(self, curso): self.curso = curso class Estado_estudiante(): #AÚN NO FUE USADO def __init__(self, nroLista = None, instancia=None, previa=False, aprobado=False, notaFinal= None, faltaHacer= None, ejercicios_faltantes = ['9)a)', '9)b)', '9)c)', '11)', '13)a)', '13)b)', '14)'], observaciones=None): self.nroLista = nroLista self.instancia = instancia # Marzo, Julio, Diciembre o Especiales self.previa = previa # Será necesario por si hace falta llenar planillas self.aprobado = aprobado self.notaFinal = notaFinal self.faltaHacer = faltaHacer self.ejercicios_faltantes = ejercicios_faltantes self.observaciones = observaciones def mostrar_datos_alumno(self): return "DATOS ESTADO ESTUDIANTE: " + \ "\nNRO LISTA: " + str(self.nroLista) + \ "\nINSTANCIA: " + str(self.instancia) + \ " --- \tPREVIA: " + str(self.previa) + \ "\nAPROBADO: " + str(self.aprobado) + \ " --- \tNOTA FINAL: " + str(self.notaFinal) + \ "\nFALTA HACER: " + str(self.faltaHacer) + \ " --- \tEJERCICIOS FALTANTES: " + str(self.ejercicios_faltantes) + \ "\nOBSERVACIONES: " + str(self.observaciones) #GETTERS def getNroLista(self): return self.nroLista def getInstancia(self): return self.instancia def getPrevia(self): return self.previa def getAprobado(self): return self.aprobado def getNotaFinal(self): return self.notaFinal def getObservaciones(self): return self.observaciones def getFaltaHacer(self): return self.faltaHacer def getEjercicios_faltantes(self): return self.ejercicios_faltantes #SETTERS def setNroLista(self, nroLista): self.nroLista = nroLista def setInstancia(self, instancia): self.instancia = instancia def setPrevia(self, previa): self.previa = previa def setAprobado(self, aprobado): self.aprobado = aprobado def setNotaFinal(self, notaFinal): self.notaFinal = notaFinal def setObservaciones(self, observaciones): self.observaciones = observaciones def setFaltaHacer(self, faltaHacer): self.faltaHacer = faltaHacer def setEjercicios_faltantes(self, ejercicios_faltantes): self.ejercicios_faltantes = ejercicios_faltantes
5156de2b523cb82ffb32b78983b997cd84316539
Offliners/Python_Practice
/code/054.py
135
3.9375
4
# "f-strings" or # string interpolation # (available in Python 3.6+) name = "Eric" print(f"Hello, {name}!") # Output: # Hello, Eric!