blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
bdee2c04aa4da5ef55f89b7ef3c7ddd60b29960e
mfkiwl/when-to-use-bbr
/server.py
1,188
3.640625
4
""" Webserver that uses specific congestion control algorithm """ import argparse import socketserver import http.server import socket class Handler(http.server.SimpleHTTPRequestHandler): # Disable logging DNS lookups def address_string(self): return str(self.client_address[0]) def start_server(port: int, cc: str): httpd = socketserver.TCPServer(("", port), Handler, bind_and_activate=True) # we set the congestion control by hand before bind and active cc_buffer = cc.encode("ascii") # notice that socket.TCP_CONGESTION is only available 3.6+ # also notice that setting socket TCP to congestion requires sudo access httpd.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_CONGESTION, cc_buffer) httpd.serve_forever() def main(): parser = argparse.ArgumentParser("Simple web server with customized congestion control algorithm") parser.add_argument("-c", "--congestion-control", choices=["bbr", "cubic"], default="bbr", type=str, dest="cc") parser.add_argument("-p", "--port", required=True, type=int, dest="port") args = parser.parse_args() start_server(args.port, args.cc) if __name__ == "__main__": main()
595852190cf145877724293faa4d38a0187d0f26
maniprataprana/algorithms
/QuickSort.py
442
4
4
def quicksort(A,begin,end) : if begin < end : split = partition(A,begin,end) quicksort(A,begin,split-1) quicksort(A,split+1,end) def partition(A,begin,end) : pivot = A[end] i = begin - 1 for j in range(begin,end) : if A[j] <= pivot : i = i + 1 A[i], A[j] = A[j], A[i] A[i+1], A[end] = A[end], A[i+1] return i+1 #use any array like below to sort A = [3,8,2,5,1,4,7,6] quicksort(A,0,len(A)-1) print A
bda67a087f0181b7133eac33588a695f1f8b1116
Gumemura/MAC0122
/Nota de aulas.py
4,220
3.546875
4
MAC 0122 Monitorias: 4ª, 5ª, e 6ª, 12:00 as 13:00, na sala 2 do CEC >>>>>>> Aula 2 - 06/08/2019 aula passada: cálculo de numero harmonico def -> cria função class -> cria classe def __init__(self) -> sempre que a função estiver entre 4 underlines (orelhas), é pq ele é da biblioteca do python class Frac: def __init__(self, num, den): ''' Inicializa os atributos da função''' self.num = num self.den = den def __str__(self): s = '%d/%d' %(self.num, self.den) return s tipos de erro em programação: sintaticos: erro de ditacao, falha na grafia do texto de linguagem formal. Exemplo: print("fdfd) Runtime Errors: erros evidenciados na exeucao do programa. Geralmente sao erros de logica. Exemplo: usar um variavel cuja existencia esta protegida por if, sem replicar essa condicao em seu uso Semantico: Erros que nao sao destacados pelo compilador mas percebidos pelo ususario/programador. Exemplo: usar uma variavel quando na verdade se desejava outra >>>>>>> Aula 3 - 08/08/2019 n teve nada de muito relevante que devesse ser anotado >>>>>>> Aula 4 - 13/08/2019 n fui :( >>>>>>> Aula 5 - 15/08/2019 Condutor da aula = Exercicio: verificar se uma string esta bem feita ou nao. Ou seja, se cada parenteses, colchetes e chaves sao fechadas na ordem inversam em foram abertas Ex.: bem formada: "([], {[]})" mau formada: "()[" - Pilhas, ou Stack em ingles #dicionario: estudar. Parece uma vetor de duas colunas, uma lista de pares A solucao para o problema é algo assim: s = input("digite o texto a ser analisado").stip() --> o stip limpa os espaços em branco abres = '([{' fechas = ')]}' pilha = stack() --> no stakc temos dois metodos principais: push("para adc elemento"); pop("que remove"); peer("espia o topo da pilha"); is_empty() "ve se esta vazia" Na verdade, a Stack() nao é uma classe natural de python. temos q implementa-la dicio = {']':'[', ')':'(', '}':'{'} --> o tipo Dicionario tmbm n existe, vamos implementa-la for i in range(len(s)): if s[i] in abres: pilha.push(s[i]) >>>>>>> Aula 6 - 20/08/2019 nao fui :( o mongol aqui esqueceu de ligar o despertador >>>>>>> Aula 7 - 22/08/2019 Aula de hj - array desenvolvimento da classe Arry2D = dois parametros: tuble, com as dimencoes da matrix e um int (ou float) com os valores das celular para fazer a classe Array, nao precisa fazer uma matriz, mas um lista. na hora de dar o print, percorremos todos os itens da lista de metemos um /n pra cada linha = >>>>>>> Aula 8 - 27/08/2019 continuacao de array. array é basicamente uma representacao de matrizes, uma lista bidimensional vista = exibicao dos valores da array mas de forma diferente >>>>>>> Aula 9 - 29/08/2019 exemplo: como determinar o caminha mais curto entre duas cidade Fazer uma rede: uma matrix cujos indices sao as cidades. se a celular for 1, as cidade indicadas no indice sao vizinhas Fila: uma pilha ao contrario >>>>>>> Aula 10 - 10/09/2019 Revendo aula passada: fazendo um mini google maps Array, onde cada linha X coluna é uma cidade. Caso haja caminho entre ambos, valor 1. Caso contrario, valor 0 Dica para criar matrizes: for i in range(n): matriz.append([0] * n) >>>>>>> ESTUDAR PRA PROVA Numeros posfixo Fila Pilhas Formas de criar uma array import numpy as np a = np.array('lista', 'tipo primitivo dos objetos') --> exemplo: a = np.array([[0,1,2],[3,4,5]], int) a = np.array(range('valor a maximo da array')) a = np.full(('tuple com as dimensoes da array'), 'valor') Principais funções com array nomeDaArray.reshape(3,4) -> altera as dimensoes da array Propriedades da arra nomeDaArray.shape() -> tuple, dimensoes da array nomeDaArray.size() -> int, quantidade de elementos contidos na array (multiplicacao dos termos da tuple retornada por shape) >>>>>>> Aula 11 - 17/09/2019 joguinho das argolinhas nas bases recusao, funcao sendo chamda dentro da propria funcao >>>>>>> Aula 12 - 19/09/2019 3 regras da recursao - RESOLVER: Se vc sabe resolver sem recursao, entao resolva assim - REDUZIR: use a funcao p se aproximar de um caso base - RECORRER: resolva o problema usando a resposta do problema menor
5781ae4cc60fca1ad1638a9cc57efe2a042f17b4
Vovanuch/python-basics-1
/elements, blocks and directions/while/while1.py
79
3.625
4
# how many stars? x = int(input()) i = 0 while (i<x): i += 1 print ('*' * i)
61aa3e14a32b910335f673f57081ca2082964c41
Avani18/LeetCode
/June LeetCoding Challenge/Day29-62.py
620
4
4
# Unique Paths # https://leetcode.com/problems/unique-paths/ '''A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). How many possible unique paths are there?''' def uniquePaths(self, m: int, n: int) -> int: n,k=n+m-2,m-1 count=min(n-k,k) up=down=1 while count>0: up*=n down*=count n-=1 count-=1 return up//down
6447999faaa1a21d2f845f6b136041c65c13bf93
ndtands/Algorithm_and_data_structer
/Practice_2/lab3/lab3_2.py
472
3.625
4
def Count(a,left,right,key): if (left == right): if(a[left]==key): return 1 else: return 0 else: mid =(left+right)//2 return Count(a,left,mid,key)+Count(a,mid+1,right,key) def Phan_tu_da_so(arr): out = 0 for i in arr: if (Count(arr,0,len(arr)-1,i)>len(arr)//2): out =1 break return out A=[int(i) for i in input("Nhap mang A: ").split(" ")] print(Phan_tu_da_so(A))
cb715dae399232ccc5b9d06b10dd70fd6b83f22a
dkarm/Hackerrank
/CrackingCodingInterview/HashtablesRansomNote.py
557
3.640625
4
def ransom_note(magazine, ransom): potential_words = {} for word in magazine: potential_words[word] =0 for word in magazine: potential_words[word] += 1 for word in ransom: if potential_words[word] > 0: potential_words[word] -= 1 else: return False return True m, n = map(int, raw_input().strip().split(' ')) magazine = raw_input().strip().split(' ') ransom = raw_input().strip().split(' ') answer = ransom_note(magazine, ransom) if (answer): print "Yes" else: print "No"
db910fa89706b094d5c9a47f4d95db0cb7e3951c
zconn/PythonCert220Assign
/students/DiannaTingg/lessons/lesson01/activity/calculator/subtracter.py
397
4.03125
4
""" This module provides a subtraction operator """ class Subtracter: """ Returns the difference of two numbers """ @staticmethod def calc(operand_1, operand_2): """ Subtracts one number from the other :param operand_1: number :param operand_2: number :return: Quotient of two numbers """ return operand_1 - operand_2
2ae5ebba1fbc678d2b6009b9cfa4155f5e02463c
Boeming/Python-Minecraft-Examples
/02-sendInteractiveArgsMessageToChat.py
936
3.640625
4
#!/usr/bin/env python # We have to import the minecraft api module to do anything in the minecraft world from mcpi.minecraft import * # We have to import sys module to get the command line arguments import sys if __name__ == "__main__": """ First thing you do is create a connection to minecraft This is like dialling a phone. It sets up a communication line between your script and the minecraft world """ # Create a connection to Minecraft # Any communication with the world must use this object mc = Minecraft.create() # get the output message as a string from keyboard input # NOTE this is python 2, in Python 3 input() should be used message = raw_input("Please enter some text to send to the chat: ") # print to the python interpreter standard output (terminal or IDLE probably) print(message) # send message to the minecraft chat mc.postToChat(message)
ec3e8b6c949819afa9d4ea720ad5a369ab3acf7d
andreodendaal/coursera_algo_toolkit
/week2_algorithmic_warmup/q4_LCM_crs3.py
470
3.65625
4
# Uses python3 import sys import math def lcm(a, b): vals = [a, b] vals.sort() LCM = vals[1] ctr = 2 while LCM % vals[0] != 0: LCM = vals[1] * ctr ctr += 1 return LCM, ctr - 1 if __name__ == "__main__": #a = int(input()) #b = int(input()) input = sys.stdin.read() a, b = map(int, input.split()) print(lcm(a, b)) # 1 1000000 # 18 35 -> 630 ctr 18 # 226553150 1023473145 -> 46374212988031350 ctr 45310630
ea173e92393c8f68773f59029fa961211c390948
raianmol172/data_structure_using_python
/construct_binaryTree_preorder_inorder.py
1,234
3.65625
4
# this is not an effective approach as it takes O(n^2) as it first takes O(n) # in pop first element from list and the searching for that element # and then slicing cause it O(n) class Node: def __init__(self, data): self.data = data self.left = None self.right = None class Solution: def preorder(self, start): if start is None: return print(start.data) self.preorder(start.left) self.preorder(start.right) def constructBinaryTree(self, preorder: list[int], inorder: list[int]): if len(inorder) == 0: return if len(preorder) == 1: return Node(preorder[0]) idx = inorder.index(preorder.pop(0)) # pop element from preorder and save the index of it in inorder. root = Node(inorder[idx]) # created a node of popped element from inorder list root.left = self.constructBinaryTree(preorder, inorder[:idx]) root.right = self.constructBinaryTree(preorder, inorder[idx + 1:]) return root preorder = [1, 2, 4, 8, 9, 5, 10, 11, 3, 6, 7] inorder = [8, 4, 9, 2, 10, 5, 11, 1, 6, 3, 7] tree = Solution() root = tree.constructBinaryTree(preorder, inorder) tree.preorder(root)
4f5bead83052f91de02d43d0cfe83add04d37022
ck624/defusr
/code/datasets/dataset_adapter.py
10,138
3.5
4
from abc import ABC, abstractmethod import numpy as np import torch import cv2 class DatasetAdapter(ABC): """ Abstract class for dataset adapters. Contains the logic for actually loading the raw data from file, and for creating the relevant datastructures. """ datapath = '' "The base folder for this dataset's files." im_width = 0 "The original image width (some datasets support multiple; this is the highest)." im_height = 0 "The original image height (some datasets support multiple; this is the highest)." im_scale = 0 "The scale at which images are returned by the adapter." nr_views = 0 "The number of views per scene." split = {'train': [], 'test': [], 'val': []} "The data split elements." ensure_multiple = 1 """ Ensure that the size of images are a multiple of this value. Will crop off the bottom right, so that camera matrices don't change. """ depth_map_prefix = "" """ Prepended to all Depth map folder names. Can be used to switch depth map inputs. """ _neighbour_selection = "closest" """ How to select neighbours for a given view. One of either "closest", "furthest", "mixed" """ def __init__(self,**kwargs): super().__init__() self.__dict__.update(kwargs) @abstractmethod def get_dataset_name(self): """ Returns an informative names for the underlying data. """ pass @abstractmethod def get_image_path(self, element, view): """ Get the location of the image file for a given view of a given element (string). The views should be zero-indexed. Arguments: element -- the element index (integer) view -- the camera index (integer) """ pass def get_single_image(self, element, view): """ Get a single image from the specified dataset element (3 x H x W torch tensor). Arguments: element -- the element index (integer) view -- the camera index (integer) """ image_path = self.get_image_path(element, view) img = cv2.imread(image_path) current_scale = img.shape[1] / (self.im_width * self.im_scale) target_multiple = int(self.ensure_multiple * current_scale) new_width = int(img.shape[1] / target_multiple) * target_multiple new_height = int(img.shape[0] / target_multiple) * target_multiple img = img[:new_height, :new_width, :] if self.im_width * self.im_scale < img.shape[1]: img = cv2.resize( img, (int(self.im_width * self.im_scale), int(self.im_height * self.im_scale)), interpolation=cv2.INTER_LANCZOS4 ) # change it to the C x H x W format required img = np.transpose(img, axes=(2, 0, 1)) return torch.from_numpy(img.astype(np.float32)) @abstractmethod def get_normal_map_path(self, element, view): """ Get the location of the normal info file for a given view of a given element (string). The views should be zero-indexed. Arguments: element -- the element index (integer) view -- the camera index (integer) """ pass def get_single_normal_map(self, element, view): """ Get a single normal map from the specified dataset element (3 x H x W torch tensor). Arguments: element -- the element index (integer) view -- the camera index (integer) """ normal_map_path = self.get_normal_map_path(element, view) normal_map = np.load(normal_map_path) current_scale = normal_map.shape[1] / (self.im_width * self.im_scale) target_multiple = int(self.ensure_multiple * current_scale) new_width = int(normal_map.shape[1] / target_multiple) * target_multiple new_height = int(normal_map.shape[0] / target_multiple) * target_multiple normal_map = normal_map[:new_height, :new_width, :] if self.im_width * self.im_scale < normal_map.shape[2]: normal_map = cv2.resize( normal_map, (int(self.im_width * self.im_scale), int(self.im_height * self.im_scale)), interpolation=cv2.INTER_NEAREST ) normal_map = np.transpose(normal_map, axes=(2, 0, 1)) return torch.from_numpy(normal_map.astype(np.float32)) def get_element_images(self, element): """ Get all images for the specified dataset element (N x 3 x H x W torch tensor). Arguments: element -- the element index (integer) """ views = [] for view in range(self.nr_views): views.append(self.get_single_image(element, view).unsqueeze(0)) return torch.cat(views, 0) @abstractmethod def get_depth_map_path(self, element, view, gt=True): """ Get the location of the depth map for a given view of a given element (string). The views should be zero-indexed. Should prepend depth_map_prefix to the depth subfolder. Arguments: element -- the element index (integer) view -- the camera index (integer) """ pass def get_single_depth_map(self, element, view, gt=True): """ Get a single depth map from the specified dataset element (1 x H x W torch tensor). Arguments: element -- the element index (integer) view -- the camera index (integer) """ depth_map_path = self.get_depth_map_path(element, view, gt) depth_map = np.expand_dims(np.load(depth_map_path),2) current_scale = depth_map.shape[1] / (self.im_width * self.im_scale) target_multiple = int(self.ensure_multiple * current_scale) new_width = int(depth_map.shape[1] / target_multiple) * target_multiple new_height = int(depth_map.shape[0] / target_multiple) * target_multiple depth_map = depth_map[:new_height, :new_width, :] if self.im_width * self.im_scale < depth_map.shape[1]: depth_map = cv2.resize( depth_map, (int(self.im_width * self.im_scale), int(self.im_height * self.im_scale)), interpolation=cv2.INTER_NEAREST )[None] else: depth_map = np.transpose(depth_map, axes=(2, 0, 1)) return torch.from_numpy(depth_map.astype(np.float32)) def get_single_depth_map_and_trust(self, element, view, gt=True): """ Get a single depth map from the specified dataset element (1 x H x W torch tensor). Arguments: element -- the element index (integer) view -- the camera index (integer) """ depth_map_path = self.get_depth_map_path(element, view, gt) depth_map = np.expand_dims(np.load(depth_map_path),2) trust_path = depth_map_path.replace('.npy', '.trust.npy') trust = np.expand_dims(np.load(trust_path),2) current_scale = depth_map.shape[1] / (self.im_width * self.im_scale) target_multiple = int(self.ensure_multiple * current_scale) new_width = int(depth_map.shape[1] / target_multiple) * target_multiple new_height = int(depth_map.shape[0] / target_multiple) * target_multiple depth_map = depth_map[:new_height, :new_width, :] trust = trust[:new_height, :new_width, :] if self.im_width * self.im_scale < depth_map.shape[1]: depth_map = cv2.resize( depth_map, (int(self.im_width * self.im_scale), int(self.im_height * self.im_scale)), interpolation=cv2.INTER_NEAREST )[None] trust = cv2.resize( trust, (int(self.im_width * self.im_scale), int(self.im_height * self.im_scale)), interpolation=cv2.INTER_NEAREST )[None] else: depth_map = np.transpose(depth_map, axes=(2, 0, 1)) trust = np.transpose(trust, axes=(2, 0, 1)) return (torch.from_numpy(depth_map.astype(np.float32)), torch.from_numpy(trust.astype(np.float32))) def set_depth_map_provenance(self, prefix): """ Sets the prefix for the Depth folder name. """ self.depth_map_prefix = prefix def get_element_depth_maps(self, element, gt=True): """ Get all depth maps for the specified dataset element (N x 1 x H x W torch tensor). Arguments: element -- the element index (integer) """ views = [] for view in range(self.nr_views): views.append(self.get_single_depth_map(element, view, gt=gt).unsqueeze(0)) return torch.cat(views, 0) @abstractmethod def get_element_cameras(self, element): """ Get all camera matrices for the specified dataset element (N x 3 x 4 torch tensor). Arguments: element -- the element index (integer) """ pass @abstractmethod def get_element_worldtf(self, element): """ Get the world transformation for the specified dataset element (4 x 4 torch tensor). Arguments: element -- the element index (integer) """ pass def set_neighbour_selection(self, approach): """ Set how neighbours are selected Arguments: approach -- the new approach (string, one of "closest", "furthest", "mixed") """ if approach not in ["closest", "furthest", "mixed"]: raise ValueError("Valid values for neighbour selection: 'closest', 'furthest', 'mixed'.") self._neighbour_selection = approach @abstractmethod def get_view_neighbours(self, cameras, center_view, nr_neighbours): """ Get the closest neighbours for the given view. Arguments: cameras -- the camera matrices (N x 3 x 4 torch tensor) center_view -- the selected view (integer) nr_neighbours -- the number of neighbours (integer) """ pass
87ca28c9651fca0a031acfb86356ee9c1386d9a1
c-meyer/AMfe
/src/amfe/io/mesh/base.py
4,226
3.578125
4
# Copyright (c) 2018, Lehrstuhl für Angewandte Mechanik, Technische Universität München. # # Distributed under BSD-3-Clause License. See LICENSE-File for more information # import logging from abc import ABC, abstractmethod __all__ = ['MeshReader', 'MeshConverter'] class MeshReader(ABC): """ Abstract super class for all mesh readers. TASKS ----- - Read line by line a stream (or file). - Call mesh converter functions for each line. NOTES ----- PLEASE FOLLOW THE BUILDER PATTERN! """ @abstractmethod def __init__(self, *args, **kwargs): return @abstractmethod def parse(self, builder): pass class MeshConverter: """ Super class for all mesh converters. """ def __init__(self, *args, **kwargs): return def build_no_of_nodes(self, no): """ Build number of nodes (optional) This function usually is optional. It can be used to enhance performance of the building process. This function can be used to preallocate arrays that contain the node coordinates Parameters ---------- no : int number of nodes in the mesh Returns ------- None """ pass def build_no_of_elements(self, no): """ Build number of elements (optional) This function usually is optional. It can be used to enhance performance of the building process. This function can be used to preallocate arrays that contain the element information Parameters ---------- no : int number of elements in the mesh Returns ------- None """ pass def build_node(self, idx, x, y, z): """ Builds a node Parameters ---------- idx : int ID of the node x : float X coordinate of the node y : float Y coordinate of the node z : float Z coordinate of the node Returns ------- None """ pass def build_element(self, idx, etype, nodes): """ Builds an element Parameters ---------- idx : int ID of an element etype : str valid amfe elementtype (shape) string nodes : iterable iterable of ints describing the connectivity of the element Returns ------- None """ pass def build_group(self, name, nodeids, elementids): """ Builds a group, i.e. a collection of nodes and elements Parameters ---------- name: str Name identifying the node group. nodeids: list List with node ids. elementids: list List with element ids. Returns ------- None """ pass def build_mesh_dimension(self, dim): """ Builds the dimensino of the mesh (optional) If this method has not been called during build process, a mesh dimension of 3 is assumed Parameters ---------- dim : int {2, 3} dimension of the mesh Returns ------- None """ pass def build_tag(self, tag_name, values2elements, dtype=None, default=None): """ Builds a tag with following dict given in tag_dict Parameters ---------- tag_name: str tag name values2elements: dict dict with following format: { tagvalue1 : [elementids], tagvalue2 : [elementids], ... } dtype: { int, float, object } data type for this tag. Only int, float or object is allowed default: default value for elementids with no tagvalue Returns ------- None """ pass def return_mesh(self): """ Returns the Mesh or the file pointer or 0 Returns ------- Object """ return None
105534f9cebb518e85cc98d8548b841f42fc26cf
aacs0130/uttapam
/2022_python_workout/04.py
895
3.765625
4
def hex_to_dec(_hex) -> int: #Input is without 0x, and only use 0-9, and A-F _dec = 0 hex_map = { 'A':10, 'B':11, 'C':12, 'D':13, 'E':14, 'F':15 } for chat in _hex: _dec *=16 if chat >= '0' and chat <= '9' : _dec+= int(chat) elif chat >= 'A' and chat <= 'F' : _dec+= hex_map[chat] return _dec if __name__ == '__main__': _hex = '6' answer = 6 _dec = hex_to_dec(_hex) print('in: %s, out: %s, answer: %s\n' % (_hex, _dec, answer)) _hex = '0' answer = 0 _dec = hex_to_dec(_hex) print('in: %s, out: %s, answer: %s\n' % (_hex, _dec, answer)) _hex = 'F' answer = 15 _dec = hex_to_dec(_hex) print('in: %s, out: %s, answer: %s\n' % (_hex, _dec, answer)) _hex = '2A' answer = 42 _dec = hex_to_dec(_hex) print('in: %s, out: %s, answer: %s\n' % (_hex, _dec, answer))
2a79d1f51e7a3be102ae575f3e1ee49381438aaa
zausnerd/technical_questions
/decode_strings.py
1,034
4.125
4
# # Question 2 -- decodeString(s): Given an encoded string, return its corresponding decoded string. # The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is repeated exactly k times. Note: k is guaranteed to be a positive integer. # For s = "4[ab]", the output should be decodeString(s) = "abababab" # For s = "2[b3[a]]", the output should be decodeString(s) = "baaabaaa" def decodeString(string): multiplier = '' current_string = '' for idx, char in enumerate(string): if char.isdigit(): multiplier += char elif char.isalpha(): current_string += char elif char == '[': substring = decodeString(string[idx + 1:]) if multiplier == '': multiplier = '1' current_string += int(multiplier) * substring return current_string return current_string print(decodeString("2[b3[a]]")) print(decodeString("4[ab]")) print(decodeString("[abcd]")) print(decodeString(""))
629995d7cd2cf157b0ff97dcd7039e5dcb396c60
parvez-golam/Python
/Alphabet_Count.py
341
3.8125
4
##################################################### # Alphabet count #################################################### text = \ """ The quick brown fox jumped over the lazy dog, so he did . """ count = 0 for c in text : if c. isalpha (): count = count + 1 print("Letter count is ", count)
eb52dad63b11368d70ee4dcb543b722b0e2f25f2
Njiiii/PrimeFactorizator
/PrimeFactorizator/PrimeFactorizator.py
3,022
4.46875
4
#Every positive whole number is possible to show as a addition between 2 or more prime numbers (for example 30 = 2 * 3 * 5). #This program is designed to show that addition. import math import collections #Prime factors of an integer goes to this list. #Final output is made with this list. factors = [] #Function to check if number given by user is a prime number. def is_this_prime(n): if n >= 2: for x in range(2, int(n)): if not (n % x): return False else: return True #This function breaks down the integer given by user to prime numbers def prime_factorization(x): for i in range(2, x): while is_this_prime(i) == True and x % i == 0: factors.append(i) x = x / i #If x is a prime number, we only append x and an extra value 1 to factors if is_this_prime(x) == True: factors.append(x) #This if-check makes sure that we append that extra 1 x given by user is a prime number #Otherwise this can lead to situations like 1234 = 2 * 1 * 617, where we don't need the extra 1 if len(factors) == 1: factors.append(1) factors.sort() #This function asks user to give a number. def ask_for_input(): a = int(input("Give a number, please: ")) return a #Now we need function to make the final output from factors list def make_output(factors): d = {x:factors.count(x) for x in factors} #keys are the prime numbers in the factors list keys = [] [keys.append(a) for a in d.keys()] #values are the number of duplicates in factors list values = [] [values.append(b) for b in d.values()] #E.g. if factors had [5, 5, 5, 7, 7], then keys would be [5, 7] and values would be [3, 2] #We'll use keys and values to create the final output: 6125 = 5^3 * 7^2 output = [] #We put x^y into output only if y < 1 #x^1 is always x so it's redundant info for i in range(len(keys)): if values[i] != 1: output.append(str(keys[i]) + "^" + str(values[i])) else: output.append(str(keys[i])) #As an extra flair, it's nice if we show output as a = b^c * d #So l is the same as the integer user gives in ask_for_input() and which is used in prime_factorization(x) l = 1 for j in range(len(factors)): l = l * factors[j] print(str(l) + " = ", end = "") print(*output, sep = " * ") #Finally we have the main-class that calls everything nicely in the right order def pf_main(): a = int(ask_for_input()) if a > 1 and a <= 25000: prime_factorization(a) make_output(factors) if a > 25000: print("Anything over 25000 is too heavy to process") if a <= 1: print("Negative integers, 0 and 1 are not allowed") pf_main()
ce786f81bc69ed1d224937b3527a4d25445622fe
Modrisco/OJ-questions
/Project Euler/001-100/017.py
1,695
3.609375
4
one_to_nine_digits =['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine'] ten_to_twenty_digits =['Ten','Eleven','Twelve','Thirteen','Fourteen','Fifteen','Sixteen','Seventeen','Eighteen','Nineteen'] twenty_to_hundred_digits = ['Twenty','Thirty','Forty','Fifty','Sixty','Seventy','Eighty','Ninety'] def digit_to_letter(n): letter = '' if n == 0: return one_to_nine_digits[0] while n > 0: if n > 0 and n < 10: letter += one_to_nine_digits[n] n -= n if n >= 10 and n < 20: letter += ten_to_twenty_digits[n - 10] n -= n if n >= 20 and n < 100: a = n // 10 letter += twenty_to_hundred_digits[a-2] n -= a * 10 if n >= 100 and n < 1000: a = n // 100 if n % 100 == 0: letter += one_to_nine_digits[a] + 'Hundred' else: letter += one_to_nine_digits[a] + 'HundredAnd' n -= a * 100 if n >= 1000 and n < 1000000: a = n // 1000 letter += digit_to_letter(a) + 'Thousand' n -= a * 1000 if n >= 1000000 and n < 1000000000: a = n // 1000000 letter += digit_to_letter(a) + 'Million' n -= a * 1000000 if n >= 1000000000 and n < 1000000000000: a = n // 1000000000 letter += digit_to_letter(a) + 'Billion' n -= a * 1000000000 if n == 1000000000000: letter = 'OneTrillion' n -= 1000000000000 return letter total_length = 0 for i in range(1, 1001): total_length += len(digit_to_letter(i)) print(total_length)
ec83a246b9828dc4cc6b1de4e47de7af79719ba5
Roctey/CookBook
/exercise_0103.py
931
3.828125
4
from collections import deque def search(lines, pattern, history=5): previous_lines = deque(maxlen=history) for line in lines: if pattern in line: yield line, previous_lines previous_lines.append(line) # Example use on a file if __name__ == '__main__': with open(r'../cookbook/somefile.txt')as f: for line, prevlines in search(f, 'python', 5): for pline in prevlines: print(pline, end='') print(line, end='') print('-' * 20) q = deque(maxlen=3) q.append(1) q.append(2) q.append(3) print(q) # deque([1, 2, 3], maxlen=3) q.append(4) print(q) # deque([2, 3, 4], maxlen=3) q.append(5) print(q) # deque([3, 4, 5], maxlen=3) q = deque() q.append(1) q.append(2) q.append(3) print(q) # deque([1, 2, 3]) q.appendleft(4) print(q) # deque([4, 1, 2, 3]) q.pop() print(q) # deque([4, 1, 2]) q.popleft() print(q) # deque([1, 2])
85f57e07928c55b9e23e5fe4da30f3af9a7f6f70
Mayuri0612/Data_Structures-Python
/DFS/1.py
740
3.6875
4
#implementation of DFS in a directed graph # trav_time = {} #for other programs time will be used #time = 0 def DFS(u): color[u] = "G" dfs_output.append(u) for v in ad_list[u]: if color[v] == "W": parent[v] = u DFS(v) color[u] = "B" ad_list1 = { "A" : ["B", "C"], "B" : ["D", "E"], "C" : ["B", "F"], "D" : [], "E" : ["F"], "F" : [] } ad_list = { "A" : ["B"], "B" : ["A","D", "E"], "C" : ["F"], "D" : ["B"], "E" : ["B"], "F" : ["C"] } #main function color = {} parent = {} dfs_output = [] for i in ad_list.keys(): color[i] = "W" parent[i] = None for u in ad_list.keys(): if color[u] == "W": DFS(u) print(dfs_output)
d6c972d955e2789e6c000205aa7ff22215911f9a
skafis/python-essentials
/search.py
448
4.1875
4
import re with open('text.txt')as text: # text = f.readlines() #text = input("enter text or paragraph to search\n") find = input("enter the word you want to search\n") for line in text: if find in line: print (line) # print (text) # if re.search(r"[find]",text, re.M): # print (find + " has been found") # else: # print("sorry "+find+ " cant be found try another word")
5e108e2ac9332711b318b2e57a1ab78464236647
katie1205/Properties_of_Numbers
/evens_odds.py
1,580
4.6875
5
#This function takes an argument and returns 'even', 'odd', or 'neither' using the following: #if the number is divisible by 2, it is even #all other numbers are either non-integers or odd def even_or_odd(x): return 'even' if x % 2 == 0 else 'odd' if type(x) == int else 'neither' #This function takes two numbers, adds them, applies the even_or_odd function, and prints statements #about the results def sum_even_or_odd(a,b): c = a + b print "%r is the sum of %r and %r" % (c, a, b) if c == int(c): print "%r is %s, %r is %s, and %d is %s." % (a, even_or_odd(a), b, even_or_odd(b), c, even_or_odd(c)) else: print "The sum is not an integer. \n" return c; #Test it out: sum_even_or_odd(7,9) #it worked sum_even_or_odd(6,4) #it worked sum_even_or_odd(5.4,2.6) #it worked #NOTE: Does NOT work on strings #sum_even_or_odd('sarah','john')<---- this led to an error #This function takes two numbers, multiplies them, applies the even_or_odd function, and prints statements #about the results def product_even_or_odd(a,b): c = a * b print "%r is the product of %r and %r" % (c, a, b) if c == int(c): print "%r is %s, %r is %s, and %d is %s." % (a, even_or_odd(a), b, even_or_odd(b), c, even_or_odd(c)) else: print "The product is not an integer. \n" return c; #Test it out product_even_or_odd(-4,-3) #it worked product_even_or_odd(5,5) #it worked product_even_or_odd(0,5) #it worked #NOTE: It only works on integers and floats! #product_even_or_odd('sarah','john') #<---this led to an error
314ce038404f842fc43c0363b84825d969139c42
NextNight/LeetCodeAndStructAndAlgorithm
/sort/select_sort.py
737
4.03125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Date : 2019-02-19 @Author : Kaka @File : select_sort.py @Software: PyCharm @Contact : @Desc : 选择排序 """ def select_sort(nums): '''选择排序:''' if nums==None or len(nums)<=1: return nums for i in range(len(nums)): min_index=i # print("i:%s" % i) for j in range(i+1,len(nums)): if nums[j]<nums[min_index]: min_index = j if min_index!=i: nums[i],nums[min_index] = nums[min_index],nums[i] print("i:%s\t min:%s\t nums:%s" % (i,min_index,nums,)) if __name__ == '__main__': nums = [17, 23, 20, 14, 12, 25, 1, 20, 81, 14, 11, 12] select_sort(nums)
c29eef260398875c093b7e28d22fe52240e3625f
jazzzest79/everyonepython
/08B-ifelse.py
613
3.953125
4
# if 판단문과 if-else 로 판단하는 프로그램 a = 3 # 변수 a 에 3을 저장합니다. if a ==2: # a 가 2 와 같은지 비교합니다. print ("A") # False 이므로 이 부분은 실행 되지 않습니다. if a == 3: # a 가 3 과 같은지 비교합니다. print ("B") # True 이므로 이 부분이 실행됩니다. if a == 4: # a 가 4 와 같은지 비교합니다. print ("C") # False 이므로 이 부분은 실행 되지 않습니다. else: print ("D") # print("C") 대신 이 부분이 실행됩니다.
95b006d1e0da62b097588c2ad840098ea9fd30b7
splotchysnow/GuanAdventCode2020
/Day1/Report Repair.py
713
3.546875
4
# TO read a file: with open("Day1/file.txt") as f: data = f.readlines() #Two For Loops to find all value that add up to be 2020; # for i in data: # for j in data: # if (int(i) + int(j) == 2020): # print(int(i) * int(j)) # I = i # break # if (int(i) == int(I)): # break def main(): I = -999 for i in data: for j in data: for z in data: if (int(i) + int(j) + int(z) == 2020): print(int(i) * int(j) * int(z)) I = i break if (int(i) == int(I)): break if (int(i) == int(I)): break main()
a4e1804071fce4a4356b31542662f3dbed954f4b
StanislavHorod/LV-431-PythonCore
/lec 08.15/CW-6.py
2,843
4.21875
4
def summan(a, b): """this func of the summa 2 numbers""" return a+b def diff(a, b): """this func for the difference between 2 numbers""" return a-b def multipli(a, b): """this func for multiplication of the 2 numbers""" return a*b def div(a, b): """this func for division of the a on the b""" return a/b def square(a, b): """this func for square a on b""" return a**(1/b) def degree(a, b): """this func for finding of the a degree b""" return a**b try: def changer(): variant= int(input("Greatings\nFor getting summa write 1\nFor getting difference write 2" + "\nFor getting multiplication write 3\nFor getting division write 4"+ "\nFor getting square write 5\nFor getting degree write 6"+ "\nFor exit write 7")) if variant == 1: a = int(input("You choose summa\nWrite first number: ")) b = int(input("Write second number: ")) res = str(summan(a=a, b=b)) print("The resault of the summa between {} and {} is {}".format(a, b, res)) elif variant == 2: a = int(input("You choose different\nWrite first number: ")) b = int(input("Write second number: ")) res = str(diff(a=a, b=b)) print("The resault of the different between {} and {} is {}".format(a, b, res)) elif variant == 3: a = int(input("You choose multiplication\nWrite first number: ")) b = int(input("Write second number: ")) res = str(multipli(a=a, b=b)) print("The resault of the multiplication between {} and {} is {}".format(a, b, res)) elif variant == 4: a = int(input("You choose division\nWrite first number: ")) b = int(input("Write second number: ")) res = str(div(a=a, b=b)) print("The resault of the division between {} and {} is {}".format(a, b, res)) elif variant == 5: a = int(input("You choose square\nWrite first number: ")) b = int(input("Write degree number: ")) res = str(div(a=a, b=b)) print("The resault of the square between {} degree {} is {}".format(a, b, res)) elif variant == 6: a = int(input("You choose degree\nWrite first number: ")) b = int(input("Write power number: ")) res = str(div(a=a, b=b)) print("The resault the degree between {} on {} is {}".format(a, b, res)) elif variant == 7: print("Thanks for using our calculator!") return 1 else: raise Exception("wrong choise") except ValueError: print("write numbers, not letters") except Exception as exi: print(exi) i = 0 while i!=1: looker = changer() if looker == 1: i = 1
012c628e658f47fb35958dd65744db30574e5ca6
smallbee3/algorithm-problems
/python/codesignal/8_matrixElementSum.py
2,847
4.15625
4
""" 8_matrixElementSum After they became famous, the CodeBots all decided to move to a new building and live together. The building is represented by a rectangular matrix of rooms. Each cell in the matrix contains an integer that represents the price of the room. Some rooms are free (their cost is 0), but that's probably because they are haunted, so all the bots are afraid of them. That is why any room that is free or is located anywhere below a free room in the same column is not considered suitable for the bots to live in. Help the bots calculate the total price of all the rooms that are suitable for them. Example For matrix = [[0, 1, 1, 2], [0, 5, 0, 0], [2, 0, 3, 3]] the output should be matrixElementsSum(matrix) = 9. Here's the rooms matrix with unsuitable rooms marked with 'x': [[x, 1, 1, 2], [x, 5, x, x], [x, x, x, x]] Thus, the answer is 1 + 5 + 1 + 2 = 9. For matrix = [[1, 1, 1, 0], [0, 5, 0, 1], [2, 1, 3, 10]] the output should be matrixElementsSum(matrix) = 9. Here's the rooms matrix with unsuitable rooms marked with 'x': [[1, 1, 1, x], [x, 5, x, x], [x, 1, x, x]] Note that the free room in the first row make the full column unsuitable for bots. Thus, the answer is 1 + 1 + 1 + 5 + 1 = 9. """ """ 181208 Time : 17 min Subject - Consider two cases in one operation (1 - sum, 2 - change the price of current room) Learning 1. low and column in [[1, 1, 1, x], [x, 5, x, x], [x, 1, x, x]] len(matrix) -> low, len(matrix[i]) -> column 2. Step by step e.g. 1) Changing all column value into '0' if '0' exist in the column -> Fail 2) Changing current column value into '0' if previous column element is '0' -> Success """ def matrixElementsSum(matrix): price_sum = 0 # for i in range(len(matrix)): # for j in range(len(matrix[i])): # if matrix[i][j] == 0: # for k in range(i, len(matrix)): # matrix[k][j] = 0 # # I even gave up finishing writing this code because it is already takes O(n³) for i in range(len(matrix)): for j in range(len(matrix[i])): # row == 0 if i == 0: price_sum += matrix[i][j] continue # if previous row was not free (This is possible because of the below code) if matrix[i-1][j] != 0: price_sum += matrix[i][j] # change the price of current room, matrix[i][j] for the next loop operation else: matrix[i][j] = 0 print(matrix) return price_sum # matrix = [[0, 1, 1, 2], # [0, 5, 0, 0], # [2, 0, 3, 3]] matrix = [[1, 1, 1, 0], [0, 5, 0, 1], [2, 1, 3, 10]] result = matrixElementsSum(matrix) print(result)
07e570ab67da18fffb3a3837595f2064578b9884
oliveiralecca/cursoemvideo-python3
/arquivos-py/CursoEmVideo_Python3_AULAS/aula-20c.py
263
3.75
4
def contador(* num): # print(num) ELE CRIA UMA TUPLA COM OS VALORES PASSADOS, ENTÃO POSSO FAZER TUDO QUE FAÇO COM UMA TUPLA for valor in num: print(f'{valor} ', end='') print('FIM!') contador(2, 1, 7) contador(8, 0) contador(4, 4, 6, 2)
b7f20ea4d03def31a4706de5c93264db812d762f
manikanta-MB/IPL-Dataset-Analytics
/Code/matches_played_by_team_by_season.py
4,205
4.09375
4
""" This Program displays the Stacked bar chart for the no.of matches played by each team in each IPL Season. To solve this problem first i divided it into 3 modules. 1.getting no.of matches played by each team seasonwise (but not ordered in ascending order of season year) 2.ordering the data(got in 1st module) in ascending order of season year. 3.Plotting the data(got in 2nd module) with the help of matplotlib library. """ # importing the required libraries to deal with csv files and to plot the data. import csv import os from matplotlib import pyplot as plt def get_team_season_matches(filename): """Creating the data of no.of matches played by each team in each season, from scratch data file, and returning it. """ team_season_matches={} seasons = set() with open(filename,"r",encoding="utf8") as file_obj: matches_reader = csv.DictReader(file_obj) for current_match_info in matches_reader: season = int(current_match_info["season"].strip()) seasons.add(season) team1 = current_match_info["team1"].strip() team2 = current_match_info["team2"].strip() if team1 not in team_season_matches: team_season_matches[team1] = {} team_season_matches[team1][season] = team_season_matches[team1].get(season,0)+1 if team2 not in team_season_matches: team_season_matches[team2] = {} team_season_matches[team2][season] = team_season_matches[team2].get(season,0)+1 seasons = sorted(list(seasons)) return team_season_matches,seasons def order_matches_seasonwise(team_season_matches,seasons): """ordering the teams and correpsonding no.of matches by Seasonwise""" teams_and_matches_seasonwise = {} for team,season_data in team_season_matches.items(): teams_and_matches_seasonwise[team]=[] for season in seasons: teams_and_matches_seasonwise[team].append(season_data.get(season,0)) # deleting duplicate "Rising Pune Supergiant" team. no_seasons = len(seasons) for i in range(no_seasons): no_matches = teams_and_matches_seasonwise['Rising Pune Supergiant'][i] teams_and_matches_seasonwise['Rising Pune Supergiants'][i] += no_matches del teams_and_matches_seasonwise['Rising Pune Supergiant'] return teams_and_matches_seasonwise def plot_the_data(teams_and_matches_seasonwise,seasons): """Plotting the Sorted data""" no_seasons = len(seasons) # it will be useful for calculating the ending position of the previous bar. prev_list = [0]*no_seasons fig = plt.figure() fig.set_figheight(12) fig.set_figwidth(12) fig_obj = fig.add_subplot(111) # Shrink current axis by 20% box = fig_obj.get_position() fig_obj.set_position([box.x0, box.y0, box.width * 0.8, box.height]) #Hardcoding the names of colors for each team colors = [ "fuchsia","maroon","red","yellow","blue","lime","purple", "black","green","olive","teal","aqua","navy","grey" ] # Creating the bar and Placing it to the right of previous team bar in each season. color_index=0 for team,current_team_matches in teams_and_matches_seasonwise.items(): color_name = colors[color_index] fig_obj.barh(seasons,current_team_matches,left=prev_list,label = team,color=color_name) prev_list = [prev_list[i]+current_team_matches[i] for i in range(no_seasons)] color_index += 1 plt.title("Number of matches played by each team Seasonwise",fontweight='bold',fontsize=20) plt.ylabel("Seasons",fontweight='bold',fontsize=15) plt.xlabel("number of matches played",fontweight='bold',fontsize=15) # Put a legend to the right of the current axis fig_obj.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.show() def execute(): """It will call all helper functions to achieve our aim""" team_season_matches,seasons = get_team_season_matches(os.getcwd()+"/../Data/matches.csv") teams_and_matches_seasonwise = order_matches_seasonwise(team_season_matches,seasons) plot_the_data(teams_and_matches_seasonwise,seasons) execute()
7a9d20a61e07d63cbe101ed29785c4c010a5c296
bmlegge/CTI110
/P4HW1_DistanceTraveled_Legge.py
416
4.09375
4
#CTI-110 #P4HW1: Distance Traveled #Bradley Legge #3/25/2018 count = 0 hours = 0 print("What is the speed of the vehicle in mph? ") speed = int(input()) print("How many hours has it traveled? ") time = int(input()) while count < time: hours = hours + 1 distance = hours * speed print("Hour Distance Traveled") print(hours," ", distance) count = count + 1
1bb346b3cdd6ca9f1624799c1d95e5328561f4b5
ihf-code/python
/session_09/answers/A6.py
553
4.15625
4
# A6 - Create a function that can accept a series of numbers and a mathematical # operand. Return the result of calculating the expression. E.g.: # calculate(1, 2, 3, 4, operand = "multiply") # calculate(65, 200, 84, 12, operand = "add") def calculator(*args, operand = "+"): total = args[0] for arg in args[1:]: if operand == "+": total += arg elif operand == "*": total *= arg return total print(calculator(1, 2)) print(calculator(1, 2, 3, 4, 5, 6)) print(calculator(4, 5, operand = "*"))
08021f4c8918e815a8fff514006d0a61c666076f
fengmikaelson/learn-python-in-a-hard-way
/ex20.py
1,167
3.96875
4
# -*- coding: utf-8 -*- # @Author: fengm # @Date: 2016-12-01 10:50:49 # @Last Modified by: fengm # @Last Modified time: 2016-12-02 09:54:23 from sys import argv script, input_file = argv def print_all(f): print(f.read()) # seek() 方法 # fileObject.seek(offset[, whence]) # 参数 # offset -- 开始的偏移量,也就是代表需要移动偏移的字节数 # whence:可选,默认值为0。给offset参数一个定义,表示要从哪个位置开始偏移;0代表从文件开头开始算起,1代表从当前位置开始算起,2代表从文件末尾算起。 def rewind(f): f.seek(0) def print_a_line(line_count, f): print(line_count, f.readline()) current_file = open(input_file) print("first let's print the whole file:\n") print_all(current_file) print("now let's rewind,kind of like a tape") rewind(current_file) print("let's print three lines:") current_line = 1 print_a_line(current_line, current_file) # print(current_line) current_line = current_line + 1 print_a_line(current_line, current_file) # print(current_line) current_line = current_line + 1 print_a_line(current_line, current_file) # print(current_line)
0ea967100c7703a8af06a69a9d70ddad6d9b4e65
pengwork/algorithm
/4.py
387
3.71875
4
# 1代表黑色,0代表白色 seq = [1, 1, 0, 1, 0, 0, 0, 1] for k in range(len(seq)-1): # 点之间的间隔 最小为1 最大为序列长度减1 for i in range(len(seq) - k): if (seq[i] == 1 and seq[i+k] == 0) or (seq[i] == 0 and seq[i+k] == 1): print(i+1,"和",i+k+1,"为一对") seq[i] = float("inf") seq[i+k] = float("inf")
3881106342ff484de70d7afd3e258ab865faca3c
Corderodedios182/Juego_Othello
/Juego_Othello.py
17,979
3.9375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: Carlos Roberto Flores Luna Description : Juego Othello desde terminal contra una IA """ #En las primeras lineas del codigo defino las funciones que posterirmente ocupo para jugar. #Importando Modulos import random import sys ######################################################### #La estructura del Tablero de Datos del Tablero de Juego# ######################################################### #La estructura es una lista de listas. La lista de listas se crea para que tablero[x][y] represente al caracter en la posicion #x sobre el eje X (izquierda a derecha) y la posicion y sobre el eje Y (arriba hacia abajo). #La funcion dibujarTablero() imprime el tablero actual del juego basado en la estrucutra de datos en la variable tablero. def dibujarTablero(tablero): # Esta funcion dibuja el tablero recibido. Devuelve None LÍNEAH = ' +---+---+---+---+---+---+---+---+' LÍNEAV = ' | | | | | | | | |' print(' 1 2 3 4 5 6 7 8') print(LÍNEAH) for y in range(8): print(LÍNEAV) print(y+1, end=' ') for x in range(8): print('| %s' % (tablero[x][y]), end=' ') print('|') print(LÍNEAV) print(LÍNEAH) #Permite comenzar un nuevo juego def reiniciarTablero(tablero): # Deja en blanco el tablero recibido como argumento, excepto la posición inicial for x in range(8): for y in range(8): tablero[x][y] = ' ' # Piezas iniciales: tablero[3][3] = 'X' tablero[3][4] = 'O' tablero[4][3] = 'O' tablero[4][4] = 'X' #Crea una nueva estructura de datos tablero y la devuelve, crea las 8 listas internas. Los espacios representan un tablero de juego completamente vacio #Lo que la variable tablero termina siendo es una lista de 8 listas, y cada una de esas listas tiene 8 cadenas. El resultado son 64 cadenas '' con un caracter espacio. def obtenerNuevoTablero(): # Crea un tablero nuevo, vacío. tablero = [] for i in range(8): tablero.append([' '] * 8) return tablero ############################################################################################################################################################# #Comprobando si una Jugada es Válida #Dada una estructura de datos tablero, la baldosa del jugador y la coordenadas XY de la jgada del jugador, esJugadaVálida() devuelve True si las reglas de #Othello permiten una jugada en esas coordenadas y False en caso contrario. # #1) Pertenecer al tablero # #2) Convertir (tocar) almenos una pieza del otro jugador ############################################################################################################################################################# def esJugadaVálida(tablero, baldosa, comienzox, comienzoy): # Devuelve False si la jugada del jugador en comienzox, comienzoy es invalida # Si es una jugada válida, devuelve una lista de espacios que pasarían a ser del jugador si moviera aquí. #Comprueba si las coordenadas XY estan fuera del tablero, o si el espacio no esta vacio. estanEnTablero() es una funcion definida mas adelante en el programa #que se asegura de que el valor de ambas coordenadas X e Y este comprendido entre 0 y 7. if tablero[comienzox][comienzoy] != ' ' or not estáEnTablero(comienzox, comienzoy): #Validamos que la jugada se encuentra dentro del tablero return False tablero[comienzox][comienzoy] = baldosa # coloca temporariamente la baldosa sobre el tablero. if baldosa == 'X': otraBaldosa = 'O' else: otraBaldosa = 'X' baldosasAConvertir = [] #El bucle for nos indica las direcciones que puede moverse una jugada dada for direcciónx, direccióny in [[0, 1], [1, 1], [1, 0], [1, -1], [0, -1], [-1, -1], [-1, 0], [-1, 1]]: #Se modifican las variables x e y para moverse en las dirreciones determinadas por direccionx y direcciony. x, y = comienzox, comienzoy x += direcciónx # primer paso en la dirección y += direccióny # primer paso en la dirección #Para que sea una jugada valida: #1)Pertenecer al tablero if estáEnTablero(x, y) and tablero[x][y] == otraBaldosa: # Hay una pieza perteneciente al otro jugador al lado de nustra pieza x += direcciónx y += direccióny if not estáEnTablero(x, y): continue #2) Convertir piezas del otro jugador while tablero[x][y] == otraBaldosa: x += direcciónx y += direccióny if not estáEnTablero(x, y): # sale del bucle while y continua en el bucle for. break if not estáEnTablero(x, y): continue if tablero[x][y] == baldosa: # Hay fichas a convertir. Caminar en dirección opuesta hasta llegar al casillero original, registrando todas las posiciones en el camino. while True: x -= direcciónx y -= direccióny if x == comienzox and y == comienzoy: break baldosasAConvertir.append([x, y]) tablero[comienzox][comienzoy] = ' ' # restablecer el espacio vacío if len(baldosasAConvertir) == 0: # Si no se convirtió ninguna baldosa, la jugada no es válida. return False return baldosasAConvertir def estáEnTablero(x, y): # Devuelve True si las coordenadas se encuentran dentro del tablero return x >= 0 and x <= 7 and y >= 0 and y <=7 #################################################################################################################################################### #OBTENIENDO UNA LISTA CON TODAS LAS JUGADAS VALIDAS # #Aqui se comienza la creacion del Arbol de Juego con las posibles jugadas que se pueden realizar en el siguiente estado # #La funcion obtenerJugadasValidas(), devuelves una lista de listas de dos elementos. Estas listas contienen las coordenadas XY de todas las jugadas #validas para el jugador correspondiente (sea jugador o computadora). #Esta funcion usa bucles anidados para comprobar cada par de coordenadas XY (las 64 combinaciones posibles) llamando a esJugadaValida() en cada iteracion. #Con esto se representa el Arbol de Juego, visualizando las jugadas con la funcion obtenerTableroConJugadasValidas() ######################################################################################################################################################## def obtenerJugadasVálidas(tablero, baldosa): # Devuelve una lista de listas [x,y] de jugadas válidas para el jugador en el tablero dado. jugadasVálidas = [] for x in range(8): for y in range(8): if esJugadaVálida(tablero, baldosa, x, y) != False: jugadasVálidas.append([x, y]) return jugadasVálidas #Representacion del Arbol de Juegadas, mas adelante especificamos la mejor jugada para la maquina. def obtenerTableroConJugadasVálidas(tablero, baldosa): # Devuelve un nuevo tablero, marcando con "." las jugadas válidas que el jugador puede realizar. réplicaTablero = obtenerCopiaTablero(tablero) for x, y in obtenerJugadasVálidas(réplicaTablero, baldosa): réplicaTablero[x][y] = '.' return réplicaTablero ######################################################################################### #FUNCIONES DE INTERACCION #Obteniendo el Puntaje del Tablero de Juego #Obteniendo la Opcion de Baldosa del Jugador #Determinado Quién Comienza #Preguntar al Jugador si Quiere Jugar de Nuevo #Mostrar Puntajes actuales del juego ######################################################################################## def obtenerPuntajeTablero(tablero): # Determina el puntaje contando las piezas. Devuelve un diccionario con claves 'X' y 'O'. puntajex = 0 puntajeo = 0 for x in range(8): for y in range(8): if tablero[x][y] == 'X': puntajex += 1 if tablero[x][y] == 'O': puntajeo += 1 return {'X':puntajex, 'O':puntajeo} def ingresarBaldosaJugador(): # Permite al jugador elegir que baldosa desea ser. # Devuelve una lista con la baldosa del jugador como primer elemento y el de la computadora como segundo. baldosa = '' while not (baldosa == 'X' or baldosa == 'O'): print('¿Deseas ser X ó O?') baldosa = input().upper() # El primer elemento en la lista es la baldosa del juegador, el segundo es la de la computadora. if baldosa == 'X': return ['X', 'O'] else: return ['O', 'X'] def quiénComienza(): # Elije al azar qué jugador comienza. if random.randint(0, 1) == 0: return 'computadora' else: return 'jugador' def jugarDeNuevo(): # Esta función devuelve True si el jugador quiere jugar de nuevo, de lo contrario devuelve False. print('¿Quieres jugar de nuevo? (sí o no)') return input().lower().startswith('s') def mostrarPuntajes(baldosaJugador, baldosaComputadora): # Imprime el puntaje actual. puntajes = obtenerPuntajeTablero(tableroPrincipal) print('Tienes %s puntos. La computadora tiene %s puntos.' % (puntajes[baldosaJugador], puntajes[baldosaComputadora])) ######################################################################################################################################### #Funciones para el DESAROOLLO DEL JUEGO #hacerJugada (colocar una baldosa en el tablero y convertir otras fichas de acuerdo con las reglas del reversi) #obtenerCopiaTablero (hace una copia para hacer pruebas sin afectar el tablero final) #esEsquina #obtenerJugadaJugador (Almacenar la jugada del jugador) ######################################################################################################################################### def hacerJugada(tablero, baldosa, comienzox, comienzoy): # Coloca la baldosa sobre el tablero en comienzox, comienzoy, y convierte cualquier baldosa del oponente. # Devuelve False si la jugada es inválida, True si es válida. baldosasAConvertir = esJugadaVálida(tablero, baldosa, comienzox, comienzoy) if baldosasAConvertir == False: return False tablero[comienzox][comienzoy] = baldosa for x, y in baldosasAConvertir: tablero[x][y] = baldosa return True def obtenerCopiaTablero(tablero): # Duplica la lista del tablero y devuelve el duplicado. réplicaTablero = obtenerNuevoTablero() for x in range(8): for y in range(8): réplicaTablero[x][y] = tablero[x][y] return réplicaTablero def esEsquina(x, y): # Devuelve True si la posicion es una de las esquinas. return (x == 0 and y == 0) or (x == 7 and y == 0) or (x == 0 and y == 7) or (x == 7 and y == 7) def obtenerJugadaJugador(tablero, baldosaJugador): # Permite al jugador tipear su jugada. # Devuelve la jugada como [x, y] (o devuelve las cadenas 'pistas' o 'salir') CIFRAS1A8 = '1 2 3 4 5 6 7 8'.split() while True: print('Ingresa tu jugada en este orden xy ejemplo 46, si deseas terminar el juego solo ingresa la palabra salir, o la paralabra pistas para activar/desactivar las pistas.') jugada = input().lower() if jugada == 'salir': return 'salir' if jugada == 'pistas': return 'pistas' if len(jugada) == 2 and jugada[0] in CIFRAS1A8 and jugada[1] in CIFRAS1A8: x = int(jugada[0]) - 1 y = int(jugada[1]) - 1 if esJugadaVálida(tablero, baldosaJugador, x, y) == False: continue else: break else: print('Esta no es una jugada válida. Ingresa la coordenada x (1-8), luego la coordenada y (1-8).') print('Por ejemplo, 81 corresponde a la esquina superior derecha.') return [x, y] ######################################################################################################## #Heuristica con busqueda informada #La maquina analiza los posibles estados siguientes y en base a ese conocimiento toma la mejor opcion #1) Ejecuta las posibles jugadas #2) Cuenta las fichas convertidas en cada jugada #3) Se queda con la que genere un mayor numero de fichas a su favor ######################################################################################################### def obtenerJugadaComputadora(tablero, baldosaComputadora): # Dado un tablero y la baldosa de la computadora, determinar dónde # jugar y devolver esa jugada como una lista [x, y]. if dificultad == 'Novato': #Solo toma la primera jugada que le aparesca en jugadasPosibles jugadasPosibles = obtenerJugadasVálidas(tablero, baldosaComputadora) # ordena al azar el orden de las jugadas posibles random.shuffle(jugadasPosibles) for x, y in jugadasPosibles: if esEsquina(x, y): return [x, y] return jugadasPosibles[0] elif dificultad == 'Intermedio': #Juega la jugada que conviera mayor numero de piezas jugadasPosibles = obtenerJugadasVálidas(tablero, baldosaComputadora) # ordena al azar el orden de las jugadas posibles random.shuffle(jugadasPosibles) # siempre jugar en una esquina si está disponible. for x, y in jugadasPosibles: if esEsquina(x, y): return [x, y] # Recorrer la lista de jugadas posibles y recordar la que da el mejor puntaje ################################################################### #Algoritmo IA para jugar contra la maquina #Analizando las jugadas y se queda con la que mejor puntaje ################################################################### mejorPuntaje = -1 for x, y in jugadasPosibles: réplicaTablero = obtenerCopiaTablero(tablero) hacerJugada(réplicaTablero, baldosaComputadora, x, y) puntaje = obtenerPuntajeTablero(réplicaTablero)[baldosaComputadora] if puntaje > mejorPuntaje: mejorJugada = [x, y] mejorPuntaje = puntaje return mejorJugada else: return "dificultad no valida" ##################### #Ejecucion del juego# ##################### print('¡Bienvenido a Reversi!') while True: # Reiniciar el tablero y el juego. tableroPrincipal = obtenerNuevoTablero() reiniciarTablero(tableroPrincipal) baldosaJugador, baldosaComputadora = ingresarBaldosaJugador() mostrarPistas = False turno = quiénComienza() print(("El " if turno == "jugador" else "La ") + turno + ' comienza.') dificultad = input("Ingresa la dificultad, 1 = Novato, 2 = Intermedio, 3 = Experto) : ") if dificultad == str(1): dificultad = 'Novato' elif dificultad == str(2): dificultad = 'Intermedio' else: dificultad = 'Experto' while True: if turno == 'jugador': # Turno del jugador if mostrarPistas: tableroConJugadasVálidas = obtenerTableroConJugadasVálidas(tableroPrincipal, baldosaJugador) dibujarTablero(tableroConJugadasVálidas) else: dibujarTablero(tableroPrincipal) mostrarPuntajes(baldosaJugador, baldosaComputadora) jugada = obtenerJugadaJugador(tableroPrincipal, baldosaJugador) if jugada == 'salir': print('¡Gracias por jugar!') sys.exit() # terminar el programa elif jugada == 'pistas': mostrarPistas = not mostrarPistas continue else: hacerJugada(tableroPrincipal, baldosaJugador, jugada[0], jugada[1]) if obtenerJugadasVálidas(tableroPrincipal, baldosaComputadora) == []: break else: turno = 'computadora' else: # Turno de la computadora dibujarTablero(tableroPrincipal) mostrarPuntajes(baldosaJugador, baldosaComputadora) input('Presiona enter para ver la jugada de la computadora.') x, y = obtenerJugadaComputadora(tableroPrincipal, baldosaComputadora) #Llama a la funcion obtenerJugadaComputadora hacerJugada(tableroPrincipal, baldosaComputadora, x, y) #Realiza la mejor jugada para la computadora if obtenerJugadasVálidas(tableroPrincipal, baldosaJugador) == []: break else: turno = 'jugador' # Mostrar el puntaje final. dibujarTablero(tableroPrincipal) puntajes = obtenerPuntajeTablero(tableroPrincipal) print('X ha obtenido %s puntos. O ha obtenido %s puntos.' % (puntajes['X'], puntajes['O'])) if puntajes[baldosaJugador] > puntajes[baldosaComputadora]: print('¡Has vencido a la computadora dificultad %s , por %s puntos! ¡Felicitaciones!' % (dificultad,puntajes[baldosaJugador] - puntajes[baldosaComputadora])) elif puntajes[baldosaJugador] < puntajes[baldosaComputadora]: print('Has perdido. La computadora te ha vencido dificultad %s , por %s puntos.' % (dificultad, puntajes[baldosaComputadora] - puntajes[baldosaJugador])) else: print('¡Ha sido un empate!') if not jugarDeNuevo(): break
ff29da2827daec7f7f86bb132e6407e4984816d0
Matheuspaixaocrisostenes/Python
/ex091.py
563
3.75
4
from random import randint from time import sleep from operator import itemgetter jogo = {'jogador 1':randint(1,6), 'jogador 2':randint(1,6), 'jogador 3':randint(1,6), 'jogador 4':randint(1,6)} ranking = list() print('valores sorteados') for k,v in jogo.items(): print(f'o {k} jogou o dado e teve o valor {v}') sleep(1) ranking = sorted(jogo.items(),key=itemgetter(1),reverse=True) print('-=' * 30) print(' == ranking do jogo. ==') for i,v in enumerate(ranking): print(f' o {i+1}° lugar {v[0]} com {v[1]}') sleep(1)
71619945dcfe827ccad3ca36069c61bb3c8b7353
Vovanuch/python-basics-1
/happy_pythoning_cource/Part_4/4.1.5.Arifm_progression/4.1.5.arifm_progression.py
965
4
4
''' Арифметическая прогрессия Напишите программу, которая определяет, являются ли три заданных числа (в указанном порядке) последовательными членами арифметической прогрессии. Формат входных данных На вход программе подаются три числа, каждое на отдельной строке. Формат выходных данных Программа должна вывести «YES» или «NO» (без кавычек) в соответствии с условием задачи. Sample Input 1: 1 2 3 Sample Output 1: YES Sample Input 2: 1 2 4 Sample Output 2: NO Sample Input 3: 2 4 8 Sample Output 3: NO ''' a = int(input().strip()) b = int(input().strip()) c = int(input().strip()) print('YES') if (b - a) == (c - b) else print('NO')
6f2b322b6af8c852bf603dd11a8dff4ca3970a3a
luisteam/lm-asir
/python/boletin2.3.py
486
3.9375
4
print("SUMA ENTRE VALORES") valor1 = int(input("Escriba un numero entero: ")) valor2 = int(input("Escriba un numero mayor que %d: " % (valor1))) if valor2 <= valor1: print("¡Le he pedido un número entero mayor que %d!" % (valor1)) else: suma = 0 for i in range(valor1, valor2 + 1): suma = suma + i print("La suma desde %d hasta %d es %d" % (valor1,valor2,suma)) for i in range(valor1,valor2): cadena=("%d + " % (i)) print(cadena, end="") print("%d = %d" % (valor2,suma))
4d44fbf29d314f1d362df9be4174e368a553e7c4
honglim99/studygroup
/yoonseok/0805/BOJ_2941_yoonseok.py
595
3.609375
4
word = input() count = 0 i = 0 l = len(word) while i <l: if ord(word[i]) <= ord('z') and ord(word[i]) >= ord('a'): count+=1 if word[i]=='c': if i <l-1 and (word[i+1]=='=' or word[i+1]=='-'): i+=1 elif word[i]=='l' or word[i]=='n': if i<l-1 and word[i+1]=='j': i+=1 elif word[i]=='s' or word[i]=='z': if i<l-1 and word[i+1]=='=': i+=1 elif word[i]=='d' : if i<l-1 and word[i+1]=='-': i+=1 if i<l-2 and word[i+1]=='z' and word[i+2]=='=': i+=2 i+=1 print(count)
d299b60b27512356df1bae0eb394ff2dc94f77d3
JavierSada/MathPython
/Support/S1 M2.py
861
4.0625
4
import random import numpy as np import matplotlib.pyplot as plt def f(x): # A function to generate example y values r = random.random() y = x-10*r-x**r return y random.seed(352) # Ensures that we all generate the same random numbers x_values = np.array(range(1,101)) # Numbers from 1 to 100 y_values = np.array([f(x) for x in x_values]) # Get y value for each x value n = len(x_values) # the number of observationsT sumx= np.sum(x_values) sumy= np.sum(y_values) sumx_y=np.sum(x_values*y_values) squarex= np.sum(x_values**2) squarey= np.sum(y_values**2) slope= round((n *(sumx_y)) - (sumx * sumy))/((n * sumx) - sumx**2) print "The slope is equal to:", slope b = round(sumy - (slope * sumx))/n print "The intercept is equal to:", b plt.plot(x_values, y_values) print "The best equation is:", "+",("y=%s"%slope+"x +%s"%b)
c8316e8c855c5474e459860916c070154fe63163
hrithikguy/ProjectEuler
/p66.py
437
3.53125
4
import math def is_square(n): if math.sqrt(n) == math.floor(math.sqrt(n)): return 1 else: return 0 max_x = 0 max_D = 0 for D in range(2, 1001): if is_square(D): continue found = 0 y = 1 while(found == 0): if is_square(1 + D*y*y): found = 1 x = math.sqrt(1 + D*y*y) if x > max_x: max_x = x max_D = D print max_x, max_D, y break y += 1 if found == 0: print D break print max_x print max_D
0e17259d921927580061740557644cb0d9417df4
lamorenove/Ejercicios-Python
/Modulo1/02_Segunda_Semana/RetoSemana2.py
2,503
3.65625
4
# Descripción del problema """ Una empresa decide incentivar a sus trabajadores respartiendo parte de su utilidad lograda en el año 2020. Para el cálculo de la bonificación que deber recibir el empleado, se tiene en cuenta su antigüedad en la empresa y un porcentaje de su salario de acuerdo con la siguiente tabla: Tiempo Bonificación Menos de 1 año 5% del salario mensual 1 año o más y menos de 2 años 7% del salario mensual 2 año o más y menos de 5 años 10% del salario mensual 5 año o más y menos de 7 años 15% del salario mensual Más de 7 años 20% del salario mensual Se requiere programar dos funciones, una función que reciba la información encapsulada del empleado en un diccionario y otra que retorne a partir de un diccionario de respuesta el mensaje de la forma "{NombreEmpleado}" - Bonificiación: Tiene una bonificación equiavalente al 7% de su salario mensual.", la bonificación otorgada al empleado se determina de acuerdo al arbol de decisiones que muestra la figura 1. """ # El esqueleto de la primera función reportarBonificacion: def reportarBonificacion(dicReporte: dict) -> dict: return dicReporte['empleado']+" - "+"Bonificación: "+str(dicReporte['bonificacion']) def generarReporteBonificacion(dicEmpleado: dict) -> dict: if dicEmpleado['antiguedad'] < 1: boni = "Tiene una Bonificación equivalente al 5 por ciento de su salario mensual" else: if (dicEmpleado['antiguedad'] >= 1) and (dicEmpleado['antiguedad'] < 2): boni = "Tiene una Bonificación equivalente al 7 por ciento de su salario mensual" else: if (dicEmpleado['antiguedad'] >= 2) and (dicEmpleado['antiguedad'] < 5): boni = "Tiene una Bonificación equivalente al 10 por ciento de su salario mensual" else: if (dicEmpleado['antiguedad'] >= 5) and (dicEmpleado['antiguedad'] < 10): boni = "Tiene una Bonificación equivalente al 15 por ciento de su salario mensual" else: boni = "Tiene una Bonificación equivalente al 20 por ciento de su salario mensual" reporteBonificacion = { "bonificacion": boni, "empleado": dicEmpleado["empleado"] } return reporteBonificacion dicEmpleado = { "id_empleado": "id_001", "empleado": "Sandra Peña", "antiguedad": 1, } print(reportarBonificacion(generarReporteBonificacion(dicEmpleado)))
4f03783f2bf080fcd2558343dd6d622cbfd9218d
SamuelmdLow/cityfinder
/product/main.py
24,770
4.21875
4
# main.py ''' Title: City Finder Client: Willian Li Author: Samuel Low Date Created: 19/6/2021 ''' # ---LIBRARIES--- # import pathlib import wikipedia # ---CREATE FULL CITY INFO CSV FILE---# # INPUT # read data from CSV files def getData(FILENAME): ''' extract data from file and process into 2D arrays :param FILENAME: (string) :return: (list) ''' FILE = open(FILENAME, encoding="ISO-8859-1") # open file RAW_DATA = FILE.readlines() # separate the content of the file by lines FILE.close() # close the file for i in range(len(RAW_DATA)): # for each line in the original file RAW_DATA[i] = RAW_DATA[i][:-1] # remove the last character (\n) RAW_DATA[i] = RAW_DATA[i].split(',') # split the line by each comma (CSV) return RAW_DATA # PROCESSING # add the data from the climate csv file to the full city array def addClimate(CLIMATE_LIST, FULL_LIST): ''' Add the information from "climate.csv" to the full list of city information :param CLIMATE_LIST: (list) list containing climate information :param FULL_LIST: (list) full list of city information :return: (list) Updated list of city information ''' global CITY_LIST # List of all cities in the city information database CLIMATE_LIST.pop(0) # Remove the header of the table CITY = None for item in CLIMATE_LIST: # for each item in the CLIMATE_LIST array if CITY != item[3]: # if a new city has been reached in the data if CITY != None: # if this is not the first time in the for loop if MONTHS == 0: AVERAGE = None else: AVERAGE = round(SUM/MONTHS,1) # calculate the average temperature # Convert the temperatures values to Celcius LOW = convertToCelcius(LOW) HIGH = convertToCelcius(HIGH) AVERAGE = convertToCelcius(AVERAGE) CITY_INFORMATION = [CITY, STATE, COUNTRY, LOW, HIGH, AVERAGE, None, None, None, None] FULL_LIST.append(CITY_INFORMATION) # Add the climate data to the list of city information if STATE != None: CITY_LIST.append(CITY + "_" + STATE + "_" + COUNTRY) else: CITY_LIST.append(CITY+"_"+COUNTRY) CITY = item[3] if item[2] != "": STATE = item[2] else: STATE = None COUNTRY = item[1] if COUNTRY == "US": COUNTRY = "United States" LOW = None HIGH = None MONTHS = 0 SUM = 0 TEMPERATURE = float(item[7]) if TEMPERATURE != -99.0: MONTHS = MONTHS + 1 SUM = SUM + TEMPERATURE # remember the temperature as the highest if it is the highest so far if LOW == None or LOW > TEMPERATURE: LOW = TEMPERATURE # remember the temperature as the lowest if it is the lowest so far if HIGH == None or HIGH < TEMPERATURE: HIGH = TEMPERATURE return FULL_LIST # add the data from the population and coordinates csv file to the full city array def addPopCords(POP_CORDS_LIST, FULL_LIST): ''' Add the information from "PopulationAndCords.csv" to the full list of City information :param POP_CORDS_LIST: (list) list containing information from "PopulationAndCords.csv" :param FULL_LIST: (list) combined list of City information :return: (list) updated combined list of city information ''' global CITY_LIST POP_CORDS_LIST.pop(0) # remover the header for item in POP_CORDS_LIST: CITY = item[1][1:-1] # remove the quotes ("") try: POPULATION = int(item[9][1:-1]) # extract the population of a city except: POPULATION = None LATITUDE = item[2][1:-1] # extract the latitude LONGITUDE = item[3][1:-1] # extract the longitude PROVINCE = item[7][1:-1] # extract the province COUNTRY = item[4][1:-1] # extract the country CODEA = CITY+"_"+COUNTRY CODE = CITY+"_"+PROVINCE+"_"+COUNTRY if CODEA in CITY_LIST: CITY_LIST[CITY_LIST.index(CODEA)] = CODE if CODE in CITY_LIST: # if the is already in the full city database # add population and coordinates information INDEX = CITY_LIST.index(CODE) FULL_LIST[INDEX][1] = PROVINCE FULL_LIST[INDEX][6] = LATITUDE FULL_LIST[INDEX][7] = LONGITUDE FULL_LIST[INDEX][8] = POPULATION else: # create the city information list with the population and coordinates information INFORMATION = [CITY, PROVINCE, COUNTRY, None, None, None, LATITUDE, LONGITUDE,POPULATION, None] # add the city information list to the full city database FULL_LIST.append(INFORMATION) CITY_LIST.append(CODE) return FULL_LIST # add the data from the university ranking csv file to the full city array def addUniversities(UNIVERSITY_LIST, FULL_LIST): ''' Add the information from "CityUniversityRankings.csv" to the combined list of City information :param UNIVERSITY_LIST: (list) list containing information from "CityUniversityRankings.csv" :param FULL_LIST: (list) combined list of City information :return: (list) updated combined list of city information ''' print("university started") global CITY_LIST rank = 916 for UNI in reversed(UNIVERSITY_LIST): UNI = UNI[0] if UNI in CITY_LIST: # if the city has been recorded for the full city database INDEX = CITY_LIST.index(UNI) # locate the city in the list FULL_LIST[INDEX][9] = rank # add the university ranking to the city's information list else: UNI = UNI.split("_") if len(UNI) == 3: worse = UNI[0]+"_"+UNI[2] i = 0 for CITY in CITY_LIST: CODE = CITY.split("_") #print(CODE) if len(CODE) == 3: CODE = CODE[0] + "_" + CODE[2] if worse == CODE: # if the city has been recorded for the full city database FULL_LIST[i][9] = rank # add the university ranking to the city's information list i = i + 1 rank = rank - 1 # Count backwards so that higher ranks will overwrite lower ones return FULL_LIST # add a unique code representing the city to the full city array def addCode(FULL_LIST): ''' Add the unique codes of each city to the city infromation list of each city :param FULL_LIST: (list) 2d list of all city information :return: (list) updated list of city information ''' for i in range(len(FULL_LIST)): # set up the items of the unique code for the city CITY = FULL_LIST[i][0] while " " in CITY: CITY = CITY[0:CITY.index(" ")] + CITY[CITY.index(" ")+1:len(CITY)] if FULL_LIST[i][1] != None: PROV = FULL_LIST[i][1][0:3] else: PROV = "" if " " in FULL_LIST[i][2]: COUN = FULL_LIST[i][2][0]+FULL_LIST[i][2][FULL_LIST[i][2].index(" ")+1] else: COUN = FULL_LIST[i][2][0:3] # add the city code to the end of the city information list FULL_LIST[i].append(CITY+PROV+COUN) return FULL_LIST # OUTPUT # write the contents of the full city array to a CSV file def createFullCityInfoCSVFile(): ''' Create a CSV file of the combined city information :return: ''' global FULL_CITY_CSV global FULL_LIST SAVED_FILE = open(FULL_CITY_CSV, "w", encoding="utf-8") # open the database SAVED_FILE.write("CITY, PROVINCE/STATE, COUNTRY, LOW TEMP, HIGH TEMP, AVERAGE TEMP, LATITUDE, LONGITUDE, POPULATION, UNIVERSITY RANKING, CODE\n") for i in FULL_LIST: # for each city in the in the list data = "" # connect the city information into a string separated by commas (CSV) for a in i: data = data + str(a) + "," data = data + "\n" # end the string with a new line SAVED_FILE.write(data) # write the string to the city information CSV file SAVED_FILE.close() # close the database # SUBROUTINES RELATED TO FILTERING CITIES # convert the list of filters into a readable form for displaying def getSpecifications(FILTERS): ''' format the list of filters into something readable to display to the user :param FILTERS: (list) list of filters on the city data, added by the user :return: (list) list of filters in a readable format for displaying to the user ''' DISP_FILTERS = [] TYPES = ["City", "Province/State", "Country", "Lowest Temperature (C°)","Highest Temperature (C°)", "Average Temperature (C°)", "Latitude", "Longitude", "Population", "University ranking"] for item in FILTERS: if item[0] == 9: # if the filter is about university ranking # add sentence about university ranking to the list DISP_FILTERS.append(TYPES[item[0]] + " is in the top " + str(item[2])) else: # add a general sentence to the list DISP_FILTERS.append(TYPES[item[0]] + " is between " + str(item[1]) + " and " + str(item[2])) return DISP_FILTERS # SUBROUTINES RELATED TO FILTERING CITIES # convert the list of filters into a readable form for displaying def getCriteria(CRITERIA): ''' format the list of criteria into something readable to display to the user :param CRITERIA: (list) list of criteria for the city data, added by the user :return: (list) list of criteria in a readable format for displaying to the user ''' DISP_CRITERIA = [] TYPES = ["City", "Province/State", "Country", "lowest temperature","highest temperature", "average temperature", "latitude", "Longitude", "population", "university ranking"] for item in CRITERIA: if item[0] == 3 or item[0] == 4 or item[0] == 5: unit = " C° " elif item[0] == 8: unit = " people " else: unit = " " # add sentence about each item in the criteria list DISP_CRITERIA.append("The ideal " + TYPES[item[0]] + " is " + str(item[1]) + unit + "(weighted at x" + str(item[2]) +")") return DISP_CRITERIA # obtain the list of cities that meet the parameters of the filter def getEligibleCities(SPECIFICATIONS): ''' get the a list of eligible cities based on the user inputed filters on city data :param SPECIFICATIONS: :return: (list) list of cities that meet the filters set by the user ''' global FULL_LIST ELIGIBLE_CITIES = [] # setup list of eligible cities for CITY in FULL_LIST: # for each city in the list of cities ELIGIBLE = True # assume the city is eligible for SPEC in SPECIFICATIONS: # for each filter in the list of filters try: if CITY[SPEC[0]] != "None": VALUE = float(CITY[SPEC[0]]) if SPEC[1] <= VALUE <= SPEC[2]: pass else: ELIGIBLE = False # if the city does not meet the filter, mark it as not eligible break else: ELIGIBLE = False # if city has no information for the filtered information, mark it not eligible break except: pass if ELIGIBLE == True: ELIGIBLE_CITIES.append(CITY) # if city remains eligible, add it to the eligible list 0,2,-2 (city, country, id) return ELIGIBLE_CITIES def decryptCode(CODE): ''' Split the information in the url into two lists :param CODE: (string) the url information :return: (list) a list with two lists that represent the information in the url ''' CRITERIA = [] # list representing items in the ranking criteria FILTER = [] # list representing the filters if "::" in CODE: # this means there is both a ranking criteria and a filter in the url RAW = CODE.split("::") CRITERIA = decryptRaw(RAW[0].split(":")) # Split the ranking criterias into their list FILTER = decryptRaw(RAW[1].split(":")) # Split the filters into their list else: RAW = CODE[4:len(CODE)] if "FLT:" in CODE: # There is only a filter in the url FILTER = decryptRaw( RAW.split(":") ) # Split the filters into their list else: # There is only a ranking criteria in the url CRITERIA = decryptRaw( RAW.split(":") ) # Split the ranking criterias into their list return [CRITERIA, FILTER] def decryptRaw(RAW): ''' Convert the string representing the list of filters or list of ranking criteria into a two dimensional array :param RAW: (string) string representing the list of filters or list of ranking criteria :return: (list) two dimensional list filters or ranking criteria ''' CLEAN = [] for i in RAW: NAME = i[0:2] if NAME == "LT": SELECTION = 3 elif NAME == "HT": SELECTION = 4 elif NAME == "AT": SELECTION = 5 elif NAME == "PP": SELECTION = 8 else: SELECTION = 9 NUMBERS = i[2:len(i)] NUMBERS = NUMBERS.split("_") NUM1 = float(NUMBERS[0]) NUM2 = float(NUMBERS[1]) CLEAN.append([SELECTION, NUM1, NUM2]) return CLEAN # organize the cities into groups of countries for displaying def getDisplay(ELIGIGBLE_CITIES): ''' organize the list of eligible cities into groups of cities that share the same country :param ELIGIGBLE_CITIES: (list) list of the cities that meet the filters set by the user :return: (list) two dimensional array containing a list of counties and a list with the corresponding cities ''' COUNTRIES = [] CITIES = [] for city in ELIGIGBLE_CITIES: # for each city in the list of eligible cities if city[2] in COUNTRIES: # if the loop has already encounterd this country CITIES[COUNTRIES.index(city[2])].append([city[0],city[-2]]) # add the city to a list in the CITY list at the same index as the country else: COUNTRIES.append(city[2]) # add the country to the end of the countries list CITIES.append([[city[0],city[-2]]]) # add the city into a list at the end of the cities list return [COUNTRIES, CITIES] def rankCities(ELIGIBLE_CITIES, CRITERIA): ''' Uses the ranking criteria to rank cities from closest to farthest from ideal :param ELIGIBLE_CITIES: (list) two dimensional list of eligible ciites and their information :param CRITERIA: (list) two dimensional list of ranking criteria :return: (list) list with two lists inside, one of labels for groups of cities, and another with the groups of cities and their codes ''' CITIES_SCORES = [] # cities along with their scored differences from the ideal values for CITY in ELIGIBLE_CITIES: # iterates through every city CITIES_SCORES.append([CITY[0], CITY[-2], 0]) # adds the city CITIES_SCORES list for ITEM in CRITERIA: # iterate through th ranking criteria if CITY[ITEM[0]] != "None": # check if the city has information on a value that is in the criteria # 1. Calculate the difference between the city and the ideal and the cities value # 2. Multiply the difference by the criteria's weighting # 3. Add this to the Cities total difference score CITIES_SCORES[-1][2] = CITIES_SCORES[-1][2] + (abs(float(CITY[ITEM[0]]) - ITEM[1]) * ITEM[2]) else: # if the city does not have information on a value that is in the criteria, remove it CITIES_SCORES.pop(-1) break # order the cities from lowest difference score to highest difference score CITIES_SCORES.sort(key=getDistance) LOWER = 0 # Start of the grouping UPPER = 1 # End of the grouping MULTIPLIER = 2 # The number that the next group will multiply in size by BOUNDARIES = [] # List of group labels ("top 1 to 5", etc) CITIES = [] # list of cities # Create groupings until they out grow the amount of cities while UPPER < len(CITIES_SCORES): if UPPER != 1: LOWER = UPPER # start the group at the end of the old group # alternate between growing by 2x and 5x (5, 10, 50, 100, 500, etc...) if MULTIPLIER == 2: MULTIPLIER = 5 else: MULTIPLIER = 2 UPPER = UPPER * MULTIPLIER # define the end of the group BOUNDARIES.append("Top " + str(LOWER + 1) + " to " + str(UPPER)) # Add the label to the BOUNDARIES list CITIES.append(CITIES_SCORES[LOWER:UPPER]) # Add the group of cities within the boundaries to the list of cities return [BOUNDARIES,CITIES] def getDistance(CITY): DISTANCE = CITY[2] return DISTANCE # locate the index of a city by it's ID def getCity(CODE): ''' obtain the city information list of a city using it's Code :param CODE: (str) unique Code which represents each city :return: (list) list of city information ''' global FULL_LIST INLIST = False INDEX = 0 # loop through the entire city list until the code matches for i in FULL_LIST: if i[-2] == CODE: # if the code matches, break from the loop and remember that the code is indeed in the city information list INLIST = True break INDEX = INDEX + 1 # if the program remembers that the code was in the city information list if INLIST == True: print(FULL_LIST[INDEX]) return FULL_LIST[INDEX] else: return None # arrange the information from a city in the city array into a paragraph for displaying def getCityInformation(CITYINFO): ''' print the available information about a city to the user :param FULL_LIST: (list) combined list of City information :return: (str) paragraph on the city ''' if CITYINFO != None: CITY = CITYINFO[0] PROVINCE = CITYINFO[1] COUNTRY = CITYINFO[2] LOW = CITYINFO[3] HIGH = CITYINFO[4] AVERAGE = CITYINFO[5] LATITUDE = CITYINFO[6] LONGITUDE = CITYINFO[7] POPULATION = CITYINFO[8] UNIVERSITY = CITYINFO[9] # add the suffix to the top university's rank if UNIVERSITY[-1] == "1": UNIVERSITY = UNIVERSITY + "st" elif UNIVERSITY[-1] == "2": UNIVERSITY = UNIVERSITY + "nd" else: UNIVERSITY = UNIVERSITY + "th" # add the geographic location of the city to the paragraph SENTENCE = "\n" + CITY + " is in " if PROVINCE != "None": SENTENCE = SENTENCE + PROVINCE + ", " + COUNTRY + ".\n" else: SENTENCE = SENTENCE + " " + COUNTRY + ".\n" # add the coordinates of the city to the paragraph if LATITUDE != "None": SENTENCE = SENTENCE + "The city's coordinates are latitude: " + LATITUDE + " , longitude: " + LONGITUDE + ".\n" # add the temperature information of the city to the paragraph if LOW != "None": SENTENCE = SENTENCE + "The temperature can get as low as " + LOW + " C and as high as " + HIGH + " C.\n" SENTENCE = SENTENCE + "The average yearly temperature is " + AVERAGE + " C.\n" # add the population of the city to the paragraph if POPULATION != "None": SENTENCE = SENTENCE + "There are around " + POPULATION + " people in the city.\n" # add the top university rank to the paragraph if UNIVERSITY[0:-2] != "None": SENTENCE = SENTENCE + "The city's top university is ranked " + UNIVERSITY + " in the world." return SENTENCE else: # error message return "Sorry! We have no information on this city." # convert Fahrenheit (useless unit) to Celcius def convertToCelcius(Fahrenheit): ''' Conver fahrenheit to a better unit of measurement (celcius) :param Fahrenheit: (float) temperature in fahrenheit :return: (float) temperature in celcius ''' CELCIUS = round(((Fahrenheit - 32) * 5) / 9, 1) # fahrenheit to celcius conversion return CELCIUS # get the wikipedia page and an image from the wikipedia page of a city def getWikipedia(CITY): ''' retrieve wikipedia page on the city and the first image in it :param city: (list) list of city information :return: (list) list containing the link to the wikipedia page and the link to the first image ''' URL = "None" MONTAGE = [] # create the search query if CITY[0] == CITY[1] or CITY[1] == "None": QUERY = CITY[0] + ", " + CITY[2] else: QUERY = CITY[0]+", "+CITY[1]+" "+CITY[2] print("Query: " + QUERY) try: # search wikipedia with the search query RESULT = wikipedia.search(QUERY) TERMS = ["montage","at_night", "downtown", "skyline", "business", "hall", "aerial","bridge","stadium"," street","mount","lake"] if len(RESULT) > 0: # if the search yielded results PAGE = wikipedia.page(RESULT[0]) URL = wikipedia.page(RESULT[0]).url # get the top result's url if len(PAGE.images) > 0: for index in range(len(PAGE.images)): x = PAGE.images[index].lower() for TERM in TERMS: if TERM in x: MONTAGE.append(PAGE.images[index]) break except: pass print(MONTAGE) print(URL) return [URL,MONTAGE] # get the flag of the country of a specific city def getFlag(CITY): ''' get the flag of the country of a city :param city: (list) city information list :return: ''' try: COUNTRY = CITY[2].lower() if COUNTRY == "united states": # united states has an exception as it is represented differently in the website FLAG = "https://cdn.countryflags.com/thumbs/united-states-of-america/flag-800.png" else: # replace any spaces in the country name with dashes while " " in COUNTRY: COUNTRY = COUNTRY[0:COUNTRY.index(" ")] + "-" + COUNTRY[COUNTRY.index(" ")+1:len(COUNTRY)] FLAG = "https://cdn.countryflags.com/thumbs/" + COUNTRY + "/flag-800.png" except: FLAG = "None" print(FLAG) return FLAG # VARIABLES CLIMATE_CSV = "Product/databases/climate.csv" POP_CORDS_CSV = "Product/databases/PopulationAndCords.csv" FULL_CITY_CSV = "Product/databases/fullCityInfo.csv" UNIVERSITY_CSV = "Product/databases/CityUniversityRankings.csv" FULL_LIST = [] CITY_LIST = [] # Get Data FIRST_RUN = True if (pathlib.Path.cwd() / FULL_CITY_CSV).exists(): FIRST_RUN = False if FIRST_RUN == True: # Create a combined array of city information CLIMATE_LIST = getData(CLIMATE_CSV) # convert the climate.csv to a list POP_CORDS_LIST = getData(POP_CORDS_CSV) # convert the PopulationAndCords.csv to a list UNIVERSITY_LIST = getData(UNIVERSITY_CSV) # convert the CityUniversityRankings.csv to a list FULL_LIST = addClimate(CLIMATE_LIST, FULL_LIST) # add data from CLIMATE_LIST list to the full city list del CLIMATE_LIST # remove the CLIMATE_LIST list from memory FULL_LIST = addPopCords(POP_CORDS_LIST, FULL_LIST) # add data from POP_CORDS_LIST list to full city list del POP_CORDS_LIST # remove the POP_CORDS_LIST list from memory FULL_LIST = addUniversities(UNIVERSITY_LIST, FULL_LIST) # add data from UNIVERSITY_LIST list to full city list del UNIVERSITY_LIST # remove the UNIVERSITY_LIST list from memory FULL_LIST = addCode(FULL_LIST) # add the unique city code to each city createFullCityInfoCSVFile() # Save the full city information list in CSV format # so that the data does not have to be compiled every time the website is run else: # Get city information from the saved CSV file FULL_LIST = getData(FULL_CITY_CSV) # convert the fullCityInfo.csv to a list FULL_LIST.pop(0) # remove the header
8bfec3b8cf51bf8e527093d2609512db46185818
ThrallOtaku/python2Test
/spider/basic/userAgentTest.py
458
3.53125
4
#coding:utf-8 #中文注释的时候需要引入这个 import urllib2 url = "http://www.baidu.com" # IE 9.0 的 User-Agent header = {"User-Agent": "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0;"} request = urllib2.Request(url, headers=header) # 也可以通过调⽤Request.add_header() 添加/修改⼀个特定的 header request.add_header("Connection","keep-alive") response = urllib2.urlopen(url) html = response.read() print html
10d2299df15c7e89986a5297e158d37f8c3a317d
yang4978/Hackerrank_for_Python
/Practice for Python/Basic Data Types/05_lists.py
683
3.9375
4
#https://www.hackerrank.com/challenges/python-lists/problem if __name__ == '__main__': N = int(input()) arr = []; for _ in range(N): arr_temp = input().strip().split(); if(arr_temp[0]=="insert"): arr.insert(int(arr_temp[1]),int(arr_temp[2])); elif(arr_temp[0]=="print"): print(arr); elif(arr_temp[0]=="remove"): arr.remove(int(arr_temp[1])); elif(arr_temp[0]=="append"): arr.append(int(arr_temp[1])); elif(arr_temp[0]=="sort"): arr.sort(); elif(arr_temp[0]=="pop"): arr.pop(); elif(arr_temp[0]=="reverse"): arr.reverse();
e35c653833fa302eaedf7d0f60cd850b1eb9339d
EEExphon/Basic_Codes_for_Python
/LIST/FCBayern list ( in Chinese ).py
763
3.6875
4
FCBayern=["诺伊尔","穆勒","聚勒","哈梅斯","莱万多夫斯基","博阿滕","里贝里","罗本","胡梅尔斯","阿拉巴","格纳布里"] M=len(FCBayern) YU="y" while YU=="y" or YU=="Y": Num=int(input("Give me a number from 0 to 10 to show you a footballer in FCBayern.")) while not Num<=10 and Num>=0: Num=int(input("Give me a number from 0 to 10 to show you a footballer in FCBayern.")) print("The footballer is",FCBayern[Num],".") CH=input("Input H to see the whole list,if you don't want, press enter.") if CH=="H" or CH=="h": for F in range (0,M): print(F,FCBayern[F]) YU=input("Continue? y or n?") print("GOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOD!")
ebb964d4a0ba1e39df911de0e7b778a65d01ab8c
sadeghjafari5528/knock-off-rest
/kor/serializers/serializer.py
441
3.5625
4
from datatypes import DataType class JsonSerializer: def serialize(self , text): datatype = DataType("json") from json import loads datatype.setData(loads(text)) return datatype def deserialize(self , data): if data.getType() == "json": return str(data.getData()) else: raise Exception("InvalidType error : type of data in JsonSerializer must be json")
1d24eacac1838384bf31bc30643bcba9dab7a06f
FantasybabyChange/python-study
/python-class-study/python_object_extend.py
877
4
4
# 类的继承 class Person: def __init__(self, name=None, age=None, hp=None): self.name = name self.__age = age self.__hp = hp def update_name(self, name): self.name = name def print_object(self): print("person name %s hp %s " % (self.name, self.__hp)) def get_age(self): return self.__age def get_hp(self): return self.__hp def update_hp(self, hp): self.__hp = hp class Boy(Person): def __init__(self, name=None, age=None, hp=None): super().__init__(name, age, hp) def print_object(self): print("Boy name %s age %s hp %s " % (self.name, self.get_age(), self.get_hp())) boy = Boy('小屁孩', 13, 30) boy.print_object() boy.update_name('xiao ihai') person = Person('大人', 30, 100) person.print_object() print(type(boy)) print(isinstance(boy, Person))
f1d048870fb47c701fa49fd74dac31b0a7a2c8f4
NeedlessTorpedo/Turtle-Module
/GoldenRect.py
845
4.1875
4
#import turtle module import turtle #import math module import math #creates the window and the turtle wn = turtle.Screen() wn.bgcolor("Lavender") trtl = turtle.Turtle() #Length of sides lngth = 100 #Draws a Square for i in range(4): trtl.left(360/4) trtl.forward(lngth) trtl.backward(lngth/2) # Angle of the golden triangle **Law of Sine** ((sin90)/(math.sqrt(5)/2) = (sinA)/1) trtl.left(63.43) #Square root of 5 divided by 2 is multiplied by length of side trtl.forward((math.sqrt(5)/2)*lngth) trtl.backward((math.sqrt(5)/2)*lngth) trtl.right(63.43) trtl.forward((math.sqrt(5)/2)*lngth) trtl.left(90) trtl.forward(lngth) trtl.left(90) trtl.forward(((math.sqrt(5)/2)*lngth)) wn.exitonclick()
4153416d10d9253332aa13c3088b77db3ccf7e76
aouyang1/InsightInterviewPractice
/three_sum_closest_austin.py
976
3.71875
4
""" >>> three_sum_closest([0, 1, 2, -3], 1) 0 >>> three_sum_closest([5, 7, -4, -10, 0, 12, 21, -3], 15) 15 """ def three_sum_closest(num, target): """ 3Sum Closest """ num.sort() curr_sum = None curr_delta = None jk_sum = {} for i in range(len(num)-2): j = i+1 k = len(num)-1 while j != k: if (j, k) not in jk_sum: jk_sum[(j, k)] = num[j] + num[k] temp_sum = num[i] + jk_sum[(j, k)] if temp_sum == target: return target elif temp_sum < target: j += 1 else: k -= 1 temp_delta = temp_sum - target if temp_delta < 0: temp_delta *= -1 if curr_sum is None or temp_delta < curr_delta: curr_sum = temp_sum curr_delta = temp_delta return curr_sum if __name__ == "__main__": import doctest doctest.testmod()
d1eb603b4545648936757ea42c50a3503043c6b5
paula867/Girls-Who-Code-Files
/list.py
554
3.5625
4
linkin_parkmembers = ["Mike Shinoda", "Chester Bennington (+)", "Dave Farrel", "Joe Hahn", "Brad Delson", "Rob Bourdon"] birth_yearsfammembers = [2003, 1969, 1975] ramdom_favoritethings = [6, "Mike", 0.0, "Bourdon", "Linkin Park", "Sciences"] fav = "Mike" #print("The names of the members of Linkin P are", linkin_parkmembers) #print("The birth years of my family members include", birth_yearsfammembers) #print("Some ramdom things I like are", ramdom_favoritethings) print(len(fav)) print("ke" in fav) print(fav[1]) print(fav[0] + fav[3]) for letter in fav: print(letter)
836b0819522e7cf96355ba13b5e086a901643032
okipriyadi/NewSamplePython
/SamplePython/samplePython/Modul/os/Fork Parent Child/_01_creating_process_with_os_fork.py
994
3.734375
4
""" The POSIX functions fork() and exec() (available under Mac OS X, Linux, and other UNIX variants) are exposed via the os module. Entire books have been written about reliably using these functions, so check the library or a bookstore for more details than this introduction presents. To create a new process as a clone of the current process, use fork() . """ import os print "saya hanya dijalankan satu kali karena saya dieksekusi sebelum forking, " pid = os.fork() print "\nini akan diulang dua kali karena dijalankan oleh parent juga childnya" if pid: print 'I am parent process, my Child process has id:', pid else: print 'I am the child' """ After the fork, two processes are running the same code. For a program to tell which one it is in, it needs to check the return value of fork() . If the value is 0 , the current process is the child. If it is not 0 , the program is running in the parent process and the return value is the process id of the child process. """
0ebe8570f373c351157f78224341697e6be16578
nigini/StackExchangeStudies
/geolocation/STP1-locations_to_look.py
800
3.671875
4
import sys def build_locations_map(locations_file_name): locations = {} with open(locations_file_name,'r') as known_locations: for line in known_locations: line_split = line.split(':') if len(line_split) == 2: location = line_split[0].strip() country = line_split[1].strip() locations[location] = country return locations if len(sys.argv) == 3: known_locations = build_locations_map(sys.argv[1]) with open(sys.argv[2],'r') as locations_to_look: for line in locations_to_look: location = line.split(':')[0].strip() if location not in known_locations: print location else: print('''Please give me two files: \n the known_locations (LOCATION:COUNTRY) and \n the toknow_locations (LOCATION:...)''')
28485b19d48dc108e249ddfd325118ae3d660418
balu/es102
/acronymize.py
185
4.03125
4
def acronymize(xs): ys = xs.split(" ") a = "" for y in ys: if y[0].isupper(): a += y[0] return a print(acronymize("Indian Institute of Technology"))
76a6a8570c07adf20364dda442a32eac98c17d52
BPPJH/Self-Driving-Buggy
/Ben's Projects/Archived Projects/Self-Driving Buggy Rev. 3/Backups/7-21-15/buggyinfo.py
4,118
3.5
4
''' This module contains methods and classes relating to interpreting data about the buggy like position and orientation. ''' import math def convertToHeading(magnetX, magnetY, magnetZ): roll = math.atan2(magnetX, magnetZ) pitch = math.atan2(magnetY, magnetZ) yaw = math.atan2(magnetY, magnetX) if yaw < 0: yaw += 2 * math.pi return roll, pitch, yaw def adjustForTilt(accelX, accelY, accelZ, roll, pitch, yaw): # forward is x, sideways is y ''' Uses 3D trig to adjust acceleration data for tilt. The reference frame is the gyroscope's initial orientation. :param accelX: float (m/s) :param accelY: float (m/s) :param accelZ: float (m/s) :param roll: float (radians) :param pitch: float (radians) :param yaw: float (radians) :return: a tuple of floats containing the new angle data ''' return (accelX * math.cos(roll) * math.cos(yaw), accelY * math.cos(pitch) * math.cos(yaw), accelZ * math.cos(pitch) * math.cos(roll)) class Position(object): def __init__(self, initial, initialV=0, metersToIndex=1): ''' This class double integrates acceleration data to get position using the Middle Riemann sum algorithm. Create multiple instances for multiple dimension: posX = buggyinfo.Position(0) posY = buggyinfo.Position(0) posZ = buggyinfo.Position(0) :param initial: a number specifying initial position :param initialV: a number specifying initial velocity :return: Instance of Position ''' self.pos = initial self.veloc = [initialV] self.accel = [] self.metersToIndex = metersToIndex def update(self, accel, dt): ''' Update position using new acceleration data and dt. :param accel: a float (m/s) :param dt: time in milliseconds since last sample from IMU :return: None ''' if len(self.accel) == 0: self.accel.append(accel) elif len(self.accel) == 1: velocX = self._integrate(self.veloc[0], accel, self.accel, dt) self.pos = self._integrate(self.pos, velocX, self.veloc, dt) elif len(self.accel) == 2: velocX = self._integrate(self.veloc[1], accel, self.accel, dt) self.pos = self._integrate(self.pos, velocX, self.veloc, dt) def _integrate(self, initial, current, avgList, dt): ''' An internal method that integrates data using the Middle Riemann sum: https://en.wikipedia.org/wiki/Riemann_sum#Middle_sum :param initial: The initial value. Either velocity or acceleration :param current: Current velocity or acceleration :param avgList: The two values to average :param dt: time in milliseconds since last sample from IMU :return: The new integrated value ''' avgList.append(current) if len(avgList) > 2: avgList.pop(0) average = sum(avgList) / len(avgList) return initial + average * dt def convert(self): return int(self.pos * self.metersToIndex) def __str__(self): return str(self.pos) def __float__(self): return float(self.pos) def __int__(self): return int(self.pos) def __eq__(self, other): if type(other) == int or type(other) == long or type(other) == float: return self.pos == other elif isinstance(other, self.__class__): return self.pos == other.pos else: return False # Tests: # posX = Data.position(0, 0) # posY = Data.position(0, 0) # # posX.update(0.01, 0.5) # posY.update(1.0, 0.5) # # time1 = time.time() # times = [] # for _ in xrange(9999): # time3 = time.time() # posX.update(0.01, 0.5) # posY.update(0.0, 0.5) # time4 = time.time() # times.append(time4 - time3) # # time2 = time.time() # # print time2 - time1, sum(times) / len(times) # # print (posX, posY)
8b652bd5168d3e483d22ac547dd225b9c325d197
junwon1994/Coursera-ML
/ex6/linearKernel.py
345
3.671875
4
def linearKernel(x1, x2): """returns a linear kernel between x1 and x2 and returns the value in sim """ # Ensure that x1 and x2 are column vectors if x1.ndim == 1: x1 = x1.reshape(-1, 1) if x2.ndim == 1: x2 = x2.reshape(-1, 1) # Compute the kernel sim = x2.T @ x1 # dot product return sim
b096e0fcc7e9a34ac6880451a5cdfd8ad189d8f9
SetaSouto/torchsight
/torchsight/utils/visualize.py
1,882
3.625
4
"""Visualize images and annotations.""" import matplotlib import numpy as np import torch from matplotlib import pyplot as plt def visualize_boxes(image, boxes, label_to_name=None): """Visualize an image and its bounding boxes. Arguments: image (PIL Image or torch.Tensor or numpy array): The image to show. boxes (torch.Tensor or numpy array): The bounding boxes with shape `(num boxes, 5 or 6)` with the x1,y1,x2,y2 for the top-left corner and the bottom-right corner and the index of the label to identify the class of the object. Optionally you can provide a 6th value for the confidence or probability of the bounding box. label_to_name (dict, optional): A dict to map the label of the class to its name. """ if torch.is_tensor(image): image = image.numpy().transpose(1, 2, 0) if torch.is_tensor(boxes): boxes = boxes.numpy() n_colors = 20 colormap = plt.get_cmap('tab20') colors = [colormap(i) for i in np.linspace(0, 1, n_colors)] _, axes = plt.subplots(1) for box in boxes: if box.shape[0] == 6: x, y, x2, y2, label, prob = box prob = ' {:.3f}'.format(prob) else: x, y, x2, y2, label = box prob = '' w, h = x2 - x, y2 - y label = int(label) color = colors[label % n_colors] axes.add_patch(matplotlib.patches.Rectangle((x, y), w, h, linewidth=2, edgecolor=color, facecolor='none')) name = label_to_name[label] if label_to_name is not None else None tag = '{}{}'.format(name, prob) if name is not None else '{}'.format(prob) plt.text(x, y, s=tag, color='white', verticalalignment='top', bbox={'color': color, 'pad': 0}) print('Bounding boxes:\n{}'.format(boxes)) axes.imshow(image) plt.show()
edfad24fec524fb35ed1ec944fda5fadc1b6a47b
javed2214/Selenium-Scripting
/Image-To-PDF.py
399
3.5625
4
# Image to PDF Converter import img2pdf from PIL import Image import os img_path = "C:/Image.jpg" # Image Path pdf_path = "C:/PDF_File.pdf" # PDF File Path image = Image.open(img_path) pdf_bytes = img2pdf.convert(image.filename) file = open(pdf_path, "wb") file.write(pdf_bytes) image.close() file.close() print("Successfully Converted into PDF!!!")
20b4ba283bcb19faa9ca1d62462e09ad7e4637f6
titojlmm/MITx6001x
/Problemas/Problem1.py
2,053
4.03125
4
# -*- coding: utf-8 -*- """ Created on Thu Feb 13 21:18:28 2020 @author: Tito """ def getRemainingMonthlyBalance(month, balance, monthlyInterestRate, monthlyPaymentRate): """ This method calculates the credit card balance after one year if a person only pays the minimum monthly payment required by the credit card company each month. Parameters ---------- month : Integer The month the balance is calculated on. balance : Number The outstanding balance on the credit card. monthlyInterestRate : Number Monthly interest rate as a decimal. monthlyInterestRate : Number Minimum monthly payment rate as a decimal. Returns ------- The remaining balance at the end of the month, not rounded. """ minimumMonthlyPayment = monthlyPaymentRate * balance monthlyUnpaidBalance = balance - minimumMonthlyPayment updatedBalanceMonth = monthlyUnpaidBalance + (monthlyInterestRate*monthlyUnpaidBalance) month += 1 if month < 12: getRemainingMonthlyBalance(month, updatedBalanceMonth, monthlyInterestRate, monthlyPaymentRate) else: print("Remaining balance: " +str(round(updatedBalanceMonth, 2))) def getRemainingBalance(balance, annualInterestRate, monthlyPaymentRate): """ This method calculate the credit card balance after one year if a person only pays the minimum monthly payment required by the credit card company each month. Parameters ---------- balance : Number The outstanding balance on the credit card. annualInterestRate : Number Annual interest rate as a decimal. monthlyInterestRate : Number Minimum monthly payment rate as a decimal. Returns ------- The remaining balance at the end of the year, not rounded. """ monthlyInterestRate = annualInterestRate / 12.0 getRemainingMonthlyBalance(0, balance, monthlyInterestRate, monthlyPaymentRate) getRemainingBalance(42, 0.2, 0.04) getRemainingBalance(484, 0.2, 0.04)
66db1782d6f5a6a8dd0a039180c89c47b14acbb6
LyriCeZ/py-core
/Programming for Everybody/grades.py
500
3.84375
4
gd = raw_input("Please enter your grade ") try: grade = float(gd) except Exception, e: print "Please enter grade in a range of 1.0 - 0.0, Thanks!!" quit() if grade > 1: print "Please enter grade in a range of 1.0 - 0.0, Thanks!" quit() elif grade >= 0.9: print "Your grade is a A" elif grade >= 0.8: print "Your grade is a B" elif grade >= 0.7: print "Your grade is a C" elif grade >= 0.6: print "Your grade is a D" elif grade < 0.6: print "Your grade is a F"
8a9fbfa1843bdec7bdd734073f3e95c17e4a11a0
sh999/Python-Study-Snippets
/class_repr_attr.py
165
3.609375
4
class User: def __init__ (self, name): self.name = name def __repr__(self): return "User name = %s" % self.name user = User("Tom") print user
1f18a986f61437644079407ee7c2914e93407685
ColinGreybosh/ProjectEuler-Python
/p019.py
2,504
3.84375
4
""" Project Euler Problem 19 ======================== You are given the following information, but you may prefer to do some research for yourself. * 1 Jan 1900 was a Monday. * Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine. * A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? """ class Date: months = { 0: (31, 'Jan'), 1: (28, 'Feb'), 2: (31, 'Mar'), 3: (30, 'Apr'), 4: (31, 'May'), 5: (30, 'Jun'), 6: (31, 'Jul'), 7: (31, 'Aug'), 8: (30, 'Sep'), 9: (31, 'Oct'), 10: (30, 'Nov'), 11: (31, 'Dec') } weekdays = { 0: 'Sun', 1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'Thu', 5: 'Fri', 6: 'Sat' } def __init__(self, weekday=2, date=1, mon=0, year=1901): self.weekday = weekday self.date = date self.mon = mon self.year = year def __str__(self): return f'{self.weekdays[self.weekday]} ' \ f'{self.date} ' \ f'{self.months[self.mon][1]} ' \ f'{self.year} ' \ f'{self.is_leap_year()}' def next_date(self): self.date += 1 self.weekday += 1 if self.weekday == 7: self.weekday = 0 if self.mon == 1 and self.is_leap_year(): if self.date == 30: self.date = 1 self.mon += 1 return if self.date > self.months[self.mon][0]: self.date = 1 self.mon += 1 if self.mon == 12: self.mon = 0 self.year += 1 def is_leap_year(self): if self.year % 400 == 0: return True if self.year % 4 == 0 and self.year % 100 != 0: return True else: return False def main(): date = Date(2, 1, 1, 1901) count = 0 while date.year != 2001: if date.date == 1 and date.weekday == 0: count += 1 date.next_date() print(count) if __name__ == '__main__': main()
49a8cd9654fd56f14492a151862ffe19ace82ae3
rajathgunners/CodingPractiseProblems
/geekforgeeks/recursiveRemoveDuplicates.py
1,254
3.625
4
"""Given a string s, recursively remove adjacent duplicate characters from the string s. The output string should not have any adjacent duplicates. Input: The first line of input contains an integer T, denoting the no of test cases. Then T test cases follow. Each test case contains a string str. Output: For each test case, print a new line containing the resulting string. Constraints: 1<=T<=100 1<=Length of string<=50 Example: Input: 2 geeksforgeek acaaabbbacdddd Output: gksforgk acac""" def removeDuplicatesUtil(s, start): global isDone if len(s) <= 1: return s flag = False while start < len(s) - 1: end = start while end < len(s)-1 and s[start] == s[end+1] : end = end+1 flag = True if flag == True: break else: start = start + 1 #print('{} {} {}'.format(s, start, end)) if start == len(s)-1: return s else: isDone = False return removeDuplicatesUtil(''.join([s[:start], s[end+1:]]), end+1 - (end-start+1)) t = int(input()) for tc in range(t): s = input() isDone = False while not isDone: isDone = True s = removeDuplicatesUtil(s, 0) print(s)
9e3c584d6abbaef261deec773a389410f4495381
rafaelperazzo/programacao-web
/moodledata/vpl_data/425/usersdata/323/92032/submittedfiles/dec2bin.py
324
3.828125
4
# -*- coding: utf-8 -*- p=int(input('Digite o número menor: ')) q=int(input('Digite o número maior: ')) p1 = p cont=0 while p>0: cont=cont+1 p=p//10 i=0 while q>0: if q%(10**cont) ==p1: i=0 break else: i=i+1 q=q//10 if i!=0: print ('N') elif i==0: print('S')
57ac2f88d033e63c723963a2a48aff490af3d022
austinsonger/CodingChallenges
/Hackerrank/Algorithms/quicksort2/quicksort2.py
494
3.984375
4
#!/usr/bin/env python import sys def print_list(ar): print(' '.join(map(str, ar))) def quicksort(ar): if len(ar) <= 1: return ar else: left = quicksort([n for n in ar if n < ar[0]]) right = quicksort([n for n in ar if n > ar[0]]) print_list(left + [ar[0]] + right) return left + [ar[0]] + right if __name__ == '__main__': n = int(sys.stdin.readline()) ar = list(map(int, sys.stdin.readline().split())) quicksort(ar)
439598aac4f7f16ea0b2a6ec378dfb9be4f435a7
hauntgossamer/Sprint-Challenge--Data-Structures-Python
/reverse/reverse.py
1,887
4.09375
4
class Node: def __init__(self, value=None, next_node=None): self.value = value self.next_node = next_node def get_value(self): return self.value def get_next(self): return self.next_node def set_next(self, new_next): self.next_node = new_next class LinkedList: def __init__(self): self.head = None def add_to_head(self, value): node = Node(value) if self.head is not None: node.set_next(self.head) self.head = node def contains(self, value): if not self.head: return False current = self.head while current: if current.get_value() == value: return True current = current.get_next() return False def reverse_list(self, node, prev): if node is self.head and not self.head: return if node is self.head and not self.head.next_node: return elif node.next_node: if node.next_node: next_node = node.get_next() node.next_node = prev return self.reverse_list(next_node, node) if node.next_node is None: self.head = node self.head.next_node = prev return # runtime of O(n) aka linear time complexity # sll = LinkedList() # sll.add_to_head(1) # sll.add_to_head(2) # sll.add_to_head(3) # sll.add_to_head(4) # sll.add_to_head(5) # sll.add_to_head(6) # sll.reverse_list(sll.head, None) # print(sll.head.get_value()) # print(sll.head.get_next().get_value()) # print(sll.head.get_next().get_next().get_value()) # print(sll.head.get_next().get_next().get_next().get_value()) # print(sll.head.get_next().get_next().get_next().get_next().get_value()) # print(sll.head.get_next().get_next().get_next().get_next().get_next().get_value())
7b73be412985cb0fa75585063e7581e3f0de024a
MKotlik/UGE
/v0.3.0/oldParser.py
7,387
3.796875
4
from display import * from matrix import * from draw import * from transformOps import * import matrixOps import time # TODO: Update the command list """ Goes through the file named filename and performs all of the actions listed in that file. The file follows the following format: Every command is a single character that takes up a line Any command that requires arguments must have those arguments in the second line. The commands are as follows: line: add a line to the edge matrix - takes 6 arguemnts (x0, y0, z0, x1, y1, z1) ident: set the transform matrix to the identity matrix - scale: create a scale matrix, then multiply the transform matrix by the scale matrix - takes 3 arguments (sx, sy, sz) move: create a translation matrix, then multiply the transform matrix by the translation matrix - takes 3 arguments (tx, ty, tz) rotate: create a rotation matrix, then multiply the transform matrix by the rotation matrix - takes 2 arguments (axis, theta) axis should be x, y or z apply: apply the current transformation matrix to the edge matrix display: draw the lines of the edge matrix to the screen display the screen save: draw the lines of the edge matrix to the screen save the screen to a file - takes 1 argument (file name) quit: end parsing See the file script for an example of the file format """ def parse_file(fname, points, polygons, transform, screen, color): with open(fname, 'r') as script: keepReading = True while keepReading: line = script.readline() cLine = line.strip("\n").lower() # --- LINE --- # if cLine == "line": args = script.readline().split(" ") if len(args) != 6: raise ValueError("line call must be followed by 6 args") else: add_edge(points, [int(args[0]), int(args[1]), int(args[ 2])], [int(args[3]), int(args[4]), int(args[5])]) # --- TRANSFORMATIONS --- # elif cLine == "ident": transform = matrixOps.createIdentity(4) elif cLine == "scale": args = script.readline().split(" ") if len(args) != 3: raise ValueError( "scale call must be followed by 3 args") else: transform = scale(transform, int( args[0]), int(args[1]), int(args[2])) elif cLine == "move": args = script.readline().split(" ") if len(args) != 3: raise ValueError("move call must be followed by 3 args") else: transform = translate(transform, int( args[0]), int(args[1]), int(args[2])) elif cLine == "rotate": args = script.readline().split(" ") if len(args) != 2: raise ValueError("rotate call must be followed by 2 args") else: transform = rotate(transform, args[0], int(args[1])) # --- CURVES --- # elif cLine == "circle": args = script.readline().split(" ") if len(args) != 4: raise ValueError("circle call must be followed by 4 args") else: add_circle(points, int(args[0]), int(args[1]), int(args[2]), int(args[3]), 1000) elif cLine == "bezier": args = script.readline().split(" ") if len(args) != 8: raise ValueError("bezier call must be followed by 8 args") else: add_bezier(points, int(args[0]), int(args[1]), int(args[2]), int(args[3]), int(args[4]), int(args[5]), int(args[6]), int(args[7]), 1000) elif cLine == "hermite": args = script.readline().split(" ") if len(args) != 8: raise ValueError("hermite call must be followed by 8 args") else: add_hermite(points, int(args[0]), int(args[1]), int(args[2]), int(args[3]), int(args[4]), int(args[5]), int(args[6]), int(args[7]), 1000) # --- 3D SHAPES --- # elif cLine == "box": args = script.readline().split(" ") if len(args) != 6: raise ValueError("box call must be followed by 6 args") else: add_box(polygons, int(args[0]), int(args[1]), int(args[2]), int(args[3]), int(args[4]), int(args[5])) elif cLine == "sphere": args = script.readline().split(" ") if len(args) != 4: raise ValueError("sphere call must be followed by 4 args") else: add_sphere(polygons, int(args[0]), int(args[1]), int(args[2]), int(args[3]), 20) # adjust steps elif cLine == "torus": args = script.readline().split(" ") if len(args) != 5: raise ValueError("sphere call must be followed by 5 args") else: add_torus(polygons, int(args[0]), int(args[1]), int(args[2]), int(args[3]), int(args[4]), 20) # --- IMAGE CMDS --- # elif cLine == "apply": if len(points) > 0: points = matrixOps.multiply(transform, points) if len(polygons) > 0: polygons = matrixOps.multiply(transform, polygons) elif cLine == "display": clear_screen(screen) # pretty sure it's necessary if len(points) > 0: draw_lines(points, screen, color) if len(polygons) > 0: draw_polygons(polygons, screen, color) display(screen) time.sleep(0.5) elif cLine == "clear": points = [] polygons = [] clear_screen(screen) # Possibly redundant elif cLine == "save": args = script.readline().split(" ") if len(args) != 1: raise ValueError("save call must be followed by 1 arg") else: clear_screen(screen) # pretty sure it's necessary if len(points) > 0: draw_lines(points, screen, color) if len(polygons) > 0: draw_polygons(polygons, screen, color) save_extension(screen, args[0]) elif cLine.startswith("#"): # This is a comment pass elif cLine == "quit": keepReading = False elif line == "\n": # Blank line pass elif line == "": # End of file keepReading = False else: raise TypeError("Script command unrecognized: " + cLine)
60b53196052156f8c90d82a926ddd2e0ac9abe87
phaustin/canvas_scripting
/e340py/dump_comments.py
1,474
3.5625
4
#!/usr/bin/env python """ example usage: dump_comments "/Users/phil/Downloads/Day 02_ Pre-Class Quiz Quiz Student Analysis Report.csv" > out.txt """ import sys import numbers import numpy as np import pandas as pd import argparse import pdb import textwrap def make_parser(): linebreaks = argparse.RawTextHelpFormatter descrip = textwrap.dedent(globals()['__doc__']) parser = argparse.ArgumentParser(formatter_class=linebreaks, description=descrip) parser.add_argument('csv_file', type=str, help='full path to csv file -- pha') return parser def main(args=None): """ args: optional -- if missing then args will be taken from command line """ parser = make_parser() args = parser.parse_args(args) df_quiz=pd.read_csv(args.csv_file) #pdb.set_trace() posvec=[] dashes='-'*20 # # find the column number that contains "Articulate" # for item in df_quiz.columns: lowercase=item.lower() posvec.append(lowercase.find('articulate')>-1) colnum=np.arange(len(df_quiz.columns))[posvec][0] # # grab all rows for that column and print to stdout # responses=df_quiz.iloc[:,colnum] for item in responses: # # skip empty cells with nan entrines # if isinstance(item,numbers.Real): continue print(f'\n{dashes}\n{item}\n{dashes}\n') if __name__=="__main__": main()
22f3f94019bc09a2edac0b8c72626a8cffe88541
dransonjs/my_python_test_codes
/PycharmProjects/Class_16_Homework/homework_0426/lemon_0426_03_homework_2.py
6,834
3.9375
4
import unittest from homework_0426.lemon_0419_07_homework import MathCalculate class TestDivide(unittest.TestCase): """ 测试减法类 """ @classmethod def setUpClass(cls): cls.file_name = 'test_result_2.txt' cls.file = open(cls.file_name, mode='a', encoding='utf8') cls.file.write('{:=^40s}\n'.format('开始执行用例')) def test_positives(self): """ 测试两个正数相除 :return: """ actual_result = MathCalculate(1, 2).divide() expect_result = 1 msg = '测试两个正数相除' fail_msg = '两个正数相除测试失败' try: self.assertEqual(actual_result, expect_result, msg=fail_msg) except AssertionError as e: print('具体异常为:{}'.format(e)) self.file.write('{},执行结果:{},具体异常为:{}\n'.format(msg, 'fail', e)) raise e else: self.file.write('{},执行结果:{}\n'.format(msg, 'pass')) def test_negatives(self): """ 测试两个负数相除 :return: """ actual_result = MathCalculate(-1, -2).divide() expect_result = 0.5 msg = '测试两个负数相除' fail_msg = '两个负数相除测试失败' try: self.assertEqual(actual_result, expect_result, msg=fail_msg) except AssertionError as e: print('具体异常为:{}'.format(e)) self.file.write('{},执行结果:{},具体异常为:{}\n'.format(msg, 'fail', e)) raise e else: self.file.write('{},执行结果:{}\n'.format(msg, 'pass')) def test_pos_neg(self): """ 测试前者正数、后者负数相除 :return: """ actual_result = MathCalculate(1, -2).divide() expect_result = -0.5 msg = '测试前者正数、后者负数相除' fail_msg = '前者正数、后者负数相除测试失败' try: self.assertEqual(actual_result, expect_result, msg=fail_msg) except AssertionError as e: print('具体异常为:{}'.format(e)) self.file.write('{},执行结果:{},具体异常为:{}\n'.format(msg, 'fail', e)) raise e else: self.file.write('{},执行结果:{}\n'.format(msg, 'pass')) def test_neg_pos(self): """ 测试前者负数、后者正数相除 :return: """ actual_result = MathCalculate(-1, 2).divide() expect_result = -0.5 msg = '测试前者负数、后者正数相除' fail_msg = '前者负数、后者正数相除测试失败' try: self.assertEqual(actual_result, expect_result, msg=fail_msg) except AssertionError as e: print('具体异常为:{}'.format(e)) self.file.write('{},执行结果:{},具体异常为:{}\n'.format(msg, 'fail', e)) raise e else: self.file.write('{},执行结果:{}\n'.format(msg, 'pass')) def test_neg_zero(self): """ 测试前者负数、后者为0相除 :return: """ actual_result = MathCalculate(-1, 0).divide() expect_result = ZeroDivisionError msg = '测试前者负数、后者为0相除' fail_msg = '前者负数、后者为0相除测试失败' try: self.assertIsInstance(actual_result, expect_result, msg=fail_msg) except AssertionError as e: print('具体异常为:{}'.format(e)) self.file.write('{},执行结果:{},具体异常为:{}\n'.format(msg, 'fail', e)) raise e else: self.file.write('{},执行结果:{}\n'.format(msg, 'pass')) def test_zero_neg(self): """ 测试前者为0、后者负数相除 :return: """ actual_result = MathCalculate(0, -2).divide() expect_result = 0 msg = '测试前者为0、后者负数相除' fail_msg = '前者为0、后者负数相除测试失败' try: self.assertEqual(actual_result, expect_result, msg=fail_msg) except AssertionError as e: print('具体异常为:{}'.format(e)) self.file.write('{},执行结果:{},具体异常为:{}\n'.format(msg, 'fail', e)) raise e else: self.file.write('{},执行结果:{}\n'.format(msg, 'pass')) def test_zero_pos(self): """ 测试前者为0、后者正数相除 :return: """ actual_result = MathCalculate(0, 2).divide() expect_result = 0 msg = '测试前者为0、后者正数相除' fail_msg = '前者为0、后者正数相除测试失败' try: self.assertEqual(actual_result, expect_result, msg=fail_msg) except AssertionError as e: print('具体异常为:{}'.format(e)) self.file.write('{},执行结果:{},具体异常为:{}\n'.format(msg, 'fail', e)) raise e else: self.file.write('{},执行结果:{}\n'.format(msg, 'pass')) def test_pos_zero(self): """ 测试前者为正数、后者为0相除 :return: """ actual_result = MathCalculate(1, 0).divide() expect_result = ZeroDivisionError msg = '测试前者为正数、后者为0相除' fail_msg = '前者为正数、后者为0相除测试失败' try: self.assertIsInstance(actual_result, expect_result, msg=fail_msg) except AssertionError as e: print('具体异常为:{}'.format(e)) self.file.write('{},执行结果:{},具体异常为:{}\n'.format(msg, 'fail', e)) raise e else: self.file.write('{},执行结果:{}\n'.format(msg, 'pass')) def test_zero_zero(self): """ 测试两个0相除 :return: """ actual_result = MathCalculate(0, 0).divide() expect_result = ZeroDivisionError msg = '测试两个0相除' fail_msg = '两个0相除测试失败' try: self.assertIsInstance(actual_result, expect_result, msg=fail_msg) except AssertionError as e: print('具体异常为:{}'.format(e)) self.file.write('{},执行结果:{},具体异常为:{}\n'.format(msg, 'fail', e)) raise e else: self.file.write('{},执行结果:{}\n'.format(msg, 'pass')) @classmethod def tearDownClass(cls): cls.file.write('{:=^40s}\n'.format('用例执行结束')) cls.file.close() if __name__ == '__main__': unittest.main()
cf64911035429aecc58eb8ed4f9c69303ebe8a36
frank217/Summer-Coding-2018
/Dynamic Programming/ jumpGame.py
1,475
3.6875
4
# Conquer and divide """ JumpGame. Given n x n board with a number 1 ~ 9 in each panel, a player try to move from topleft corner to bottom right corner. The number on panel mean how many blocks a Player can move down or right. Can player reach the end? Input : fanmeet.txt 4 FFFMMM MMMFFF FFFFF FFFFFFFFFF FFFFM FFFFFMMMMF MFMFMFFFMMMFMF MMFFFFFMFFFMFFFFFFMFFFMFFFFMFMMFFFFFFF Expected Output : 1 6 2 2 """ def jump(board,x,y,cache): n = len(board) if y >= n or x >= n: return 0 if y == n - 1 and x == n-1 : return 1 result = cache[x][y] # If there was cached info use it if result != -1: return result # If no cache find the value jumpsize = board[x][y] result = (jump(board, x + jumpsize, y, cache) or jump(board,x, y+jumpsize, cache)) cache[x][y] = result return result f_out = open('jumpOutput.txt', 'w') f_in = open('jump.txt', 'r') # print (f_in.readlines()) lines = [line.strip() for line in f_in.readlines()][0:] # print (lines) cur = 1 for case in range(int(lines[0])): n = int(lines[cur]) cur +=1 board = [] for i in range(n): line = [] for j in lines[cur+i]: line.append(int(j)) board.append(line) cur += n cache = [[-1 for i in range(len(board))] for i in range(len(board))] # print (board,cache) result = jump(board,0,0, cache) print (cache) print (result) # break f_out.close()
d056787a0a4dda79c8d7d125b5cfd646035b5728
WeberLiu94/Data-Structure-and-Algorithms-for-Python-1
/Recursion/integer part of log2n.py
225
3.78125
4
def integer_log2n(number, result): if number < 2: return result else: return integer_log2n(number/2, result+1) #整数部分是元素能够整除2的次数 result = integer_log2n(12, 0) print(result)
ed99ff3dcc7cdc2dd4dbebe6840e3812fb547a41
AlyoshaS/ProgFuncional-Python
/Exercicios-Prog-Funcional/4.py
490
4.125
4
#!/usr/bin/python # coding: latin-1 # início - recursão mútua # 04. Defina dois predicados lógicos '[even]' e '[odd]' que # indiquem se um número 'n' passado como argumento é par ou ímpar respectivamente. # Não é permitido o uso do operador '%' (resto da divisão). def even(n): if n == 0: return True else: return odd(n-1) def odd(n): if n == 0: return False else: return even(n-1) print(even(5), even(6)) print(odd(5), odd(6))
e728fdb1825fe9d9ea161446df1a3e365c268b70
shruti-par/cs6200
/Assignment1/count_duplicates.py
219
3.78125
4
# Program to count the number of duplicate links encountered during focused BFS input_file = open("Duplicate_links_Task2.txt", 'r') c = sum(1 for line in input_file) print("Number of duplicate links encountered: ", c)
1fe69b614a17e17228ee33e07689e8920c303ee5
anilkohli98/My-Assignments
/tuples.py
325
3.859375
4
tup=(1,2,3,4,4)#this is a packing of tuples #imutable #hetrogenius #used for storing large amount of data #faster than lists #baki sb kuch same h lists k jese print(tup) v1,v2,v3,v4=tup print(v1)#this is unpacking of tuples tup=(1,2,3,4,(1,2,3,4)) print(tup) print(tup.count(1))#counts the number wit in it print(tup[4][0:])
c0abb1de3be7cd1fec68d5cf18705038c8ac8e70
NikaEgorova/goiteens-python3-egorova
/lesson_tasks/lesson7/num2.py
79
3.703125
4
nums = {1: "one", 2: "two", 3: "three"} for key in nums.keys(): print(key)
fecd846b3dcf62a288378065d8123726e961c173
LiyangLingIntel/TextExtractor
/src/py/test/full_text.py
6,460
3.5625
4
# 2019-05-28 # Full Text Search on monthly sentences and projection sentences import os, re, xlwt from py.extractor import InfoTools, ConvenantTools if __name__ == '__main__': """ Monthly & Projection extraction core steps: 1. According to keywords to do full text search, cut before and after keywords 150 words as sentences 1.1. "financial statement, financial report, consolidated, consolidating, balance sheet, cash flow statement, 
 statement of cash flow, income statement, statement of income, audited, unaudited" for Monthly 1.2. "budgeted budgets budget projections projected projection forecasted forecast anticipated anticipations anticipation plans plan" for Projections For Projections 2.1 For each sentence, find the position of "month,monthly", if there are any numbers or words representing number among before and after the position 3 words, this sentence would be filtered. 2.2 For each sentence, 5 wordsb Before and after "plan, plans", there should NOT have any "stock, equity, incentive, option, retire, retirement, pension, employee" 2.3 For each sentence, there should have "provide, deliver, delivery, report, prepare, submit, send, express, communicate, convey, direct, guide, assign, issue, grant" What's more 3. USE a variable to record whether the first ten valid lines of each file contain words like "bank*, debt*, loan*, credit*,borrow*" or not 4. USE a variable to record whether the file is original or not, by keys "AMENDED, AMENDMENT, RESTATED, revis, amend, modif, restate, supplement, addendum" 5. Use three xlsx file to contain results, one for file name/is amended/is debt...,one for monthly,one for projection """ info_tools = InfoTools() covenant_processor = ConvenantTools() fail_list = [] text_folder = './text/txt_result/' suc_counter = 0 err_counter = 0 date_dict = {} year_file_dic = {} years = [1996, 2018] for year in range(*years): year_folder = os.path.join(text_folder, str(year)) year_file_dic[year] = [file for file in os.listdir(year_folder) if file.endswith('.txt')] types = ['basic', 'duedate', 'proj'] headers = {} headers['basic'] = ['name', 'is_original', 'is_debt', 'first_lines'] headers['duedate'] = ['name', 'shorten_sen', 'is_new', 'due_date_sen'] headers['proj'] = ['name', 'shorten_sen', 'is_new', 'projection_sen'] books = {} sheets = {} row_counter = {} for year, file_names in tuple(year_file_dic.items())[:1]: # 初始化excel workbook,否则信息会累加到后面的文件中 for t in types: books[t] = xlwt.Workbook() sheets[t], row_counter[t] = info_tools.write_xls_header(headers[t], books[t]) date_dict[year] = {'duedate': 0, 'proj': 0} year_folder = os.path.join(text_folder, str(year)) for name in file_names: is_debt = False # check first line to get origin and debt info about this contract with open(os.path.join(year_folder, name), 'r', encoding='utf-8') as f: lines = [line for line in f.readlines() if line.strip()] first_lines = covenant_processor.get_n_lines(5, lines) is_origin = True if covenant_processor.is_original(first_lines) else False is_debt = True if re.search(info_tools.debt_pat, covenant_processor.get_n_lines(10, lines)) else False content = '\n'.join(lines) del lines # cleaning content = re.subn(r'\-[0-9]{1,2}\-', '', content)[0] content = re.subn(r'[-=_ ]{5,}', '', content)[0] fin_sens = info_tools.global_search_by_fin_key(content, 150) proj_sens = info_tools.global_search_by_proj_key(content, 150) fin_full_shorten_sens = info_tools.global_filter_by_key(fin_sens, pattern='month_pat') proj_full_shorten_sens = info_tools.global_filter_by_key(proj_sens, pattern='date_pat') # write info into xls by each file iteration sheets['basic'], row_counter['basic'] = info_tools.write_xls_sheet(sheet=sheets['basic'], row=row_counter['basic'], headers=headers['basic'], name=name, is_original=is_origin, is_debt=is_debt, first_lines=first_lines) if fin_full_shorten_sens: date_dict[year]['duedate'] += 1 sheets['duedate'], row_counter['duedate'] = info_tools.write_xls_sheet(sheet=sheets['duedate'], row=row_counter['duedate'], headers=headers['duedate'], name=name, matched_sens=fin_full_shorten_sens) if proj_full_shorten_sens: date_dict[year]['proj'] += 1 sheets['proj'], row_counter['proj'] = info_tools.write_xls_sheet(sheet=sheets['proj'], row=row_counter['proj'], headers=headers['proj'], name=name, matched_sens=proj_full_shorten_sens) for t in types: books[t].save(os.path.join('./output/fulltext', f'{t}_{year}.xls')) del books[t] print(f'{year}: ') print('monthly\t', date_dict[year]['duedate'], ' / ', len(year_file_dic[year])) print('project\t', date_dict[year]['proj'], ' / ', len(year_file_dic[year])) print('finished!')
19a70fffa93e3640d8da078d11e99f9dd500bca3
python-yc/pycharm_script
/入门学习/socket_tcp_server_eg.py
2,051
3.671875
4
""" # 6.2 TCP编程 - 面向连接的传输,即每次传输之前都需要先建立一个链接 - 客户端和服务器两个程序需要编写 - Server端的编写流程 - 1.建立socket负责具体通信,这个socket其实只负责接受对方的请求 - 2.绑定端口号和地址 - 3.监听接入的访问socket - 4.接收访问的socket,可以理解接受访问即建立了一个通讯的连接通路 - 5.接收对方的发送内容,利用接收到的socket接收内容 - 6.如果有必要,给对方发送反馈信息 - 7.关闭连接通路 """ #socket模块负责socket编程 import socket #模拟服务器的函数 def tcp_srv(): #1.建立socket,建立socket,socket是负责具体通信的一个实例 #需要用到两个参数 #socket.AF_INET:使用ipv4协议 #socket.SOCK_DGRAM:使用UDP通信 sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #2.绑定ip和port #127.0.0.1:这个ip地址代表的是机器本身 #78998:自己指定一个端口号 #地址是一个tuple类型,(ip,port) addr = ("127.0.0.1",8998) sock.bind(addr) #3.监听接入的访问socket sock.listen() while True: # 4.接受访问的socket,可以理解接受访问即建立了一个通讯的连接通路 # accept返回的元组第一个元素赋值给skt,第二个赋值给addr skt, addr = sock.accept() # 5.接收对方的发送内容,利用接收到的socket接收内容 # 500代表接收使用的buffersize #msg = skt.reveive(500) msg = skt.recv(500) # 接收到的是bytes格式内容 #想得到str格式的需要进行解码 rst = "Received msg:{0} from {1}".format(msg,addr) print(rst) # 6.如果有必要,给对方发送反馈消息 skt.send(rst.decode()) # 7.关闭连接通路 skt.close() if __name__ == '__main__': print("Starting server......") tcp_srv() print("Ending server......")
09e375e3a6b31bb292d09f7d8553a845e773bf8c
Patito1042/Telegram-Bot-Axie-Help
/utils/db_api/db_load.py
852
3.6875
4
import sqlite3 conn = sqlite3.connect('database.db') cursor = conn.cursor() # Создать таблицу при запуске приложения def create_db(): cursor.execute("""CREATE TABLE IF NOT EXISTS users( userid INT PRIMARY KEY, name TEXT, privileges INT DEFAULT 0, language STRING DEFAULT RU, currencies STRING DEFAULT USD, fraction INT DEFAULT 100); """) conn.commit() # Добавить данные в таблицу командой "@Обновить БД" из admin_command def upgrade_table_user_db(): cursor.execute("""ALTER TABLE users ADD COLUMN language STRING DEFAULT RU;""") cursor.execute("""ALTER TABLE users ADD COLUMN currencies STRING DEFAULT USD;""") cursor.execute("""ALTER TABLE users ADD COLUMN fraction INT DEFAULT 100;""") conn.commit()
ccf22290ec97dba9963b552f902f5f1bf0fab458
zoushiqing/python
/第二章 python核心编程/第1节 python核心编程/类当做装饰器.py
1,103
3.578125
4
class Test(object): # 如果没有这个直接 对象() 会报错 def __call__(self, *args, **kwargs): pass # # 在init方法之前调用 # def __new__(cls, *args, **kwargs): # pass # # # 在对象删除时触发__del__(self),然后再删除对象自己。 # def __del__(self): # pass # # # 不知道大家再写程序是,打印一个实例化对象时,打印的其实时一个对象的地址。而通过__str__()函数就可以帮助我们打印对象中具体的属性值,或者你想得到的东西。 # def __str__(self): # pass # # # 新生对象不能 动态添加这些属性 # __slots__ = ("haha", "hheh") t = Test() t() class Test1(object): def __init__(self, func): print("执行了init---") self.__func = func def __call__(self, *args, **kwargs): print("执行了call--") self.__func() @Test1 def test(): print("test---") # 当还没执行test()方法的时候 就会调用类的init方法了 # 执行了init--- # test() # 执行了call-- # test---
3db87841ad9ce5d2d17891aac7ff7aa1e8ce9734
XXXalice/cardgame
/cardgame/Deck.py
1,479
3.640625
4
class Deck: def __init__(self): #デッキを構築するよ〜 #ジョーカーを入れるオプションはつけてないよ〜 card_elem = ["spade","heart","clover","diamond"] self.deck = [elem + "_" + str(num) for num in range(1,14) for elem in card_elem] def shuffle(self): #まぜまぜ〜 import random random.shuffle(self.deck) def draw(self,num=1, num_inspect=False): #num枚山札から引くよ〜 #カードに描かれた数値のみ知りたいときはnum_inspectをTrueにして呼び出してね cards = [] for iterate in range(num): drawed = self.deck[0] cards.append(drawed) self.deck.remove(drawed) return self.inspect(cards=cards, is_elem=False) if num_inspect == True else cards def inspect(self, cards, is_elem=False): #カードの属性もしくは数値を調べるよ〜 #数値を調べたいときはis_elemをFalseにして呼び出してね int型のリストを返すよ idx = 0 if is_elem == True else 1 inspected = [] for card in cards: inspected.append(card.split("_")[idx]) if idx == 1: inspected = list(map(int, inspected)) return inspected def distribute(self, num=1): cards = [] for dist in range(num): self.shuffle() cards += self.draw() return cards
201a1451136f655da44dae9139ea56739c0b9214
neverkor/labi
/python/laba8.py
3,000
3.515625
4
import numpy as np import matplotlib.pyplot as plt import time # Расчет по формуле (x-centr_x)**2 + (y - centr_y)**2 <= radius**2 def calc(x, y): for key in x: key_x = (key - centr_x)**2 result_x.append(key_x) for key in y: key_y = (key - centr_y)**2 result_y.append(key_y) result = list(map(lambda a, b: a + b, result_x, result_y)) enter = 0 not_enter = 0 for key in result: if key <= radius**2: enter += 1 else: not_enter += 1 print('Входит или лежит на окружности точек:', enter, '\nНе входит:', not_enter) print('Центр окружности:', centr_x, ';', centr_y) print('Точек всего:', point) # Поиск точек по одной размерности def search(x, y): global os_y global os_x point_x = float(input('Введите координату поиска X: ')) start = time.time() for key in x: if key == point_x: os_x.append(key) print('На этой координате найдено точек:', len(os_x)) len_x = len(os_x) if len(os_x) != len(y): os_y = os_y[:len_x] end = time.time() times.append(end - start) print('Время выполнения поиска точек:', *times) # Графическое изображение (не обязательно, так нагляднее) def graphic(x, y): global os_x global os_y circle = plt.Circle((centr_x, centr_y), radius, color='blue', fill=False) fig, ax = plt.subplots() ax.add_artist(circle) ax.axis("equal") plt.xlim(-50, 50) plt.ylim(-50, 50) plt.scatter(x, y, s=0.5, color='red') plt.scatter(os_x, os_y, s=1, color='black') plt.show() os_x = [] os_y = y centr_x = float(input('Введите координату Х для центра окружности: ')) centr_y = float(input('Введите координату Y для центра окружности: ')) radius = float(input('Введите радиус окружности: ')) point = int(input('Введите количество точек: ')) times = [] # Генерация случайных координат для точек x = np.random.random_integers(-49, 49, point) y = np.random.random_integers(-49, 49, point) result_x = [] result_y = [] calc(x, y) os_x = [] os_y = y # Цикл поиска и графического изображения while radius > 0: search(x, y) graphic(x, y) # Выход по желанию exit_prog = input('Хотите выйти? (y/n): ') if 'y' in exit_prog: print('Вы вышли из программы.') break # Запись в файл времени выполнения times = str(times) file = open('time.txt', 'w') file.write(times) file.close() print('Время выполнения записано в файл time.txt')
2cc0adac32b24618513afde7903fb3b6ed830e72
KaviGamer/first_python
/test.py
479
4.0625
4
import random; rn = [1,2,3,4,5,6,7,8,9,10]; rnc = random.choice(rn); print(rnc); print("Number Guessing Game!"); print("Instructions:"); print("Guess a number between one to ten"); gn = input("Guess a number --> "); while gn>rn: print("YOU'RE WRONG. GUESS A NUMBER LESS THAN "+str(gn)); gn = input("Guess a number --> "); while gn<rn: print("YOU'RE WRONG. GUESS A NUMBER MORE THAN "+str(gn)); gn = input("Guess a number --> "); if gn==rn: print("YOU WIN!");
7dacf4e2164c5bda1dcda4f9f2d6dc1e58aa30db
UNASP-SISTEMAS-DE-INFORMACAO/introducao-ao-github-yugo-harago
/aula02.py
163
3.921875
4
import pandas as pd print("cadastro produto") d1 = {'id':[1,2,3],'name':['frozen','fire','gun'],'price':[10,15,30]} df1 = pd.DataFrame(d1) print(df1) print(df1)
78c46376de5a272f371fba36717f9f9d81fc9131
TheFatPanda97/Introduction-to-Python
/Assignment 3/handins/A3Ailen_Meng.py
2,554
4.25
4
from typing import Dict A = ["", "", ""] B = ["", "", ""] C = ["", "", ""] possible_moves = ["A1", "A2", "A3", "B1", "B2", "B3", "C1", "C2", "C3"] lines = ["A", "B", "C", "1", "2", "3", "/", "\\"] game_board = [A, B, C] """ This is the logic portion of Tic Tac Toe game you are in charge of.x Note: store this and the visualizer.py in the same folder, otherwise the game may not display Words Definition: iff: if and only if meaning both direction of a logic statement has to be true Eg: you will pass iff you get 50 Direction 1: you will pass if you get a 50 (True) Direction 2: if you get a 50, you will pass(True) """ def validate_string(x, lst) -> bool: """ Returns True iff string is in lst. """ return x in lst def setup_game() -> Dict[str, int]: """ Determines the piece of choice for the player 1 and player 2. >>>setup_game() """ xo = '' while xo != 'x' and xo != 'o' and xo != 'X' and xo != 'O': xo = str(input("Choose x or o:")) if xo == 'x' or xo == 'X': return {"P1": 1, "P2": 0} else: return {"P1": 0, "P2": 1} def print_board(): """ Prints out the contents of the game board. """ [print(game_board[i]) for i in range(3)] def create_section(section: str): """ Returns a sublist of the specified section. Sublists should always start with an element in the A column and end with an element in the C column. >>> create_section("A") ['', '', ''] """ if section == 'A': return A if section == 'B': return B if section == 'C': return C if section == '1': return [A[0], B[0], C[0]] if section == '2': return [A[1], B[1], C[1]] if section == '3': return [A[2], B[2], C[2]] if section == '/': return [A[2], B[1], C[0]] if section == '\\': return [A[0], B[1], C[2]] def concat_section(lst): """ Returns the section as a concatenate string. Shawn, you have found an easter egg! I will now delete your system 32. """ return ' '.join(lst).replace(' ', '') def check_win(symbol): """ Returns true iff the specified symbol has a line of 3 in a row within the game board. """ for i in lines: if concat_section(create_section(i)).count(symbol) == 3: return True def board_full(): """ Returns true iff the board is full """ for i in game_board: for x in i: if x != '1' and x != '0': return False return True
4ae2cc6fd8c4cb60e722256c6984cd24488c2a81
Abdurrahmans/Data-Structure-And-Algorithm
/CheckPolindromNumber.py
327
4.15625
4
number = int(input("Enter a number:")) ReversNumber = 0 temp = number while temp!=0: RightDigit = temp%10 ReversNumber=(ReversNumber*10) + RightDigit temp //=10 if ReversNumber==number: print(" {} is Polindrome number".format(number)) else: print(" {} is not Polindrome number".format(number))
df0cbc33da43e1612c5edd79fbc72b64fb3f4fef
marcinwal/eulerFun
/euler004.py
422
3.515625
4
def isPalindrom(string): if len(string) <= 1: return True if (string[0] != string[-1]): return False return isPalindrom(string[1:-1]) def findMaxThreeDigitsMultPalindrom(): max=(0,0,0) for i in range(100,999): for j in range(i,999): number = i * j if isPalindrom(str(number)) and number>max[0]: max = (number,i,j) return max print findMaxThreeDigitsMultPalindrom()
a93db487ca0a5a453edf6fe2375a2be25951553d
GlenboLake/DailyProgrammer
/C206E_recurrence_relations_1.py
451
3.75
4
from functools import reduce def recur(init, relation): steps = relation.split() return reduce(lambda x, step: eval(str(x)+str(step)), steps, init) def print_recurrence(init, relation, times): print('Term 0:', init) for i in range(times): init = recur(init, relation) print('Term {}: {}'.format(i+1, init)) if __name__ == '__main__': print_recurrence(1, '*2 +1', 10) print() print_recurrence(1, '*-2', 8)
6f27731ef9a0ebb8f9d6d239c4947c4b93210ef0
zuoyuanwei/package
/code/rectcover of mat.py
446
3.65625
4
# -*- coding:utf-8 -*- class Solution: def rectCover(self, number): # write code here if number == 0: return 0 if number == 1: return 1 if number == 2: return 2 else: f = [None] * number f[0] = 1 f[1] = 2 for i in range(2, number): f[i] = f[i - 1] + f[i - 2] a = f[number - 1] return a
73447338e24691b4a4bafaf338fbf0ebf6a772df
v-v-d/algo_and_structures_python
/Lesson_1/9.py
870
4.21875
4
# 9.Вводятся три разных числа. Найти, какое из них # является средним (больше одного, но меньше другого). try: num_1 = float(input('Введите число №1: ')) num_2 = float(input('Введите число №2: ')) num_3 = float(input('Введите число №3: ')) if num_1 == num_2 == num_3: print('Числа одинаковые') elif num_1 == num_2 or num_1 == num_3 or num_2 == num_3: print('Два из трех чисел одинаковые') else: if num_2 < num_1 < num_3: print(num_1) elif num_1 < num_2 < num_3: print(num_2) else: print(num_3) except ValueError: print('Необходимо ввести число, разделитель - точка')
156c005202783feaa5dfbf4e87f366825d93add3
wowchois/study
/Algorithm/Programmers/kakao_2019_blind_level2_오픈채팅방.py
825
3.8125
4
''' TEST CASE INPUT : ["Enter uid1234 Muzi", "Enter uid4567 Prodo","Leave uid1234","Enter uid1234 Prodo","Change uid4567 Ryan"] RESULT : ["Prodo님이 들어왔습니다.", "Ryan님이 들어왔습니다.", "Prodo님이 나갔습니다.", "Prodo님이 들어왔습니다."] https://programmers.co.kr/learn/courses/30/lessons/42888 ''' def solution(record): answer = [] spArr = [x.split() for x in record] nameDict = {} for i in spArr : if i[0] != 'Leave' : nameDict[i[1]] = i[2] for j in spArr : if j[0] == 'Change' : continue txt = '{0}님이 '.format(nameDict[j[1]]) if j[0] == 'Enter' : txt += '들어왔습니다.' elif j[0] == 'Leave' : txt += '나갔습니다.' answer.append(txt) return answer
0ddd7e5920147d31267f808773ee4591a0565f8b
nilsmartel/ai-lecture
/csp/backtracking.py
1,317
3.9375
4
#!/usr/local/bin/python3 def backtrack(variables, domain, constraints, setup={}): # create clones so we won't mutate call arguments setup = dict(setup) # Chose a variable var = variables[0] # set variable chosen at this step to all possilbe values # in domain for d in domain: setup[var] = d # all constraints are satisfied if all([c(setup) for c in constraints]): # Solution found if len(variables) == 1: return setup result = backtrack(variables[1:], domain, constraints, setup) # No solutions found on this way if result is None: continue return result # No solution found return None # Test Example from Lecture 4.2 - Backtracing def example(): variables = ['a', 'b', 'c'] domain = [1, 2, 3] # Only returns false, if all keys # can be found inside the dict def req(d, keys): m = [key in d for key in keys] return not all(m) constraints = [ lambda d: req(d, ['a', 'b']) or d['a'] > d['b'], lambda d: req(d, ['c', 'b']) or d['b'] != d['c'], lambda d: req(d, ['a', 'c']) or d['a'] != d['c'], ] backtrack(variables, domain, constraints) result = example() print(result)
e5a5f83437e0f276aa62a101433d63364a05ee4a
alexiusacademia/diversion-dam-analysis
/utilities/geometry.py
514
4.15625
4
def interpolate(x1, x3, y1, y2, y3): """ Linear interpolation :param x1: :param x3: :param y1: :param y2: :param y3: :return: """ return (y2 - y3) / (y1 - y3) * (x1 - x3) + x3; def interpolate2(y2, x, y): """ Search and interpolate. :param y2: Given y :param x: List of x :param y: List of y :return: """ for i in range(len(x) - 1): if (y2 >= y[i]) and (y2 <= y[i+1]): return interpolate(x[i], x[i+1], y[i], y2, y[i+1])
1b46a5d318539556d024fd9094551c1346e6dec0
Ashilley/SCAMP-Assesment
/work.py
530
4.3125
4
#fabonacci sequense num_of_terms = int(input(" How many terms? ")) first1, second2 = 0, 1 count = 0 # check if the number of terms is valid if num_of_terms <= 0: print("Please enter a positive number") elif num_of_terms == 1: print("Fibonacci sequence upto",num_of_terms,":") print(first1) else: print("Fibonacci sequence:") while count < num_of_terms: print(first1) nth = first1 + second2 # update values first1 = second2 second2 = nth count += 1
5d09ee433a0c1b6bd2835fe0912cd71d9f7e4e6f
anirban2304/Python
/Tkinter_Windows/kilogram_converter.py
876
3.78125
4
import tkinter as tk window = tk.Tk() def kilogram_to_units(): grams = float(e1_value.get())*1000 pounds = float(e1_value.get())*2.20462 ounces = float(e1_value.get())*35.274 t1.delete("1.0", tk.END) t2.delete("1.0", tk.END) t3.delete("1.0", tk.END) t1.insert(tk.END, grams) t2.insert(tk.END, pounds) t3.insert(tk.END, ounces) l1 = tk.Label(window, text = "Kg") l1.grid(row = 0, column =0) e1_value = tk.StringVar() e1 = tk.Entry(window, textvariable = e1_value) e1.grid(row = 0, column = 1) b1 = tk.Button(window, text = "Convert", command = kilogram_to_units) b1.grid(row = 0, column = 2) t1 = tk.Text(window, height = 1, width = 20) t1.grid(row = 1, column = 0) t2 = tk.Text(window, height = 1, width = 20) t2.grid(row = 1, column = 1) t3 = tk.Text(window, height = 1, width = 20) t3.grid(row = 1, column = 2) window.mainloop()
f21658d75b9324ab27fba344ba6370162e985ddb
armanshafiee/allback
/line22.py
807
3.890625
4
class point: def __init__ (self , x , y ): self. x = x self. y = y def distance(p): c=sqrt( (p.x-self. x)**2 + (p.y-self.y)**2 ) return c class line : def __init__ (self, s,e): self.s = s self.e = e self.width = 1 self.color = "black" def increase(self,size): self.width=self.width + size def get_length(self): return self.s.get_distance(self.e) def slope(self): z=self.s.x-self.e.x t=self.s.y=self.e.y dd=z/t return dd def arecross(self ,l): if slope(l) == slope(self): return False else : return True #class ploygon: # def __init__ ():
3758df0af078426dd3180534e6e818bb3cebcd9b
hquan212/leetcodeSolutionsPython
/2.add-two-numbers.py
756
3.671875
4
# # @lc app=leetcode id=2 lang=python3 # # [2] Add Two Numbers # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: result = head = ListNode(0) carry = 0 while l1 or l2 or carry: if l1: carry += l1.val l1 = l1.next if l2: carry += l2.val l2 = l2.next temp = ListNode(carry%10) result.next = temp result= result.next carry //= 10 return head.next # @lc code=end
e87b59f9ffc726d8c243783f68fb704498f73010
Bibin22/pythonclass
/functionalprogramming/map,filter,reduce.py
599
3.578125
4
lst = [10,11,12,13,14,15,2] #map(function,iterable) squre = list(map(lambda num:num**2, lst)) print('square', squre) cubes = list(map(lambda num:num**3, lst)) print('cubes', cubes) #filter even = list(filter(lambda no: no%2==0, lst)) print('even', even) #reduce from functools import * sum = reduce(lambda n1, n2: n1+n2, lst) print(sum) minimum = reduce(lambda n1, n2: n1 if n1<n2 else n2, lst) print(minimum) maximum = reduce(lambda n1, n2: n1 if n1>n2 else n2, lst) print(maximum) evenmin = reduce(lambda n1, n2: n1 if n1<n2 else n2, list(filter(lambda n: n%2 ==0, lst))) print(evenmin)
477e76ad3a90f36c22d12396d0b17de6e30c3385
HalfMoonFatty/F
/042. AddSum.py
663
3.8125
4
''' Problem: 给一个正数n, 打印出所有相加的组合 例如 10 可以打印出: 1+1+1+...1 1+2+1+...1 9+1 10 ''' # Time complexity: O(k) -- k is the number of sums # Space complexity: O(k * average Length) k == 2 ^ n' def addSum(target): def helper(index, target, sums, res, result): if sums == target: result.append(res[:]) for i in range(index, target+1): if sums + i > target: return helper(i, target, sums+i, res+str(i), result) return result = [] helper(1, target, 1, '1', result) return result + [str(target)] target = 10 print addSum(target)
d5d06554d0f7d8c598d357732f8db83e0252d024
DMamrenko/Kattis-Problems
/autori.py
156
3.84375
4
#Autori inp = list(input()) answer = "" for letter in inp: if letter == letter.upper() and letter != "-": answer += letter print(answer)
a30b1732ed724d3541c4159d234149a4bb965252
dylanlittler/scraper
/scraper/scraping.py
1,935
3.5625
4
# These modules are required for web scraping from bs4 import BeautifulSoup import requests # Function name shows that only one site reliably works right now def search_stackoverflow(url, tag, attribute, return_url=None): links_dict = {} links = [] link_title = [] r = requests.get(url) soup = BeautifulSoup(r.text, "lxml") # class_ allows user to specify which 'a' tags are required for link in soup.find_all(tag, class_=attribute): # user may specify whether a url should be appended to the link provided # in case a relative path is used on the site # return_url will only be appended if relative path is used. if return_url and link.get('href')[0:4] != "http": links.append(return_url + link.get('href')) else: links.append(link.get('href')) for link in links: # Based on stackoverflow url, the subdirectory is stripped and formatted # to make a clean title # index number must be set in case the last character of `link` is `/` # which would cause the last element after splitting to be an empty string if link[-1] == "/": index = -2 else: index = -1 link_title.append(link.split("/")[index].replace("-", " ").capitalize()) for i in range(len(links)): # Dict consists of the title and link for each entry, to be formatted in HTML links_dict[link_title[i]] = links[i] return links_dict if __name__ == "__main__": # Tests to be deleted once the scraper works more reliably with other sites print(search_stackoverflow("http://stackoverflow.com/unanswered/tagged/python", "a", "question-hyperlink")) r = requests.get("https://duckduckgo.com/?q=stackoverflow&t=hy&atb=v102-3&ia=about") soup = BeautifulSoup(r.text, "lxml") for link in soup.find_all("div", class_="results"): print(link)
94a32fe9ac999e7238dae678b19cfb5aef02c902
sakshipathakf/assignment2
/Q2.py
880
4.59375
5
Question2 List comprehensions are used for creating new lists from other iterables. As list comprehensions return lists, they consist of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element. 1st-[1,2,3,4,5,6,7,8,9,10] print(1st) list1=[i for i in range(11,19)] print(list1) #list.append(x) list1.append(20) print(list1) #list.insert(i, x) list1.insert(8,19) print (list1) #list.extend(iterable) 1st.extend(1ist1) print(1st) #list.remove(x) 1st.remove(20) print(1st) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [11, 12, 13, 14, 15, 16, 17, 18] [11, 12, 13, 14, 15, 16, 17, 18, 20] [11, 12, 13, 14, 15, 16, 17, 18, 19, 20] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]