blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
529ed8b188e4ecb5a05d28a5b431150aae425239
Sakina28495/Fashion
/demo.py
215
3.53125
4
def codemaker(urstring): output=list(urstring) print(output) for index,letter in enumerate(urstring): for vowels in 'aeiou': if letter==vowels: output[index]='x' return output print(codemaker('Sammy'))
3456da0d36a1771bce68108957a7e6713aea83b4
eltobito/devart-template
/project_code/test2.py
515
3.828125
4
import Image picture = Image.open("picture.jpg") # Get the size of the image width, height = picture.size() # Process every pixel for x in width: for y in height: current_color = picture.getpixel( (x,y) ) print current_color #################################################################### # Do your logic here and create a new (R,G,B) tuple called new_color #################################################################### picture.putpixel( (x,y), new_color)
7dd133e44d846b84c1cda13c84ff3dc50aed1148
jadynk404/CMPT120-Project
/dictionary.py
1,169
3.984375
4
#Worked with Emmanuel Batista def main(): title = "Interactive Dictionary" print(title) myFile = input("Please input the name of your file: ").strip() myFile = myFile.lower() with open(myFile, "r") as myFile: #reads file and assigns value to variables dictionary = myFile.readlines() word1 = dictionary[0].strip() def1 = dictionary[1].strip() word2 = dictionary[2].strip() def2 = dictionary[3].strip() inDictionary = { word1 : def1, word2 : def2 } x = 1 while x==1: #searches txt file for user input uinput = "Please input a word you would like to have defined: " prompt = input(uinput).strip() prompt = prompt.lower() if prompt == word1: print(inDictionary[word1]) elif prompt == word2: print(inDictionary[word2]) elif prompt == "": x = 0 else: invalid = "I'm sorry. This word is not stored in our dictionary." print(invalid) x = 1 def copyrightt(): c = "This file was created by Jadyn Kennedy 4/27/2020" main() copyrightt()
7db722bc3d5e417139bb055937e9315289f90b52
cgraaaj/PracticeProblems
/Add two numbers as a linked list/main.py
1,176
3.796875
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution: result = None def addTwoNumbers(self, l1, l2, c=0): v1 = [] v2 = [] res = [] while l1: v1.append(l1.val) v2.append(l2.val) l1 = l1.next l2 = l2.next v1.reverse() v2.reverse() v1 = int("".join([str(integer) for integer in v1])) v2 = int("".join([str(integer) for integer in v2])) res = [int(i) for i in str(v1 + v2)] res.reverse() for v in res: self.insert(v) return self.result def insert(self,data): node = ListNode(data) if self.result is None: self.result = node return n = self.result while n.next is not None: n= n.next n.next = node l1 = ListNode(2) l1.next = ListNode(4) l1.next.next = ListNode(3) l2 = ListNode(5) l2.next = ListNode(6) l2.next.next = ListNode(4) result = Solution().addTwoNumbers(l1, l2) while result: print(result.val), result = result.next
fbb3938b667cba8afe5144c023cacbd833028f03
crashtack/exercism
/python/clock/clock.py
1,144
4.34375
4
class Clock(object): """ A Clock class that ignores date """ def __init__(self, hours=0, minutes=0): """ Initialize the Clock object """ self.hours = hours % 24 self.minutes = minutes self.time_min = (self.hours * 60) + self.minutes self.time_min = self.time_min % 1440 def add(self, minute=0): """ Add minutes to the time and check for overflow """ self.time_min += minute self.time_min = self.time_min % 1440 return self.__str__() def __eq__(self, other): """ Check if time_min is equal """ if isinstance(other, self.__class__): return self.time_min == other.time_min else: return False def __ne__(self, other): """ Check if time_min is not equal """ return not self.__eq__(other) def __hash__(self): """ Return a hash of the time value """ return hash(self.time_min) def __str__(self): """ Returns the hh:mm time format """ return '{:02d}:{:02d}'.format( int(self.time_min / 60) % 24, self.time_min % 60 )
11aad31a77cdbca35a0961b5cfb1c46d56c438c4
miguelencastillogar/SeleniumPythonGitJenkinsAllureReporting
/Ejemplos_Python/11-input-2.py
562
4.03125
4
# Formulamos los mandatos que debe cumplir el usuario pregunta = '\nAgrega un numero y te dire si es par o impar ' pregunta += '(Escribe "Cerrar o cerrar" para salir de la aplicacion) ' # Variable booleana que mantendra el while iterandose preguntar = True while preguntar: numero = input(pregunta) if numero == "Cerrar" or numero == "cerrar": preguntar = False else: numero = int(numero) if numero % 2 == 0: print(f'El numero {numero} es par') else: print(f'El numero {numero} es impar')
f877815460bf804c8756d2dbb49cbe2cea568e10
miguelencastillogar/SeleniumPythonGitJenkinsAllureReporting
/Ejemplos_Python/14-clases-5.py
2,681
3.9375
4
class Restaurante: def __init__(self, nombre, categoria, precio): # Por defecto estas variables estan publicas # self.nombre = nombre # self.categoria = categoria # self.precio = precio # Para hacerlas PROTECTED unicamente al inicio del nombre # del atributo le agregamos un guion bajo # self._nombre = nombre # self._categoria = categoria # self._precio = precio # Para hacerlas PRIVATE unicamente al inicio del nombre # del atributo le agregamos doble guion bajo self.__nombre = nombre self.__categoria = categoria self.__precio = precio # Getters def get_nombre(self): return self.__nombre def get_categoria(self): return self.__categoria def get_precio(self): return self.__precio # Setters def set_nombre(self, nombre): self.__nombre = nombre def set_categoria(self, categoria): self.__categoria = categoria def set_precio(self, precio): self.__precio = precio def mostrar_informacion(self): print( f'Nombre: {self.__nombre} \nCategoria: {self.__categoria} \nPrecio: {self.__precio}\n') # Polimorfismo es la habilidad de tener diferentes comportamientos # basado en que subclase se esta utilizando, relacionado muy # estrechamente con herencia. class Hotel(Restaurante): def __init__(self, nombre, categoria, precio, alberca): # Hacemos referencia a la clase padre super().__init__(nombre, categoria, precio) # Aqui se aplica el polimorfismo, ya que este atributo # unicamente existe y se utiliza al momento de utilizar # la clase Hotel self.__alberca = alberca # Agregamos un metodo que solo existe en el Hotel # Aqui se aplica el polimorfismo, ya que este comportamiento # unicamente existe y se utiliza al momento de utilizar # la subclase Hotel def get_alberca(self): return self.__alberca def set_alberca(self, alberca): self.__alberca = alberca # Reescribir un metodo (debe llamarse igual) def mostrar_informacion(self): # Se puede utilizar tanto self o super para hacer referencia a la clase padre: # super().get_nombre() o self.get_nombre() # super().get_categoria() o self.get_categoria() # super().get_precio() o self.get_precio() print( f'Nombre: {super().get_nombre()} \nCategoria: {self.get_categoria()} \nPrecio: {self.get_precio()} \nAlberca: {self.__alberca}\n') print('\n') hotel = Hotel('Cadena de Hoteles Dreams', '5 Estrellas', 250, 'Si') hotel.mostrar_informacion()
11743b0257a83b0df21ab3daadcb2483468eaa83
miguelencastillogar/SeleniumPythonGitJenkinsAllureReporting
/Ejemplos_Python/05-numeros-2.py
401
3.828125
4
def suma(a=0, b=0): print(a + b) suma(2, 3) suma(4, 1) suma(8, 12) suma() def resta(a=0, b=0): print(a - b) resta(2, 3) resta(4, 1) resta(8, 12) resta() def multiplicacion(a=0, b=0): print(a * b) multiplicacion(2, 3) multiplicacion(4, 1) multiplicacion(8, 12) multiplicacion() def division(a=0, b=1): print(a / b) division(2, 3) division(4, 1) division(8, 12) division()
87267ed67fb71ac07755fff6f81fb02f2f7b4a95
miguelencastillogar/SeleniumPythonGitJenkinsAllureReporting
/Ejemplos_Python/10-diccionarios-1.py
1,528
3.875
4
# Creando un diccionario (objeto) simple cancion = { # llave : valor (Para agregar mas valores los separamos por comas) 'artista': 'Metallica', 'cancion': 'Enter Sandman', 'lanzamiento': 1992, 'likes': 3000 } # Imprimir todos los valores print(cancion) # Acceder a los elementos del diccionario print(cancion['artista']) print(cancion['lanzamiento']) # Mezclar con un string y tomando en cuenta que si procedemos # de esta manera: print(f'Estoy escuchando {cancion['artista']}') # obtendremos un error y siendo la unica solucion asignar el # valor del diccionario (objeto) a una variable y luego # mezclarla con un String. artista = cancion['artista'] print(f'Estoy escuchando a {artista}') # Imprimir todos los valores antes de agregar nuevo valor print(cancion) # Agregar nuevos elementos # debido a que la nueva propiedad no existe, pues automaticamente la grega cancion['palylist'] = 'Heavy Metal' # Imprimir todos los valores despues de agregar nuevo valor print(cancion) # Imprimir todos los valores antes de modificacion print(cancion) # Agregar nuevos elementos # debido a que la propiedad existe, pues modifica su valor cancion['cancion'] = 'Seek & Destroy' # Imprimir todos los valores despues de modificacion print(cancion) # Imprimir todos los valores antes de eliminar propiedad print(cancion) # Agregar nuevos elementos # debido a que la propiedad existe, pues modifica su valor del cancion['lanzamiento'] # Imprimir todos los valores despues de eliminar propiedad print(cancion)
0f9b703805d7afabd6a9d0313076f003f0d16b3a
bobbyscharmann/flypy
/examples/main.py
714
3.796875
4
from flypy.neural_networks.activation_functions import Sigmoid, ReLU from flypy.neural_networks import NeuralNetworkTwoLayers import numpy as np l = ReLU() #l.plot(-10, 10, derivative=False) print("Hello world.") nn_architecture = [ {"input_dim": 2, "output_dim": 4}, #{"input_dim": 4, "output_dim": 6}, #{"input_dim": 6, "output_dim": 6}, #{"input_dim": 6, "output_dim": 4}, {"input_dim": 4, "output_dim": 1}, ] X = np.asarray([[0, 0], [0, 1], [1, 0], [1,1]]).T Y = np.asarray([[0], [1], [1], [0]]) nn = NeuralNetworkTwoLayers(X=X, Y=Y, nn_architecture=nn_architecture, activation=Sigmoid) nn.train(X, Y)
1210ad4c30493aefaa6585472991a79894bdae58
bobbyscharmann/flypy
/flypy/reinforcement_learning/cartpole/random_agent.py
783
3.5
4
"""Implementation of the OpenAI Gym CartPole exercise with a random sampling of the action space. In other words, a vey simplistic (or dumb) agent)""" import gym env = gym.make("CartPole-v0") env.reset() # Couple of variables for knowing when the episode is over done: bool = False # Keeping track of total aware and steps total_reward: float = 0 steps: int = 0 # Iterate until the episode is over while not done: # Step the environment choosing a random action from the Environment action space state, reward, done, info = env.step(action=env.action_space.sample()) # Accumulate steps and awards steps += 1 total_reward += reward env.render() # Print some general information about the episode print(f"Total Reward in {total_reward} in {steps} steps.")
a899cbea277c1183228ac5f7396dce5347c69279
numbertheory/nanogenmo
/verb.py
991
3.5
4
"""Get a random verb, from a given tense""" import random def get(tense): """ Get a verb in the right tense """ verbs = {'past': ['spoke', 'baked', 'competed', 'smoked', 'switched', 'unlocked'], 'present': ['speaks', 'bakes', 'competes', 'smokes', 'switches', 'unlocks'], 'future': ['speak', 'bake', 'compete', 'smoke', 'switch', 'unlock'], 'past_perfect': ['spoken', 'baked', 'competed', 'smoked', 'switched', 'unlocked'], 'future_perfect': ['spoken', 'baked', 'competed', 'smoked', 'switched', 'unlocked']} if tense == 'future': helper = ['will', ''] elif 'future_perfect': helper = ['will', 'have'] elif 'past_perfect': helper = ['had', ''] else: helper = ['', ''] return helper, random.choice(verbs[tense])
deb0106dadea39101d8c40357c3f41f9383a9937
GarryK97/Python
/Hashtable/Task5.py
2,715
4.4375
4
from Task3 import HashTable def read_file_removesp(file_name): """ Read a text file and convert it to a list of words without any special characters. :param file_name: File to read :return: the list of words """ f = open(file_name, 'rt', encoding='UTF8') file_list = [] for line in f: line = line.strip() # Remove whitespaces line = line.split(" ") # Split by words for i in range(len(line)): word_nosp = "" # String that will store word with no special character line[i] = line[i].lower() # Lower the word to make search easy for char in line[i]: # for each character in word, if char.isalpha(): # if the character is not special character (if it is alphabet), word_nosp += char # Add it to word_nosp if word_nosp != "": # To prevent adding white spaces and already existing words file_list.append(word_nosp) # Append the word with no special character f.close() return file_list book1 = read_file_removesp("Book1.txt") book2 = read_file_removesp("Book2.txt") book3 = read_file_removesp("Book3.txt") book_hashtable = HashTable(399989, 1091) # Making a hash table for books in [book1, book2, book3]: for word in books: try: count = book_hashtable[word] # if the word exists in hash table, count will store the value of it book_hashtable[word] = count + 1 # + 1 count except KeyError: book_hashtable[word] = 1 # If the word does not exist in hash table, it means a new word needs to be added # Making a non-duplicate words list words_list = [] for books in [book1, book2, book3]: for word in books: if word not in words_list: words_list.append(word) # Finding Maximum max_count = 0 max_word = "" for word in words_list: if book_hashtable[word] > max_count: # if word count > current maximum word count, max_count = book_hashtable[word] # Change to new max count and word max_word = word # Finding common, uncommon, rare words common_words = [] uncommon_words = [] rare_words = [] for word in words_list: # Zipf's law in simple python code if book_hashtable[word] > (max_count / 100): common_words.append(word) elif book_hashtable[word] > (max_count / 1000): uncommon_words.append(word) else: rare_words.append(word) print("Number of common words : " + str(len(common_words))) # Prints the result print("Number of uncommon words : " + str(len(uncommon_words))) print("Number of rare words : " + str(len(rare_words)))
0d471841786f140724e55f0452db3469f9043be7
GarryK97/Python
/Algorithms/Dijkstra&Bellman-Ford.py
13,153
3.640625
4
import heapq """ Graph implementation for best_trades """ class Trade_Graph: def __init__(self, num_vertices): """ Initialize Graph object :param num_vertices: Total number of vertices :Complexity: Best Time: O(V), Worst Time: O(V), Auxiliary Space: O(V) V = Total number of vertices in graph """ self.vertices = [None for x in range(num_vertices)] for i in range(num_vertices): self.vertices[i] = Trade_Vertex(i) def add_edge(self, edge): """ Adds edge to each vertex, by using Edge object :param edge: Edge object to add :Complexity: Best Time: O(1), Worst Time: O(1), Auxiliary Space: O(1) """ vertex = self.vertices[edge.u] vertex.add_edge(edge) """ Vertex implementation for best_trades """ class Trade_Vertex: def __init__(self, id): """ Initialize Vertex object :param id: id of vertex :Complexity: Best Time: O(1), Worst Time: O(1), Auxiliary Space: O(1) """ self.id = id self.edges = [] # Stores all the edges of a vertex def add_edge(self, edge): """ adds an edge to this vertex :param edge: Edge object to add :Complexity: Best Time: O(1), Worst Time: O(1), Auxiliary Space: O(1) """ self.edges.append(edge) """ Edge implementation for best_trades """ class Trade_Edge: def __init__(self, u, v, w): """ Initialize Edge object :param u: Source Vertex (Start Vertex) id :param v: Destination Vertex (End Vertex) id :param w: Weight of the edge :Complexity: Best Time: O(1), Worst Time: O(1), Auxiliary Space: O(1) """ self.u = u # Source self.v = v # Destination self.w = w # Exchange amount def best_trades(prices, starting_liquid, max_trades, townspeople): """ Calculates the best trade with the given max_trades, using Bellman-Ford algorithm :param prices: List of prices of each Liquid :param starting_liquid: Starting Liquid ID :param max_trades: Maximum number of trades :param townspeople: List of Lists, Trades offered by each people :return: the Optimal Profit found :Complexity: Best Time: O(TM), Worst Time: O(TM), Auxiliary Space: O(TM) T = Total number of Trade offers M = Max_trades """ a_graph = Trade_Graph(len(prices)) # Initialize Graph by number of liquids. So, vertex = each liquid # Adds all the trade offers as edges to the graph for people in townspeople: for offer in people: u = offer[0] v = offer[1] w = offer[2] a_graph.add_edge(Trade_Edge(u, v, w)) # Initialize a table for Bellman-Ford algorithm, the table will store the optimal amount of each liquid amount = [[float("-inf") for i in range(max_trades+1)] for j in range(len(prices))] amount[starting_liquid][0] = 1 # Starts Bellman-Ford algorithm, repeat Max_trades time for i in range(1, max_trades+1): for liquid in amount: # Copy the previous i liquid[i] = liquid[i-1] for vertex in a_graph.vertices: for edge in vertex.edges: # Relax all the edges price_stored = prices[edge.v] * (amount[edge.v][i-1]) price_new = prices[edge.v] * (amount[edge.u][i-1] * edge.w) if price_stored < price_new: # If new optimal price is found, replace the table. amount[edge.v][i] = amount[edge.u][i-1] * edge.w # Gets the maximum price using the table obtained. max_price = 0 for i in range(len(amount)): if max_price < amount[i][-1] * prices[i]: max_price = amount[i][-1] * prices[i] return round(max_price) # ============================= Q3 ============================ """ Graph implementation for opt_delivery """ class Graph: def __init__(self, num_vertices): """ Initialize Graph object :param num_vertices: Total number of vertices :Complexity: Best Time: O(V), Worst Time: O(V), Auxiliary Space: O(V) V = Total number of vertices in graph """ self.vertices = [None for x in range(num_vertices)] for i in range(num_vertices): self.vertices[i] = Vertex(i) def add_edges_list(self, edges_list): """ Gets List of edges in (u, v, w) format and adds all the edge to this graph :param edges_list: List of edges in (u, v, w) format :Complexity: Best Time: O(E), Worst Time: O(E), Auxiliary Space: O(1) E = Total number of Edges """ for edge in edges_list: u = edge[0] v = edge[1] w = edge[2] vertex = self.vertices[u] vertex.add_edge(Edge(u, v, w)) # Adds Undirected edge, simply swap u and v vertex2 = self.vertices[v] vertex2.add_edge(Edge(v, u, w)) def get_vertex_byid(self, id): """ Gets the vertex by using its id :param id: Vertex id to get :return: a Vertex with matching id :Complexity: Best Time: O(1), Worst Time: O(1), Auxiliary Space: O(1) """ return self.vertices[id] def reset_vertices(self): """ Reset the status of all the vertices in this graph :Complexity: Best Time: O(V), Worst Time: O(V), Auxiliary Space: O(1) V = Total number of vertices in graph """ for vertex in self.vertices: vertex.previous = None vertex.cost = float("inf") """ Vertex implementation for opt_delivery """ class Vertex: def __init__(self, id): """ Initialize Vertex object :param id: the id of Vertex :Complexity: Best Time: O(1), Worst Time: O(1), Auxiliary Space: O(1) """ self.id = id self.edges = [] self.previous = None self.cost = float("inf") def add_edge(self, edge): """ Adds an edge to this vertex, using Edge object :param edge: Edge object to add :Complexity: Best Time: O(1), Worst Time: O(1), Auxiliary Space: O(1) """ self.edges.append(edge) """ Edge implementation for opt_delivery """ class Edge: def __init__(self, u, v, w): """ Initialize Edge object :param u: Source Vertex (Start Vertex) id :param v: Destination Vertex (End Vertex) id :param w: Weight of the edge :Complexity: Best Time: O(1), Worst Time: O(1), Auxiliary Space: O(1) """ self.u = u # Source self.v = v # Destination self.w = w # Exchange amount def opt_delivery(n, roads, start, end, delivery): """ Finds the optimal cost of going to 'end' city from 'start' city. :param n: Number of cities :param roads: List of tuples (u, v, w), which represents a road :param start: the starting city :param end: the destination city :param delivery: a tuple (u, v, p) represents a delivery. U = pick-up city, V = Delivery Destination, P = Profit of the delivery :return: (Optimal cost, Optimal Path) found :Complexity: Best Time: O(V^2), Worst Time: O(V^2), Auxiliary Space: O(V) V = Total number of vertices in graph """ def update_heap(graph, min_heap): """ Updates the heap when the costs of vertices are changed. :param graph: Graph object :param min_heap: heap to update :Complexity: Best Time: O(V), Worst Time: O(V), Auxiliary Space: O(1) V = Total number of vertices in graph """ for i in range(len(min_heap)): vertex_id = min_heap[i][1] vertex = graph.vertices[vertex_id] min_heap[i] = (vertex.cost, vertex.id) heapq.heapify(min_heap) def backtrack_path(graph, start, end): """ Backtrack the previous id of vertices and reconstruct the optimal path. :param graph: Graph object :param start: the source vertex id :param end: the destination vertex id :return: Reconstructed Path, using backtracking :Complexity: Best Time: O(1), Worst Time: O(V), Best Auxiliary Space: O(1), Worst Auxiliary Space: O(V) V = Total number of vertices in graph """ if start == end: # If same start and end, there will be no previous. So return directly to prevent error return [end] path = [] path.insert(0, end) previous_vertex_id = graph.vertices[end].previous previous_vertex = graph.vertices[previous_vertex_id] while previous_vertex_id != start: path.insert(0, previous_vertex_id) previous_vertex_id = graph.vertices[previous_vertex.id].previous previous_vertex = graph.vertices[previous_vertex_id] path.insert(0, start) return path def find_lowest_cost(graph, start, end): """ Finds the optimal path that requires the lowest travelling cost from start to end, using Dijkstra algorithm :param graph: Graph object :param start: the source vertex id :param end: the destination vertex id :return: Optimal cost and Optimal path found :Complexity: Best Time: O(V^2), Worst Time: O(V^2), Auxiliary Space: O(V) V = Total number of vertices in graph """ graph.reset_vertices() # Resets the status of all the vertices in the graph before computes minheap = [] # a list to implement min heap # Initialize the min heap. Each element is a tuple (cost, vertex_id) for vertex in graph.vertices: if vertex.id == start: minheap.append((0, start)) vertex.cost = 0 else: minheap.append((float("inf"), vertex.id)) heapq.heapify(minheap) # Make the list as min heap, O(V) time complexity while len(minheap) > 0: # = Visit every vertex in the graph, O(V) time complexity current_cost, current_vid = heapq.heappop(minheap) current_vertex = graph.get_vertex_byid(current_vid) for edge in current_vertex.edges: # Go every edge of a vertex discovored_vertex = graph.vertices[edge.v] discovored_cost = discovored_vertex.cost if current_cost + edge.w < discovored_cost: # if a new optimal cost is found, replace it discovored_vertex.cost = current_cost + edge.w discovored_vertex.previous = current_vertex.id # Store the previous vertex to reconstruct path later. update_heap(graph, minheap) # Updates the heap after the change of the costs of vertices. O(V) time complexity optimal_cost = graph.vertices[end].cost # Gets the optimal cost optimal_path = backtrack_path(graph, start, end) # Reconstruct the optimal path return optimal_cost, optimal_path # ====== Actual Codes for opt_delivery a_graph = Graph(n) # Initialize a graph. So, Cities = vertices a_graph.add_edges_list(roads) # Adds roads as edges. So, Roads = Edges # Calculates the optimal cost and path without delivery optimal_cost_nodelivery, optimal_path_nodelivery = find_lowest_cost(a_graph, start, end) # Calculates the optimal cost and path of going start to pick-up city optimal_cost_to_pickup, path1 = find_lowest_cost(a_graph, start, delivery[0]) # Calculates the optimal cost and path of going pick-up to delivery destination city optimal_cost_to_deliver, path2 = find_lowest_cost(a_graph, delivery[0], delivery[1]) # # Calculates the optimal cost and path of going delivery destination city to end city optimal_cost_to_end, path3 = find_lowest_cost(a_graph, delivery[1], end) # Sum up the cost and path of performing delivery optimal_cost_delivery = (optimal_cost_to_pickup + optimal_cost_to_deliver + optimal_cost_to_end) - delivery[2] optimal_path_delivery = path1[:-1] + path2 + path3[1:] # Slicing to prevent adding same path again # Compare optimal cost of performing delivery and no delivery. if optimal_cost_delivery >= optimal_cost_nodelivery: final_optimal_cost = optimal_cost_nodelivery final_optimal_path = optimal_path_nodelivery else: final_optimal_cost = optimal_cost_delivery final_optimal_path = optimal_path_delivery return final_optimal_cost, final_optimal_path
b0f1454101fcd2aa96d12bc55bfa6aebcd002103
VinceWu-bit/Decision-Chessboard-Puzzle
/env.py
2,181
3.515625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2021/6/12 18:15 # @Author: Vince Wu # @File : env.py import numpy as np class ChessBoardEnv: def __init__(self): self.chessboard = np.array([0, 0, 0, 0]) self.key_dic = {0: 1, 1: 1, 14: 1, 15: 1, # 4维立方体编码规则 6: 2, 7: 2, 8: 2, 9: 2, 4: 3, 5: 3, 10: 3, 11: 3, 2: 4, 3: 4, 12: 4, 13: 4} self.key = 0 def reset(self): self.chessboard = np.array([0, 0, 0, 0]) return self.state_to_obs() def step(self, action, player): if player == 1: # 监狱长1 assert 0 <= action <= 63 self.key = action // 16 action = action % 16 for i in range(4): self.chessboard[3-i] = action // 2 ** (3 - i) action -= self.chessboard[3-i] * 2 ** (3 - i) return self.key, self.state_to_obs() elif player == 2: # 囚犯1 assert 0 <= action <= 3 self.chessboard[action] = 1 - self.chessboard[action] return self.key, self.state_to_obs() elif player == 3 or player == 4: # 监狱长2、囚犯2 assert 0 <= action <= 5 if action <= 2: self.switch(action, action + 1) elif action == 3: self.switch(3, 0) else: self.switch(action - 4, action - 2) if player == 4: # 囚犯2,结束 # print(self.state_to_key(), self.key) return 1 if self.state_to_key() == self.key else -1, True else: return self.key, self.state_to_obs() def state_to_key(self): key = 0 for i in range(4): key += self.chessboard[i] * 2 ** i return self.key_dic[key]-1 def switch(self, a, b): self.chessboard[a], self.chessboard[b] = self.chessboard[b], self.chessboard[a] def state_to_obs(self): obs = 0 for i in range(4): obs += self.chessboard[i] * (2 ** i) # print(self.chessboard) # print(obs) return obs
606de1aa9e681af56f022880698088b3ea58904d
nidakhawar/PracticePythonExcercises
/AverageOfSubjects.py
510
4.1875
4
biology=float(input("Please input your Biology score:")) chemistry=float(input("Please input your Chemistry score:")) physics=float(input("Please input your Physics score:")) if biology<40: print("Fail") if chemistry<40: print("Fail") if physics<40: print("Fail") else: score=((biology+chemistry+physics)/3) if score >=70: print("first") elif score>=60: print("2.1") elif score>=50: print("pass") elif score>=40: print("pass") else: print("fail")
2fe1eb2779838cbd559241374b9f94d6b36bc413
KevinSilva11/Python_The_Huxley
/PH.py
145
3.546875
4
ph = float(input()) if ph < 7: print('Acida') else: if ph > 7: print('Basica') else: print('Neutra')
bc5650df61ac37eef9df8a63e2b7d0b147d512da
SuzaneFer/phyton-basico-graficos
/ComparandoGenomas.py
799
3.5
4
#Neste estudo de caso, faremos a comparação entre duas sequências de DNA: # (1) ser humano; vs. (2) bactéria. import matplotlib.pyplot as plt import random entrada = open("bacteria.fasta").read() saida = open("bacteria.html","w") cont = {} # Dicionário for i in ['A', 'T', 'C', 'G']: for j in ['A', 'T', 'C', 'G']: cont[i+j]=0 # Para tirar a quebra de linha entrada = entrada.replace("\n"," ") for k in range(len(entrada)-1): cont[entrada[k]+entrada[k+1]] += 1 # Printar em HTML i = 1 for k in cont: transparencia = cont[k]/max(cont.values()) #pegar o maior valor saida.write("<div style='width:100px; border:1px solid #111; height: 100px; float: left; background-color:rgba(0,0,255, "+str(transparencia)+"')></div>") saida.close()
976cc8ab3327128b679d3d205e8c2dc1b2daae0b
zacharykaczor/Small-Programs
/odd_numbers.py
535
4.1875
4
# Based on https://www.youtube.com/watch?v=LkIK8f4yvOU. # The Difference of Two Squares. number = int(input("Please enter a positive odd number: ")) while number % 2 == 0 or number < 0: number = int(input( "Please enter a positive number: " if number < 0 else "Please enter an odd number: " )) root_2 = number // 2 root_1 = root_2 + 1 print(f"The roots are { root_1 } and { root_2 }.") print(f"The squares are { root_1 ** 2 } and { root_2 ** 2 }.") print(f"{ root_1 ** 2 } - { root_2 ** 2 } = { number }.")
c2f1391ee6e1ce4aa1cca4a81314f323495dc655
ProspePrim/PythonGB
/Lesson 5/task_5_2.py
985
3.96875
4
#Создать текстовый файл (не программно), сохранить в нем несколько строк, #выполнить подсчет количества строк, количества слов в каждой строке. with open('test.txt', 'w') as my_f: my_l = [] line = input('Введите текст \n') while line: my_l.append(line + '\n') line = input('Введите текст \n') if not line: break my_f.writelines(my_l) with open('test.txt' , 'r') as f: i = 0 for el in f: i += 1 print(f"Строка {i}: {el}") count = len(el) - el.count("\n") print(f"Количество знаков: {count}") print(f"Количество слов в строке: {len(el.split())} ") print('_____________________________________') print('*'*20) print(f"Количество строк: {i}")
05da3490735523a90c3b6a6a206a5445ac6e8fa4
ProspePrim/PythonGB
/Lesson 2/task_2_4.py
524
4.03125
4
#Пользователь вводит строку из нескольких слов, разделённых пробелами. #Вывести каждое слово с новой строки. Строки необходимо пронумеровать. #Если в слово длинное, выводить только первые 10 букв в слове. a = input("введите строку ") list_a = [] i = 0 list_a = a.split() for _ in range(len(list_a)): print(f"{list_a[i][0:10]}") i += 1
cc84abe6637d76e56a7ac2c958ebd7c8a808c1c1
ProspePrim/PythonGB
/Lesson 2/task_2_1.py
628
4.125
4
#Создать список и заполнить его элементами различных типов данных. #Реализовать скрипт проверки типа данных каждого элемента. #Использовать функцию type() для проверки типа. #Элементы списка можно не запрашивать у пользователя, а указать явно, в программе. list_a = [5, "asdv", 15, None, 10, "asdv", False] def type_list(i): for i in range(len(list_a)): print(type(list_a[i])) return type_list(list_a)
8ff0adfd4e67aa0a69a45ebda1eb30ec290dcd49
ProspePrim/PythonGB
/Lesson 7/task_7_1.py
1,162
3.65625
4
class Cell: cells: int def __init__(self, cells: int): self.cells = cells def __str__(self): return str(self.cells) def __int__(self): return self.cells def __add__(self, cells: 'Cell'): return Cell(self.cells + cells.cells) def __sub__(self, cells: 'Cell'): if (result := self.cells - cells.cells) < 0: return "Разница меньше нуля" else: return Cell(result) def __mul__(self, cells: 'Cell'): return Cell(self.cells * cells.cells) def __truediv__(self, cells: 'Cell'): return Cell(self.cells - cells.cells) @staticmethod def make_order(cell: 'Cell', n: int): fullrow, lastrow = divmod(cell.cells, n) return '\n'.join([str('*') * n for _ in range(0, fullrow)]) + '\n' + '*' * lastrow cell0 = Cell(5) cell1 = Cell(10) cell2 = Cell(12) print('cell0 + cell2', cell0 + cell2) print('cell1 - cell2', cell1 - cell2) print('cell2 - cell1', cell2 - cell1) print('cell0 * cell1', cell0 * cell1) print('cell1 / cell0', cell1 / cell0) print(cell1.make_order(cell1, 4))
bce8bf614aca3883f2ac618caa8f00bc32a5dd73
costacoz/python_design_patterns
/behavioral/iterator.py
1,296
4.5
4
# Iterators are built into Python. # It can be engaged, using 'iter(arg*)' function # arg* - can be list, tuple, dic, set and string. # Below is the example of using it. # fruits_tuple = {'apple', 'blueberry', 'cherry', 'pineapple'} # fruits_tuple = ('apple', 'blueberry', 'cherry', 'pineapple') # fruits_tuple = ['apple', 'blueberry', 'cherry', 'pineapple'] fruits_tuple = 'apples' fruits_iterator = iter(fruits_tuple) print(next(fruits_iterator)) print(next(fruits_iterator)) print(next(fruits_iterator)) print(fruits_iterator.__next__()) # Loop through an iterator fruits_tuple = ('apple', 'blueberry', 'cherry', 'pineapple') for f in fruits_tuple: print(f) # # To create an iterator manually we need to implement iter and next # in __iter__ we initialize iterator, same as in __init__, and return iterator class Iterator: def __iter__(self): self.a = 2 return self # must always return iterator object def __next__(self): if self.a < 10: x = self.a self.a += 1 return x else: raise StopIteration # to stop iterator in loop iterable_obj = Iterator() # iterator = iter(iterable_obj) # print(next(iterator)) # print(next(iterator)) # print(next(iterator)) for i in iterable_obj: print(i)
a387b981c804a8e38ba20ce58d2417d82bc4dd89
muhammadyou/PythonTutorial
/ThreadingExample.py
1,758
4.09375
4
import threading import time class Example(threading.Thread): def run(self): for _ in range(10): time.sleep(1) print(threading.current_thread().getName()) def example(): for _ in range(10): time.sleep(1) print("hELlo") def example1(name, x): print("From example1 function {}".format(x)) for _ in range(10): time.sleep(1) print("Hi") def one(): global y lock.acquire() try: y =5 print(y) except: pass finally: lock.release() def two(): global y lock.acquire() try: y =3 print(y) except: pass finally: lock.release() def main(): #-- LOCK global lock lock = threading.Lock() first = threading.Thread(target=one, name='Lock1 Thread') second = threading.Thread(target=two, name='Lock2 Thread') first.start() second.start() threading.Thread(target = example, name="Example Thread").start() t = threading.Thread(target = example1, args=("Example 1 Thread", 5), name='Example 1 Thread') t.start() t.join() # -- it doesnt allow all thread to run altogether, so this threads runs only before starts another threads print("The thread is {}".format(t.is_alive())) x = Example(name="Yousuf") y = Example(name="OMer") print("The thread is {}".format(t.is_alive())) x.start() y.start() print("The number of threads running are {}".format(threading.active_count())) # prints the number of threads running print(threading.enumerate()) # tells you the threads running such as their name print("The active thread is {}".format(threading.active_count())) if __name__ == '__main__': main()
717852b99833f1e2f9470bb7e906f0cb29d7874e
bjolley74/myTKfiles
/lesson1.py
255
3.859375
4
"""lesson1.py - message box: creates a tk message box""" from tkinter import * from tkinter import messagebox root = Tk() root.withdraw() messagebox.showinfo('Bobby\' World', 'Hello Y\'all! This is a message from Bobby\nThis is some really cool stuff')
9c47ecc06cd8e6525255f441528d9deae2655c9f
jgu13/Miscellaneous
/Python/ecosys_simulator/ecosystem_simulator.py
13,854
4.125
4
# Jiayao Gu # 260830725 import random import matplotlib.pyplot as plt class Animal: # Initializer method def __init__(self, my_species, row, column): """ Constructor method Args: self (Animal): the object being created my_species (str): species name ("Lion" or "Zebra") row (int): row for the new animal column (int): column for the new animal Returns: Nothing Behavior: Initializes a new animal, setting species to my_species """ self.species = my_species self.row = row self.col = column self.age = 0 self.time_since_last_meal = 0 def __str__(self): """ Creates a string from an object Args: self (Animal): the object on which the method is called Returns: str: String summarizing the object """ s= self.species+" at position ("+str(self.row)+","+str(self.col)+"):, age="+str(self.age)+", time_since_last_meal="+\ str(self.time_since_last_meal) return s def can_eat(self, other): """ Checks if self can eat other Args: self (Animal): the object on which the method is called other (Animal): another animal Returns: boolean: True if self can eat other, and False otherwise """ # WRITE YOUR CODE FOR QUESTION 3 HERE if self.species == "Lion" and other.species == "zebra": return True else: return False def time_passes(self): """ Increases age and time_since_last_meal Args: self (Animal): the object on which the method is called Returns: Nothing Behavior: Increments age and time_since_last_meal """ # WRITE YOUR CODE FOR QUESTION 4 HERE self.age += 1 self.time_since_last_meal += 1 return def dies_of_old_age(self): """ Determines if an animal dies of old age Args: self (Animal): the object on which the method is called Returns: boolean: True if animal dies of old age, False otherwise """ # WRITE YOUR CODE FOR QUESTION 5 HERE if (self.species == "Lion" and self.age >= 18) or (self.species == "Zebra" and self.age >= 7): return True else: return False def dies_of_hunger(self): """ Determines if an animal dies of hunger Args: self (Animal): the object on which the method is called Returns: boolean: True if animal dies of hunger, False otherwise """ # WRITE YOUR CODE FOR QUESTION 6 HERE if self.species == "Lion" and self.time_since_last_meal >= 6: return True else: return False def will_reproduce(self): """ Determines if an animal will reproduce this month Args: self (Animal): the object on which the method is called Returns: boolean: True if ready to reproduce, False otherwise """ # WRITE YOUR CODE FOR QUESTION 7 HERE if self.species=="Zebra": if self.age==3 or self.age==6 and self.dies_of_old_age()==False: return True else: return False elif self.species=="Lion": if self.age==7 or self.age==14 and self.age<18 and self.dies_of_hunger()==False: return True else: return False # end of Animal class def initialize_population(grid_size): """ Initializes the grid by placing animals onto it. Args: grid_size (int): The size of the grid Returns: list of animals: The list of animals in the ecosystem """ all_animals=[] all_animals.append(Animal("Lion",3,5)) all_animals.append(Animal("Lion",7,4)) all_animals.append(Animal("Zebra",2,1)) all_animals.append(Animal("Zebra",5,8)) all_animals.append(Animal("Zebra",9,2)) all_animals.append(Animal("Zebra",4,4)) all_animals.append(Animal("Zebra",4,8)) all_animals.append(Animal("Zebra",1,2)) all_animals.append(Animal("Zebra",9,4)) all_animals.append(Animal("Zebra",1,8)) all_animals.append(Animal("Zebra",5,2)) return all_animals def print_grid(all_animals, grid_size): """ Prints the grid Args: all_animals (list of animals): The animals in the ecosystem grid_size (int): The size of the grid Returns: Nothing Behavior: Prints the grid """ #get the set of tuples where lions and zebras are located lions_tuples = { (a.row,a.col) for a in all_animals if a.species=="Lion"} zebras_tuples = { (a.row,a.col) for a in all_animals if a.species=="Zebra"} print("*"*(grid_size+2)) for row in range(grid_size): print("*",end="") for col in range(grid_size): if (row,col) in lions_tuples: print("L",end="") elif (row,col) in zebras_tuples: print("Z",end="") else: print(" ",end="") print("*") print("*"*(grid_size+2)) def sort_animals(all_animals): """ Sorts the animals, left to right and top to bottom Args: all_animals (list of animals): The animals in the ecosystem Returns: Nothing Behavior: Sorts the list of animals """ def get_key(a): return a.row+0.001*a.col all_animals.sort(key=get_key) def my_random_choice(choices): """ Picks ones of the elements of choices Args: choices (list): the choices to choose from Returns: One of elements in the list """ if not choices: return None # for debugging purposes, we use this fake_random_choice function def getKey(x): return x[0]+0.001*x[1] return min(choices, key=getKey) # for actual random selection, replace the above this: #return random.choice(choices) def list_neighbors(current_row, current_col, grid_size): """ Produces the list of neighboring positions Args: current_row (int): Current row of the animal current_col (int): Current column of the animal grid_size (int): The size of the gride Returns: list of tuples of two ints: List of all position tuples that are around the current position, without including positions outside the grid """ # WRITE YOUR CODE FOR QUESTION 1 HERE i = current_row j = current_col List = [] for row_increment in range(-1,2): new_row = i + row_increment for col_increment in range(-1,2): new_col = j + col_increment if new_col == j and new_row == i: pass elif (new_row > 0 and new_row < grid_size) and (new_col > 0 and new_col < grid_size): List.append((new_row, new_col)) return List def random_neighbor(current_row, current_col, grid_size, only_empty=False, animals=[]): """ Chooses a neighboring positions from current position Args: current_row (int): Current row of the animal current_col (int): Current column of the animal size (int): Size of the grid only_empty (boolean): keyword argument. If True, we only consider neighbors where there is not already an animal animals (list): keyword argument. List of animals present in the ecosystem Returns: tuple of two int: A randomly chosen neighbor position tuple """ # WRITE YOUR CODE FOR QUESTION 2 HERE all_neighbors = [n for n in list_neighbors(current_row, current_col, grid_size)] next_cell = my_random_choice(all_neighbors) i = next_cell[0] j = next_cell[1] if not(only_empty): return next_cell else: for animal in animals: if animal.row == i and animal.col == j: all_neighbors.remove((animal.row,animal.col)) if len(all_neighbors) == 0: return None return next_cell #next_cell does not have an animal def one_step(all_animals, grid_size): """ simulates the evolution of the ecosystem over 1 month Args: all_animals (list of animals): The animals in the ecosystem grid_size (int): The size of the grid Returns: list fo str: The events that took place Behavior: Updates the content of animal_grid by simulating one time step """ sort_animals(all_animals) # ensures that the animals are listed # from left to right, top to bottom # run time_passes on all animals for animal in all_animals: animal.time_passes() # make animals die of old age events = [] dead = [] for animal in all_animals: if(animal.dies_of_old_age()): dead.append(animal) events.append("{} dies of old age at position {} {}".format(animal.species, animal.row, animal.col)) # make animals die of hunger elif(animal.dies_of_hunger()): dead.append(animal) events.append("{} dies of hunger at position {} {}".format(animal.species,animal.row, animal.col)) for a in all_animals: if a in dead: all_animals.remove(a) # move animals new_row, new_col = random_neighbor(animal.row, animal.col, grid_size, False, all_animals) eaten = [] for animal in all_animals: # search for animal that on the new cell present_animal = [n for n in all_animals if n.row == new_row and n.col == new_col and n not in eaten] #there is an animal in the new cell if present_animal != []: # search for the animal at the new_position #3 cases: # if a lion moves to a cell contains a zebra, lion eats zebra and lion moves to new_position, zebra is removed from the cel present_animal = present_animal[0] if animal.can_eat(present_animal): events.append(animal.species+" moves from "+str(animal.row)+" "+str(animal.col)+" to "+str(new_row)+" "+str(new_col)+" and eats a zebra") animal.row = new_row #update position animal.col = new_col animal.time_since_last_meal = 0 #update the time since last meal eaten.append(present_animal) # if a zebra moves to a cell contains a lion, zebra is eaten and removed from its position elif present_animal.can_eat(animal): events.append(animal.species+" moves from "+str(animal.row)+" "+str(animal.col)+" to "+str(new_row)+" "+str(new_col)+ " and is eaten by a lion") eaten.append(animal) present_animal.time_since_last_meal = 0 # if the same animals present, animals stay, nothing happens else: # two animals are the same species events.append(animal.species+" moves from "+str(animal.row)+" "+str(animal.col)+" to "+str(new_row)+" "+str(new_col)+ " but there is an animal of the same species") #new cell does not contain an animal else: events.append(animal.species+" moves from "+str(animal.row)+" "+str(animal.col)+" to "+str(new_row)+" "+str(new_col)) animal.row = new_row animal.col = new_col for a in all_animals: if a in eaten: all_animals.remove(a) # since animals have moved, we sort the list of animals again, so that # we consider them for reproduction in the right order sort_animals(all_animals) babies = [] # reproduce animals for animal in all_animals: if animal.will_reproduce(): result = random_neighbor(animal.row, animal.col, grid_size, False, all_animals) if result == None: return; else: # new cell is empty baby_row, baby_col = result all_animals.append(Animal(animal.species, baby_row, baby_col)) #add baby to all_animals list events.append("A new baby {} is born at {} {}".format(animal.species, baby_row, baby_col)) def run_whole_simulation(grid_size = 10, simulation_duration = 20, image_file_name="population.png"): """ Executes the entire simulation Args: grid_size (int): Size of the grid simulation_duration (int): Number of steps of the simulation image_file_name (str): name of image to be created. Returns: Nothing Behavior: Simulates the evolution of an animal grid Generates graph of species abundance and saves it to populations.png """ # Do not change this; this initializes the animal population all_animals = initialize_population(grid_size) # WRITE YOUR CODE FOR QUESTION 9 HERE lions = [] zebras = [] for time in range(simulation_duration): num_of_lions = 0 num_of_zebras = 0 for animal in all_animals: if animal.species == "Lion": num_of_lions += 1 elif animal.species == "Zebra": num_of_zebras += 1 lions.append(num_of_lions) zebras.append(num_of_zebras) one_step(all_animals, grid_size) plt.plot(range(simulation_duration), lions, "b", label="Lions") plt.plot(range(simulation_duration), zebras, "r", label = "zebras") plt.xlabel("time") plt.ylabel("Number of individuals") plt.legend(loc = "best") plt.savefig(image_file_name)
0b602263ce8b46a900c767c974efcce4ca0b2984
JDWree/Practice
/Python/mastermind.py
3,436
4.1875
4
# Simple version of the game 'mastermind' #---------------------------------------- # Version 1.0 Date: 5 April 2020 #---------------------------------------- # Player vs computer # A random code gets initialized. The player has 10 guesses to crack the code. # The game tells the player when it has a right digit in the code but on the wrong # spot as 'd' (from digit). If a player as a correct digit on the correct spot, # the game returns a 'c'. # An example: # The code is 1234 # The player guesses 1359 # The game will return 'cd' on this guess since 1 is correct and there is a 3. #------------------------------------------------------------------------------- ### Packages ### from random import randint #------------------------------------------------------------------------------ # Explanation of the game to the player: print(""" You are about to play a simple version of 'Mastermind'. The computer will create a code of 4 unique digits from 0-9. So no 2 the same digits will be used in the code. You have to guess the code within 10 tries. After every guess the game will give you feedback. If you have a correct digit but not in the right place, it will return a 'd'. if you have a correct digit on the correct spot, it will return a 'c'. An example: The code is 1234. Your guess is 2538. The game will return 'cd' as feedback. Good luck! """) #------------------------------------------------------------------------------ # Initialization of the code to break: code = [] while len(code)<4: dgt = randint(0,9) if dgt not in code: code.append(dgt) else: pass print("The code has been initialized.") #------------------------------------------------------------------------------ # Function that prompts the player for its guess and returns the feedback def guess(): print("Make your guess:") g = input("> ") ges = g.strip() if len(ges) != 4 or not ges.isdigit(): print("You didn't make a proper guess?!") print("Type in your guess for the 4-digit code.") print("For example 1234 .") guess() else: feedback = "" for i in range(len(ges)): if int(ges[i]) == code[i]: feedback+='c' elif int(ges[i]) in code: feedback +='d' else: pass return feedback #------------------------------------------------------------------------------ # Looping over max ammount of guesses. # Prompting everytime the player for its guess. # When the player makes a correct guess, stop looping. found = False number_of_guesses = 0 while not found and number_of_guesses < 10: fdbck = guess() number_of_guesses+=1 #print(fdbck) print("\nFeedback on your guess: %s\n" % ''.join(sorted(list(fdbck)))) if fdbck == 'cccc': found = True else: print("You have %d guesses left." % (10 - number_of_guesses)) #------------------------------------------------------------------------------ if found: print("\n\t\t\t***CONGRATULATIONS!***\n\n") print("You have beaten the game with %d guesses left!" % (10 - number_of_guesses)) else: print("\n\t\t\t***FAIL***\n\n") print("Oh, bommer. You didn't manage to guess the correct code in time!") print("Better luck next time!") #------------------------------------------------------------------------------
059b163345985fdcfee9f3e410de39e001218782
gagaspbahar/prak-pengkom-20
/P02_16520289/P02_16520289_02.py
744
3.5625
4
# NIM/Nama : 16520289/Gagas Praharsa Bahar # Tanggal : 4 November 2020 # Deskripsi: Problem 2 - Konversi basis K ke basis 10 #Kamus #int sm = jumlah bilangan dalam basis 10 #int n = jumlah digit #int k = basis awal #int i = counter #Inisialisasi variabel sm = 0 n = int(input("Masukkan nilai N: ")) k = int(input("Masukkan nilai K: ")) #Algoritma for i in range(n-1,-1,-1): #Loop dari n-1 sampai 0 digit = int(input("Masukkan digit ke " + str(n-i) + ": ")) #Input digit sm += k**i * digit #Kalikan basis dengan nilai digit ke-berapa lalu tambahkan ke sm #Output print("Bilangan dalam basis 10 adalah", sm)
885e989095d06495061674fe1e2696b815df9463
gagaspbahar/prak-pengkom-20
/H03_16520289/H03_16520289_01.py
436
3.609375
4
# NIM/Nama : 16520289/Gagas Praharsa Bahar # Tanggal : 15 November 2020 # Deskripsi: Problem 1 - Penulisan Terbalik # Kamus # int n = panjang array # int ar[] = array penampung angka #Algoritma #Input n = int(input("Masukkan N: ")) #Inisialisasi array dan memasukkan angka ke array ar = [0 for i in range(n)] for i in range(n): ar[i] = int(input()) #Pembalikkan array print("Hasil dibalik: ") for i in range(n-1,-1,-1): print(ar[i])
5966f2409f0998aa515f8f40b56f3339a2d4298a
plaer182/Python3
/test_random_symbol.py
1,575
3.546875
4
#!/usr/bin/env python3 from random_symbols import random_symbol import string def test_length_name(): """ Check length of element in list of results """ try: random_symbol(["Annannannannannannannannannannannannannannanna", "Boris", "Evgenia", "Viktor"]) except: pass else: raise Exception("incorrect input accepted or ignored") def test_correctness(): """ Check basic functionality using happy path """ list_of_names_1 = ["Anna", "Boris", "Evgenia", "Viktor"] name_plus_symbols = random_symbol(list_of_names_1) symbols = '$€₽₪' letters_counter = 0 symbols_counter = 0 for elem in name_plus_symbols: for char in elem: if char.isalpha(): letters_counter += 1 elif char in symbols: symbols_counter += 1 else: if char.isprintable(): raise Exception("Unknown type of char: ", char) else: raise Exception("Unknown type of char: unprintable ", hex(char)) assert symbols_counter == letters_counter def test_incorrectness(): """ Check basic functionality using unhappy path """ try: random_symbol(["Anna!!", "~Boris~", "Evge,,nia", "Vik/tor"]) except: pass else: raise Exception("incorrect input accepted or ignored") if __name__ == '__main__': test_length_name() test_correctness() test_incorrectness()
2724d92157d61f930c089931f2b55042dcfe9f0e
plaer182/Python3
/FizzBuzz(1-100)(hw2).py
354
4.15625
4
number = int(input('Enter the number: ')) if 0 <= number <= 100: if number % 15 == 0: print("Fizz Buzz") elif number % 3 == 0: print("Fizz") elif number % 5 == 0: print("Buzz") else: print(number) elif number < 0: print("Error: unknown symbol") else: print("Error: unknown symbol")
df113dafcc1cf93b98304cc6f8f33efbe0a2e296
plaer182/Python3
/fahrenheit_to_celsius(hw1).py
158
4.125
4
celsius = float(input('Enter the temperature in degrees to Сelsius> ')) fahrenheit = celsius * 1.8 + 32 print(str(fahrenheit) + ' degrees to Fahrenheit')
08fe50d6f996a359bd2346667554abde47a94c47
Jamesbwwh/Minesweeper
/Minesweeper/Minefield.py
3,057
3.78125
4
import random def generate(difficulty): mineField = printMineField(difficulty) height = len(mineField) width = len(mineField[0]) ranges = width * height mines = random.randint(ranges // 8, ranges // 7) # mines = 4; # comment or remove this line. for testing only. print "Difficulty: ", difficulty, "Mines: ", mines, "Height: ", height, "Width: ", width ranges -= 1 for mine in range(mines): while(True): placeMine = random.randint(0, ranges) x = placeMine // width y = placeMine % width if mineField[x][y] != 9: mineField[x][y] = 9 if x - 1 >= 0: #Top if y - 1 >= 0: #Top-Left if mineField[x - 1][y - 1] != 9: mineField[x - 1][y - 1] += 1 if mineField[x - 1][y] != 9: mineField[x - 1][y] += 1 if y + 1 < width: #Top-Right if mineField[x - 1][y + 1] != 9: mineField[x - 1][y + 1] += 1 if y - 1 >= 0: #Left if mineField[x][y - 1] != 9: mineField[x][y - 1] += 1 if y + 1 < width: #Right if mineField[x][y + 1] != 9: mineField[x][y + 1] += 1 if x + 1 < width: #Bottom if y - 1 >= 0: #Bottom-Left if mineField[x + 1][y - 1] != 9: mineField[x + 1][y - 1] += 1 if mineField[x + 1][y] != 9: mineField[x + 1][y] += 1 if y + 1 < width: #Bottom-Right if mineField[x + 1][y + 1] != 9: mineField[x + 1][y + 1] += 1 break return mineField, mines def printMineField(difficulty): #easy difficulty if (difficulty == 1): minefield = [[0] * 9 for i in xrange(9)] return minefield #medium difficulty if (difficulty == 2): minefield = [[0] * 16 for i in xrange(16)] return minefield #hard difficulty if (difficulty == 3): minefield = [[0] * 20 for i in xrange(20)] return minefield #Very hard difficulty if (difficulty == 4): minefield = [[0] * 25 for i in xrange(25)] return minefield #custom difficulty if (difficulty == 0): width = input("Enter the width : ") height = input("Enter the height : ") minefield = [[0] * width for i in xrange(height)] return minefield def displayTestMineField(minemap, limiter): counter = 0 #prints until reach k value specified as the limiter for i in range(len(minemap)): if (counter != limiter): print minemap[i] counter +=1 #displayTestMineField(printMineField(1), 2) #for i in range(len(mineField)): # for j in range(len(mineField[i])): # print mineField[i][j], # print ""
f677307abacfa8b8c1e095bf3eeffaa1f94ffe0f
iman2008/first-repo
/random1.py
187
3.875
4
#defining 10 random number between 10 and 20 import random def random_numer(): i=0 while (i<=10): x = random.random() * 20 if 10 <= x <= 20: print (x) i=i+1 random_numer()
0f23631ef11d79a29889cb820371aa21ffaecde8
iman2008/first-repo
/lab4task1.py
336
3.765625
4
def sum_adder (mlist): """this will add up the content of the list""" total = 0 s_list = mlist for item in s_list: if isinstance(item,int): total = total + item elif isinstance (item,list): total=total+sum_adder (item) else: return "you have not select proper list" return total x = [90,10,11] print (sum_adder(x))
9b624ac6dee525b0da68baa1196f8b273486d237
Mentos15/Python_2
/paswords.py
691
3.5625
4
#! python3 # paswords.py PASWORDS = { 'email': 'vital2014','vk':'Vital2014','positive':'vital2014'} import sys,pyperclip if len(sys.argv)<2: print('Использование: python paswords.py[Имя учетной записи] - копирование пароля учетной записи') sys.exit() account = sys.argv[1] # первый аргумент командной строки - это имя учетной записи if account in PASWORDS: pyperclip.copy(PASWORDS[account]) print ('Пароль для'+ account+'скопирован в буфер.') else: print('Учетная запись'+account+'отсутствует в списке')
db6a67f488a152ccc2768d3d24728afb318f10de
CodecoolBP20172/pbwp-3rd-si-code-comprehension-kristofilles
/comprehension.py
2,101
4.3125
4
"""Its a bot what randomly choose a number between 1 and 20, and the user need to guess within 6 round what number was choosen by the bot.""" import random #import the random module guessesTaken = 0 #assign 0 to guessesTaken variable print('Hello! What is your name?') #print out this sentence myName = input() #assign a user input to myName variable number = random.randint(1, 20) #assign a randomly choosen integer(between 1 and 20) to number variable print('Well, ' + myName + ', I am thinking of a number between 1 and 20.') #printing out this sentence with the given name while guessesTaken < 6: #loop while the guessesTaken variable is less then 6 print('Take a guess.') #print out this sentence guess = input() #assign a user input to guess variable guess = int(guess) #making type conversion changing the value of the guess variable to integer from string guessesTaken += 1 #increasing the value of the guessesTaken by 1 if guess < number: #doing something if guess value is lower than number value print('Your guess is too low.') #if its true print out this sentence if guess > number: #doing something if the guess value is higher than the number value print('Your guess is too high.') #if its true print out this sentence if guess == number: #doing something if the guess value is equal with the number value break #if its true the loop is immediately stop if guess == number: #doing something if the guess value is equal with the number value guessesTaken = str(guessesTaken) #making type conversion changing the value of the guessesTaken variable to string from integer print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!') #print out how many try needed to the user to guess out if guess != number: #doing something if guess value is not equal with number value number = str(number) #making type conversion changing the value of the number variable to string from integer print('Nope. The number I was thinking of was ' + number) #print out the randomly choosen number
19a4a42767f001a14afeb4debed9ef26c6e69afe
rdugh/pythonds9
/pythonds9/trees/binary_tree.py
1,028
3.8125
4
class BinaryTree: def __init__(self, key): self.key = key self.left_child = None self.right_child = None def insert_left(self, key): if self.left_child is None: self.left_child = BinaryTree(key) else: # if there IS a left child t = BinaryTree(key) t.left_child = self.left_child self.left_child = t def insert_right(self, key): if self.right_child is None: self.right_child = BinaryTree(key) else: # if there IS a right child t = BinaryTree(key) t.right_child = self.right_child self.right_child = t def get_right_child(self): return self.right_child def get_left_child(self): return self.left_child def get_root_val(self): return self.key def set_root_val(self, new_key): self.key = new_key def __repr__(self): return f"BinaryTree({self.key!r})"
6ced4a96655281b60edd62a77ea9e76b6f79bd55
brentEvans/algorithm_practice
/Python/algo.py
2,264
3.640625
4
class Node: def __init__(self, value): self.val = value self.next = None class SLL: def __init__(self): self.head = None def addBack(self,value): new_node = Node(value) if self.head == None: self.head = new_node else: runner = self.head while runner.next != None: runner = runner.next runner.next = new_node return self def display_list(self): runner = self.head this_list = [] while runner != None: this_list.append(runner.val) runner = runner.next print(this_list) def removeNeg(self): if self.head == None: return "Empty" while self.head.val < 0: self.head = self.head.next runner = self.head while runner.next != None: if runner.next.val < 0: runner.next = runner.next.next else: runner = runner.next return self def move_to_front(self,value): if self.head == None: return "Empty List" runner = self.head start = self.head while runner.next != None: if runner.next.val == value: move = runner.next runner.next = runner.next.next self.head = move move.next = start runner = runner.next return self def partition(self, pivot): if self.head == None: return "Empty list" runner = self.head while runner.next != None: if runner.next.val == pivot: self.move_to_front(runner.next.val) else: runner = runner.next runner = self.head while runner.next != None: if runner.next.val < pivot: self.move_to_front(runner.next.val) else: runner = runner.next return self new_list = SLL() new_list.addBack(5) new_list.addBack(3) new_list.addBack(2) new_list.addBack(4) new_list.addBack(5) new_list.addBack(9) new_list.addBack(-7) new_list.addBack(8) new_list.display_list() new_list.partition(4) new_list.display_list()
07bd3a329eafee4c2398a08943aeb985a282b6f2
onionmccabbage/pythonTrainingMar2021
/using_ternary.py
474
4.40625
4
# Python has one ternary operator # i.e. an operator that takes THREE parts # all other operators are binary, i.e. they take TWO parts # e.g. a = 1 or 3+2 # the ternary operator works like this # 'value if true' 'logical condition' 'value if false' x = 6 y = 5 print("x" if x>y else "y") # alternative syntax for the ternary operator nice = False personality = ("horrid", "lovely")[nice] # spot the index 0 or 1 print("My cat is {}".format(personality)) #
8b08218eb70b47bfb0aa02cfacf775dcdb2a3089
onionmccabbage/pythonTrainingMar2021
/py2demo.py
242
3.859375
4
print "hello" # Python 2 print('also hello') # also works in Python 2 # division of ints 7/3 # is 2 in Py2 and 3 and a bit in Py 3 # py 2 has a 'long' data type - change it to 'float' # some py 2 functions were re-defined in py 3
8b888a5341335f8976cfc23b7ede527047886ec3
AnindKiran/N_Queen-s-Problem-Solution-in-Python
/Final N-Queens Project.py
3,087
4.28125
4
a="""This is a program used to display ALL solutions for the famous N-Queens Problem in chess. The N-Queens Problem is a problem where in an N-sized chess board, we have to place N Queens in such a way that no one queen can attack any other queen""" print(a) print() a="""This program will take your input and will generate the solutions for the board size of your input""" #This function generates an nxn board as a matrix def generateboard(n): try: n=int(n) board=[[0]*n for i in range(n)] return board except Exception as e: print("The following error has occured:",e) #This function displays the solution def FinalSolution(board): for i in board: for j in i: if j: print('Q',end=' ') else: print('.',end=' ') print() print() #This is the main algorithm of the program, and determines whether a queen can #be placed in a particular box or not. It considers a particular location in #a chessboard and sees if another queen can attack the location under #consideration. def safe(board,row,col): #TO CHECK IF THE CURRENT ROW IS SAFE c=len(board) for i in board[row]: if i: return 0 #TO CHECK IF THE CURRENT COLUMN IS SAFE for i in range(len(board)): if board[i][col]: return 0 a,b=row,col #TO CHECK IN THE BOTTOM-RIGHT DIRECTION while a<c and b<c: if board[a][b]: return 0 a=a+1 b=b+1 a,b=row,col #TO CHECK IN THE TOP-LEFT DIRECTION while a>=0 and b>=0: if board[a][b]: return 0 a=a-1 b=b-1 a,b=row,col #TO CHECK IN THE TOP-RIGHT DIRECTION while a>=0 and b<c: if board[a][b]: return 0 a=a-1 b=b+1 a,b=row,col #TO CHECK IN THE BOTTOM-LEFT DIRECTION while a<c and b>=0: if board[a][b]: return 0 a=a+1 b=b-1 return 1 #This function takes the generated board, and tries all possible combinations #of queens. It places the queens in all locations to see which is the correct #overall solution. The best part about this function is that it if it sees that #N-queens cannot be placed, it does not restart but instead continues from the #last value. Number=0 def solve(board,row=0): if board != None: global Number if row>=len(board): FinalSolution(board) Number+=1 return for col in range(len(board)): if safe(board,row,col): board[row][col]=1 solve(board,row+1)#The board is returned here when a solution #is found and the program is out of the function. board[row][col]=0 n=input("Enter the size 'n' of the board:") a=generateboard(n) solve(a) print("The number of solutions for the",n,"x",n,"board is:", Number)
04860c836937ba8bc594c64d7c9b752ea564269e
jeremy-robb/KnoxClassRecommender
/tools.py
3,239
4
4
from lists import * takeFrom = [] def chooseMajors(): print("") print("To choose a major, type the first 3 letters of the specialization, followed by the first 2 letters of the degree") print("Examples: CS BA (Computer Science BA) , MATBA (Math BA) , PHYMI (Physics minor)") print("Choose major one") while True: major1 = input() if isAdded(major1.upper()): break else: print("Choose any of the following: ", added) while True: print("Choose major two") major2 = input() if isAdded(major2.upper()) and major2.upper() != major1.upper(): break else: print("Choose any of the following (besides the first major): ", added) takeFrom.append(major1.upper()) takeFrom.append(major2.upper()) if "PHY" in major1.upper() or "PHY" in major2.upper(): takeFrom.append("MATBA") return major([major1.upper(), major2.upper()]) def getTranscript(): print("If you already have your transcript code (as given by this program), paste it here. If not, press enter to continue. If you do not have a transcript (incoming students), type 'new'") start = input() if len(start) > 0 and start[0] == "~": return list(start[1:].split("-")) print("To start, navigate to your unofficial transcript page (https://my.knox.edu/ICS/Registrar/Student_Tools/Unofficially_Transcript.jnz), and copy paste (ctrl a, ctrl c) the entire page here (ctrl v)") final = "~" trancount = 0 fileread = open("courses", "r") avail = [] while True: line = fileread.readline() if not line: break if line[5:8] not in avail: avail.append(line[5:8]) while True: word = input() trancount += 1 if trancount == 175: print("It looks like something went wrong, message Jeremy Robb (jarobb@knox.edu) to recieve instructions on how to properly paste in your transcript") if word == "Unofficial Transcript PDF ": break counter = 0 flag = False if not word[0:3] in avail: continue for x in word: if x.isdigit() and len(word) - counter - 3 > 0: flag = True break counter += 1 if not flag: continue # at this point we can assume it's a class I need to add if "N/A" in word: continue final += word[0:3] + " " + word[counter:counter+3] + "-" debug = input() # This is just to get rid of the final line if len(final) > 1: print("") print("Your code is: ") print(final) return list(final[1:].split("-")) else: print("It looks like something went wrong, message Jeremy Robb (jarobb@knox.edu) to recieve instructions on how to properly paste in your transcript") return [] def addStatus(transcript): if len(transcript) >= 27: transcript.append("SOP") transcript.append("JUN") transcript.append("SEN") elif len(transcript) >= 18: transcript.append("SOP") transcript.append("JUN") elif len(transcript) >= 9: transcript.append("SOP") return transcript
4a16ad732d79913225b5e89bc29acc27bf81937c
Lexical-Lad/Machine-Learning-Python-R-Matlab-codes
/Machine Learning A-Z Template Folder/Part 1 - Data Preprocessing/PreprocessingPractice.py
1,626
3.609375
4
import numpy as np import pandas as pd import matplotlib.pyplot as mlt import os #os.chdir(...) dataset = pd.read_csv("Data.csv") #splitting the dataset into the feature matrix and the dependent variable vector X = dataset.iloc[:,:-1].values y = dataset.iloc[:,-1].values #conpensating for the missing values, if any from sklearn.preprocessing import Imputer imputer = Imputer(missing_values = "NaN", strategy = "mean", axis = 0) imputer = imputer.fit(X[:,(1,2)]) X[:,(1,2)] = imputer.transform(X[:,(1,2)]) #encoding the categorical features into numerical values from sklearn.preprocessing import LabelEncoder labelencoder_X = LabelEncoder() X[:,0] = labelencoder_X.fit_transform(X[:,0]) labelencoder_y = LabelEncoder() y = labelencoder_y.fit_transform(y) #compensating for the numertical disparity betweeen the newly assigned numerical labels(only for model where the disparity is not a requisite), by creating dummy, binary features from sklearn.preprocessing import OneHotEncoder onehotencoder = OneHotEncoder(categorical_features = [0]) X = onehotencoder.fit_transform(X).toarray() #splitting the dataset into training and test set from sklearn.cross_validation import train_test_split X_train,X_test,y_train,y_test = train_test_split(X,y, test_size = 0.2) #not providing a seed(for random sampling each time) #scaling the features from sklearn.preprocessing import StandardScaler sc_X = StandardScaler() X_train = sc_X.fit_transform(X_train) X_test = sc_X.transform(X_test) #scaling y only for regresiion problems sc_y = StandardScaler() y_train = sc_y.fit_transform(y_train) y_test = sc_y.transform(y_test)
3d0d26f588dfeb0d23e179fbdf94a6b35f0388a8
lazyseals/crawler
/products/category_parser.py
18,232
3.671875
4
from products import items as d # Foreach shop a unique parser must be written that executes the following steps: # 1. Category name and product name to lower case # 2. Check if a product in category name needs to be replaced by a mister m category # 3. Determine mister m category based on a pattern in the product name # # In order to integrate a new shop into the parser # the following additional steps are required to make the previously defined steps working: # For step 2: Define a dict in items.py with the following naming scheme: toparse_<shopname> # -> This dict contains categories that hold product which belong at least into 2 different mister m categories # For step 3: Define a if/if structure with pattern matching in product name to determine the mister m category # -> Foreach mister m category define exactly 1 if or if case # -> Sort the if/if structure alphabetically # # If 1 shop is excluded from category matching based on product name, then mention it here with a short reason why # - Body and Fit: All categories that are parsed define a mister m category # Match categories from shop rockanutrition to mister m categories. # Matching based on product name. def parse_rocka(category, product): # Categories a product can be in categories = [] # Product name to lower case for better string matching product = product.lower() # Category name to lower case for better string matching category = category.lower() # Check if product category needs to be placed into another category if category == 'vitamine & minerale' or category == 'drinks' or category == 'bake & cook': # Check product name for patterns in order to replace category with mister m category if 'vitamin b' in product: categories.append('Vitamin B') if 'vitamin d' in product: categories.append('Vitamin D') if 'essentials' in product or 'strong' in product: categories.append('Multivitamine') if 'magnesium' in product: categories.append('Magnesium') if 'milk' in product or 'whey' in product: categories.append('Protein Drinks') if 'swish' in product or 'work' in product: categories.append('Energy Drinks') if 'cino' in product: categories.append('Tee & Kaffee') if 'oil' in product: categories.append('Speiseöle') if 'bake' in product: categories.append('Backmischungen') # Return all categories a product is in return categories # Match categories from shop fitmart to mister m categories. # Matching based on product name. def parse_fitmart(category, product): # Categories a product can be in categories = [] # Product name to lower case for better string matching product = product.lower() # Category name to lower case for better string matching category = category.lower() # Check if product category needs to be placed into another category if category in d.toparse_fitmart: # Check product name for patterns in order to replace category with mister m category if 'brötchen' in product: categories.append('Brot') if 'brownie' in product or 'pancakes' in product or 'waffles' in product or 'mischung' in product: categories.append('Backmischungen') if 'candy' in product: categories.append('Süßigkeiten') if 'chips' in product or 'flips' in product or 'nachos' in product: categories.append('Chips') if 'crank' in product: categories.append('Trainingsbooster') if 'crispies' in product: categories.append('Getreide') if 'dream' in product or 'creme' in product or 'spread' in product or 'choc' in product or 'cream' in product or \ 'butter' in product or 'plantation' in product or 'walden' in product: categories.append('Aufstriche') if 'muffin' in product or 'cookie' in product: categories.append('Cookies & Muffins') if 'pasta' in product or 'pizza' in product: categories.append('Pizza & Pasta') if 'pudding' in product: categories.append('Pudding') if 'truffle' in product or 'riegel' in product or 'waffel' in product or 'snack' in product or \ 'bar' in product: categories.append('Schokolade') if 'sauce' in product or 'callowfit' in product: categories.append('Gewürze & Saucen') if 'zerup' in product or 'sirup' in product or 'syrup' in product: categories.append('Syrup') # Return all categories a product is in return categories # Match categories from shop myprotein to mister m categories. # Matching based on product name. def parse_myprotein(category, product): # Categories a product can be in categories = [] # Product name to lower case for better string matching product = product.lower() # Category name to lower case for better string matching category = category.lower() # Check if product category needs to be placed into another category if category in d.toparse_myprotein: # Check product name for patterns in order to replace category with mister m category if 'aakg' in product: categories.append('AAKG') if 'aufstrich' in product or 'butter' in product or 'dip pot' in product: categories.append('Aufstriche') if 'antioxidant' in product or 'maca' in product: categories.append('Antioxidantien') if 'bar' in product or 'rocky road' in product or 'carb crusher' in product or 'flapjack' in product: categories.append('Proteinriegel') if 'beeren' in product: categories.append('Beeren') if 'bcaa drink' in product or 'protein wasser' in product: categories.append('Protein Drinks') if 'beta-alanin' in product: categories.append('Beta Alanin') if 'bohnen' in product: categories.append('Bohnen') if 'casein' in product: categories.append('Casein Protein') if 'choc' in product or 'schokolade' in product: categories.append('Schokolade') if 'chromium' in product or 'electrolyte' in product or 'eisen' in product: categories.append('Mineralstoffe') if 'citrullin' in product: categories.append('Citrullin') if 'cla' in product: categories.append('CLA') if 'cookie' in product or 'keks' in product or 'brownie' in product: categories.append('Cookies & Muffins') if 'crisps' in product: categories.append('Chips') if 'curcurmin' in product: categories.append('Curcurmin') if 'eaa' in product: categories.append('EAA') if 'eiklar' in product: categories.append('Eiklar') if 'erbsenprotein' in product: categories.append('Erbsenprotein') if 'fat binder' in product or 'thermo' in product or 'diet aid' in product or 'thermopure boost' in product\ or 'glucomannan' in product or 'diet gel' in product: categories.append('Fatburner') if 'fiber' in product: categories.append('Superfoods') if 'flavdrop' in product: categories.append('Aromen und Süßstoffe') if 'gel' in product: categories.append('Weitere') if 'glucosamin' in product: categories.append('Glucosamin') if 'glucose' in product or 'dextrin carbs' in product or 'palatinose' in product: categories.append('Kohlenhydratpulver') if 'glutamin' in product: categories.append('Glutamin') if 'granola' in product or 'crispies' in product or 'oats' in product or 'hafer' in product: categories.append('Getreide') if 'hmb' in product: categories.append('HMB') if 'koffein' in product: categories.append('Koffein') if 'latte' in product or 'mocha' in product or 'kakao' in product or 'tee' in product: categories.append('Tee & Kaffee') if 'magnesium' in product: categories.append('Magnesium') if 'mahlzeitenersatz' in product: categories.append('Mahlzeitenersatz-Shakes') if 'maltodextrin' in product: categories.append('Maltodextrin') if 'mandeln' in product or 'samen' in product or 'nüsse' in product or 'nut' in product: categories.append('Nüsse & Samen') if 'öl' in product: categories.append('Speiseöle') if 'ornithin' in product: categories.append('Ornithin') if 'pancake' in product or 'cake' in product: categories.append('Backmischungen') if 'performance mix' in product or 'recovery blend' in product or 'collagen protein' in product or \ 'dessert' in product: categories.append('Protein Mischungen') if 'phosphatidylserin' in product or 'leucin' in product or 'tribulus' in product: categories.append('Planzliche Nahrungsergänzungsmittel') if 'pork crunch' in product: categories.append('Jerkey') if 'pre-workout' in product or 'pump' in product or 'pre workout' in product or 'preworkout' in product: categories.append('Trainingsbooster') if 'reis' in product: categories.append('Alltägliche Lebensmittel') if 'sirup' in product: categories.append('Syrup') if "soja protein" in product: categories.append("Sojaprotein") if 'soße' in product: categories.append('Gewürze & Saucen') if 'spaghetti' in product or 'penne' in product or 'fettuccine' in product: categories.append('Pizza & Pasta') if 'taurin' in product: categories.append('Taurin') if 'tyrosin' in product: categories.append('Tyrosin') if 'veganes performance bundle' in product: categories.append('Veganes Protein') if 'vitamin b' in product: categories.append('Vitamin B') if 'vitamins bundle' in product or 'multivitamin' in product or 'immunity plus' in product or \ 'the multi' in product: categories.append('Multivitamine') if 'vitamin c' in product: categories.append('Vitamin C') if 'vitamin d' in product: categories.append('Vitamin D') if 'waffel' in product or 'protein ball' in product: categories.append('Schokolade') if 'whey' in product: categories.append('Whey Protein') if 'zink' in product: categories.append('Zink') if 'bcaa' in product or 'amino' in product: # Many product with amino in -> Make sure this is the last categories.append('BCAA') # Return all categories a product is in return categories # Match categories from shop zecplus to mister m categories. # Matching based on product name. def parse_zecplus(category, product): # Categories a product can be in categories = [] # Product name to lower case for better string matching product = product.lower() # Category name to lower case for better string matching category = category.lower() # Check if product category needs to be placed into another category if category in d.toparse_zecplus: # Check product name for patterns in order to replace category with mister m category if "all in one" in product: categories.append("Multivitamine") if "antioxidan" in product: categories.append("Antioxidantien") if "arginin" in product: categories.append("Arginin") if "aroma" in product: categories.append("Aromen und Süßstoffe") if "arthro" in product: categories.append("Glucosamin") if "bcaa" in product: categories.append("BCAA") if "beta alanin" in product: categories.append("Beta Alanin") if "casein" in product: categories.append("Casein Protein") if "citrullin" in product: categories.append("Citrullin") if "creatin" in product: categories.append("Creatin") if "dextrose" in product: categories.append("Dextrose") if "eaa" in product: categories.append("EAA") if "fischöl" in product: categories.append("Omega-3") if "gaba" in product: categories.append("Gaba") if "gainer" in product: categories.append("Weight Gainer") if "glutamin" in product: categories.append("Glutamin") if "greens" in product: categories.append("Pflanzliche Nahrungsergänzungsmittel") if "kickdown" in product or "testosteron booster" in product: categories.append("Trainingsbooster") if "koffein" in product: categories.append("Koffein") if "kohlenhydrate" in product: categories.append("Kohlenhydratpulver") if "kokosöl" in product: categories.append("Speiseöle") if "liquid egg" in product: categories.append("Eiklar") if "maltodextrin" in product: categories.append("Maltodextrin") if "mehrkomponenten" in product: categories.append("Protein Mischungen") if "nährstoff optimizer" in product or "sleep" in product: categories.append("Probiotika") if "nudeln" in product or "pizza" in product: categories.append("Pizza & Pasta") if "oats" in product: categories.append("Getreide") if "proteinriegel" in product: categories.append("Proteinriegel") if "reis protein" in product: categories.append("Reisprotein") if "pulvermischung" in product or "pancakes" in product or 'bratlinge' in product: categories.append("Backmischungen") if "tryptophan" in product or "intraplus" in product or 'leucin' in product: categories.append("Aminosäuren Komplex") if "vitamin b" in product: categories.append("Vitamin B") if "vitamin c" in product: categories.append("Vitamin C") if "vitamin d" in product: categories.append("Vitamin D") if "whey" in product or "clean concentrate" in product: categories.append("Whey Protein") if "zink" in product: categories.append("Zink") # Return all categories a product is in return categories # Match categories from shop zecplus to mister m categories. # Matching based on product name. def parse_weider(category, product): # Categories a product can be in categories = [] # Product name to lower case for better string matching product = product.lower() # Category name to lower case for better string matching category = category.lower() # Check if product category needs to be placed into another category if category in d.toparse_weider: # Check product name for patterns in order to replace category with mister m category if "ace" in product or "mineralstack" in product or "megabolic" in product or "multi vita" in product\ or "joint caps" in product: categories.append("Multivitamine") if "amino blast" in product or "amino nox" in product or "amino egg" in product or "amino powder" in product\ or "amino essential" in product: categories.append("Aminosäuren Komplex") if "amino power liquid" in product or "bcaa rtd" in product or "eaa rtd" in product or "rush rtd" in product: categories.append("Aminosäuren Getränke") if "arginin" in product: categories.append("Arginin") if "bar" in product or "classic pack" in product or "riegel" in product or "wafer" in product: categories.append("Proteinriegel") if "bcaa" in product: categories.append("BCAA") if "glucan" in product: categories.append("Antioxidantien") if "casein" in product: categories.append("Casein Protein") if "cla" in product: categories.append("CLA") if "creme" in product: categories.append("Aufstriche") if "coffee" in product: categories.append("Tee & Kaffee") if "cookie" in product: categories.append("Cookies & Muffins") if "eaa" in product: categories.append("EAA") if "fresh up" in product: categories.append("Aromen und Süßstoffe") if "glucosamin" in product: categories.append("Glucosamin") if "glutamin" in product: categories.append("Glutamin") if "hmb" in product: categories.append("HMB") if "magnesium" in product: categories.append("Magnesium") if "omega 3" in product: categories.append("Omega-3") if "protein low carb" in product or "protein shake" in product or "starter drink" in product: categories.append("Protein Drinks") if "pump" in product or "rush" in product: categories.append("Trainingsbooster") if "soy 80" in product: categories.append("Sojaprotein") if "thermo stack" in product: categories.append("Fatburner") if "vegan protein" in product: categories.append("Veganes Protein") if "water" in product: categories.append("Ohne Kalorien") if "whey" in product or "protein 80" in product: categories.append("Whey Protein") if "zinc" in product: categories.append("Zink") # Return all categories a product is in return categories
653b56c505745fb2947589692c3a628d149d27ef
robertmplewis/playground
/wordquiz.py
649
3.921875
4
#!/usr/bin/env python import operator def main(): print word_count() def word_count(): word_totals = { } book_contents = f.read() book_contents = book_contents.replace('\n', ' ') book_contents = book_contents.replace(',', '') book_contents = book_contents.replace('.', '') book_contents = book_contents.replace('"', '') book_split = book_contents.split(' ') for word in book_split: if word not in word_totals: word_totals[word] = 1 word_totals[word] += 1 word_totals = sorted(word_totals.items(), key=operator.itemgetter(1)) return word_totals f = open('rob-book.txt','r') if __name__ == '__main__': main()
375b0579cdbe45e4a66d954f8d5e767f8ef70546
justEhmadSaeed/ai-course-tasks
/Python Assignment 1/Part 2/Task 5.py
261
4.28125
4
# Write a list comprehension which, from a list, generates a lowercased version of each string # that has length greater than five strings = ['Some string', 'Art', 'Music', 'Artifical Intelligence'] for x in strings: if len(x) > 5: print(x.lower())
a54b52aee8ebf3cf44dc050ee68699aa4c6ee011
justEhmadSaeed/ai-course-tasks
/Python Assignment 1/Part 3/Task 3.2.py
306
3.6875
4
# One line function for intersection # Uncomment below code to generate random lists intersection = lambda a, b: list(set(a) & set(b)) # import random # a = [] # b = [] # for i in range(0, 10): # a.append(random.randint(0, 20)) # b.append(random.randint(5, 20)) # print(intersection(a, b))
af2ca98dfba5c5fdf958422f55c0685bef3937e4
JanBednarik/micropython-matrix8x8
/examples/game_of_life.py
1,870
3.5
4
import pyb from matrix8x8 import Matrix8x8 def neighbors(cell): """ Yields neighbours of cell. """ x, y = cell yield x, y + 1 yield x, y - 1 yield x + 1, y yield x + 1, y + 1 yield x + 1, y - 1 yield x - 1, y yield x - 1, y + 1 yield x - 1, y - 1 def advance(board): """ Advance to next generation in Conway's Game of Life. """ new_board = set() for cell in ((x, y) for x in range(8) for y in range(8)): count = sum((neigh in board) for neigh in neighbors(cell)) if count == 3 or (count == 2 and cell in board): new_board.add(cell) return new_board, new_board == board def generate_board(): """ Returns random board. """ board = set() for x in range(8): for y in range(8): if pyb.rng() % 2 == 0: board.add((x, y)) return board def board_to_bitmap(board): """ Returns board converted to bitmap. """ bitmap = bytearray(8) for x, y in board: bitmap[x] |= 0x80 >> y return bitmap def restart_animation(display): """ Shows restart animation on display. """ for row in range(8): display.set_row(row, 0xFF) pyb.delay(100) for row in range(8): display.clear_row(7-row) pyb.delay(100) display = Matrix8x8(brightness=0) board, still_life = None, False while True: # init or restart of the game if still_life or not board: board = generate_board() restart_animation(display) pyb.delay(500) display.set(board_to_bitmap(board)) pyb.delay(500) # advance to next generation board, still_life = advance(board) display.set(board_to_bitmap(board)) # finish dead if not board: pyb.delay(1500) # finish still if still_life: pyb.delay(3000)
c6324a495ce9b5cd11784e34e4da56c427482e1f
daniellopes04/uva-py-solutions
/list2/120 - Stacks of Flapjacks.py
1,011
3.5
4
# -*- coding: UTF-8 -*- def main(): while True: try: unsorted = list(map(int, input().split())) current = unsorted.copy() final = sorted(unsorted) N = len(final) steps = [] for i in range(len(current) - 1, -1, -1): index = current.index(final[i]) if index == i: continue if index == 0: current[0:i + 1] = current[0:i + 1][::-1] steps.append(N - i) else: current[0:index + 1] = current[0:index + 1][::-1] current[0:i + 1] = current[0:i + 1][::-1] steps.append(N - index) steps.append(N - i) steps.append(0) print(" ".join(map(str, unsorted))) print(" ".join(map(str, steps))) except(EOFError) as e: break if __name__ == '__main__': main()
0babe69773bebc354b6da02c83f1fd151b4034dc
daniellopes04/uva-py-solutions
/list3/902 - Password Search.py
943
3.5625
4
# -*- coding: UTF-8 -*- def main(): while True: try: line = input().strip() while line == "": line = input().strip() items = line.split() if len(items) == 2: n = int(items[0]) text = items[1] else: n = int(items[0]) text = input().strip() while text == '': text = input().strip() frequency = {} for i in range(len(text) - n + 1): substr = text[i:i+n] if substr in frequency: frequency[substr] += 1 else: frequency[substr] = 1 password = max(frequency.keys(), key=(lambda k: frequency[k])) print(password) except(EOFError): break if __name__ == '__main__': main()
8353125ae9724cfef90b738d8aad6998ca78f8fe
SpCrazy/crazy
/code/SpiderDay03/bs4_learn/hello.py
283
3.5
4
from urllib.request import urlopen from bs4 import BeautifulSoup response = urlopen("http://www.pythonscraping.com/pages/page1.html") bs = BeautifulSoup(response.read(),"html.parser") print(bs.h1) print(bs.h1.get_text()) print(bs.h1.text) print(bs.html.body.h1) print(bs.body.h1)
4788dd580886d9d056d2c5847cacda6b2a95628e
SpCrazy/crazy
/code/SpiderDay1_Thread/condition/concumer.py
821
3.78125
4
import time from threading import Thread, currentThread class ConsumerThread(Thread): def __init__(self, thread_name, bread, condition): super().__init__(name=thread_name) self.bread = bread self.condition = condition def run(self): while True: self.condition.acquire() if self.bread.count > 0: time.sleep(2) self.bread.consume_bread() print(currentThread().name + "消费了面包,当前面包数量为:", self.bread.count) self.condition.release() else: print("面包已消费完," + currentThread().name + ",请等待生产,当前面包数量为:", self.bread.count) self.condition.notifyAll() self.condition.wait()
8c0d380707fd8ed99cba1e6e44a13b63313bc0c7
whlg0501/2018_PAT
/1004.py
1,663
3.578125
4
""" 1004 成绩排名 (20)(20 分) 读入n名学生的姓名、学号、成绩,分别输出成绩最高和成绩最低学生的姓名和学号。 输入格式:每个测试输入包含1个测试用例,格式为 第1行:正整数n 第2行:第1个学生的姓名 学号 成绩 第3行:第2个学生的姓名 学号 成绩 第n+1行:第n个学生的姓名 学号 成绩 其中姓名和学号均为不超过10个字符的字符串,成绩为0到100之间的一个整数,这里保证在一组测试用例中没有两个学生的成绩是相同的。 输出格式:对每个测试用例输出2行,第1行是成绩最高学生的姓名和学号,第2行是成绩最低学生的姓名和学号,字符串间有1空格。 输入样例: 3 Joe Math990112 89 Mike CS991301 100 Mary EE990830 95 输出样例: Mike CS991301 Joe Math990112 """ class student(object): def __init__(self, name, id, points): self.name = name self.id = id self.points = points def main(): studentsList = [] n = int(input()) count = 0 while(count < n): input_string = input().split(" ") studentsList.append(student(input_string[0], input_string[1], int(input_string[2]))) count += 1 max = studentsList[0] min = studentsList[0] for i in range(0, len(studentsList)): if(studentsList[i].points > max.points): max = studentsList[i] if(studentsList[i].points < min.points): min = studentsList[i] print("{} {}".format(max.name, max.id)) print("{} {}".format(min.name, min.id)) main() # 注意format比%要好用的多
c9fd907f7db76ed478ad64875951242b3dcebf0f
whlg0501/2018_PAT
/1049.py
1,239
3.5625
4
""" 1049 数列的片段和(20)(20 分)提问 给定一个正数数列,我们可以从中截取任意的连续的几个数,称为片段。例如,给定数列{0.1, 0.2, 0.3, 0.4},我们有(0.1) (0.1, 0.2) (0.1, 0.2, 0.3) (0.1, 0.2, 0.3, 0.4) (0.2) (0.2, 0.3) (0.2, 0.3, 0.4) (0.3) (0.3, 0.4) (0.4) 这10个片段。 给定正整数数列,求出全部片段包含的所有的数之和。如本例中10个片段总和是0.1 0.3 + 0.6 + 1.0 + 0.2 + 0.5 + 0.9 + 0.3 + 0.7 + 0.4 = 5.0。 输入格式: 输入第一行给出一个不超过10^5^的正整数N,表示数列中数的个数,第二行给出N个不超过1.0的正数,是数列中的数,其间以空格分隔。 输出格式: 在一行中输出该序列所有片段包含的数之和,精确到小数点后2位。 输入样例: 4 0.1 0.2 0.3 0.4 输出样例: 5.00 """ # l = [1,2,3,4] # for i in range(0, len(l) + 1): # for j in range(0,i): # print(l[j:i]) def main(): result = 0.0 num = input() l = input().split(" ") l = [float(x) for x in l] for i in range(0, len(l) + 1): for j in range(0, i): # print(l[j:i]) result += sum(l[j:i]) print("%.2f" %result) main()
23d0b02ba64c2aca3becf467d88c692109aab9f8
patnaik89/string_python.py
/condition.py
1,696
4.125
4
""" Types of conditional statements:- comparision operators (==,!=,>,<,<=,>=) logical operators (and,or,not) identity operators (is, is not) membership operators (in, not in) """ x, y = 2,9 print("Adition", x + y) print("multiplication", x * y) print("subtraction", x - y) print("division", x/y) print("Modular", x%y) print("floor division", x//y) print("power: ", x ** y) # finding a 'number' is there in given list or not list1 = [22,24,36,89,99] if 24 in list1: print(True) else:print(False) # examples on if elif and else conditions if x>y: print("x is maximum") elif y>x: print("y is maximum") else: print("both are equal") # Finding the odd and even numbers in given list list1 = [1,2,3,5,6,33,24,67,4,22,90,99] for num in range(len(list1)): if num % 2 == 0: print("Even Numbers are:", num,end=", ") else: print("The Odd Numbers are:", num) # Dynamic list using loops list2 = [] for number in range(10): if number % 2 == 0: # finding Even numbers in given range list2.append(number) print("Even numbers are:", list2) # finding all odd numbers within range 40 list1=[] for num in range(40): if num % 2 != 0: list1.append(num) print("odd numbers are", list1) # Dynamic set set1 = set() for number in range(10): set1.add(number) print("numbers in given range are:",set1) # printing duplicate elements list1=[1,1,2,4,4,5,44,56,2,99,49,99] l=sorted(set(list1)) # removing duplicate elements print(l) dup_list=[] for number in range(len(l)): if (list1.count(l[number]) > 1): dup_list.append(l[number]) print("duplicate elements in a list are: ",dup_list)
c0bd2b9a856537ea24d75bc6e73ec5396c0a987b
seanjib99/pythonProject14
/python 1.py
954
4
4
#s.n students take k apples and distribute each student evenly #The remaining parts remain in the basket. #How many apples will each single student get? #How many apples will remain in the basket?The programs read the numbers N and k. N=int(input("enter the number of students in class")] K= int(input("enter the number of apple:")} apples_get(K//N) remaining_apples=(K%N) print(f"each student got {apples_get}") print (f"The remaining apples are {remaining_apples}") # 4.N Given the integer N - the number of minutes that is passed since midnight. # How many hours and minutes are displayed on the 24h digital clock? # The program should print two numbers: # The number of hours(between 0 and 23) and the number of minutes (between 0 and 59) N = int(input("Enter the number of minutes passed since midnight: ")) hours = N//60 minutes = N%60 print(f"The hours is {hours}") print(f"The minutes is {minutes}") print(f"It's {hours}:{minutes} now.")
59eb59d435bb953bdc73df7a5df3d285dbfd6c93
cmillecan/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/1-last_digit.py
460
4.03125
4
#!/usr/bin/python3 import random number = random.randint(-10000, 10000) last_digit = abs(number) % 10 if number < 0: last_digit = -last_digit if last_digit > 5: print("Last digit of {:d} is {:d} and is greater \ than 5".format(number, last_digit)) elif last_digit == 0: print("Last digit of {:d} is {:d} and \ is 0".format(number, last_digit)) else: print("Last digit of {:d} is {:d} and is \ less than 6 and not 0".format(number, last_digit))
65ec659dbb339de8bfbfe81ae2556dcc314c8f0c
cmillecan/holbertonschool-higher_level_programming
/0x0B-python-input_output/13-student.py
816
3.875
4
#!/usr/bin/python3 """ Task 13 """ class Student: """Defines a student""" def __init__(self, first_name, last_name, age): """ Instantiation """ self.first_name = first_name self.last_name = last_name self.age = age def to_json(self, attrs=None): """ Retrieves a dictionary representation of Student. """ if attrs is None: return self.__dict__ else: new = {} for key in attrs: if key in self.__dict__: new[key] = self.__dict__[key] return new def reload_from_json(self, json): """ Replaces all attributes of the Student instance. """ for key in json: setattr(self, key, json[key])
bb204dab03699a3aaa32f558c92fd8fc697449ab
arkkhanu/Final-Project-OCR
/Server/hough_rect.py
6,941
3.609375
4
""" Module for finding a rectangle in the image, using Hough Line Transform. """ import itertools from typing import Union import numpy as np import cv2 import matplotlib.pyplot as plt from scipy.spatial import distance import consts def find_hough_rect(img: np.ndarray) -> Union[None, np.ndarray]: """ Find the main rectangle in the image using Hough Line Transform. If a rectangle is found, returning the ordered four points that define the rectangle, else returning None. """ img = cv2.GaussianBlur(img, (7, 7), 0) edged = cv2.Canny(img, 50, 250, apertureSize=3) lines = cv2.HoughLinesP(edged, rho=1, theta=np.pi / 180, threshold=150, minLineLength=img.shape[0] // 10, maxLineGap=img.shape[0] // 10) if lines is None: return None lines = lines.reshape((len(lines), 4)) # remove unnecessary dimension # sort lines by their lengths, from longest to shortest lines = sorted(lines, key=lambda l: distance.euclidean((l[0], l[1]), (l[2], l[3])), reverse=True) longest_lines = lines[:10] # take the longest lines # debug_show_lines(longest_lines, img.shape) pts = get_lines_intersect(longest_lines, img.shape[1], img.shape[0]) if pts is None: # hasn't managed to find four points of intersection return None return order_points(np.array(pts)) def get_lines_intersect(lines: list, img_width: int, img_height: int) -> Union[None, list[tuple[int, int]]]: """ Get the intersection points of the lines, only if there are exactly four of them. Reduce mistakes by filtering close points and unwanted points of intersection. """ # get the line equation for each of the lines line_equations = [get_line_equation(*line) for line in lines] pts = set() # get combination of two lines at a time for (m1, b1), (m2, b2) in itertools.combinations(line_equations, 2): if pt := get_intersection_point(m1, b1, m2, b2, img_width, img_height): pts.add(pt) pts = filter_close_pts(list(pts), min_pts_dst=img_width // 10) if len(pts) != 4: return None return pts def get_intersection_point(m1: float, b1: float, m2: float, b2: float, img_width: int, img_height: int) \ -> Union[None, tuple[int, int]]: """ Get the intersection points of two lines. If the point-of-intersection is out of bounds or the angle between the two lines is too small, returning None. Otherwise, returning the point. """ if m1 == m2: # slopes equal, lines will never meet return None # if either line is vertical, get the x from the vertical line, # and the y from the other line if m1 == consts.INFINITY: x = b1 y = m2 * x + b2 elif m2 == consts.INFINITY: x = b2 y = m1 * x + b1 else: x = (b2 - b1) / (m1 - m2) # equation achieved by solving m1*x+b1 = m2*x+b2 y = m1 * x + b1 if x < 0 or x > img_width - 1 or y < 0 or y > img_height - 1: # point-of-intersection out of bounds return None # obtain the angle between the two lines if m1 * m2 == -1: alpha = np.pi / 2 # lines are perpendicular, cannot divide by zero else: alpha = np.arctan(np.abs((m1 - m2) / (1 + m1 * m2))) if alpha < np.pi / 16: # if the angle is too small, then the two lines are almost # parallel, discard point of intersection return None return int(x), int(y) def filter_close_pts(pts: list[tuple[int, int]], min_pts_dst: int = 100) -> list[tuple[int, int]]: """ Remove points that are too close one another (usually caused by duplicate lines or lines very close to each other). """ filtered_pts = pts[:] for i, pt1 in enumerate(pts): for j, pt2 in enumerate(pts[i + 1:]): if distance.euclidean(pt1, pt2) < min_pts_dst and pt2 in filtered_pts: filtered_pts.remove(pt2) return filtered_pts def get_line_equation(x1, y1, x2, y2) -> tuple[float, float]: """ Get line equation (of the form y=mx+b), defined by two points. Returning the slope and b. If the two dots are on the same vertical line, then the line passing between them cannot be represented by the equation y=mx+b, therefore in that case returning 'infinite' slope and the x value of the vertical line. """ if x1 == x2: return consts.INFINITY, x1 # can't divide by zero, returning 'infinite' slope instead m = (y2 - y1) / (x2 - x1) # slope = dy / dx b = -m * x1 + y1 # derived from y=mx+b return m, b def order_points(pts: np.ndarray) -> np.ndarray: """ Order the points of the rectangle according to the following order: top-left, top-right, bottom-right, bottom-left. """ # prepare an array to hold the ordered points rect = np.zeros((4, 2), dtype=np.float32) # the top-left point will have the smallest sum, whereas # the bottom-right point will have the largest sum s = pts.sum(axis=1) rect[0] = pts[np.argmin(s)] rect[2] = pts[np.argmax(s)] # compute the difference between the points, the # top-right point will have the smallest difference, # whereas the bottom-left will have the largest difference diff = np.diff(pts, axis=1) rect[1] = pts[np.argmin(diff)] rect[3] = pts[np.argmax(diff)] return rect def rect_area(ordered_pts: np.ndarray) -> float: """Calculate the area of the quadrilateral defined by the ordered points.""" # get x and y in vectors x, y = zip(*ordered_pts) # shift coordinates x_ = x - np.mean(x) y_ = y - np.mean(y) # calculate area correction = x_[-1] * y_[0] - y_[-1] * x_[0] main_area = np.dot(x_[:-1], y_[1:]) - np.dot(y_[:-1], x_[1:]) return 0.5 * np.abs(main_area + correction) # ----------- FOR DEBUGGING ----------- def debug_show_lines(lines, img_shape): temp = np.ones(img_shape) * 255 for line in lines: x1, y1, x2, y2 = line pt1, pt2 = debug_extend_line(x1, y1, x2, y2, img_shape[1], img_shape[0]) cv2.line(temp, pt1, pt2, 0, 7) plt.imshow(temp) plt.show() def debug_extend_line(x1, y1, x2, y2, img_width, img_height): if x1 == x2: return (x1, 0), (x1, img_height) m = (y2 - y1) / (x2 - x1) b = -m * x1 + y1 # derived from y-y1 = m(x-x1) f = lambda x: m * x + b if b < 0: pt1 = (int(-b // m), 0) elif b > img_height: pt1 = (int((img_height - b) // m), img_height - 1) else: pt1 = (0, int(f(0))) if f(img_width) > img_height: pt2 = (int((img_height - b) // m), img_height - 1) elif f(img_width) < 0: pt2 = (int(-b // m), 0) else: pt2 = (img_width, int(f(img_width))) return pt1, pt2
b24585f353af5a15200c7c9ef10d920ed3862fc5
SuryaDeepthiR/competitive-programming
/competitive-programming/Week2/Day-6/InPlaceShuffle.py
449
3.9375
4
import random def random_number(floor,ceiling): return random.randint(floor,ceiling) def shuffle(the_list): # Shuffle the input in place length = len(the_list) for i in range(0,length-1): j = random_number(0,length-1) the_list[i],the_list[j] = the_list[j],the_list[i] sample_list = [1, 2, 3, 4, 5] print 'Sample list:', sample_list print 'Shuffling sample list...' shuffle(sample_list) print sample_list
834612676d77e7be218b1898422ba94fff11196f
liadbiz/Leetcode-Solutions
/src/python/dynamic_programming/minimum-ascii-delete-sum-for-two-strings.py
1,970
3.828125
4
""" Given two strings s1, s2, find the lowest ASCII sum of deleted characters to make two strings equal. Example 1: Input: s1 = "sea", s2 = "eat" Output: 231 Explanation: Deleting "s" from "sea" adds the ASCII value of "s" (115) to the sum. Deleting "t" from "eat" adds 116 to the sum. At the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this. Example 2: Input: s1 = "delete", s2 = "leet" Output: 403 Explanation: Deleting "dee" from "delete" to turn the string into "let", adds 100[d]+101[e]+101[e] to the sum. Deleting "e" from "leet" adds 101[e] to the sum. At the end, both strings are equal to "let", and the answer is 100+101+101+101 = 403. If instead we turned both strings into "lee" or "eet", we would get answers of 433 or 417, which are higher. Note: 0 < s1.length, s2.length <= 1000. All elements of each string will have an ASCII value in [97, 122]. Source: https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/ """ class Solution: def minimumDeleteSum(self, s1: str, s2: str) -> int: l1, l2 = len(s1), len(s2) # dp_sums[i][j] means the minimum delete sum for string s1[i:] and s2[j:] dp_sums = [[0] * (l2 + 1) for _ in range(l1 + 1)] for i in range(l1 - 1, -1, -1): dp_sums[i][l2] = dp_sums[i+1][l2] + ord(s1[i]) for i in range(l2 - 1, -1, -1): dp_sums[l1][i] = dp_sums[l1][i+1] + ord(s2[i]) for i in range(l1 - 1, -1, -1): for j in range(l2 - 1, -1, -1): if s1[i] == s2[j]: dp_sums[i][j] = dp_sums[i+1][j+1] else: dp_sums[i][j] = min(dp_sums[i+1][j] + ord(s1[i]), dp_sums[i][j+1] + ord(s2[j])) return dp_sums[0][0] if __name__ == "__main__": s1 = "sea" s2 = "eat" s12 = "delete" s22 = "leet" print(Solution().minimumDeleteSum(s1, s2)) print(Solution().minimumDeleteSum(s12, s22))
38ca97cf3452797e9460b01dcf61559d53643669
liadbiz/Leetcode-Solutions
/src/python/dynamic_programming/number_of_longest_increasing_subsequence.py
1,446
3.984375
4
""" 673. Number of Longest Increasing Subsequence source: https://leetcode-cn.com/problems/number-of-longest-increasing-subsequence/ Given an unsorted array of integers, find the number of longest increasing subsequence. Example 1: Input: [1,3,5,4,7] Output: 2 Explanation: The two longest increasing subsequence are [1, 3, 4, 7] and [1, 3, 5, 7]. Example 2: Input: [2,2,2,2,2] Output: 5 Explanation: The length of longest continuous increasing subsequence is 1, and there are 5 subsequences' length is 1, so output 5. Note: Length of the given array will be not exceed 2000 and the answer is guaranteed to be fit in 32-bit signed int. """ class Solution: def findNumberOfLIS(self, nums: List[int]) -> int: result, max_len = 0, 0 dp = [[1, 1] for _ in range(len(nums))] # {length, number} pair for i in range(len(nums)): for j in range(i): if nums[i] > nums[j]: if dp[i][0] == dp[j][0]+1: dp[i][1] += dp[j][1] elif dp[i][0] < dp[j][0]+1: dp[i] = [dp[j][0]+1, dp[j][1]] if max_len == dp[i][0]: result += dp[i][1] elif max_len < dp[i][0]: max_len = dp[i][0] result = dp[i][1] return result if __name__ == "__main__": nums = [1, 3, 5, 4, 7] assert Solution().findNumberOfLIS(nums) == 2, "result is not correct"
f21b75948484cc34cea7d9d166dc47e72611749d
liadbiz/Leetcode-Solutions
/src/python/degree_of_array.py
1,373
4.15625
4
""" Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements. Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums. Example 1: Input: [1, 2, 2, 3, 1] Output: 2 Explanation: The input array has a degree of 2 because both elements 1 and 2 appear twice. Of the subarrays that have the same degree: [1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2] The shortest length is 2. So return 2. Example 2: Input: [1,2,2,3,1,4,2] Output: 6 Note: nums.length will be between 1 and 50,000. nums[i] will be an integer between 0 and 49,999. """ class Solution: def findShortestSubArray(self, nums): """ :type nums: List[int] :rtype: int """ import collections import operator fre_dict = collections.Counter(nums).most_common() max_fre = max(fre_dict, key = operator.itemgetter(1))[1] def fre_sub(i): return len(nums) - nums.index(i) - nums[::-1].index(i) return min(fre_sub(i[0]) for i in fre_dict if i[1] == max_fre) if __name__ == "__main__": nums1 = [1, 2, 2, 3, 1] nums2 = [1,2,2,3,1,4,2] print(Solution().findShortestSubArray(nums1)) print(Solution().findShortestSubArray(nums2))
7859a42286274f9710a439def03707787e93641b
liadbiz/Leetcode-Solutions
/src/python/greedy_algorithm/jump_game_2.py
2,740
3.984375
4
""" Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. Example: Input: [2,3,1,1,4] Output: 2 Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. Note: You can assume that you can always reach the last index. """ class Solution: # 思路1: 时间复杂度为O(n),空间复杂度为O(n) # 第一步:求出每一个点能跳到的最远的地方 # 第二步:求出能到达每一个点的最小的坐标 # 第三步:从最后一个点出发,依次原则能到达该点的最小的点为jump经过的点。 # 可以证明此贪心过程为最优。 # 实际上还是保留了很多没有用的信息,显然比第二个方法编程要复杂一些。 def jump(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) - 1 reachs = [i + nums[i] for i in range(n)] min_reach_index = [float('inf')] * (n + 1) m = 0 for i,r in enumerate(reachs): min_reach_index[m:r + 1] = [min(i, _) for _ in min_reach_index[m:r + 1]] if r == n: break m = r + 1 res = 0 while n != 0: n = min_reach_index[n] res += 1 return res # 思路2: 时间复杂度为o(n),空间复杂度为O(1) # 遍历nums,维护变量max_index表示当前遍历过的点能跨到的最远的地方,变量 # crt_max_index表示我现在所在的点能跳到的最远的地方,当i大于crt_max_index的时候 # 说明我不能一次就跳到i,所以我要作出一次jump的选择,很明显,应该跳到max_index # 对应的那个位置,但是这个位置并不重要,我们只需要将次数加一即可,然后更新 # crt_max_index为max_index即可。 def jump(self, nums): """ :type nums: List[int] :rtype: int """ res = 0 max_index = 0 crt_max_index = 0 for i, l in enumerate(nums): if i > crt_max_index: crt_max_index = max_index res += 1 max_index = max(max_index, i + l) return res if __name__ == "__main__": nums1 = [2,3,1,1,4] nums2 = [2, 0, 2, 0, 1] nums3 = [1, 1, 1, 1] nums4 = list(range(1, 25001))[::-1] + [1, 0] print(Solution().jump(nums1)) print(Solution().jump(nums2)) print(Solution().jump(nums3)) print(Solution().jump(nums4))
56ea95418a0ec5e08e1b85a87c7cd257e38754d4
liadbiz/Leetcode-Solutions
/src/python/dynamic_programming/Palindromic_string.py
1,191
4
4
""" #647 palindromic string https://leetcode.com/problems/palindromic-substrings/ Given a string, your task is to count how many palindromic substrings in this string. The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters. Example 1: Input: "abc" Output: 3 Explanation: Three palindromic strings: "a", "b", "c". Example 2: Input: "aaa" Output: 6 Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". Note: The input string length won't exceed 1000. """ class Solution: def countSubstrings(self, s: str) -> int: n = len(s) result = [[0] * n for _ in range(n)] # each char in s is a palindromic string for i in range(n): result[i][i] = 1 for i in range(n - 2, -1, -1): for j in range(n): if j - i > 2: result[i][j] = 1 if s[i] == s[j] and result[i+1][j-1] else 0 else: result[i][j] = 1 if s[i] == s[j] else 0 return sum(sum(l) for l in result) if __name__ == "__main__": s = 'abc' print(Solution().countSubstrings(s))
426bcfbcc836cd23ca4f5e00057781bf180f22e1
liadbiz/Leetcode-Solutions
/src/python/validate_binary_search_tree.py
763
4.0625
4
""" Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. source: https://leetcode.com/problems/validate-binary-search-tree/ """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isValidBST(self, root: 'TreeNode') -> 'bool': pass if __name__ == "__main__": print(Solution().isValidBST())
3d6ff3e1c81878b956d537ba48a19df178ee55a5
liadbiz/Leetcode-Solutions
/src/python/dynamic_programming/mininum_cost_for_tickets.py
2,204
4.0625
4
""" In a country popular for train travel, you have planned some train travelling one year in advance. The days of the year that you will travel is given as an array days. Each day is an integer from 1 to 365. Train tickets are sold in 3 different ways: + a 1-day pass is sold for costs[0] dollars; + a 7-day pass is sold for costs[1] dollars; + a 30-day pass is sold for costs[2] dollars. The passes allow that many days of consecutive travel. For example, if we get a 7-day pass on day 2, then we can travel for 7 days: day 2, 3, 4, 5, 6, 7, and 8. Return the minimum number of dollars you need to travel every day in the given list of days. problem source: https://leetcode.com/problems/minimum-cost-for-tickets/ """ from functools import lru_cache class Solution: # complexity: O(365) # space: O(365) # dp via days def mincostTickets(self, days: 'List[int]', costs: 'List[int]') -> 'int': days = set(days) durations = [1, 7, 30] # return the cost of traveling from day d to 365 def dp(i): if i > 365: return 0 elif i in days: return min(dp(i + d) + c for c, d in zip(costs, durations)) else: return dp(i + 1) return dp(1) # complexity: O(N) # space: O(N) # N is the length of `days` # dp via window def mincostTickets2(self, days: 'List[int]', costs: 'List[int]') -> 'int': durations = [1, 7, 30] N = len(days) def dp(i): if i >= N: return 0 res = float('inf') j = i for c, d in zip(costs, durations): while j < N and days[j] < days[i] + d: j += 1 res = min(res, c+dp(j)) return res return dp(0) if __name__ == "__main__": days =[1,4,6,7,8,20] costs = [2, 7, 15] days2 = [1,2,3,4,5,6,7,8,9,10,30,31] costs2= [2,7,15] print(Solution().mincostTickets(days, costs)) print(Solution().mincostTickets(days2, costs2)) print(Solution().mincostTickets2(days, costs)) print(Solution().mincostTickets2(days2, costs2))
498b0478db6e99d4bb321585b4c4fce7f2a9e269
liadbiz/Leetcode-Solutions
/src/python/largest_common_prefix.py
3,031
4.15625
4
""" description: Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". Example 1: Input: ["flower","flow","flight"] Output: "fl" Example 2: Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings. Note: All given inputs are in lowercase letters a-z. Issues: 1. The basic idea is: step1: find the min length of all str in the input list strs. step2: fix min_index at 0, increase max_index by 1 each iteration, check if the slice [min_index, max_index] of all In step 2, we can iterate the length from 1 to max_len. We can also iterate the length from max_len to 1. Obviously, the first one has the greatercomplexity. 2. difference between ' is not ' and ' != ': ' is not ' means the same object, ' != ' means the equal object, so we can not use ' is not ' is 'if' expression for judging if two prefix from different str are the same. see https://stackoverflow.com/questions/2209755/python-operation-vs-is-not for more information 3. ' else ' statement after ' for ' loop means: if the for loop exit normally, the code in 'else' will be excuted. """ class Solution: def longestCommonPrefix1(self, strs): """ :type strs: List[str] :rtype: str """ # handle empty list case if not strs: return "" # if not empty # step 1: find the min length of all string in list min_len = min([len(s) for s in strs]) # step2: fix min_index at 0, increase max_index by 1 each iteration, check if the slice # [min_index, max_index] of all for i in range(min_len, 0, -1): for j in range(len(strs) - 1): if strs[j][:i] != strs[j + 1][:i]: break else: return strs[0][:i] return "" def longestCommonPrefix2(self, strs): """ :type strs: List[str] :rtype: str """ # handle empty list case if not strs: return "" # if not empty # step 1: find the min length of all string in list min_len = min([len(s) for s in strs]) # step2: fix min_index at 0, increase max_index by 1 each iteration, check if the slice # [min_index, max_index] of all common_str = "" for i in range(1, min_len + 1): for j in range(len(strs) - 1): if strs[j][:i] != strs[j + 1][:i]: return strs[0][:(i - 1)] else: common_str = strs[0][:i] return common_str if __name__ == "__main__": strs1 = ["flower","flow","flight"] strs2 = ["dog","racecar","car"] # test solution1 print(Solution().longestCommonPrefix1(strs1)) print(Solution().longestCommonPrefix1(strs2)) # test solution2 print(Solution().longestCommonPrefix2(strs1)) print(Solution().longestCommonPrefix2(strs2))
36afe84aaa377106aa8a4eb6706c015a88fa7a49
liadbiz/Leetcode-Solutions
/src/python/reverse_integer.py
920
3.96875
4
""" Given a 32-bit signed integer, reverse digits of an integer. Example1: Input: 123 output: 321 Example2: Input: -123 Output: -321 Example3: Input: 120 Output: 21 Notes: what if the result overflow? what have learned: 1. in python 2, we can use cmp() function to get sign of the difference of two number a and b, in python 3, we can use (a > b) - (a < b) 2. str() function: int number to string """ class Solution: def reverse1(self, x): """ :type x: int :rtype: int """ if x < 0; return -self.reverse1(-x) result = 0 while x: result = result * 10 + x % 10 x //= 10 return result if result < 2 ** 31 else 0 def reverse2(self, x): """ :type x: int :rtype: int """ s = (x > 0) - (0 < x) r = int(str(s * x)[::-1]) return s * r * (r < 2**31)
6aac68ffc80dba1f5c76492a7dc37016f632556d
liadbiz/Leetcode-Solutions
/src/python/power_of_four.py
963
4
4
""" Given an integer (signed 32 bits), write a function to check whether it is a power of 4. Example 1: Input: 16 Output: true Example 2: Input: 5 Output: false Follow up: Could you solve it without loops/recursion? """ class Solution: def isPowerOfFour(self, num): """ :type num: int :rtype: bool """ if num < 0: return False mask = 1 while mask < num: mask <<= 2 return True if mask & num else False def isPowerOfFour2(self, num): """ :type num: int :rtype: bool """ return True if num > 0 and not num & (num - 1) and num & 0x55555555 else False if __name__ == "__main__": print(Solution().isPowerOfFour(1)) print(Solution().isPowerOfFour(16)) print(Solution().isPowerOfFour(218)) print(Solution().isPowerOfFour2(1)) print(Solution().isPowerOfFour2(16)) print(Solution().isPowerOfFour2(218))
8cab006e87d608bdce1899e00044e13f8f09c3f2
liadbiz/Leetcode-Solutions
/src/python/minimum_moves2.py
990
4.03125
4
""" Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, where a move is incrementing a selected element by 1 or decrementing a selected element by 1. You may assume the array's length is at most 10,000. Example: Input: [1,2,3] Output: 2 Explanation: Only two moves are needed (remember each move increments or decrements one element): [1,2,3] => [2,2,3] => [2,2,2] Idea: The minimum moves only occur when all the element moves to the median. """ class Solution: def minMoves2(self, nums): """ :type nums: List[int] :rtype: int """ nums.sort() return sum(nums[~i] - nums[i] for i in range(len(nums) // 2)) # solution2, same idea. """ median = sorted(nums)[len(nums) / 2] return sum(abs(num - median) for num in nums) """ if __name__ == "__main__": case1 = [1, 2, 3] print(Solution().minMoves2(case1))
26715c6de77437da8a9084c3aea2db86910a527d
liadbiz/Leetcode-Solutions
/src/python/greedy_algorithm/split_array_into_consecutive_subsequences.py
2,647
4.09375
4
""" You are given an integer array sorted in ascending order (may contain duplicates), you need to split them into several subsequences, where each subsequences consist of at least 3 consecutive integers. Return whether you can make such a split. Example 1: Input: [1,2,3,3,4,5] Output: True Explanation: You can split them into two consecutive subsequences : 1, 2, 3 3, 4, 5 Example 2: Input: [1,2,3,3,4,4,5,5] Output: True Explanation: You can split them into two consecutive subsequences : 1, 2, 3, 4, 5 3, 4, 5 Example 3: Input: [1,2,3,4,4,5] Output: False Note: The length of the input is in range of [1, 10000] """ class Solution: # 思路:第一个函数是我一开始的想法,遍历nums中的元素,然后如果不能添加到之前 # 出现的连续序列的话,就算作是重新调整开始一个连续序列,如果能的话,添加到 # 最近的一个序列(长度最短),但是复杂度比较高,所以不能AC(超时) def isPossible1(self, nums): """ :type nums: List[int] :rtype: bool """ import collections dq = collections.deque() for n in nums: for i in reversed(dq): if i[1] == n - 1: i[1] += 1 break else: dq.append([n, n]) print(dq) return all(True if p[1] - p[0] >= 2 else False for p in dq ) # 这个方法复杂度就小很多,O(n)。 # 因为其实保留具体的连续子序列的信息是没有必要的,上一个函数之所以会超时, # 就是因为保留了无用信息。而该方法很好的解决了这个问题 # 来自: https://leetcode.com/problems/split-array-into-consecutive- # subsequences/discuss/106514/Python-esay-understand-solution def isPossible2(self, nums): """ :type nums: List[int] :rtype: bool """ import collections left = collections.Counter(nums) end = collections.Counter() for i in nums: if not left[i]: continue left[i] -= 1 if end[i - 1] > 0: end[i - 1] -= 1 end[i] += 1 elif left[i + 1] and left[i + 2]: left[i + 1] -= 1 left[i + 2] -= 1 end[i + 2] += 1 else: return False return True if __name__ == '__main__': nums1 = [1, 2, 3, 4, 5] nums2 = [1,2,3,3,4,4,5,5] nums3 = [1,2,3,4,4,5] print(Solution().isPossible(nums1)) print(Solution().isPossible(nums2)) print(Solution().isPossible(nums3))
49ebb1d0c3806b92ab6c158447171ceca908da42
liadbiz/Leetcode-Solutions
/src/python/greedy_algorithm/course_schedule_3.py
2,124
3.859375
4
""" There are n different online courses numbered from 1 to n. Each course has some duration(course length) t and closed on dth day. A course should be taken continuously for t days and must be finished before or on the dth day. You will start at the 1st day. Given n online courses represented by pairs (t,d), your task is to find the maximal number of courses that can be taken. Example: Input: [[100, 200], [200, 1300], [1000, 1250], [2000, 3200]] Output: 3 Explanation: There're totally 4 courses, but you can take 3 courses at most: First, take the 1st course, it costs 100 days so you will finish it on the 100th day, and ready to take the next course on the 101st day. Second, take the 3rd course, it costs 1000 days so you will finish it on the 1100th day, and ready to take the next course on the 1101st day. Third, take the 2nd course, it costs 200 days so you will finish it on the 1300th day. The 4th course cannot be taken now, since you will finish it on the 3300th day, which exceeds the closed date. Note: The integer 1 <= d, t, n <= 10,000. You can't take two courses simultaneously. """ class Solution: # 思路:按照结束时间排序,依次遍历courses,维护一个变量start,表示当前学习的课程 # 花费的总时间,也是下一个课程的开始时间,如果不能学习当前遍历课程,说明之前某个 # 课程花费时间太长了,因此去掉该课程,进而学习当前遍历课程,这样只会让start变小 # 因此不会降低课程安排的最优性。这也证明了贪心法能得到最优解。 def scheduleCourse(self, courses): """ :type courses: List[List[int]] :rtype: int """ import heapq courses.sort(key=lambda x:x[1]) hq = [] start = 0 for t, e in courses: start += t heapq.heappush(hq, -t) while start > e: start += heapq.heappop(hq) return len(hq) if __name__ == "__main__": courses = [[100, 200], [200, 1300], [1000, 1250], [2000, 3200]] print(Solution().scheduleCourse(courses))
893104e3a4ade89aa31e82a18df0695a040fbd9e
liadbiz/Leetcode-Solutions
/src/python/range_sum_query.py
771
3.71875
4
""" # 303 Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. Example: Given nums = [-2, 0, 3, -5, 2, -1] sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3 Note: You may assume that the array does not change. There are many calls to sumRange function. Accepted 128,904 Submissions 350,101 source: https://leetcode.com/problems/range-sum-query-immutable/ """ class NumArray: def __init__(self, nums: List[int]): self.nums = nums self.cache = dict() def sumRange(self, i: int, j: int) -> int: if not self.cache.get((i,j)): result = sum(self.nums[i:j+1]) self.cache[(i, j)] = result return result return self.cache[(i,j)]
be8da5d6998ab0d7cde8a800612dbabe81830c77
liadbiz/Leetcode-Solutions
/src/python/onebit_twobit.py
2,948
4.03125
4
""" 717. 1-bit and 2-bit Characters We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11). Now given a string represented by several bits. Return whether the last character must be a one-bit character or not. The given string will always end with a zero. Example 1: Input: bits = [1, 0, 0] Output: True Explanation: The only way to decode it is two-bit character and one-bit character. So the last character is one-bit character. Example 2: Input: bits = [1, 1, 1, 0] Output: False Explanation: The only way to decode it is two-bit character and two-bit character. So the last character is NOT one-bit character. Note: 1 <= len(bits) <= 1000. bits[i] is always 0 or 1. Idea: + My thought: Iterate the `bits`, and check each two element pair, if the the pair equals to [1, 1] or [1, 0], increase `index` to `index + 2`, else `index + 1`. Stop the iteration if the index reach to `len(bits) - 2` or `len(bits) - 1`. If the `index` equals to the former, return False, and return True if it equals to the latter. + Increament pointer: When reading from the i-th position, if bits[i] == 0, the next character must have 1 bit; else if bits[i] == 1, the next character must have 2 bits. We increment our read-pointer i to the start of the next character appropriately. At the end, if our pointer is at bits.length - 1, then the last character must have a size of 1 bit. + Greedy The second-last 0 must be the end of a character (or, the beginning of the array if it doesn't exist). Looking from that position forward, the array bits takes the form [1, 1, ..., 1, 0] where there are zero or more 1's present in total. It is easy to show that the answer is true if and only if there are an even number of ones present. """ class Solution: def isOneBitCharacter(self, bits): """ :type bits: List[int] :rtype: bool """ index = 0 l = len(bits) while index < l - 2: b = bits[index: (index + 2)] if b == [1, 0] or b == [1, 1]: index += 2 elif b == [0, 1] or b == [0, 0]: index += 1 print(index) return False if index == l - 2 else True def isOneBitCharacter2(self, bits): i = 0 while i < len(bits) - 1: i += bits[i] + 1 return i == len(bits) - 1 def isOneBitCharacter3(self, bits): parity = bits.pop() while bits and bits.pop(): parity ^= 1 return parity == 0 if __name__ == "__main__": case1 = [1, 0, 0] case2 = [1, 1, 1, 0] case3 = [0, 1, 0] print(Solution().isOneBitCharacter(case1)) print(Solution().isOneBitCharacter(case2)) print(Solution().isOneBitCharacter(case3))
04d56f4cfc176ede74a148b901dad5120b4b1270
Calico888/First-Steps---Quiz
/quiz 2.py
6,549
4.25
4
# Strings for the different difficulties easy_string = """I have a __1__ that one day this __2__ will rise up, and live out the true meaning of its creed: We hold these truths to be self-evident: that all men are created equal. Martin Luther King jr The greatest __3__ in living lies not in never falling, but in __4__ every time we fall. Nelson Mandela That is one small __5__ for a man, one giant leap for __6__. Neil Armstrong""" answer_list1 = ["dream", "nation", "glory", "rising", "step", "mankind" ] medium_string = """Do not __1__ the chickens before they are __2__. An eye for an __3__, a tooth for a __4__. Accept that some days you are the __5__, and some days you are the __6__.""" answer_list2 = ["count", "hatched", "eye", "tooth", "pigeon", "statue"] hard_string = """Judge your __1__ by what you had to give up in __2__ to get it. Dalai Lama In the end, it is not the __3__ in your life that count. It is the __4__ in your years. Abraham Lincoln Be the __5__ that you wish to see in the __6__ Mahatma Gandhi""" answer_list3 = ["success", "order", "years", "life", "change", "world"] def string_to_difficulty(difficulty): """ The method gets the difficulty as a string and returns the string, which belongs to the choosen difficulty and return and print it. parameters: input is the difficulty as a string. return: Is the string which belongs to difficulty. """ if difficulty == "easy": print easy_string return easy_string elif difficulty == "medium": print medium return medium_string else: print hard_string return hard_string def answer_list_to_difficulty(difficulty): """ The method gets the difficulty as string and returns the answers, which are strings and they are stored in a list parameters: input is the difficulty as a string return: the strings in a list. """ if difficulty == "easy": return answer_list1 elif difficulty == "medium": return answer_list2 else: return answer_list3 def difficulty(): """ The method has no input, the user is asked to choose the difficulty, also there is a check a while loop to make sure that the user chooses a difficulty, which is available. parameters: User input which is stored as string. return: the difficulty as a string """ difficult_grade = raw_input("Please enter your difficulty: easy, medium, hard: ") if difficult_grade == "easy" or difficult_grade == "medium" or difficult_grade == "hard": return difficult_grade while difficult_grade != "easy" or difficult_grade != "medium" or difficult_grade != "hard": difficult_grade = raw_input("Invalid Input, please enter easy, medium or hard: ") return difficult_grade def find_the_gaps(number, text_with_gaps): """ The method gets the number,as a int, which shows the gaps which we currently searching for. Also the method gets the text as a string. Then the methode is searching in the text for the number, which is transformed into a string, with a for loop. And if the number is found, the part of the text is returned. parameters: input is a number as int and the text as a string. return: None, when the number isn't found or the part of the text with the number in it as a string. """ number = str(number) for pos in text_with_gaps: if number in pos : return pos return None def answer_is_right(quiz_string, replacement, controll_answer): """ The method gets three inputs: the text as List with strings in it, replacement, which is a string and the right answer as string. First the text is transformed into a string and after that the replacement is replaced through the right answer. After that the the new text is printed. The next is to transform the string into a list again and return it. parameters: quiz string as list filled with strings, replacement is a string and the controll answer is a string,too. return: text with the right answer in it as list. """ quiz_string = " ".join(quiz_string) quiz_string = quiz_string.replace(replacement, controll_answer) print quiz_string quiz_string = quiz_string.split() return quiz_string def play_the_game(difficulty): """ The input for this method is the difficulty as a string. First the answer and the text as a string, which are belonging to the difficulty is defined to the methods string_to_difficulty and answer_list_to_difficulty. After that, there is a for loop which is going through the answer list to make sure every gap is filled. In the next step the the method find_the_gaps is used to find the gap which belongs to the actual number. Then the user has to fill in the first gap. if the answer is wrong, a while starts until the user entered the right answer or the countdown has reached 0. The method answer_is_right starts then. When every gap is filled the method returns a string. parameters: input is difficulty as string, in the method number as a int is used to show on which gap is searched for at the moment return: string when the quiz is solved or the countdown has reached 0. """ quiz_string = string_to_difficulty(difficulty) quiz_string = quiz_string.split() answer_list = answer_list_to_difficulty(difficulty) number = 1 countdown = 3 for element in answer_list: replacement = find_the_gaps(number,quiz_string) if replacement != None: user_answer = raw_input("Please enter your answer: ") if user_answer.lower() == answer_list[number - 1].lower(): quiz_string = answer_is_right(quiz_string, replacement, answer_list[number - 1]) number += 1 else: while user_answer.lower() != answer_list[number - 1].lower() or countdown > 0: user_answer = raw_input("Try again! You have " +str(countdown)+ " more tries: ") countdown = countdown - 1 if countdown == 0: return "Game Over" if user_answer.lower() == answer_list[number - 1].lower(): quiz_string = answer_is_right(quiz_string, replacement, answer_list[number - 1]) number += 1 break return "You win! Quiz solved!" print play_the_game(difficulty())
a060b33270c6c736e397f22f81ebab6f68b1a4e8
arcae/git_lesson-1
/data/portcsv.py
626
3.671875
4
#using csv module import csv def portfolio_cost(filename): ''' Computes total shares*proce for a CSV file with name,shares,price data' ''' total = 0.0 with open(filename,'r') as f: rows = csv.reader(f) headers = next(rows) #skip first row for headers for rowno, row in enumerate(rows,start=1): try: row[2] = int(row[2]) row[3] = float(row[3]) except ValueError as err: print('Row:',rowno, 'Bad row:',row) print('Row:',rowno, 'Reason:', err) continue #skip to the next row total += row[2]*row[3] return total total = portfolio_cost('Mydata1.csv') print('Total cost:', total)
a849d96ef408d998a3ec1b17ce74d6b02f7992ad
saurabhc123/unsupervised
/source/Ops.py
630
4.09375
4
from abc import ABC, abstractmethod class Ops(ABC): def __init__(self, name): self.name = name pass @abstractmethod def perform_op(self): print ("Performing op:" , self.name) pass class Addition(Ops): def __init__(self, name="Addition"): Ops.__init__(self, name) def perform_op(self): Ops.perform_op(self) print ("Performed op:"+ self.name) class Subtraction(Ops): def __init__(self, name="Subtraction"): Ops.__init__(self, name) def perform_op(self): print ("Performed op:"+ self.name) op = Addition() op.perform_op()
9516c757ff8eacaff3edb929e59fc7032610f4f1
QuinPoley/ChessGame
/pieces.py
8,000
3.703125
4
class Piece: def __init__(self, color, letter, number): self.position = letter, number self.letter = letter self.number = number self.color = color self.hasMoved = False def returnLegalMoves(): return None def move(self, letter, number): firstmove = False if(not self.hasMoved): self.hasMoved = True firstmove = True self.letter = letter self.number = number return firstmove def returnHasMoved(self): return self.hasMoved class Pawn(Piece): def __init__(self, color, letter, number): super().__init__(color, letter, number) self.value = 1 def returnLegalMoves(self): legalmoves = [] if (self.color == "white"): #it can only move up that column, or capture in adjacent columns. legalmoves.append((self.letter, (self.number+1))) legalmoves.append(((self.letter+1), (self.number+1))) legalmoves.append(((self.letter-1), (self.number+1))) if(self.hasMoved == False): legalmoves.append((self.letter, (self.number+2))) else: legalmoves.append((self.letter, (self.number-1))) legalmoves.append(((self.letter+1), (self.number-1))) legalmoves.append(((self.letter-1), (self.number-1))) if(self.hasMoved == False): legalmoves.append((self.letter, (self.number-2))) return legalmoves # Giving all possible moves now, if piece can capture we check for that later def __str__(self): return self.color + " pawn @ " + chr(96+self.letter) +","+ self.number.__str__() # 96 Because the letter a is 97, and letter is 1 indexed class King(Piece): def __init__(self, color, letter, number): super().__init__(color, letter, number) self.value = 100 def returnLegalMoves(self): legalmoves = [] #it doesnt matter if we include moves off board because the only clicks registered are on the board if(self.letter > 1): legalmoves.append(((self.letter-1), self.number)) if(self.number > 1): legalmoves.append(((self.letter-1), (self.number-1))) if(self.number < 8): legalmoves.append(((self.letter-1), (self.number+1))) if(self.letter < 8): legalmoves.append(((self.letter+1), self.number)) if(self.number > 1): legalmoves.append(((self.letter+1), (self.number-1))) if(self.number < 8): legalmoves.append(((self.letter+1), (self.number+1))) if(self.number > 1): legalmoves.append((self.letter, (self.number-1))) if(self.number < 8): legalmoves.append((self.letter, (self.number+1))) if(self.hasMoved == False): legalmoves.append(((self.letter+2), self.number)) # Castle legalmoves.append(((self.letter-2), self.number)) return legalmoves def __str__(self): return self.color + " King @ " + chr(96+self.letter) +","+ self.number.__str__() class Queen(Piece): def __init__(self, color, letter, number): super().__init__(color, letter, number) self.value = 10 def returnLegalMoves(self): legalmoves = [] howFar = 9-self.letter if 9-self.letter < 9-self.number else 9-self.number #9? for x in range(1, howFar): legalmoves.append(((self.letter+x), (self.number+x)))# Diag Fwd Right howFar = self.letter if self.letter < 9-self.number else 9-self.number for x in range(1, howFar): legalmoves.append(((self.letter-x), (self.number+x)))# Diag Fwd Left howFar = 9-self.letter if 9-self.letter < self.number else self.number for x in range(1, howFar): legalmoves.append(((self.letter+x), (self.number-x)))# Diag Back Right howFar = self.letter if self.letter < self.number else self.number for x in range(1, howFar): legalmoves.append(((self.letter-x), (self.number-x)))# Diag Back Left for x in range((self.letter+1), 9): legalmoves.append((x, self.number)) for x in range(1, self.letter): legalmoves.append((x, self.number)) for x in range((self.number+1), 9): legalmoves.append((self.letter, x)) for x in range(1, self.number): legalmoves.append((self.letter, x)) return legalmoves def __str__(self): return self.color + " Queen @ " + chr(96+self.letter) +","+ self.number.__str__() class Bishop(Piece): def __init__(self, color, letter, number): super().__init__(color, letter, number) self.value = 3 def returnLegalMoves(self): legalmoves = [] howFar = 9-self.letter if 9-self.letter < 9-self.number else 9-self.number #9? for x in range(1, howFar): legalmoves.append(((self.letter+x), (self.number+x)))# Diag Fwd Right howFar = self.letter if self.letter < 9-self.number else 9-self.number for x in range(1, howFar): legalmoves.append(((self.letter-x), (self.number+x)))# Diag Fwd Left howFar = 9-self.letter if 9-self.letter < self.number else self.number for x in range(1, howFar): legalmoves.append(((self.letter+x), (self.number-x)))# Diag Back Right howFar = self.letter if self.letter < self.number else self.number for x in range(1, howFar): legalmoves.append(((self.letter-x), (self.number-x)))# Diag Back Left return legalmoves def __str__(self): return self.color + " Bishop @ " + chr(96+self.letter) +","+ self.number.__str__() class Knight(Piece): def __init__(self, color, letter, number): super().__init__(color, letter, number) self.value = 3 def returnLegalMoves(self): legalmoves = [] # This one is trickiest, +1 and the other is +2 if(self.letter > 1): if(self.number < 7): legalmoves.append(((self.letter-1), (self.number+2))) if(self.number > 2): legalmoves.append(((self.letter-1), (self.number-2))) if(self.letter < 8): if(self.number < 7): legalmoves.append(((self.letter+1), (self.number+2))) if(self.number > 2): legalmoves.append(((self.letter+1), (self.number-2))) if(self.letter < 7): if(self.number > 1): legalmoves.append(((self.letter+2), (self.number-1))) if(self.number < 8): legalmoves.append(((self.letter+2), (self.number+1))) if(self.letter > 2): if(self.number < 8): legalmoves.append(((self.letter-2), (self.number+1))) if(self.number > 1): legalmoves.append(((self.letter-2), (self.number-1))) return legalmoves def __str__(self): return self.color + "Knight @" + chr(96+self.letter) +","+ self.number.__str__() class Rook(Piece): def __init__(self, color, letter, number): super().__init__(color, letter, number) self.value = 5 def returnLegalMoves(self): legalmoves = [] for x in range((self.letter+1), 9): legalmoves.append((x, self.number)) for x in range(1, self.letter): legalmoves.append((x, self.number)) for x in range((self.number+1), 9): legalmoves.append((self.letter, x)) for x in range(1, self.number): legalmoves.append((self.letter, x)) return legalmoves def __str__(self): return self.color + "Rook @" + chr(96+self.letter) +","+ self.number.__str__()
8e03751fb6c7e483d09dec12e3606bef9a443189
jtbarker/pyocto-wordcounter
/countwordfreq.py
690
4.0625
4
#! /usr/bin/python """ this program breaks a string into a list of component words and counts each word, by Jon Barker, 2014-1-7""" # import matplotlib # import os # print(dir(matplotlib)) def main(): print "input a sentence and i will count the words for you" sentence = str(input("your sentence: ")) main() # def wordcount(x): # global a # a = x.split(" ") # if __name__ == "__main__": # main() # tester = "i am a an awesome person hello thanks hello goodbye" # def wordcount(x): # global a # a = x.split(" ") # return a # wordcount(tester) # lis = [] # for i in range(1,len(a)): # if j in a == i: # for c in tester: # lis.append(c)
d052bdd3529c7c444cbec14bc1fe3ce1ae5b6093
shaikafiya/pythonprogramming
/pangram.py
141
3.734375
4
s=input() n=[] for i in s: if(i not in n): n.append(i) if(len(n)==27 or len(n)==28): print("yes") else: print("no")
88f49fdde71ecb4ffcdbe49a889e058190d0feb9
shaikafiya/pythonprogramming
/even num between two intervals.py
101
3.515625
4
n,m=input().split() n=int(n) m=int(m) for k in range(n+1,m): if(k%2==0): print(k,end=" ")
359d0387e3684f13ae34726654419d169fb22efb
frankc95/exercise
/workbook_01.py
140
3.796875
4
weight_lbs = input('Weight (lbs): ') weight_kg = int(weight_lbs) * 0.45 txt = "your weight in kilograms is " print (txt + str(weight_kg))
0194f671da5971a2f30a4df885e6318312f6c172
jeremysinger/python-forloop-parser
/tests/test3.py
277
4
4
for i in range(0,10): for j in range(0,i): for k in range(i,j): print(i,j) for a in range(5): for b in range(2): print('foo') for x in range(a): for y in range(a-1): for z in range(y): print('bar')
f9b68289368ca68d3bc557f7e11261c9d8683c79
mikyqwe/python.py
/firstday.py
483
4.09375
4
"""Write a script that writes the day of the week for the New Year Day, for the last x years (x is given as argument).""" import time saptamana=["Luni","Marti","Miercuri","Joi","Vineri","Sambata","Duminica"] def f(x): date="01-01" for i in range(1,x+1): currentYear=2020+1-i currentdate=date+"-"+str(currentYear) formatedate=time.strptime(currentdate,"%m-%d-%Y") print("Pentru anul {} prima zi a saptamanii este {}".format(currentYear,saptamana[formatedate.tm_wday])) f(5)
057a72a1e97177d2266389973837f9edf8b67806
deepalikushwaha18/SDET-Training-Python
/Activity2.py
160
4.1875
4
num=int(input("enter number:")) mod = num % 2 if mod > 0: print("You picked an odd number.") else: print("You picked an even number.")
5945cce076d47a3dc3f23ed6dad61a3153ae4721
MarcPartensky/Python-Games
/Game Structure/geometry/version4/myrect.py
7,466
4
4
class Rect: """Define a pure and simple rectangle.""" def createFromCorners(corners): """Create a rectangle.""" coordonnates=Rect.getCoordonnatesFromCorners(corners) #print("c:",coordonnates) return Rect(coordonnates[:2],coordonnates[2:]) def createFromRect(rect): """Create a rect from a pygame rect.""" coordonnates=Rect.getCoordonnatesFromRect(rect) return Rect(coordonnates[:2],coordonnates[2:]) def createFromCoordonnates(coordonnates): """Create a rect using the coordonnates.""" return Rect(coordonnates[:2],coordonnates[2:]) def __init__(self,position,size): """Create a rectangle.""" self.position=position self.size=size def getCorners(self): """Return the corners of the case.""" px,py=self.position sx,sy=self.size return (px-sx/2,py-sy/2,px+sx/2,py+sy/2) def setCorners(self): """Set the corners of the case.""" coordonnates=self.getCoordonnatesFromCorners(corners) self.position=coordonnates[:2] self.size=coordonnates[2:] def __contains__(self,position): """Determine if a position is in the rectangle.""" x,y=position return (self.xmin<=x<=self.xmax) and (self.ymin<=y<=self.ymax) def getCoordonnates(self): """Return the coordonnates ofthe rectangle.""" return self.position+self.size def setCoordonnates(self,coordonnates): """Set the coordonnates of the rectangle.""" self.position=coordonnates[:2] self.size=coordonnates[2:] def getRect(self): """Return the rect of the rectangle.""" return Rectangle.getRectFromCoordonnates(self.getCoordonnates) def setRect(self,rect): """Set the rect of the rectangle.""" self.setCoordonnates(Rectangle.getCoordonnatesFromRect(rect)) def getCenter(self): """Return the center of the rectangle.""" return self.position def setCenter(self,centers): """Set the center of the rectangle.""" self.position=center def getX(self): """Return the x component.""" return self.position[0] def setX(self,x): """Set the x component.""" self.position[0]=x def getY(self): """Return the y component.""" return self.position[1] def setY(self,y): """Set the y component.""" self.position[1]=y def getSx(self): """Return the size of the x component.""" return self.size[0] def setSx(self,sx): """Set the size of the x component.""" self.size[0]=sx def getSy(self): """Return the size of the y component.""" return self.size[1] def setSy(self,sy): """Set the size of the y component.""" self.size[1]=sy def getXmin(self): """Return the minimum of the x component.""" return self.position[0]-self.size[0]/2 def setXmin(self,xmin): """Set the minimum of the x component.""" self.position[0]=xmin+self.size[0]/2 def getYmin(self): """Return the minimum of the y component.""" return self.position[1]-self.size[1]/2 def setYmin(self,ymin): """Set the minimum of the y component.""" self.position[1]=ymin+self.size[1]/2 def getXmax(self): """Return the maximum of the x component.""" return self.position[0]+self.size[0]/2 def setXmax(self,xmax): """Set the maximum of the x component.""" self.position[0]=xmax-self.size[0]/2 def getYmax(self): """Return the maximum of the y component.""" return self.position[1]+self.size[1]/2 def setYmax(self,ymax): """Set the maximum of the y component.""" self.position[1]=ymax-self.size[1]/2 corners=property(getCorners,setCorners,"Allow the user to manipulate the corners as an attribute for simplicity.") rect=property(getRect,setRect,"Allow the user to manipulate the rect of the rectangle easily.") coordonnates=property(getCoordonnates,setCoordonnates,"Allow the user to manipulate the coordonnates of the rectangle easily for simplicity.") x=property(getX,setX,"Allow the user to manipulate the x component easily.") y=property(getY,setY,"Allow the user to manipulate the y component easily.") sx=property(getSx,setSx,"Allow the user to manipulate the size in x component easily.") sy=property(getSy,setSy,"Allow the user to manipulate the size in y component easily.") xmin=property(getXmin,setXmin,"Allow the user to manipulate the minimum of x component easily.") xmax=property(getXmax,setXmax,"Allow the user to manipulate the maximum of x component easily.") ymin=property(getYmin,setYmin,"Allow the user to manipulate the minimum of y component easily.") ymax=property(getYmax,setYmax,"Allow the user to manipulate the maximum of y component easily.") def getCornersFromCoordonnates(coordonnates): """Return the corners (top_left_corner,bottom_right_corner) using the coordonnates (position+size).""" """[x,y,sx,sy] -> [mx,my,Mx,My]""" x,y,sx,sy=coordonnates mx,my=x-sx/2,y-sy/2 Mx,My=x+sx/2,y+sy/2 corners=(mx,my,Mx,My) return corners def getCoordonnatesFromCorners(corners): """Return the coordonnates (position+size) using the corners (top_left_corner,bottom_right_corner).""" """[mx,my,Mx,My] -> [x,y,sx,sy]""" mx,my,Mx,My=corners sx,sy=Mx-mx,My-my x,y=mx+sx/2,my+sy/2 coordonnates=(x,y,sx,sy) return coordonnates def getCoordonnatesFromRect(rect): """Return the coordonnates (position,size) using the rect (top_left_corner,size).""" """[x,y,sx,sy] -> [mx,my,sx,sy]""" mx,my,sx,sy=rect x,y=mx+sx/2,my+sy/2 coordonnates=[x,y,sx,sy] return coordonnates def getRectFromCoordonnates(coordonnates): """Return the rect (top_left_corner,size) using the coordonnates (position,size).""" """[mx,my,sx,sy] -> [x,y,sx,sy]""" x,y,sx,sy=coordonnates mx,my=x-sx/2,y-sy/2 rect=[mx,my,sx,sy] return rect def getRectFromCorners(corners): """Return the rect (top_left_corner,size) using the corners (top_left_corner,bottom_right_corner).""" """[mx,my,Mx,My] -> [mx,my,sx,sy]""" mx,my,Mx,My=corners sx,sy=Mx-mx,My-my rect=[mx,my,sx,sy] return rect def getCornersFromRect(rect): """Return the (top_left_corner,bottom_right_corner) using the corners rect (top_left_corner,size).""" """[mx,my,Mx,My] -> [mx,my,sx,sy]""" mx,my,sx,sy=rect Mx,My=mx+sx,my+sy corners=[mx,my,Mx,My] return corners def crossRect(self,other): """Determine the rectangle resulting of the intersection of two rectangles.""" if self.xmax<other.xmin or self.xmin>other.xmax: return if self.ymax<other.ymin or self.ymin>other.ymax: return xmin=max(self.xmin,other.xmin) ymin=max(self.ymin,other.ymin) xmax=min(self.xmax,other.xmax) ymax=min(self.ymax,other.ymax) #print([xmin,ymin,xmax,ymax]) return Rect.createFromCorners([xmin,ymin,xmax,ymax]) def resize(self,n=1): """Allow the user to resize the rectangle.""" for i in range(2): self.size[i]*=n
e9432b4362be20638c2d72af1fb3a37f3e67c889
MarcPartensky/Python-Games
/Game Structure/geometry/version5/mysyracuse.py
1,528
3.53125
4
from myabstract import Point,Segment class Branch: def __init__(self,n=1,g=0): """Create a branch.""" self.n=n self.g=g def children(self): """Return the childen branches of the branch.""" children=[Branch(self.n*2,self.g+1)] a=(self.n-1)//3 if a%2==1: children.append(Branch(a,self.g+1)) return children def show(self,surface): """Show the branch to the surface.""" p=self.point() for c in self.children(): pc=c.point() s=Segment(p,pc) s.show(surface) def point(self): """Return the point associated to the branch.""" return Point(self.n,self.g) class Tree: """Syracuse tree.""" def __init__(self,limit=10): """Create a syracuse tree.""" self.branches=[] self.limit=limit def __call__(self,branch=Branch()): """Calculate the branches recursively.""" if branch.g<self.limit: for c in branch.children(): self.branches.append(c) self(c) def show(self,surface): """Show the tree on the surface.""" for branch in self.branches: branch.show(surface) if __name__=="__main__": from mysurface import Surface surface=Surface() tree=Tree() tree() while surface.open: surface.check() surface.control() surface.clear() surface.show() tree.show(surface) surface.flip()
4a25f75e797b7ca5915b7c8689482a6f329a8af1
MarcPartensky/Python-Games
/Game Structure/geometry/version3/mypoint.py
6,376
4.09375
4
from math import pi,sqrt,atan,cos,sin import random mean=lambda x:sum(x)/len(x) import mycolors class Point: def random(min=-1,max=1,radius=0.1,fill=False,color=mycolors.WHITE): """Create a random point using optional minimum and maximum.""" x=random.uniform(min,max) y=random.uniform(min,max) return Point(x,y,radius=radius,fill=fill,color=color) def turnPoints(angles,points): """Turn the points around themselves.""" l=len(points) for i in range(l-1): points[i].turn(angles[i],points[i+1:]) def showPoints(surface,points): """Show the points on the surface.""" for point in points: point.show(surface) def __init__(self,*args,mode=0,size=[0.1,0.1],width=1,radius=0.1,fill=False,color=mycolors.WHITE): """Create a point using x, y, radius, fill and color.""" args=list(args) if len(args)==1: args=args[0] if type(args)==list or type(args)==tuple: self.x=args[0] self.y=args[1] else: raise Exception("The object used to define the point has not been recognised.") elif len(args)==2: if (type(args[0])==int and type(args[1])==int) or (type(args[0]==float) and type(args[1])==float): self.x=args[0] self.y=args[1] else: raise Exception("The list of objects used to define the point has not been recognised.") else: raise Exception("The list object used to define the point has not been recognised because it contains too many components.") self.mode=mode self.size=size self.width=width self.radius=radius self.fill=fill self.color=color def __call__(self): """Return the coordonnates of the points.""" return [self.x,self.y] def __position__(self): """Return the coordonnates of the points.""" return [self.x,self.y] def __contains__(self,other): """Return bool if objects is in point.""" ox,oy=other[0],other[1] if self.radius>=sqrt((ox-self.x)**2+(oy-self.y)**2): return True else: return False def __getitem__(self,index): """Return x or y value using given index.""" if index==0: return self.x if index==1: return self.y def __setitem__(self,index,value): """Change x or y value using given index and value.""" if index==0: self.x=value if index==1: self.y=value def rotate(self,angle=pi,point=[0,0]): """Rotate the point using the angle and the center of rotation. Uses the origin for the center of rotation by default.""" v=Vector(self.x-point[0],self.y-point[1]) v.rotate(angle) new_point=v(point) self.x,self.y=new_point def turn(self,angle=pi,points=[]): """Turn the points around itself.""" for point in points: point.rotate(angle,self) def move(self,*step): """Move the point using given step.""" self.x+=step[0] self.y+=step[1] def showCross(self,window,color=None,size=None,width=None): """Show the point under the form of a cross using the window.""" if not color: color=self.color if not size: size=self.size if not width: width=self.width x,y=self sx,sy=size xmin=x-sx/2 ymin=y-sy/2 xmax=x+sx/2 ymax=y+sy/2 window.draw.line(window.screen,color,[xmin,ymin],[xmax,ymax],width) window.draw.line(window.screen,color,[xmin,ymax],[xmax,ymin],width) def showCircle(self,window,color=None,radius=None,fill=None): """Show a point under the form of a circle using the window.""" if not color: color=self.color if not radius: radius=self.radius if not fill: fill=self.fill window.draw.circle(window.screen,color,[self.x,self.y],radius,not(fill)) def show(self,window,mode=None,color=None,size=None,width=None,radius=None,fill=None): """Show the point on the window.""" if not mode: mode=self.mode if mode==0 or mode=="circle": self.showCircle(window,color=color,radius=radius,fill=fill) if mode==1 or mode=="cross": self.showCross(window,color=color,size=size,width=width) def showText(self,window,text,size=20,color=mycolors.WHITE): """Show the name of the point on the window.""" window.print(text,self,size=size,color=color) def __add__(self,other): """Add the components of 2 objects.""" return Point(self.x+other[0],self.y+other[1]) def __sub__(self,other): """Substract the components of 2 objects.""" return Point(self.x-other[0],self.y-other[1]) def __iter__(self): """Iterate the points of the form.""" self.iterator=0 return self def __next__(self): """Return the next point threw an iteration.""" if self.iterator < 2: if self.iterator==0: value=self.x if self.iterator==1: value=self.y self.iterator+=1 return value else: raise StopIteration def truncate(self): """Truncate the position of the point by making the x and y components integers.""" self.x=int(self.x) self.y=int(self.y) def __str__(self): """Return the string representation of a point.""" return "Point:"+str(self.__dict__) if __name__=="__main__": from mysurface import Surface from myvector import Vector surface=Surface(fullscreen=True) p1=Point(0,0,color=mycolors.RED,fill=True) p2=Point(5,0,color=mycolors.GREEN,fill=True) p3=Point(10,0,color=mycolors.BLUE,fill=True) p4=Point(15,0,color=mycolors.YELLOW,fill=True) p5=Point(20,0,color=mycolors.ORANGE,fill=True) points=[p1,p2,p3,p4,p5] points=[Point(5*i,0,radius=0.2) for i in range(10)] angles=[i/1000 for i in range(1,len(points))] while surface.open: surface.check() surface.control() surface.clear() surface.show() Point.turnPoints(angles,points) Point.showPoints(surface,points) surface.flip()
7c3ba27c237a61201655c18fd2520838b5215778
MarcPartensky/Python-Games
/Mandelbrot/mandelbrot1.py
1,621
3.640625
4
import numpy as np from matplotlib import pyplot as plt from matplotlib import colors #%matplotlib inline settings=[-2.0,0.5,-1.25,1.25,3,3,80] def mandelbrot(z,maxiter): c = z for n in range(maxiter): if abs(z) > 2: return n z = z*z + c return maxiter def mandelbrot_set(xmin,xmax,ymin,ymax,width,height,maxiter): r1 = np.linspace(xmin, xmax, width) r2 = np.linspace(ymin, ymax, height) return (r1,r2,[mandelbrot(complex(r, i),maxiter) for r in r1 for i in r2]) def mandelbrot_image(xmin,xmax,ymin,ymax,width=3,height=3,maxiter=80,cmap='hot'): print("Initiating the mandelbrot image.") dpi = 72 #Zoom of the image img_width = dpi * width #Find the width of the image using the zoom and the width of the set img_height = dpi * height #Same operation for the height x,y,z = mandelbrot_set(xmin,xmax,ymin,ymax,img_width,img_height,maxiter) #Find the set print("The set is done.") print(type(z[0])) fig, ax = plt.subplots(figsize=(width, height),dpi=72) #get plt components ticks = np.arange(0,img_width,3*dpi) #find the steps x_ticks = xmin + (xmax-xmin)*ticks/img_width #split the x axis plt.xticks(ticks, x_ticks) y_ticks = ymin + (ymax-ymin)*ticks/img_width #split the y axis plt.yticks(ticks, y_ticks) print("Image settings are done.") norm = colors.PowerNorm(0.3) #Cool colors i guess ax.imshow(z,cmap=cmap,origin='lower',norm=norm) #create a dope heat map print("Image is done.") mandelbrot_image(-2.0,0.5,-1.25,1.25,maxiter=80,cmap='gnuplot2') #img=Image.fromarray(ms,'RGB') #img.show()
237174569b314b5ad7b2df0f9d0cc2bc80a5a3f2
MarcPartensky/Python-Games
/Game Structure/geometry/version3/myvector.py
8,935
3.71875
4
from mydirection import Direction from mypoint import Point from math import cos,sin from cmath import polar import mycolors import random class Vector: def random(min=-1,max=1,color=mycolors.WHITE,width=1,arrow=[0.1,0.5]): """Create a random vector using optional min and max.""" x=random.uniform(min,max) y=random.uniform(min,max) return Vector(x,y,color=color,width=width,arrow=arrow) def createFromPolarCoordonnates(norm,angle,color=mycolors.WHITE,width=1,arrow=[0.1,0.5]): """Create a vector using norm and angle from polar coordonnates.""" x,y=Vector.cartesian([norm,angle]) return Vector(x,y,color=color,width=width,arrow=arrow) def createFromSegment(segment,color=mycolors.WHITE,width=1,arrow=[0.1,0.5]): """Create a vector from a segment.""" return Vector.createFromTwoPoints(segment.p1,segment.p2,color=color,width=width,arrow=arrow) def createFromTwoPoints(point1,point2,color=mycolors.WHITE,width=1,arrow=[0.1,0.5]): """Create a vector from 2 points.""" x=point2.x-point1.x y=point2.y-point1.y return Vector(x,y,color=color,width=width,arrow=arrow) def createFromPoint(point,color=mycolors.WHITE,width=1,arrow=[0.1,0.5]): """Create a vector from a single point.""" return Vector(point.x,point.y,color=color,width=width,arrow=arrow) def createFromLine(line,color=mycolors.WHITE,width=1,arrow=[0.1,0.5]): """Create a vector from a line.""" angle=line.angle() x,y=Vector.cartesian([1,angle]) return Vector(x,y,color=color,width=width,arrow=arrow) def polar(position): """Return the polar position [norm,angle] using cartesian position [x,y].""" return list(polar(complex(position[0],position[1]))) def cartesian(position): """Return the cartesian position [x,y] using polar position [norm,angle].""" return [position[0]*cos(position[1]),position[0]*sin(position[1])] def __init__(self,*args,color=(255,255,255),width=1,arrow=[0.1,0.5]): """Create a vector.""" args=list(args) if len(args)==1: args=args[0] if type(args)==Point: self.x=args.x self.y=args.y elif type(args)==list or type(args)==tuple: if type(args[0])==Point and type(args[1])==Point: self.x=args[1].x-args[0].x self.y=args[1].y-args[0].y elif (type(args[0])==int or type(args[0])==float) and (type(args[1])==int or type(args[1])==float): self.x=args[0] self.y=args[1] else: raise Exception("The list of objects used to define the vector has not been recognised.") else: raise Exception("The object used to define the vector has not been recognised.") self.color=color self.width=width self.arrow=arrow def show(self,p,window,color=None,width=None): """Show the vector.""" if not color: color=self.color if not width: width=self.width q=self(p) v=-self.arrow[0]*self #wtf v1=v%self.arrow[1] v2=v%-self.arrow[1] a=v1(q) b=v2(q) window.draw.line(window.screen,color,p(),q(),width) window.draw.line(window.screen,color,q(),a(),width) window.draw.line(window.screen,color,q(),b(),width) def __iter__(self): """Iterate the points of the form.""" self.iterator=0 return self def __next__(self): """Return the next point threw an iteration.""" if self.iterator<2: if self.iterator==0: value=self.x if self.iterator==1: value=self.y self.iterator+=1 return value else: raise StopIteration def __neg__(self): """Return the negative vector.""" x=-self.x y=-self.y return Vector(x,y,width=self.width,color=self.color) def colinear(self,other): """Return if two vectors are colinear.""" return self.x*other.y-self.y*other.x==0 __floordiv__=colinear def scalar(self,other): """Return the scalar product between two vectors.""" return self.x*other.x+self.y*other.y def cross(self,other): """Determine if a vector crosses another using dot product.""" return self.scalar(other)==0 def __imul__(self,factor): """Multiply a vector by a given factor.""" if type(factor)==int or type(factor)==float: self.x*=factor self.y*=factor else: raise Exception("Type "+str(type(factor))+" is not valid. Expected float or int types.") def __mul__(self,factor,color=None,width=None,arrow=None): """Multiply a vector by a given factor.""" if not color: color=self.color if not width: width=self.width if not arrow: arrow=self.arrow if type(factor)==int or type(factor)==float: return Vector(self.x*factor,self.y*factor,color=color,width=width,arrow=arrow) else: raise Exception("Type "+str(type(factor))+" is not valid. Expected float or int types.") __rmul__=__mul__ #Allow front extern multiplication using back extern multiplication with scalars def __truediv__(self,factor): """Multiply a vector by a given factor.""" if type(factor)==Vector: pass else: x=self.x/factor y=self.y/factor return Vector(x,y,width=self.width,color=self.color) def __add__(self,other): """Add two vectors together.""" return Vector(self.x+other.x,self.y+other.y,width=self.width,color=self.color) def __iadd__(self,other): """Add a vector to another.""" self.x+=other.x self.y+=other.y return self def rotate(self,angle): """Rotate a vector using the angle of rotation.""" n,a=Vector.polar([self.x,self.y]) a+=angle self.x=n*cos(a) self.y=n*sin(a) def __mod__(self,angle): """Return the rotated vector using the angle of rotation.""" n,a=Vector.polar([self.x,self.y]) a+=angle return Vector(n*cos(a),n*sin(a),color=self.color,width=self.width,arrow=self.arrow) __imod__=__mod__ def __getitem__(self,index): """Return x or y value using given index.""" if index==0: return self.x if index==1: return self.y def __setitem__(self,index,value): """Change x or y value using given index and value.""" if index==0: self.x=value if index==1: self.y=value def __call__(self,*points): """Return points by applying the vector on those.""" new_points=[point+self for point in points] if len(points)==1: return new_points[0] else: return new_points def apply(self,point): """Return the point after applying the vector to it.""" return self+point def allApply(self,points): """Return the points after applying the vector to those.""" new_points=[point+self for point in points] return new_points def angle(self): """Return the angle of a vector with the [1,0] direction in cartesian coordonnates.""" return Vector.polar([self.x,self.y])[1] def norm(self): """Return the angle of a vector with the [1,0] direction in cartesian coordonnates.""" return Vector.polar([self.x,self.y])[0] def __xor__(self,other): """Return the angle between two vectors.""" return self.angle()-other.angle() def __invert__(self): """Return the unit vector.""" a=self.angle() position=Vector.cartesian([1,a]) return Vector(position) def __str__(self): """Return a string description of the vector.""" text="Vector:"+str(self.__dict__) return text if __name__=="__main__": from mysurface import Surface window=Surface(fullscreen=True) p1=Point(5,1) p2=Point(5,4) p3=Point(3,2) v1=Vector.createFromTwoPoints(p1,p2) v4=Vector.random(color=mycolors.YELLOW) v3=~v1 v3.color=mycolors.ORANGE print(tuple(v3)) x,y=v1 #Unpacking test print("x,y:",x,y) print(v1) #Give a string representation of the vector v2=0.8*v1 #Multiply vector by scalar 0.8 p4=v2(p1) v2.color=(255,0,0) p4.color=(0,255,0) while window.open: window.check() window.clear() window.show() window.control() #Specific to surfaces v1.show(p1,window) v2%=0.3 #Rotate the form by 0.3 radian v2.show(p1,window) v3.show(p1,window) window.print("This is p1",tuple(p1)) p2.show(window) p4.show(window) window.flip()
e4f909f0ecdf3f3529efe9de530ab31df9e4c1ed
MarcPartensky/Python-Games
/Game Structure/geometry/version4/myabstract.py
74,221
3.9375
4
from math import pi,sqrt,atan,cos,sin from cmath import polar from mytools import timer import math import random import mycolors average=mean=lambda x:sum(x)/len(x) digits=2 #Number of digits of precision of the objects when displayed class Point: """Representation of a point that can be displayed on screen.""" def origin(d=2): """Return the origin.""" return Point([0 for i in range(d)]) null=neutral=zero=origin def random(corners=[-1,-1,1,1],radius=0.02,fill=False,color=mycolors.WHITE): """Create a random point using optional minimum and maximum.""" xmin,ymin,xmax,ymax=corners x=random.uniform(xmin,xmax) y=random.uniform(ymin,ymax) return Point(x,y,radius=radius,fill=fill,color=color) def distance(p1,p2): """Return the distance between the two points.""" return math.sqrt(sum([(c1-c2)**2 for (c1,c2) in zip(p1.components,p2.components)])) def turnPoints(angles,points): """Turn the points around themselves.""" l=len(points) for i in range(l-1): points[i].turn(angles[i],points[i+1:]) def showPoints(surface,points): """Show the points on the surface.""" for point in points: point.show(surface) def createFromVector(vector): """Create a point from a vector.""" return Point(vector.x,vector.y) def __init__(self,*components,mode=0,size=[0.1,0.1],width=1,radius=0.02,fill=False,color=mycolors.WHITE,conversion=True): """Create a point using its components and optional radius, fill, color and conversion.""" if components!=(): if type(components[0])==list: components=components[0] self.components=list(components) self.mode=mode self.size=size self.width=width self.radius=radius self.fill=fill self.color=color self.conversion=conversion def __len__(self): """Return the number of components of the point.""" return len(self.components) def setX(self,value): """Set the x component.""" self.components[0]=value def getX(self): """Return the x component.""" return self.components[0] def delX(self): """Delete the x component and so shifting to a new one.""" del self.components[0] def setY(self,value): """Set the y component.""" self.components[1]=value def getY(self): """Return the y component.""" return self.components[1] def delY(self): """Delete the y component.""" del self.components[1] x=property(getX,setX,delX,"Allow the user to manipulate the x component easily.") y=property(getY,setY,delY,"Allow the user to manipulate the y component easily.") def __eq__(self,other): """Determine if two points are equals by comparing its components.""" return abs(self-other)<10e-10 def __ne__(self,other): """Determine if two points are unequals by comparing its components.""" return tuple(self)!=tuple(other) def __position__(self): """Return the coordonnates of the points.""" return [self.x,self.y] def __contains__(self,other): """Determine if an object is in the point.""" x,y=other return self.radius>=sqrt((x-self.x)**2+(y-self.y)**2) def __getitem__(self,index): """Return x or y value using given index.""" return self.components[index] def __setitem__(self,index,value): """Change x or y value using given index and value.""" self.components[index]=value def __abs__(self): """Return the distance of the point to the origin.""" return Vector.createFromPoint(self).norm def __tuple__(self): """Return the components in tuple form.""" return tuple(self.components) def __list__(self): """Return the components.""" return self.components def rotate(self,angle=pi,point=None): """Rotate the point using the angle and the center of rotation. Uses the origin for the center of rotation by default.""" if not point: point=Point.origin(d=self.dimension) v=Vector.createFromTwoPoints(point,self) v.rotate(angle) self.components=v(point).components def turn(self,angle=pi,points=[]): """Turn the points around itself.""" for point in points: point.rotate(angle,self) def move(self,*step): """Move the point using given step.""" self.x+=step[0] self.y+=step[1] def around(self,point,distance): """Determine if a given point is in a radius 'distance' of the point.""" return self.distance(point)<=distance def showCross(self,window,color=None,size=None,width=None,conversion=None): """Show the point under the form of a cross using the window.""" if not color: color=self.color if not size: size=self.size if not width: width=self.width if not conversion: conversion=self.conversion x,y=self sx,sy=size xmin=x-sx/2 ymin=y-sy/2 xmax=x+sx/2 ymax=y+sy/2 window.draw.line(window.screen,color,[xmin,ymin],[xmax,ymax],width,conversion) window.draw.line(window.screen,color,[xmin,ymax],[xmax,ymin],width,conversion) def showCircle(self,window,color=None,radius=None,fill=None,conversion=None): """Show a point under the form of a circle using the window.""" if not color: color=self.color if not radius: radius=self.radius if not fill: fill=self.fill if not conversion: conversion=self.conversion window.draw.circle(window.screen,color,[self.x,self.y],radius,fill,conversion) def show(self,window,color=None,mode=None,fill=None,radius=None,size=None,width=None,conversion=None): """Show the point on the window.""" if not mode: mode=self.mode if mode==0 or mode=="circle": self.showCircle(window,color,radius,fill,conversion) if mode==1 or mode=="cross": self.showCross(window,color,size,width,conversion) def showText(self,context,text,text_size=20,color=mycolors.WHITE): """Show the text next to the point on the window.""" context.print(text,self.components,text_size,color=color) def __add__(self,other): """Add two points.""" return Point([c1+c2 for (c1,c2) in zip(self.components,other.components)]) def __iadd__(self,other): """Add a point to the actual point.""" self.components=[c1+c2 for (c1,c2) in zip(self.components,other.components)] __radd__=__add__ def __sub__(self,other): """Add a point to the actual point.""" return Point([c1-c2 for (c1,c2) in zip(self.components,other.components)]) def __isub__(self,other): """Add a point to the actual point.""" self.components=[c1-c2 for (c1,c2) in zip(self.components,other.components)] __rsub__=__sub__ def __sub__(self,other): """Substract the components of 2 objects.""" return Point(self.x-other[0],self.y-other[1]) def __ge__(self,other): """Determine if a point is farther to the origin.""" return self.x**2+self.y**2>=other.x**2+other.y**2 def __gt__(self,other): """Determine if a point is farther to the origin.""" return self.x**2+self.y**2>other.x**2+other.y**2 def __le__(self,other): """Determine if a point is the nearest to the origin.""" return self.x**2+self.y**2<=other.x**2+other.y**2 def __lt__(self,other): """Determine if a point is the nearest to the origin.""" return self.x**2+self.y**2<other.x**2+other.y**2 def __iter__(self): """Iterate the points of the form.""" self.iterator=0 return self def __next__(self): """Return the next point threw an iteration.""" if self.iterator<len(self.components): self.iterator+=1 return self.components[self.iterator-1] else: raise StopIteration def truncate(self): """Truncate the position of the point by making the x and y components integers.""" for i in range(self.dimension): self.components[i]=int(self.components[i]) def __str__(self): """Return the string representation of a point.""" return "p("+",".join([str(round(c,digits)) for c in self.components])+")" def getPosition(self): """Return the components.""" return self.components def setPosition(self,position): """Set the components.""" self.components=position def getDimension(self): """Return the dimension of the point.""" return len(self.components) def setDimension(self,dimension): """Set the dimension of the point by setting to 0 the new components.""" self.components=self.components[:dimension] self.components+=[0 for i in range(dimension-len(self.components))] def delDimension(self): """Delete the components of the points.""" self.components=[] position=property(getPosition,setPosition,"Same as component although only component should be used.") dimension=property(getDimension,setDimension,delDimension,"Representation of the dimension point which is the length of the components.") class Direction: """Base class of lines and segments.""" def __init__(self): #position,width,color): pass class Vector: def null(d=2): """Return the null vector.""" return Vector([0 for i in range(d)]) neutral=zero=null def random(corners=[-1,-1,1,1],color=mycolors.WHITE,width=1,arrow=[0.1,0.5]): """Create a random vector using optional min and max.""" xmin,ymin,xmax,ymax=corners x=random.uniform(xmin,xmax) y=random.uniform(ymin,ymax) return Vector(x,y,color=color,width=width,arrow=arrow) def sum(vectors): """Return the vector that correspond to the sum of all the vectors.""" result=Vector.null() for vector in vectors: result+=vector return result def average(vectors): """Return the vector that correspond to the mean of all the vectors.""" return Vector.sum(vectors)/len(vectors) mean=average def collinear(*vectors,e=10e-10): """Determine if all the vectors are colinear.""" l=len(vectors) if l==2: v1=vectors[0] v2=vectors[1] return abs(v1.x*v2.y-v1.y-v2.x)<e else: for i in range(l): for j in range(i+1,l): if not Vector.collinear(vectors[i],vectors[j]): return False return True def sameDirection(*vectors,e=10e-10): """Determine if all the vectors are in the same direction.""" l=len(vectors) if l==2: v1=vectors[0] v2=vectors[1] return (abs(v1.angle-v2.angle)%(2*math.pi))<e else: for i in range(l): for j in range(i+1,l): if not Vector.sameDirection(vectors[i],vectors[j]): return False return True def createFromPolarCoordonnates(norm,angle,color=mycolors.WHITE,width=1,arrow=[0.1,0.5]): """Create a vector using norm and angle from polar coordonnates.""" x,y=Vector.cartesian([norm,angle]) return Vector(x,y,color=color,width=width,arrow=arrow) def createFromSegment(segment,color=mycolors.WHITE,width=1,arrow=[0.1,0.5]): """Create a vector from a segment.""" return Vector.createFromTwoPoints(segment.p1,segment.p2,color=color,width=width,arrow=arrow) def createFromTwoPoints(point1,point2,color=mycolors.WHITE,width=1,arrow=[0.1,0.5]): """Create a vector from 2 points.""" return Vector([c2-c1 for (c1,c2) in zip(point1.components,point2.components)],color=color,width=width,arrow=arrow) def createFromTwoTuples(tuple1,tuple2,color=mycolors.WHITE,width=1,arrow=[0.1,0.5]): """Create a vector from 2 tuples.""" return Vector([c2-c1 for (c1,c2) in zip(tuple1,tuple2)],color=color,width=width,arrow=arrow) def createFromPoint(point,color=mycolors.WHITE,width=1,arrow=[0.1,0.5]): """Create a vector from a single point.""" return Vector(point.x,point.y,color=color,width=width,arrow=arrow) def createFromLine(line,color=mycolors.WHITE,width=1,arrow=[0.1,0.5]): """Create a vector from a line.""" angle=line.angle x,y=Vector.cartesian([1,angle]) return Vector(x,y,color=color,width=width,arrow=arrow) def polar(position): """Return the polar position [norm,angle] using cartesian position [x,y].""" return list(polar(complex(position[0],position[1]))) def cartesian(position): """Return the cartesian position [x,y] using polar position [norm,angle].""" return [position[0]*cos(position[1]),position[0]*sin(position[1])] def __init__(self,*args,color=mycolors.WHITE,width=1,arrow=[0.1,0.5]): """Create a vector.""" if len(args)==1: args=args[0] self.components=list(args) self.color=color self.width=width self.arrow=arrow def setNull(self): """Set the components of the vector to zero.""" self.components=[0 for i in range(len(self.components))] #X component def setX(self,value): """Set the x component.""" self.components[0]=value def getX(self): """Return the x component.""" return self.components[0] def delX(self): """Delete the x component and so shifting to a new one.""" del self.components[0] #Y component def setY(self,value): """Set the y component.""" self.components[1]=value def getY(self): """Return the y component.""" return self.components[1] def delY(self): """Delete the y component.""" del self.components[1] #Angle def getAngle(self): """Return the angle of a vector with the [1,0] direction in cartesian coordonnates.""" return Vector.polar(self.components)[1] def setAngle(self,value): """Change the angle of the points without changing its norm.""" n,a=Vector.polar(self.components) self.components=Vector.cartesian([n,value]) def delAngle(self): """Set to zero the angle of the vector.""" self.setAngle(0) #Norm def getNorm(self): """Return the angle of a vector with the [1,0] direction in cartesian coordonnates.""" return Vector.polar(self.components)[0] def setNorm(self,value): """Change the angle of the points without changing its norm.""" n,a=Vector.polar(self.components) self.components=Vector.cartesian([value,a]) #Position def getPosition(self): """Return the components.""" return self.components def setPosition(self,position): """Set the components.""" self.components=position def delPosition(self): """Set the vector to the null vector.""" self.components=[0 for i in range(len(self.components))] x=property(getX,setX,delX,doc="Allow the user to manipulate the x component easily.") y=property(getY,setY,delY,doc="Allow the user to manipulate the y component easily.") norm=property(getNorm,setNorm,doc="Allow the user to manipulate the norm of the vector easily.") angle=property(getAngle,setAngle,doc="Allow the user to manipulate the angle of the vector easily.") position=property(getPosition,setPosition,doc="Same as components.") def show(self,context,p=Point.neutral(),color=None,width=None): """Show the vector.""" if not color: color=self.color if not width: width=self.width q=self(p) v=-self*self.arrow[0] #wtf v1=v%self.arrow[1] v2=v%-self.arrow[1] a=v1(q) b=v2(q) context.draw.line(context.screen,color,p.components,q.components,width) context.draw.line(context.screen,color,q.components,a.components,width) context.draw.line(context.screen,color,q.components,b.components,width) def showFromTuple(self,context,t=(0,0),**kwargs): """Show a vector from a tuple.""" p=Point(*t) self.show(context,p,**kwargs) def showText(self,surface,point,text,color=None,size=20): """Show the text next to the vector.""" if not color: color=self.color v=self/2 point=v(point) surface.print(text,tuple(point),color=color,size=size) def __len__(self): """Return the number of components.""" return len(self.components) def __iter__(self): """Iterate the points of the form.""" self.iterator=0 return self def __next__(self): """Return the next point threw an iteration.""" if self.iterator<len(self.components): self.iterator+=1 return self.components[self.iterator-1] else: raise StopIteration def __neg__(self): """Return the negative vector.""" return Vector([-c for c in self.components]) def colinear(self,other,e=10e-10): """Return if two vectors are colinear.""" return abs(self.x*other.y-self.y*other.x)<e __floordiv__=colinear def scalar(self,other): """Return the scalar product between two vectors.""" return self.x*other.x+self.y*other.y def cross(self,other): """Determine if a vector crosses another using dot product.""" return self.scalar(other)==0 def __mul__(self,factor): """Multiply a vector by a given factor.""" if type(factor)==int or type(factor)==float: return Vector([c*factor for c in self.components]) else: raise NotImplementedError raise Exception("Type "+str(type(factor))+" is not valid. Expected float or int types.") __imul__=__rmul__=__mul__ #Allow front extern multiplication using back extern multiplication with scalars def __truediv__(self,factor): """Multiply a vector by a given factor.""" if type(factor)==Vector: raise NotImplementedError else: return Vector([c/factor for c in self.components]) def __add__(self,other): """Add two vector together.""" return Vector([c1+c2 for (c1,c2) in zip(self.components,other.components)]) def __sub__(self,other): """Sub two vector together.""" return Vector([c1-c2 for (c1,c2) in zip(self.components,other.components)]) __iadd__=__radd__=__add__ __isub__=__rsub__=__sub__ def rotate(self,angle): """Rotate a vector using the angle of rotation.""" n,a=Vector.polar([self.x,self.y]) a+=angle self.x=n*cos(a) self.y=n*sin(a) def __mod__(self,angle): """Return the rotated vector using the angle of rotation.""" n,a=Vector.polar([self.x,self.y]) a+=angle return Vector(n*cos(a),n*sin(a),color=self.color,width=self.width,arrow=self.arrow) __imod__=__mod__ def __getitem__(self,index): """Return x or y value using given index.""" return self.position[index] def __setitem__(self,index,value): """Change x or y value using given index and value.""" self.position[index]=value def __call__(self,*points): """Return points by applying the vector on those.""" if points!=(): if type(points[0])==list: points=points[0] if len(points)==0: raise Exception("A vector can only be applied to a point of a list of points.") elif len(points)==1: return points[0]+self else: return [point+self for point in points] def applyToPoint(self,point): """Return the point after applying the vector to it.""" return self+point def applyToPoints(self,points): """Return the points after applying the vector to those.""" return [point+self for point in points] def __xor__(self,other): """Return the angle between two vectors.""" return self.angle-other.angle def __invert__(self): """Return the unit vector.""" a=self.angle x,y=Vector.cartesian([1,a]) return Vector(x,y) def __str__(self): """Return a string description of the vector.""" return "v("+",".join([str(round(c,digits)) for c in self.components])+")" def __tuple__(self): """Return the components in tuple form.""" return tuple(self.components) def __list__(self): """Return the components.""" return self.components class Segment(Direction): def null(): """Return the segment whoose points are both the origin.""" return Segment([Point.origin() for i in range(2)]) def random(corners=[-1,-1,1,1],width=1,color=mycolors.WHITE): """Create a random segment.""" p1=Point.random(corners) p2=Point.random(corners) return Segment([p1,p2],width=width,color=color) def __init__(self,*points,width=1,color=mycolors.WHITE): """Create the segment using 2 points, width and color.""" if points!=(): #Extracting the points arguments under the same list format if type(points[0])==list: points=points[0] if len(points)==1: points=points[0] if len(points)!=2: raise Exception("A segment must have 2 points.") self.points=list(points) self.width=width self.color=color def __str__(self): """Return the string representation of a segment.""" return "s("+str(self.p1)+","+str(self.p2)+")" def __call__(self,t=1/2): """Return the point C of the segment so that Segment(p1,C)=t*Segment(p1,p2).""" return (t*self.vector)(self.p1) def sample(self,n,include=True): """Sample n points of the segment. It is also possible to include the last point if wanted.""" return [self(t/n) for t in range(n+int(include))] __rmul__=__imul__=__mul__=lambda self,t: Segment(self.p1,self(t)) def getCenter(self): """Return the center of the segment in the general case.""" return Point(*[(self.p1[i]+self.p2[i])/2 for i in range(min(len(self.p1.components),len(self.p2.components)))]) def setCenter(self,np): """Set the center of the segment.""" p=self.getCenter() v=Vector.createFromTwoPoints(p,np) print("v",v) for i in range(len(self.points)): self.points[i]=v(self.points[i]) def getAngle(self): """Return the angle of the segment.""" return self.vector.angle def setAngle(self): """Set the angle of the segment.""" self.vector.angle=angle def show(self,window,color=None,width=None): """Show the segment using window.""" if not color: color=self.color if not width: width=self.width window.draw.line(window.screen,color,[self.p1.x,self.p1.y],[self.p2.x,self.p2.y],width) #self.showInBorders(window,color,width) def showInBorders(self,window,color=None,width=None): """Show the segment within the boundaries of the window.""" #It it really slow and it doesn't work as expected. xmin,ymin,xmax,ymax=window.getCorners() p=[Point(xmin,ymin),Point(xmax,ymin),Point(xmax,ymax),Point(xmin,ymax)] f=Form(p) if (self.p1 in f) and (self.p2 in f): window.draw.line(window.screen,color,[self.p1.x,self.p1.y],[self.p2.x,self.p2.y],width) elif (self.p1 in f) and not (self.p2 in f): v=Vector.createFromTwoPoints(self.p1,self.p2) hl=HalfLine(self.p1,v.angle) p=f.crossHalfLine(hl) if p: print(len(p)) p=p[0] window.draw.line(window.screen,color,[self.p1.x,self.p1.y],[p.x,p.y],width) elif not (self.p1 in f) and (self.p2 in f): v=Vector.createFromTwoPoints(self.p2,self.p1) hl=HalfLine(self.p2,v.angle) p=f.crossHalfLine(hl) if p: print(len(p)) p=p[0] window.draw.line(window.screen,color,[p.x,p.y],[self.p2.x,self.p2.y],width) else: ps=f.crossSegment(self) if len(ps)==2: p1,p2=ps window.draw.line(window.screen,color,[p1.x,p1.y],[p2.x,p2.y],width) def __contains__(self,point,e=10e-10): """Determine if a point is in a segment.""" if point==self.getP1(): return True v1=Vector.createFromTwoPoints(self.p1,point) v2=self.getVector() return (abs(v1.angle-v2.angle)%(2*math.pi)<e) and (v1.norm<=v2.norm) def __len__(self): """Return the number of points.""" return len(self.points) def __iter__(self): """Iterate the points of the form.""" self.iterator=0 return self def __next__(self): """Return the next point through an iteration.""" if self.iterator<len(self.points): if self.iterator==0: value=self.p1 if self.iterator==1: value=self.p2 self.iterator+=1 return value else: raise StopIteration def __getitem__(self,index): """Return the point corresponding to the index given.""" return [self.points][index] def __setitem__(self,index,value): """Change the value the point corresponding value and index given.""" self.points[index]=value def getLine(self,correct=True): """Return the line through the end points of the segment.""" return Line(self.p1,self.angle,self.width,self.color,correct=correct) def getVector(self): """Return the vector that goes from p1 to p2.""" return Vector.createFromTwoPoints(self.p1,self.p2) def setVector(self,vector): """Set the vector that goes from p1 to p2.""" self.p2=vector(self.p1) def getLength(self): """Return the length of the segment.""" return self.vector.norm def setLength(self,length): """Set the length of the segment.""" self.vector.norm=length def rotate(self,angle,point=None): """Rotate the segment using an angle and an optional point of rotation.""" if not point: point=self.middle self.p1.rotate(angle,point) self.p2.rotate(angle,point) def __or__(self,other): """Return bool for (2 segments are crossing).""" if isinstance(other,Segment): return self.crossSegment(other) if isinstance(other,Line): return self.crossLine(other) if isinstance(other,HalfLine): return other.crossSegment(self) if isinstance(other,Form): return form.crossSegment(self) def getXmin(self): """Return the minimum of x components of the 2 end points.""" return min(self.p1.x,self.p2.x) def getYmin(self): """Return the minimum of y components of the 2 ends points.""" return min(self.p1.y,self.p2.y) def getXmax(self): """Return the maximum of x components of the 2 end points.""" return max(self.p1.x,self.p2.x) def getYmax(self): """Returnt the maximum of y components of the 2 end points.""" return max(self.p1.y,self.p2.y) def getMinima(self): """Return the minima of x and y components of the 2 end points.""" xmin=self.getXmin() ymin=self.getYmin() return (xmin,ymin) def getMaxima(self): """Return the maxima of x and y components of the 2 end points.""" xmax=self.getXmax() ymax=self.getYmax() return (xmax,ymax) def getCorners(self): """Return the minimum and maximum of x and y components of the 2 end points.""" minima=self.getMinima() maxima=self.getMaxima() return minima+maxima def parallel(self,other): """Determine if the line is parallel to another object (line or segment).""" return (other.angle==self.angle) def crossSegment(self,other,e=10**-14): """Return the intersection point of the segment with another segment.""" sl=self.getLine() ol=other.getLine() point=sl.crossLine(ol) if point: if point in self and point in other: return point def crossLine(self,other): """Return the intersection point of the segment with a line.""" if self.parallel(other): return None line=self.getLine() point=other.crossLine(line) if point is not None: if point in self and point in other: return point def getP1(self): """Return the first point of the segment.""" return self.points[0] def setP1(self,p1): """Set the first point of the segment.""" self.points[0]=p1 def getP2(self): """Return the second point of the segment.""" return self.points[1] def setP2(self,p2): """Set the second point of the segment.""" self.points[1]=p2 p1=property(getP1,setP1,"Allow the user to manipulate the first point of the segment easily.") p2=property(getP2,setP2,"Allow the user to manipulate the second point of the segment easily.") middle=center=property(getCenter,setCenter,"Representation of the center of the segment.") vector=property(getVector,setVector,"Representation of the vector of the segment.") angle=property(getAngle,setAngle,"Representation of the angle of the segment.") length=property(getLength,setLength,"Representation of the length of the segment.") class Line(Direction): def random(min=-1,max=1,width=1,color=mycolors.WHITE): """Return a random line.""" point=Point.random(min,max) angle=random.uniform(min,max) return Line(point,angle,width,color) def createFromPointAndVector(point,vector,width=1,color=mycolors.WHITE): """Create a line using a point and a vector with optional features.""" return Line(point,vector.angle,width=1,color=color) def createFromTwoPoints(point1,point2,width=1,color=mycolors.WHITE): """Create a line using two points with optional features.""" vector=Vector.createFromTwoPoints(point1,point2) return Line(point1,vector.angle,width=1,color=color) def __init__(self,point,angle,width=1,color=mycolors.WHITE,correct=True): """Create the line using a point and a vector with optional width and color. Caracterizes the line with a unique system of components [neighbour point, angle]. The neighbour point is the nearest point to (0,0) that belongs to the line. The angle is the orientated angle between the line itself and another line parallel to the x-axis and crossing the neighbour point. Its range is [-pi/2,pi/2[ which makes it unique.""" self.point=point self.angle=angle self.width=width self.color=color if correct: self.correct() def __eq__(self,l): """Determine if two lines are the same.""" return l.point==self.point and l.angle==self.angle def correctAngle(self): """Correct angle which is between [-pi/2,pi/2[.""" self.angle=(self.angle+math.pi/2)%math.pi-math.pi/2 def correctPoint(self,d=2): """Correct the point to the definition of the neighbour point.""" self.point=self.projectPoint(Point.origin(d)) def correct(self): """Correct the line.""" self.correctAngle() self.correctPoint() def getCompleteCartesianCoordonnates(self): """Return a,b,c according to the cartesian equation of the line: ax+by+c=0.""" """Because there are multiple values of a,b,c for a single line, the simplest combinaision is returned.""" v=self.vector p1=self.point p2=v(self.point) if v.x==0: a=1 b=0 c=-p1.x else: a=-(p1.y-p2.y)/(p1.x-p2.x) b=1 c=-(a*p1.x+b*p1.y) return (a,b,c) def getReducedCartesianCoordonnates(self): """Return a,b according to the reduced cartesian equation of the line: y=ax+b.""" return (self.slope,self.ordinate) def getAngle(self): """Return the angle of the line.""" return self.angle def setAngle(self,angle): """Set the angle of the line.""" self.angle=angle self.correctAngle() def delAngle(self): """Set the angle of the line to zero.""" self.angle=0 #angle=property(getAngle,setAngle,delAngle,"Representation of the angle of the line after correction.") def rotate(self,angle,point=Point(0,0)): """Rotate the line.""" #Incomplete self.angle+=angle self.correctAngle() def getPoint(self): """Return the neighbour point.""" return self.point def setPoint(self,point): """Set the neighbour point to another one.""" self.point=point self.correctPoint() def delPoint(self): """Set the neighbour point to the origin.""" self.point=Point.origin() #point=property(getPoint,setPoint,delPoint,"Representation of the neighbour point of the line after correction.") def getUnitVector(self): """Return the unit vector of the line.""" return Vector.createFromPolarCoordonnates(1,self.angle) def setUnitVector(self,vector): """Set the unit vector of the line.""" self.angle=vector.angle def getNormalVector(self): """Return the normal vector of the line.""" vector=self.getUnitVector() vector.rotate(math.pi/2) return vector def setNormalVector(self,vector): """Set the normal vector of the line.""" self.angle=vector.angle+math.pi/2 def getSlope(self): """Return the slope of the line.""" return math.tan(angle) def setSlope(self,slope): """Set the slope of the line by changing its angle and point.""" self.angle=math.atan(slope) def getOrdinate(self): """Return the ordinate of the line.""" return self.point.y-self.slope*self.point.x def setOrdinate(self,ordinate): """Set the ordinate of the line by changing its position.""" self.slope self.angle self.point def getFunction(self): """Return the affine function that correspond to the line.""" return lambda x:self.slope*x+self.ordinate def setFunction(self,function): """Set the function of the line by changing its slope and ordinate.""" self.ordinate=function(0) self.slope=function(1)-function(0) def getReciproqueFunction(self): """Return the reciproque of the affine function that correspond to the line.""" return lambda y:(y-self.ordinate)/self.slope def evaluate(self,x): """Evaluate the line as a affine function.""" return self.function(x) def devaluate(self,y): """Evaluate the reciproque function of the affine funtion of the line.""" return self.getReciproqueFunction(y) def __or__(self,other): """Return the point of intersection between the line and another object.""" if isinstance(other,Line): return self.crossLine(other) if isinstance(other,Segment): return self.crossSegment(other) if isinstance(other,HalfLine): return other.crossLine(self) if isinstance(other,Form): return other.crossLine(self) def crossSegment(self,other,e=10**-13): """Return the point of intersection between a segment and the line.""" #Extract the slopes and ordinates line=other.getLine() point=self.crossLine(line) if not point: return None x,y=point #Determine if the point of intersection belongs to both the segment and the line xmin,ymin,xmax,ymax=other.getCorners() #If it is the case return the point if xmin-e<=x<=xmax+e and ymin-e<=y<=ymax+e: return Point(x,y,color=self.color) #By default if nothing is returned the function returns None def crossLine(self,other): """Return the point of intersection between two lines with vectors calculation.""" a,b=self.point c,d=other.point m,n=self.vector o,p=other.vector if n*o==m*p: return None #The lines are parallels x=(a*n*o-b*m*o-c*m*p+d*m*o)/(n*o-m*p) y=(x-a)*n/m+b return Point(x,y) def parallel(self,other): """Determine if the line is parallel to another object (line or segment).""" return other.angle==self.angle def __contains__(self,point,e=10e-10): """Determine if a point belongs to the line.""" v1=self.vector v2=Vector.createFromTwoPoints(self.point,point) return v1.colinear(v2,e) def getHeight(self,point): """Return the height line between the line and a point.""" return Line(point,self.normal_vector.angle) def distanceFromPoint(self,point): """Return the distance between a point and the line.""" return Vector.createFromTwoPoints(point,self.crossLine(self.getHeight(point))).norm def projectPoint(self,point): """Return the projection of the point on the line.""" vector=self.getNormalVector() angle=vector.angle line=Line(point,angle,correct=False) projection=self.crossLine(line) return projection def projectSegment(self,segment): """Return the projection of a segment on the line.""" p1,p2=segment p1=self.projectPoint(p1) p2=self.projectPoint(p2) return Segment(p1,p2,segment.width,segment.color) def getSegmentWithinXRange(self,xmin,xmax): """Return the segment made of the points of the line which x component is between xmin and xmax.""" yxmin=self.evaluate(xmin) yxmax=self.evaluate(xmax) p1=Point(xmin,yxmin) p2=Point(xmax,yxmax) return Segment(p1,p2) def getSegmentWithinYRange(self,ymin,ymax): """Return the segment made of the points of the line which y component is between ymin and ymax.""" xymin=self.devaluate(ymin) xymax=self.devaluate(ymax) p1=Point(xymin,ymin) p2=Point(xymax,ymax) return Segment(p1,p2,width=self.width,color=self.color) def oldgetSegmentWithinCorners(self,corners): """Return the segment made of the poins of the line which are in the area delimited by the corners.""" xmin,ymin,xmax,ymax=corners yxmin=self.evaluate(xmin) yxmax=self.evaluate(xmax) xymin=self.devaluate(ymin) xymax=self.devaluate(ymax) nxmin=max(xmin,xymin) nymin=max(ymin,yxmin) nxmax=min(xmax,xymax) nymax=min(ymax,yxmax) p1=Point(nxmin,nymin) p2=Point(nxmax,nymax) return Segment(p1,p2,width=self.width,color=self.color) def getSegmentWithinCorners(self,corners): """Return the segment made of the poins of the line which are in the area delimited by the corners.""" xmin,ymin,xmax,ymax=corners p1=Point(xmin,ymin) p2=Point(xmax,ymin) p3=Point(xmax,ymax) p4=Point(xmin,ymax) s1=Segment(p1,p2) s2=Segment(p2,p3) s3=Segment(p3,p4) s4=Segment(p4,p1) segments=[s1,s2,s3,s4] points=[] for segment in segments: cross=self.crossSegment(segment) if cross: points.append(cross) if len(points)==2: return Segment(*points) def getPointsWithinCorners(self,corners): """Return the segment made of the poins of the line which are in the area delimited by the corners.""" xmin,ymin,xmax,ymax=corners p1=Point(xmin,ymin) p2=Point(xmax,ymin) p3=Point(xmax,ymax) p4=Point(xmin,ymax) v1=Vector(p1,p2) v2=Vector(p2,p3) v3=Vector(p3,p4) v4=Vector(p4,p1) l1=Line.createFromPointAndVector(p1,v1) l2=Line.createFromPointAndVector(p2,v2) l3=Line.createFromPointAndVector(p3,v3) l4=Line.createFromPointAndVector(p4,v4) lines=[l1,l3] points=[] for line in lines: cross=self.crossLine(line) if cross: points.append(cross) if not points: lines=[l2,l4] for line in lines: cross=self.crossLine(line) if cross: points.append(cross) return points def show(self,surface,width=None,color=None): """Show the line on the surface.""" if not color: color=self.color if not width: width=self.width corners=surface.getCorners() segment=self.getSegmentWithinCorners(corners) if segment: p1,p2=segment segment.show(surface,width=width,color=color) vector=unit_vector=property(getUnitVector,setUnitVector,"Allow the client to manipulate the unit vector easily.") normal_vector=property(getNormalVector,setNormalVector,"Allow the client to manipulate the normal vector easily.") slope=property(getSlope,setSlope,"Allow the client to manipulate the slope of the line easily.") ordinate=property(getOrdinate,setOrdinate,"Allow the client to manipulate the ordinate of the line easily.") function=property(getFunction,setFunction,"Allow the client to manipulate the function of the line.") #reciproque_function=property(getReciproqueFunction,setReciproqueFunction,"Allow the user to manipulate easily the reciproque function.") class HalfLine(Line): def createFromLine(line): """Create a half line.""" return HalfLine(line.point,line.angle) def __init__(self,point,angle,color=mycolors.WHITE,width=1): """Create a half line.""" super().__init__(point,angle,color=color,width=width,correct=False) def getLine(self,correct=True): """Return the line that correspond to the half line.""" return Line(self.point,self.angle,correct=correct) def getPoint(self): """Return the point of the half line.""" return self.point def setPoint(self,point): """Set the point of the half line.""" self.point=point def show(self,surface,width=None,color=None): """Show the line on the surface.""" if not color: color=self.color if not width: width=self.width xmin,ymin,xmax,ymax=surface.getCorners() points=[Point(xmin,ymin),Point(xmax,ymin),Point(xmax,ymax),Point(xmin,ymax)] form=Form(points) points=form.crossHalfLine(self) points+=[self.point]*(2-len(points)) if len(points)>0: surface.draw.line(surface.screen,color,points[0],points[1],width) def __contains__(self,point,e=10e-10): """Determine if a point is in the half line.""" v1=self.vector v2=Vector.createFromTwoPoints(self.point,point) return abs(v1.angle-v2.angle)<e def __or__(self,other): """Return the intersection point between the half line and another object.""" if isinstance(other,Line): return self.crossLine(other) if isinstance(other,Segment): return self.crossSegment(other) if isinstance(other,HalfLine): return self.crossHalfLine(other) if isinstance(other,Form): return form.crossHalfLine(self) def crossHalfLine(self,other): """Return the point of intersection of the half line with another.""" ml=self.getLine(correct=False) ol=other.getLine(correct=False) point=ml.crossLine(ol) if point: if (point in self) and (point in other): return point def crossLine(self,other): """Return the point of intersection of the half line with a line.""" ml=self.getLine(correct=False) point=ml.crossLine(other) if point: if (point in self) and (point in other): return point def crossSegment(self,other): """Return the point of intersection of the half line with a segment.""" ml=self.getLine(correct=False) ol=other.getLine(correct=False) point=ml.crossLine(ol) if point: if (point in self) and (point in other): return point def __str__(self): """Return the string representation of a half line.""" return "hl("+str(self.point)+","+str(self.angle)+")" class Form: def random(corners=[-1,-1,1,1],n=random.randint(1,10),**kwargs): """Create a random form using the point_number, the minimum and maximum position for x and y components and optional arguments.""" points=[Point.random(corners) for i in range(n)] form=Form(points,**kwargs) form.makeSparse() return form def anyCrossing(forms): """Determine if any of the forms are crossing.""" if len(forms)==1:forms=forms[0] l=len(forms) for i in range(l): for j in range(i+1,l): if forms[i].crossForm(forms[j]): return True return False def allCrossing(forms): """Determine if all the forms are crossing.""" if len(forms)==1:forms=forms[0] l=len(forms) for i in range(l): for j in range(i+1,l): if not forms[i].crossForm(forms[j]): return False return True def cross(*forms): """Return the points of intersection between the crossing forms.""" if len(forms)==1:forms=forms[0] l=len(forms) points=[] for i in range(l): for j in range(i+1,l): points.extend(forms[i].crossForm(forms[j])) return points def intersectionTwoForms(form1,form2): """Return the form which is the intersection of two forms.""" if form1==None: return form2 if form2==None: return form1 if form1==form2==None: return None points=form1.crossForm(form2) if not points: return None for point in form1.points: if point in form2: points.append(point) for point in form2.points: if point in form1: points.append(point) form=Form(points) form.makeSparse() return form def intersection(forms): """Return the form which is the intersection of all the forms.""" result=forms[0] for form in forms[1:]: result=Form.intersectionTwoForms(result,form) return result def unionTwoForms(form1,form2): """Return the union of two forms.""" intersection_points=set(form1.crossForm(form2)) if intersection_points: all_points=set(form1.points+form2.points) points=all_points.intersection(intersection_points) return [Form(points)] else: return [form1,form2] def union(forms): """Return the union of all forms.""" """This function must be recursive.""" if len(forms)==2: return Form.unionTwoForms(forms[0],forms[1]) else: pass result=forms[0] for form in forms[1:]: result.extend(Form.union(form,result)) return result def __init__(self,points,fill=False,point_mode=0,point_size=[0.01,0.01],point_radius=0.01,point_width=1,point_fill=False,side_width=1,color=None,point_color=mycolors.WHITE,side_color=mycolors.WHITE,area_color=mycolors.WHITE,cross_point_color=mycolors.WHITE,cross_point_radius=0.01,cross_point_mode=0,cross_point_width=1,cross_point_size=[0.1,0.1],point_show=True,side_show=True,area_show=False): """Create the form object using points.""" self.points=points self.point_mode=point_mode self.point_size=point_size self.point_width=point_width self.point_radius=point_radius self.point_color=point_color or color self.point_show=point_show self.point_fill=point_fill self.side_width=side_width self.side_color=side_color or color self.side_show=side_show self.area_color=area_color or color self.area_show=area_show or fill self.cross_point_color=cross_point_color self.cross_point_radius=cross_point_radius self.cross_point_mode=cross_point_mode self.cross_point_width=cross_point_width self.cross_point_size=cross_point_size def __str__(self): """Return the string representation of the form.""" return "f("+",".join([str(p) for p in self.points])+")" def setFill(self,fill): """Set the form to fill its area when shown.""" self.area_show=fill def getFill(self): """Return if the area is filled.""" return self.area_show fill=property(getFill,setFill,doc="Allow the user to manipulate easily if the area is filled.") def __iadd__(self,point): """Add a point to the form.""" self.points.append(point) return self def __isub__(self,point): """Remove a point to the form.""" self.points.remove(point) return self def __mul__(self,n): """Return a bigger form.""" vectors=[n*Vector(*(p-self.center)) for p in self.points] return Form([vectors[i](self.points[i]) for i in range(len(self.points))]) def __imul__(self,n): """Return a bigger form.""" vectors=[n*Vector(*(p-self.center)) for p in self.points] self.points=[vectors[i](self.points[i]) for i in range(len(self.points))] return self __rmul__=__mul__ def __iter__(self): """Iterate the points of the form.""" self.iterator=0 return self def __next__(self): """Return the next point threw an iteration.""" if self.iterator < len(self.points): iterator=self.iterator self.iterator+=1 return self.points[iterator] else: raise StopIteration def __eq__(self,other): """Determine if 2 forms are the same which check the equalities of their components.""" return sorted(self.points)==sorted(other.points) def getCenter(self): """Return the point of the center.""" mx=mean([p.x for p in self.points]) my=mean([p.y for p in self.points]) return Point(mx,my,color=self.point_color,radius=self.point_radius) def setCenter(self,center): """Set the center of the form.""" p=center-self.getCenter() for point in self.points: point+=p def getSegments(self): """"Return the list of the form sides.""" l=len(self.points) return [Segment(self.points[i%l],self.points[(i+1)%l],color=self.side_color,width=self.side_width) for i in range(l)] def setSegments(self,segments): """Set the segments of the form by setting its points to new values.""" self.points=[s.p1 for s in segments][:-1] def showAll(self,surface,**kwargs): """Show the form using a window.""" #,window,point_color=None,side_color=None,area_color=None,side_width=None,point_radius=None,color=None,fill=None,point_show=None,side_show=None if not "point_show" in kwargs: kwargs["point_show"]=self.point_show if not "side_show" in kwargs: kwargs["side_show"]=self.side_show if not "area_show" in kwargs: kwargs["area_show"]=self.area_show if kwargs["area_show"]: self.showAllArea(surface,**kwargs) if kwargs["side_show"]: self.showAllSegments(surface,**kwargs) if kwargs["point_show"]: self.showAllPoints(surface,**kwargs) def showFast(self,surface,point=None,segment=None,area=None): """Show the form using the surface and optional objects to show.""" if point: self.showPoints(surface) if segment: self.showSegments(surface) if area: self.showArea(surface) def show(self,surface): """Show the form using the surface and optional objects to show.""" if self.area_show: self.showArea(surface) if self.side_show: self.showSegments(surface) if self.point_show: self.showPoints(surface) def showFastArea(self,surface,color=None): """Show the area of the form using optional parameters such as the area of the color.""" if not color: color=self.area_color ps=[tuple(p) for p in self.points] if len(ps)>1: surface.draw.polygon(surface.screen,color,ps,False) def showAllArea(self,surface,**kwargs): """Show the area of the form using optional parameters such as the area of the color. This function is slower than the previous one because it checks if the dictionary or attributes contains the area_color.""" if not "area_color" in kwargs: kwargs["area_color"]=self.area_color ps=[tuple(p) for p in self.points] if len(ps)>1: surface.draw.polygon(surface.screen,kwargs["area_color"],ps,False) def showArea(self,surface): """Show the area of the form.""" ps=[tuple(p) for p in self.points] if len(ps)>1: surface.draw.polygon(surface.screen,self.area_color,ps,False) def showPoints(self,surface): """Show the points.""" for point in self.points: point.show(surface) def showFastPoints(self,surface, color=None, mode=None, radius=None, size=None, width=None, fill=None): """Show the points of the form using optional parameters.""" if not color: color=self.point_color if not radius: radius=self.point_radius if not mode: mode=self.point_mode if not size: size=self.point_size if not width: width=self.point_width if not fill: fill=self.point_fill for point in self.points: point.show(surface,color,mode,fill,radius,size,width) def showAllPoints(self,surface,**kwargs): """Show the points of the form using optional parameters. This method is slower than the previous one because it checks if the dictionary of attributes contains the arguments.""" if not "point_color" in kwargs: kwargs["point_color"]= self.point_color if not "point_radius" in kwargs: kwargs["point_radius"]= self.point_radius if not "point_mode" in kwargs: kwargs["point_mode"]= self.point_mode if not "point_size" in kwargs: kwargs["point_size"]= self.point_size if not "point_width" in kwargs: kwargs["point_width"]= self.point_width if not "point_fill" in kwargs: kwargs["point_fill"]= self.point_fill for point in self.points: point.show(surface, color=kwargs["point_color"], mode=kwargs["point_mode"], fill=kwargs["point_fill"], radius=kwargs["point_radius"], size=kwargs["point_size"], width=kwargs["point_width"]) @timer def showFastSegments(self,surface,color=None,width=None): """Show the segments of the form.""" if not color: color=self.segment_color if not width: width=self.segment_width for segment in self.segments: segment.show(surace,color,width) def showSegments(self,surface): """Show the segments without its parameters.""" for segment in self.segments: segment.show(surface) def showAllSegments(self,surface,**kwargs): """Show the segments of the form.""" if not "side_color" in kwargs: kwargs["side_color"]=self.side_color if not "side_width" in kwargs: kwargs["side_width"]=self.side_width for segment in self.segments: segment.show(surface,color=kwargs["side_color"],width=kwargs["side_width"]) def showFastCrossPoints(self,surface,color=None,mode=None,radius=None,width=None,size=None): """Show the intersection points of the form crossing itself.""" points=self.crossSelf() if not color: color=self.cross_point_color if not mode: mode=self.cross_point_mode if not radius: radius=self.cross_point_radius if not width: width=self.cross_point_width if not size: size=self.cross_point_size for point in points: point.show(surface,color=color,mode=mode,radius=radius,width=width,size=size) def showCrossPoints(self,surface): """Show the intersection points of the form crossing itself.""" for point in self.cross_points: point.show(surface) def __or__(self,other): """Return the points of intersections with the form and another object.""" if isinstance(other,HalfLine): return self.crossHalfLine(other) if isinstance(other,Line): return self.crossLine(other) if isinstance(other,Segment): return self.crossSegment(other) if isinstance(other,Form): return self.crossForm(other) def crossForm(self,other): """Return the bool: (2 sides are crossing).""" points=[] for myside in self.sides: for otherside in other.sides: point=myside.crossSegment(otherside) if point: points.append(point) return points def crossDirection(self,other): """Return the list of the points of intersection between the form and a segment or a line.""" points=[] for side in self.sides: cross=side|other if cross: points.append(cross) return points def crossHalfLine(self,other): """Return the list of points of intersection in order between the form and a half line.""" points=[] for segment in self.segments: cross=other.crossSegment(segment) if cross: points.append(cross) hp=other.point objects=[(p,Point.distance(p,hp)) for p in points] objects=sorted(objects,key=lambda x:x[1]) return [p for (p,v) in objects] def crossLine(self,other): """Return the list of the points of intersection between the form and a line.""" points=[] for segment in self.segments: cross=segment.crossLine(other) if cross: points.append(cross) return points def crossSegment(self,other): """Return the list of the points of intersection between the form and a segment.""" points=[] for side in self.sides: point=side.crossSegment(other) if point: points.append(point) return points def crossSelf(self,e=10e-10): """Return the list of the points of intersections between the form and itself.""" results=[] l=len(self.segments) for i in range(l): for j in range(i+1,l): point=self.segments[i].crossSegment(self.segments[j]) if point: if point in self.points: results.append(point) return results def convex(self): """Return the bool (the form is convex).""" x,y=self.center angles=[] l=len(self.points) for i in range(l-1): A=self.points[(i+l-1)%l] B=self.points[i%l] C=self.points[(i+1)%l] u=Vector.createFromTwoPoints(A,B) v=Vector.createFromTwoPoints(C,B) angle=v^u if angle>pi: return True return False def getSparse(self): #as opposed to makeSparse which keeps the same form and return nothing """Return the form with the most sparsed points.""" cx,cy=self.center list1=[] for point in self.points: angle=Vector.createFromTwoPoints(point,self.center).angle list1.append((angle,point)) list1=sorted(list1,key=lambda x:x[0]) points=[element[1] for element in list1] return Form(points,fill=self.fill,side_width=self.side_width,point_radius=self.point_radius,point_color=self.point_color,side_color=self.side_color,area_color=self.area_color) def makeSparse(self): """Change the form into the one with the most sparsed points.""" self.points=self.getSparse().points def __contains__(self,point): """Return the boolean: (the point is in the form).""" h=HalfLine(point,0) ps=self.crossHalfLine(h) return len(ps)%2==1 def rotate(self,angle,point=None): """Rotate the form by rotating its points from the center of rotation. Use center of the shape as default center of rotation.""" #Actually not working if not point: point=self.center for i in range(len(self.points)): self.points[i].rotate(angle,point) def move(self,step): """Move the object by moving all its points using step.""" for point in self.points: l=min(len(step),len(point.position)) for i in range(l): point.position[i]=step[i] def setPosition(self,position): """Move the object to an absolute position.""" self.center.position=position def getPosition(self,position): """Return the position of the geometric center of the form.""" return self.center.position def addPoint(self,point): """Add a point to the form.""" self.points.append(point) def addPoints(self,points): """Add points to the form.""" self.points.extend(points) __append__=addPoint __extend__=addPoints def removePoint(self,point): """Remove a point to the form.""" self.point.remove(point) __remove__=removePoint def update(self,keys): """Update the points.""" for point in self.points: point.update(keys) def __getitem__(self,index): """Return the point of index index.""" return self.points[index] def __setitem__(self,index,value): """Change the points of a form.""" self.points[index]=value def area(self): """Return the area of the form using its own points. General case in 2d only for now...""" l=len(self.points) if l<3: #The form has no point, is a single point or a segment, so it has no area. return 0 elif l==3: #The form is a triangle, so we can calculate its area. a,b,c=[Vector.createFromSegment(segment) for segment in self.sides] A=1/4*sqrt(4*a.norm**2*b.norm**2-(a.norm**2+b.norm**2-c.norm**2)**2) return A else: #The form has more points than 3, so we can cut it in triangles. area=0 C=self.center for i in range(l): A=self.points[i] B=self.points[(i+1)%l] triangle=Form([A,B,C]) area+=Form.area(triangle) return area def __len__(self): """Return number of points.""" return len(self.points) def __xor__(self,other): """Return the list of forms that are in the union of 2 forms.""" if type(other)==Form: other=[other] return Form.union(other+[self]) def __and__(self,other): """Return the list of forms that are in the intersection of 2 forms.""" points=form.crossForm(other) points+=[point for point in self.points if point in other] points+=[point for point in other.points if point in self] if points: return Form(points) #Color def setColor(self,color): """Color the whole form with a new color.""" self.point_color=color self.side_color=color self.area_color=color def getColor(self): """Return the color of the segments because it is the more widely used.""" return self.side_color def delColor(self): """Set the color of the form.""" self.side_color=mycolors.WHITE self.point_color=mycolors.WHITE self.area_color=mycolors.WHITE def setPointColor(self,color): """Set the color of the points of the form.""" for point in self.points: point.color=color def setPointMode(self,mode): """Set the mode of the points.""" for point in self.points: point.mode=mode def setPointFill(self,fill): """Set the fill of the points.""" for point in self.points: self.fill=fill def setPointKey(self,key,value): """Set the value of the points with the key and the value.""" for point in self.points: point.__dict__[key]=value def setPointKeys(self,keys,values): """Set the values of the points with the keys and the values.""" l=min(len(keys),len(values)) for i in range(l): for point in self.points: point.__dict__[keys[i]]=values[i] getCrossPoints=crossSelf #points= property(getPoints,setPoints,"Represents the points.") #If I do this, the program will be very slow... sides=segments= property(getSegments,setSegments,"Represents the segments.") center=point= property(getCenter,setCenter,"Represents the center.") color= property(getColor,setColor,delColor,"Represents the color.") cross_points= property(getCrossPoints, "Represents the point of intersections of the segments.") #cross_points= property(getCrossPoints,setCrossPoints,delCrossPoints, "Represents the point of intersections of the segments.") #point_color= property(getPointColor,setPointColor,delPointColor,"Represents the color of the points.") #point_mode= property(getPointMode,setPointMode,delPointMode,"Represents the mode of the points.") #point_fill= property(getPointFill,setPointFill,delPointFill,"Represents the fill of the circle that represents the point.") #point_radius= property(getPointRadius,setPointRadius,delPointRadius,"Represents the radius of the circle that represents the point.") #point_size= property(getPointSize,setPointSize,delPointSize,"Represents the size of the cross that represents the point.") #point_width= property(getPointWidth,setPointWidth,delPointWidth,"Represents the width of the cross that represents the point.") #segment_color= property(getSegmentColor,setSegmentColor,delSegmentColor,"Represents the color of the segments.") #segment_width= property(getSegmentWidth,setSegmentWith,delSegmentWidth,"Represents the width of the segments.") class Circle: def random(min=-1,max=1,fill=0,color=mycolors.WHITE,border_color=None,area_color=None,center_color=None,radius_color=None,radius_width=1,text_color=None,text_size=20): """Create a random circle.""" point=Point.random(min,max) radius=1 return Circle.createFromPointAndRadius(point,radius,color,fill) def createFromPointAndRadius(point,radius,**kwargs): """Create a circle from point.""" return Circle(*point,radius=radius,**kwargs) def __init__(self,*args,radius,fill=False,color=mycolors.WHITE,border_color=None,area_color=None,center_color=None,radius_color=None,radius_width=1,text_color=None,text_size=20): """Create a circle object using x, y and radius and optional color and width.""" if len(args)==1: args=args[0] self.position=args self.radius=radius self.fill=fill if color: if not border_color: border_color=color if not area_color: area_color=color if not radius_color: radius_color=color if not text_color: text_color=color self.border_color=border_color self.area_color=area_color self.center_color=center_color self.radius_color=radius_color self.radius_width=radius_width self.text_color=text_color self.text_size=text_size def getX(self): """Return the x component of the circle.""" return self.position[0] def setX(self,value): """Set the x component of the circle.""" self.position[0]=value def getY(self): """Return the y component of the circle.""" return self.position[1] def setY(self,value): """Set the y component of the circle.""" self.position[1]=value def getPoint(self): """Return the point that correspond to the center of the circle.""" return Point(self.position) def setPoint(self,point): """Set the center point of the circle by changing the position of the circle.""" self.position=point.position x=property(getX,setX,"Allow the user to manipulate the x component easily.") y=property(getY,setY,"Allow the user to manipulate the y component easily.") center=point=property(getPoint,setPoint,"Allow the user to manipulate the point easily.") def center(self): """Return the point that correspond to the center of the circle.""" return Point(self.position) def show(self,window,color=None,border_color=None,area_color=None,fill=None): """Show the circle on screen using the window.""" if color: if not area_color: area_color=color if not border_color: border_color=color if not border_color: border_color=self.border_color if not area_color: area_color=self.area_color if not fill: fill=self.fill if fill: window.draw.circle(window.screen,area_color,[self.x,self.y],self.radius,True) window.draw.circle(window.screen,border_color,[self.x,self.y],self.radius) def showCenter(self,window,color=None,mode=None): """Show the center of the screen.""" if not color: color=self.center_color if not mode: mode=self.center_mode self.center.show(window,mode=mode,color=color) def showText(self,window,text,color=None,size=None): """Show a text next to the circle.""" if not color: color=self.text_color if not size: size=self.text_size self.center.showText(window,text,color=color,size=size) def showRadius(self,window,color=None,width=None): """Show the radius of the circle.""" if not color: color=self.radius_color if not width: width=self.radius_width vector=Vector.createFromPolarCoordonnates(self.radius,0,color=color) vector.show(window,self.center,width=width) vector.showText(surface,self.center,"radius",size=20) def __call__(self): """Return the main components of the circle.""" return [self.position,self.radius] def isCrossingCircle(self,other): """Determine if two circles are crossing.""" vector=Vector.createFromTwoPoints(self.center,other.center) return vector.norm<self.radius+other.radius def crossCircle(self,other): """Return the intersections points of two circles if crossing else return None.""" if self.isCrossingCircle(other): s=Segment(self.center,other.center) m=s.middle n=math.sqrt(self.radius**2-(s.norm/2)**2) a=s.angle+math.pi/2 v1=Vector.createFromPolarCoordonnates(n,a) v2=Vector.createFromPolarCoordonnates(n,-a) p1=v1(m) p2=v2(m) return [p1,p2] if __name__=="__main__": from mycontext import Surface surface=Surface(name="Abstract Demonstration",fullscreen=True) p1=Point(10,0,radius=0.05,color=mycolors.YELLOW) p2=Point(20,20,radius=0.05,color=mycolors.YELLOW) #origin=Point(0,0) origin=Point.origin() l1=HalfLine(origin,math.pi/4) l2=Line(p1,math.pi/2,correct=False) s1=Segment(p1,p2) print(Point.null) while surface.open: #Surface specific commands surface.check() surface.control() surface.clear() surface.show() #Actions l1.rotate(0.01,p2) l2.rotate(-0.02,p1) s1.rotate(0.03) p=l1|l2 o=Point(0,0) p3=l2.projectPoint(o) f=Form([p1,p2,p3],area_color=mycolors.RED,fill=True) #Show surface.draw.window.print("l1.angle: "+str(l1.angle),(10,10)) surface.draw.window.print("l2.angle: "+str(l2.angle),(10,30)) surface.draw.window.print("f.area: "+str(f.area()),(10,50)) f.show(surface) f.center.show(surface) s1.show(surface) o.show(surface,color=mycolors.GREY) o.showText(surface,"origin") p3.showText(surface,"origin's projection") p3.show(surface,color=mycolors.LIGHTGREY) if p: p.show(surface,color=mycolors.RED) p.showText(surface,"intersection point",color=mycolors.RED) p1.show(surface) p1.showText(surface,"p1") p2.show(surface) p2.showText(surface,"p2") l1.show(surface,color=mycolors.GREEN) l1.point.show(surface,color=mycolors.LIGHTGREEN,mode="cross",width=3) l1.vector.show(surface,l1.point,color=mycolors.LIGHTGREEN,width=3) l2.show(surface,color=mycolors.BLUE) l2.point.show(surface,color=mycolors.LIGHTBLUE,mode="cross",width=3) l2.vector.show(surface,l2.point,color=mycolors.LIGHTBLUE,width=3) #Flipping the screen surface.flip()
2114723258f1a9a8d3b0281676020098d7629943
MarcPartensky/Python-Games
/Game Structure/geometry/version5/modulo.py
1,888
3.6875
4
import math class Modulo: def __init__(self, n, a=None): """'n' is the number, and 'a' is the modulo""" if a == None: self.a = float("inf") else: self.a = a self.n = n % self.a # Type conversions def __str__(self): return str(self.n) def __int__(self): return self.n def __float__(self): return float(self.n) # Operations # Addition def __add__(self, other): return (self.n + other.n) % self.a __radd__ = __add__ def __iadd__(self, other): self.n = (self.n + other.n) % self.a return self # Subtraction def __sub__(self, other): return (self.n - other.n) % self.a __rsub__ = __sub__ def __isub__(self, other): self.n = (self.n - other.n) % self.a return self # Multiplication def __mul__(self, m): return (self.n * float(m)) % self.a __rmul__ = __mul__ def __imul__(self, m): self.n = (self.n * float(m)) % self.a return self # True division def __truediv__(self, m): return (self.n / float(m)) % self.a __rtruediv__ = __truediv__ def __itruediv__(self, m): self.n = (self.n / float(m)) % self.a return self # Floor division def __floordiv__(self, m): return (self.n // float(m)) % self.a __rfloordiv__ = __floordiv__ def __ifloordiv__(self, m): self.n = (self.n // float(m)) % self.a return self # Exponentiation def __pow__(self, m): return (self.n ** float(m)) % self.a __rpow__ = __pow__ def __ipow__(self, m): self.n = (self.n ** float(m)) % self.a return self if __name__ == "__main__": a = Modulo(5, 2 * math.pi) b = Modulo(202, 2 * math.pi) c = Modulo(62) print(((a + b - c * a) * 5 / 2) ** 2)
5d304023128714c95e67ec1ed77c8d4f1b3f33a9
MarcPartensky/Python-Games
/Intersection/myposition.py
2,382
3.546875
4
from math import sqrt,cos,sin from cmath import polar from numpy import array,dot class Position: base="xyztabcdefhijklmnopqrsuvw" angle_base="ab" def __init__(self,*data,base=None,system="cartesian"): """Save a position using cartesian coordonnates.""" self.system=system if self.system is "cartesian": self.data=array(data) if self.system is "polar": self.data=polar(list(data)) if base: self.base=base else: self.base=Position.base[:len(self.data)] def __call__(self): return list(self.data) def __str__(self,system="cartesian"): """Gives a representation of the position.""" if system is "cartesian": return " ".join([str(self.base[i])+"="+str(self.data[i]) for i in range(len(self.data))]) if system is "polar": pass x=lambda self:self.data[self.base.index("x")] y=lambda self:self.data[self.base.index("y")] z=lambda self:self.data[self.base.index("z")] t=lambda self:self.data[self.base.index("t")] __repr__=__str__ __add__=lambda self,other:self.data+other.data __sub__=lambda self,other:self.data-other.data def __mul__(self,other): if type(other) is Position: return Position(dot(self.data,other.data)) else: return Position([self.data*other]) def __sub__(self,other): pass def __len__(self): """Return number of dimension of the position.""" return len(self.data) def polar(self,position=None): """Return an array of the polar coordonnates using optionnal position.""" if not position: position=self.data position=list(position) if len(position)==2: return array(polar(complex(*position))) else: raise Exception(str(position)+" is not a cartesian position.") def cartesian(self,position=None): """Return an array of the cartesian position using optional polar position.""" if not position: position=self.data if len(position)==2: return array([position[0]*cos(position[1]),position[0]*sin(position[1])]) else: raise Exception(str(position)+" is not a polar position.") a=Position(2,6) b=Position(2,4) print((a*b).data) print(a.polar()) print(a.cartesian()) print(Position.polar(a.data)) print(a)
6a5961313d688e4136885a19f2cd33e6592ff4cd
LanHikari22/Mutu-chan
/Commands/botcmd.py
3,002
3.765625
4
class BotCMD: """ abstraction class of a bot command. Create this for every command except very fundemental ones Override methods as necessary. """ # execution activation command for when listening for mention commands command = None # defined error_code constants SUCCESS = 0 # success! you can execute this successfully. COMMAND_MISMATCH = -1 # not even the command matches. COMMAND_MATCH = 1 # in case the command matches, the error code is always positive! This isn't a success. INVALID_ARGV_FORMAT = -2# in case the argv is not a list of strings... def __init__(self, command:str): self.command = command def execute(self, argv): """action of command, if argv is None, you shall deal with the consequences""" print("*executes abstract magic!*") def get_error_code(self, command, argv=None): """ determines whether the command can activate. This can be based on whether the given command matches the activation command, but it also can be based on argument vector checks and making sure that the arguments are valid. :param command; command thought to be the activation command :param argv: argument vector, contains command and extra arguments for the command :returns: 0 if successful, -1 if command doesn't match, or an error code indicating why it shouldn't activate. """ if self.command == command: return self.COMMAND_MATCH else: return self.COMMAND_MISMATCH def get_error_msg(self, error_code:int): """ this should be syncronized with the errorcodes returned by should_activate() it helps prompting the user why their input was wrong. :param errorcode: error code indicating why a certain command/argument vector are not valid input :returns: a specified message per every define error code, or None if none are found """ error_msg = "" if error_code == self.COMMAND_MISMATCH: error_msg = "Command Mismatch" elif error_code == self.COMMAND_MATCH: error_msg = "Command Match" elif error_code == self.INVALID_ARGV_FORMAT: error_msg = "Invalid argv Format: must be a list of strings" else: error_msg = None return error_msg @staticmethod def get_help_format(): """ defines the help_format of this command. ex. "<number> <number>". does not contains command. :return: the format the command should be in """ return "applyMagic --on Target" @staticmethod def get_help_doc(): """ a little more detail into what a command does. This should be fairly basic. If sophisticated help is required, implement that separately. :return: documentation about the usage of a command """ return "I'm just an abstract wand~ in an astract world~"
58529d86ce20df905e85e7641408699ba48a0aa2
YpchenLove/py-example
/8-list.py
416
3.765625
4
# l = [1, 2, 3, 4, 5] # print(l[0]) # print(l[1: 2]) # print(l[-2: -1]) # print(l[:]) # print(l[0:5:2]) l = [1, 2, 1, 1, 3, 4, 5, -1] l2 = [7, 8, 9] print(l[-1:]) # [5] print(l[-1::-1]) # [5, 4, 3, 2, 1] print(len(l)) print(max(l)) print(min(l)) print(l.count(1)) l.append(88) print(l) l.pop() print(l) l.remove(5) print(l) l.reverse() print(l) l.sort(reverse=False) print(l) l.index(-1) print(l, 12)
a4682975b00b3a87be7e293ae844bd921e3d4db7
zjipsen/chef-scheduler
/chef.py
652
3.6875
4
class Chef: days_in_week = 5 def __init__(self, name, unavailable=[], since=6, times=0, vacation=False): self.name = name self.unavailable = unavailable self.since = since self.times = times self.init_since = since self.init_times = times self.vacation = vacation def cook(self): self.since = max(self.since - 6, 0) self.times += 1 def dont_cook(self): self.since += 1 def __str__(self): return " " + self.name + self.padding_to_six() def padding_to_six(self): return " " * (6 - len(self.name) + 1) NOBODY = Chef("-")
6e9541ca3a2030a5fdcbd1f28d4937afe60ae03e
MeitarEitan/Devops0803
/1.py
449
3.671875
4
my_first_name = "Meitar" age = 23 is_male = False hobbies = ["Ski", "Guitar", "DevOps"] eyes = ("brown", "blue", "green") # cant change (tuple) # myself = ["aviel", "buskila", 30, "identig"] myself = {"first_name": my_first_name, "last_name": "Eitan", "age": age} # dictionary print("Hello World!") print(my_first_name) print(age) print(is_male) print(hobbies[1]) hobbies[1] = "Travel" print(hobbies[1]) print(hobbies) print(myself["first_name"])