blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
87f7fea9e16f8aa7dbaa1fdd060b4bc9301663d8
adelq/project-euler
/52.py
485
3.6875
4
def numhash(num): num = str(num) digithash = {0:0, 1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0} for digit in num: digithash[int(digit)] += 1 return digithash i = 1 while True: spechash = numhash(i) if spechash == numhash(2*i): if spechash == numhash(3*i): if spechash == numhash(4*i): if spechash == numhash(5*i): if spechash == numhash(6*i): print(i) break else: i+=1 else: i+=1 else: i+=1 else: i+=1 else: i += 1
46cbebecf360194534ad020c3ecd78eb83acdc3b
adit-sinha/Solutions-to-Practice-Python
/(15) Reverse Word Order.py
95
3.625
4
a = input("Please enter your sentence here.") u = a.split()[::-1] d = " ".join(u) print(d)
b0677d17d22162a8db8819920fa99049d995f2d0
pauloesampaio/simple_image_clf
/web/src/simple_image_clf.py
2,641
3.59375
4
import streamlit as st import pandas as pd import requests from tensorflow.image import resize, decode_image from tensorflow.keras.applications.resnet import ( ResNet50, decode_predictions, preprocess_input, ) def download_image(url, target_size=(224, 224)): """Function to download images from url and resize it to a target size Args: url (string): Image url. target_size (tuple, optional): [int]. Final size the image should be resized to. Defaults to (224, 224). Returns: np.array: Image as a numpy array """ response = requests.get(url) image = decode_image(response.content) # Display image on streamlit front end st.image(image.numpy(), width=224) resized_image = resize(image, target_size, antialias=True) return resized_image.numpy() def preprocess_image(image): """Helper function to pre process image according to the neural net documentation. Args: image (np.array): Image as a numpy array. Returns: np.array: Image as a numpy array. """ reshaped_image = image.reshape((1,) + image.shape) preprocessed_input = preprocess_input(reshaped_image) return preprocessed_input def decode_result(prediction): """Transform prediction indexes into human readable category Args: prediction (np.array): Batch of predictions Returns: pd.DataFrame: prediction dataframe with human readable categories. """ decoded_prediction = decode_predictions(prediction) result_dict = pd.DataFrame( data=[w[2] for w in decoded_prediction[0]], index=[w[1] for w in decoded_prediction[0]], columns=["probability"], ) # Display prediction result on streamlit front end st.write(result_dict) return result_dict @st.cache def load_model(target_size=(224, 224)): """Function to load neural network to memory. Args: target_size (tuple, optional): [int]. Image size to be used by the model. Defaults to (224, 224). Returns: tf.keras.Model: Keras model loaded into memory. """ model = ResNet50(input_shape=(target_size + (3,))) return model if __name__ == "__main__": model = load_model() # Write title on streamlit front end st.write( """ # Simple image clf ## Enter the image url """ ) # Input box on streamlit front end url = st.text_input("Enter image url") if url: current_image = download_image(url) model_input = preprocess_image(current_image) prediction = model.predict(model_input) result = decode_result(prediction)
2f533bce3b3d7db218ff088861a919b87c577738
tinkle1129/Leetcode_Solution
/String/8. String to Integer (atoi).py
1,548
3.5
4
########################################### # Author: Tinkle # E-mail: shutingnupt@gmail.com # Name: String to Integer.py # Creation Time: 2017/6/22 ########################################### ''' Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases. Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front. ''' class Solution(object): def output(self,ans,id_sign): a=0 if id_sign==0: a=ans else: a=id_sign*ans if a>=2147483647: a=2147483647 if a<=-2147483648: a=-2147483648 return a def myAtoi(self, str): """ :type str: str :rtype: int """ if not len(str): return 0 id_sign=0 id_begin=0 ans=0 for i in str: if i=='+' or i=='-': if id_sign==0: id_sign=44-ord(i) id_begin=1 else: return 0 elif i==' ': if id_begin!=0: return self.output(ans,id_sign) elif ord(i)>=48 and ord(i)<=57: ans=ans*10+ord(i)-ord('0') id_begin=1 else: return self.output(ans,id_sign) return self.output(ans,id_sign)
17220c1b5e3ffe659bb621dca41e1c0ef68cc926
rafalacerda1530/Python
/Aulas Sec 8/Função com parametros.py
2,005
4.6875
5
""" Funções com parametros -Funções que recebm dados - FUnções Podem receber N parametros, podemos receber quantos parametros quisermos e els são separados por virgula - o Return deve ser colocado no bloco da função """ """ # ela recebe um parametro e é obrigatorio colocar por ex: print(quadrado(2)) # o 2 é o parametro def quadrado(numero): # o metodo vai receber um valor(numero) e vai fazer # numero * numero return numero * numero print(quadrado(2)) # numero * mumero = 2*2 """ """ # refatorando def cantar_parabens(aniversariante): print('Parabens para você') print('Nessa data querida') print('Muitas felicidades') print('Muitos anos de vida') print(f'Viva o/a {aniversariante}') cantar_parabens('Rafael') """ """ # FUnções com varios parametros def soma(a, b): return a + b def mult(num1, num2): return num1 * num2 def outra(num1, b, msg): return (num1 + b) * msg print(soma(10, 10)) # valor de a e b print(mult(10, 10)) # valor de num1 e num2 print(outa(10, 10, "A")) # valor de num1 b e msg # ta fazendo o resultado de num1 + b vez o a # ou seja 20 vezes o B """ """ # Nomeando paranmetros def nome_completo(nome, completo): # eles devem fazer sentido return f"Seu nome completo é: {nome} {completo}" print(nome_completo(input('Digite o primeiro nome: '), input('digite o sobrenome: '))) # A diferença entre parametros e argumentos # Parametros são variaveis decladas na definição de uma função # def nome_completo(nome, completo): # parametro é o nome, completo # Argumentos são dados passados durante a execução de uma função # print(nome_completo(input('Digite o primeiro nome: ') o input é o argumento """ """ # Argumento nomeado (keyword arguments) def nome_completo(nome, completo): # eles devem fazer sentido return f"Seu nome completo é: {nome} {completo}" a = input('Digite o nome: ') b = input('Digite sobrenome: ') print(nome_completo(nome=a, completo=b)) """
6858d1aebd9114c6db53ae8d039fa9a21d3c9b63
micko45/python_code
/codeabby/4.py
279
3.578125
4
#!/usr/bin/env python #min-of-two count = raw_input("data:\n") answer = [] for i in range(0, int(count)): num1, num2 = raw_input().split() if int(num1) < int(num2): answer.append(num1) else: answer.append(num2) for x in range(len(answer)): print answer[x],
b842bc1848312fc881eaf9dab8e46730f783cd61
BolajiOlajide/pythonbo
/sample_yield.py
205
3.796875
4
names = ["Bolaji", "Emmanuel", "Olajide"] def read_names(): for name in names: yield name def get_names(): for name in read_names(): print('Reading ===> ' + name) get_names()
c5aa96a71a88e9cf6e5ecea0c698b29642b802c4
tsaomao/GenPiFromRandomThrows
/trial.py
1,058
3.5625
4
# Process per group of trials: # Process per trial: # Process per observation: # Generate 2 numbers # Test for coprimality # Count number of coprimes in a field of some number of pairs # Find observed probability of these coprimes # Calculate pi from sqrt(6/observed probability) # Compare pi from each trial to true value # Figure out where/whether to/how to dump raw data and/or trial results meta # data to external data dump import math import random random.seed() def evalRandomPair(rrange): if rrange == 0: rrange = 1 r1 = random.randrange(rrange) r2 = random.randrange(rrange) if math.gcd(r1, r2) > 1: return 1 else: return 0 # Check arguments for override option # Check second for parameters file and read parameters from that # If no override options or parameters file, prompt for parameters # Default parameters: # trialsize defines number of random pairs trialsize = 1000 # randomrange defines upper value of random range randomrange = 500 for i in range(10): print(evalRandomPair(randomrange))
4de488b731af4a6ed62177b00c3560ef24f1aae3
hc9599/git_start
/Git_Test/mul_table.py
352
3.984375
4
while True: mul_no = int(input('Enter the number you want to have multiplication number: ')) range_no = int(input('Enter the number till you want multiplication: ')) for i in range(1, range_no+1): print(mul_no, 'X', i, '=', mul_no*i) choice_op = str(input('Want to continue(y/n): ')) if choice_op == 'n': break
700ddc5a6340308b21af309cc95d76e5d5fa5460
Seonghoon-Yu/leetcode
/0167_Two_Sum_II_Input_array_is_sorted.py
1,486
3.5
4
# 1. 투 포인터 풀이 # numbers가 정렬되어 있으므로 투 포인터를 이용하여 풀 수 있습니다. class Solution: def twoSum(self, numbers, target): left, right = 0, len(numbers) - 1 while left < right: sum = numbers[left] + numbers[right] if sum < target: # sum이 target보다 작으면 left += 1 left += 1 elif sum > target: # sum이 target보다 크면 right -= 1 right -= 1 else: return left +1, right+1 # 2. 이진 검색 class Solution: def twoSum(self, numbers, target): for k, v in enumerate(numbers): # left = k + 1로 설정하여 범위 제한 left, right = k + 1, len(numbers) - 1 expected = target - v # 이진 검색으로 나머지 값 판별 while left <= right: mid = left + (right - left) // 2 if numbers[mid] < expected: left = mid + 1 elif numbers[mid] > expected: right = mid - 1 else: return k + 1, mid + 1 # 3. bisect 모듈 이용 class Solution: def twoSum(self, numbers, target): for k, v in enumerate(numbers): expected = target - v i = bisect.bisect_left(numbers,expected, lo=k+1) if i < len(numbers) and numbers[i] == expected: return k + 1, i + 1
3cc7e58cdae8c3c29598a51131b8d4c6e1b1a9f4
luodousha/Every_day
/DAY2/分支.py
629
4.15625
4
#单分支: name = '赵志强' if name=='赵志强': print('老单身狗%s'%name) #双分支: girl_friend = '' if girl_friend: print('恭喜啊,居然有女朋友了') else: print('求求你快恋爱吧.%s.'%name) #多分支: ''' 判断成绩档次小程序 90-100 A 80-89 B 60-79 C 40-59 D 0 -39 E 程序启动,用户输入成绩,根据成绩打印等级 ''' score = int(input('请输入你的成绩:')) if 90<= score <= 100: print('A') elif 79<score<90: print('B') elif 59<score<80: print('C') elif 39<score<60: print('D') elif 0<=score <40 : print('E') else: print('输入错误,请重试')
a7b9a7fc575bb72fb1ddc2337ad945c7bbd64825
LokeshVadlamudi/DataStructuresLC
/Day46.py
136
3.671875
4
# 280. Wiggle Sort # nums = [3,5,2,1,6,4] # # for i in range(len(nums)): # nums[i:i+2]=sorted(nums[i:i+2],reverse=i%2) # print(nums)
b578754f3488f742b1b2d432bb0e19bdf5d55b00
sumanthreddy24/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/0-square_matrix_simple.py
188
3.71875
4
#!/usr/bin/python3 def square_matrix_simple(matrix=[]): sqr_mtx = [] for row in matrix: row = list(map(lambda x: x**2, row)) sqr_mtx.append(row) return sqr_mtx
dc7bfa438159c049096f4b4f9cb6810a4c87de1a
snowdj/cs_course
/Algorithms/challenges/lc500_keyboard_row.py
819
4.03125
4
""" Time: O(n) Space: O(n) Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below. Example 1: Input: ["Hello", "Alaska", "Dad", "Peace"] Output: ["Alaska", "Dad"] Note: You may use one character in the keyboard more than once. You may assume the input string will only contain letters of alphabet. """ class Solution(object): def findWords(self, words): """ :type words: List[str] :rtype: List[str] """ keyrows = ('asdfghjkl', 'qwertyuiop', 'zxcvbnm') output = [] for w in words: for row in keyrows: if all(x.lower() in row for row in keyrows for x in w): output.append(w) break return output
86ce3de1c4a7fb954c8d726b8a7c2216a198954a
ljia2/leetcode.py
/solutions/tree/654.Maximum.Binary.Tree.py
4,476
3.921875
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def constructMaximumBinaryTree(self, nums): """ Given an integer array with no duplicates. A maximum tree building on this array is defined as follow: The root is the maximum number in the array. The left subtree is the maximum tree constructed from left part subarray divided by the maximum number. The right subtree is the maximum tree constructed from right part subarray divided by the maximum number. Construct the maximum tree by the given array and output the root node of this tree. Example 1: Input: [3,2,1,6,0,5] Output: return the tree root node representing the following tree: 6 / \ 3 5 \ / 2 0 \ 1 Note: The size of the given array will be in the range [1,1000]. :type nums: List[int] :rtype: TreeNode Time O(n^2) Space O(n) """ if not nums: return None n = len(nums) max_index = 0 for i in range(1, n): if nums[i] > nums[max_index]: max_index = i lroot = self.constructMaximumBinaryTree(nums[:max_index]) # nums[max_index+1:] has to be valid, rroot = self.constructMaximumBinaryTree(nums[max_index+1:]) if max_index + 1 < n else None root = TreeNode(nums[max_index]) root.left, root.right = lroot, rroot return root s = Solution() print(s.constructMaximumBinaryTree([3,2,1,6,0,5])) class LinearSolution(object): def constructMaximumBinaryTree(self, nums): """ Given an integer array with no duplicates. A maximum tree building on this array is defined as follow: The root is the maximum number in the array. The left subtree is the maximum tree constructed from left part subarray divided by the maximum number. The right subtree is the maximum tree constructed from right part subarray divided by the maximum number. Construct the maximum tree by the given array and output the root node of this tree. Example 1: Input: [3,2,1,6,0,5] Output: return the tree root node representing the following tree: 6 / \ 3 5 \ / 2 0 \ 1 Note: The size of the given array will be in the range [1,1000]. :type nums: List[int] :rtype: TreeNode # intuition: because we are traversing from left to right # and because from a dividing node standpoint, nodes with value smaller than itself will be on the left (because we have not seen the right values yet!) # traverse the list and build the tree along the way # keep track a stack, where the bottom of stack is the largest value we have seen # so far # make sure the numbers in stack is in decreasing order # for each new value we see, we make it into a TreeNode # if new value is smaller than top of the stack, we push new value in stack # append the new treenode to the right of previous TreeNode # if new value is greater than top of stack. Keep poping from the stack until the stack is empty or top of stack value is greater than the new value # append the last node being poped as the left node of new node O(n) O(n) """ if not nums: return None if len(nums) == 1: return TreeNode(nums[0]) # stack store the node in decreasing order. # node1.right = node2; node2.right = node3....... stack = [] for num in nums: cur = TreeNode(num) # find the largest node whose value < num, it should be the left child of cur. while stack and stack[-1].val < num: cur.left = stack.pop() # if stack, the top node must bigger than num # cur must be the right child of that top node. if stack: stack[-1].right = cur # push cur into stack. stack.append(cur) return stack[0] ls = LinearSolution() print(ls.constructMaximumBinaryTree([3,2,1,6,0,5]))
7018fdecdd2714528038d38b77dbc265237fc29b
FDio/csit
/resources/libraries/python/PLRsearch/log_plus.py
3,557
3.609375
4
# Copyright (c) 2021 Cisco and/or its affiliates. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module holding functions for avoiding rounding underflows. Some applications wish to manipulate non-negative numbers which are many orders of magnitude apart. In those circumstances, it is useful to store the logarithm of the intended number. As math.log(0.0) raises an exception (instead returning -inf or nan), and 0.0 might be a result of computation caused only by rounding error, functions of this module use None as -inf. TODO: Figure out a more performant way of handling -inf. The functions handle the common task of adding or subtracting two numbers where both operands and the result is given in logarithm form. There are conditionals to make sure overflow does not happen (if possible) during the computation.""" import math def log_plus(first, second): """Return logarithm of the sum of two exponents. Basically math.log(math.exp(first) + math.exp(second)) which avoids overflow and uses None as math.log(0.0). TODO: replace with scipy.special.logsumexp ? Test it. :param first: Logarithm of the first number to add (or None if zero). :param second: Logarithm of the second number to add (or None if zero). :type first: float :type second: float :returns: Logarithm of the sum (or None if zero). :rtype: float """ if first is None: return second if second is None: return first if second > first: retval = second + math.log(1.0 + math.exp(first - second)) else: retval = first + math.log(1.0 + math.exp(second - first)) return retval def log_minus(first, second): """Return logarithm of the difference of two exponents. Basically math.log(math.exp(first) - math.exp(second)) which avoids overflow and uses None as math.log(0.0). TODO: Support zero difference? TODO: replace with scipy.special.logsumexp ? Test it. :param first: Logarithm of the number to subtract from (or None if zero). :param second: Logarithm of the number to subtract (or None if zero). :type first: float :type second: float :returns: Logarithm of the difference. :rtype: float :raises RuntimeError: If the difference would be non-positive. """ if first is None: raise RuntimeError(u"log_minus: does not support None first") if second is None: return first if second >= first: raise RuntimeError(u"log_minus: first has to be bigger than second") factor = -math.expm1(second - first) if factor <= 0.0: msg = u"log_minus: non-positive number to log" else: return first + math.log(factor) raise RuntimeError(msg) def safe_exp(log_value): """Return exponential of the argument, or zero if the argument is None. :param log_value: The value to exponentiate. :type log_value: NoneType or float :returns: The exponentiated value. :rtype: float """ if log_value is None: return 0.0 return math.exp(log_value)
2cb6994012ba776828f3e3a09d3e95f05ccd7bd0
sledziu32/python_nauka
/petlaif.py
506
4.125
4
""" zapraszam na https://github.com/sledziu32/python_nauka """ """ porównanie liczb czy są takie same """ x = int(5) #y = "5" nie można porównać ciągu z liczbą y = float(5) #float może być równy intigerowi jeżeli nie ma części ułamkowych if x == y: print("super! ") else: print("niestety") a = 5 b = 5 if a != b: print("wartości są różne") else: print("wartości są równe") q = 6 < 4 if q: print(q) #wypisze True else: print(q) #wypisze False
12cd95926d0ec0c32fc5e80edd2cb4e31b2be07e
amarantejoacil/estudo-python
/manipulacao_arquivo/io_desafio_csv.py
762
3.890625
4
#!/usr/local/bin/python3 # -*- coding: latin1 -*- import csv # import urllib.request #from urllib import request # funciona mas nao sei como kkk import urllib2 def read(url): req = urllib2.Request(url) resposta = urllib2.urlopen(req) for cidade in csv.reader(resposta): print('Cidade: {}, Cidade: {}'.format(cidade[8], cidade[3])) """ def read(url): with request.urlopen(url) as entrada: print('baixando csv') dados = entrada.read().decode('latin1') print('download finalizado') for cidade in csv.reader(dados.splitlines()): print('a') # print(f'{cidade[8]}: {cidade[3]}') """ if __name__ == '__main__': read(r'http://files.cod3r.com.br/curso-python/desafio-ibge.csv')
6b5a1a8ce5a0465db30a9c0c2668bb7238c19d37
tganesan70/epai3-session14-tganesan70
/dataMerger.py
14,155
3.875
4
# Session-14 : Ganesan Thiagarajan # 13-Aug-2021 import csv from itertools import islice from collections import namedtuple # # Create the namedtuple templates for parking various records and date format # date_of_record = namedtuple('date', 'day, month, year') person_record = namedtuple('per_record', 'ssn,first_name,last_name,gender,language') employment_record = namedtuple('emp_record', 'employer,department,employee_id,ssn') update_record = namedtuple('upd_record', 'ssn,updated_date, updated_time,created_date, created_time') vehicle_record = namedtuple('veh_record', 'ssn,vehicle_make,vehicle_model,model_year') merged_record = namedtuple('merg_record','ssn,first_name, last_name, gender,language, \ employer, department, employee_id, \ updated_date, updated_time, created_date, created_time, \ vehicle_make, vehicle_model, model_year') def read_file(file_name): """ Function: Read the CSV file which contains the records Params: file_name - to be read with fullpath Returns one row at a time as a lazy iterator """ with open(file_name) as f: rows = csv.reader(f, delimiter=',', quotechar='"') yield from rows per_header_read = 1 per_records = [] per_records_count = 0 def read_personal_records(file_name): """ Function: Read the CSV file which contains the personal records :param file_name: Filename as a string with full path to read the personal details records :return: Number of records in the global list of personal records """ global per_header_read global per_records_count for rec in read_file(file_name): if per_header_read == 1: per_header_read = 0 else: per_records.append(person_record(*rec)) per_records_count += 1 return per_records_count-1 emp_header_read = 1 emp_records = [] emp_records_count = 0 def read_employment_records(file_name): """ Function: Read the CSV file which contains the employment records :param file_name: Filename as a string with full path to read the employment details records :return: Number of records in the global list of employment records """ global emp_header_read global emp_records_count for rec in read_file(file_name): if emp_header_read == 1: emp_header_read = 0 else: emp_records.append(employment_record(*rec)) emp_records_count += 1 return emp_records_count-1 veh_header_read = 1 veh_records = [] veh_records_count = 0 def read_vehicle_records(file_name): """ Function: Read the CSV file which contains the vehicle records :param file_name: Filename as a string with full path to read the vehicle details records :return: Number of records in the global list of vehicle records """ global veh_header_read global veh_records_count for rec in read_file(file_name): if veh_header_read == 1: veh_header_read = 0 else: veh_records.append(vehicle_record(*rec)) veh_records_count += 1 return veh_records_count-1 upd_header_read = 1 upd_records = [] upd_records_count = 0 def read_update_records(file_name): """ Function: Read the CSV file which contains the update records :param file_name: Filename as a string with full path to read the update details records :return: Number of records in the global list of update records """ global upd_header_read global upd_records_count for rec in read_file(file_name): if upd_header_read == 1: upd_header_read = 0 else: # Split the time and date and store it in proper format temp = rec[1].split("T") date_mm_yy_yyyy = [int(i) for i in temp[0].split("-")] date_updated = date_of_record(date_mm_yy_yyyy[2],date_mm_yy_yyyy[1], date_mm_yy_yyyy[0]) # Date as date object time_updated = temp[1] temp = rec[2].split("T") date_mm_yy_yyyy = [int(i) for i in temp[0].split("-")] date_created = date_of_record(date_mm_yy_yyyy[2],date_mm_yy_yyyy[1], date_mm_yy_yyyy[0]) # Date as date object time_created = temp[1] upd_records.append(update_record(rec[0],date_updated,time_updated,date_created,time_created)) upd_records_count += 1 return upd_records_count-1 def match_per_record(file_name, ssn): """ Function: Read the CSV file which contains the employment records with matching ssn :param file_name: Filename as a string with full path to read the employment details records :return: record that matches ssn in employment records """ for per_rec in read_file(file_name): ssn_rec = per_rec[0] if ssn_rec != ssn: continue else: break #print(f'Matched ssn: {ssn} with the record ssn : {ssn_rec}') per_record = person_record(*per_rec) return per_record def match_emp_record(file_name, ssn): """ Function: Read the CSV file which contains the employment records with matching ssn :param file_name: Filename as a string with full path to read the employment details records :return: record that matches ssn in employment records """ for emp_rec in read_file(file_name): ssn_rec = emp_rec[-1] if ssn_rec != ssn: continue else: break #print(f'Matched ssn: {ssn} with the record ssn : {ssn_rec}') emp_record = employment_record(*emp_rec) return emp_record def match_veh_record(file_name, ssn): """ Function: Read the CSV file which contains vehicle records with matching ssn :param file: Filename as a string with full path to read the vehicle details records :return: record that matches ssn in vehicle records """ for veh_rec in read_file(file_name): ssn_rec = veh_rec[0] if ssn_rec != ssn: continue else: break #print(f'Matched ssn: {ssn} with the record ssn : {ssn_rec}') veh_record = vehicle_record(*veh_rec) return veh_record def match_upd_record(file_name, ssn): """ Function: Read the CSV file which contains update records with matching ssn :param file: Filename as a string with full path to read the update details records :return: record that matches ssn in update records """ for upd_rec in read_file(file_name): ssn_rec = upd_rec[0] if ssn_rec != ssn: continue else: break #print(f'Matched ssn: {ssn} with the record ssn : {ssn_rec}') temp = upd_rec[1].split("T") date_mm_yy_yyyy = [int(i) for i in temp[0].split("-")] date_updated = date_of_record(date_mm_yy_yyyy[2], date_mm_yy_yyyy[1], date_mm_yy_yyyy[0]) # Date as date object time_updated = temp[1] temp = upd_rec[2].split("T") date_mm_yy_yyyy = [int(i) for i in temp[0].split("-")] date_created = date_of_record(date_mm_yy_yyyy[2], date_mm_yy_yyyy[1], date_mm_yy_yyyy[0]) # Date as date object time_created = temp[1] upd_record = update_record(upd_rec[0], date_updated, time_updated, date_created, time_created) return upd_record def create_merged_records(per_rec_file, emp_rec_file, upd_rec_file, veh_rec_file): """ Function: To merge all the records for corresponding SSN stored across multiple files Paranms: 4 filenames for set of different parameters but with common SSN Returns: List of combined records (as namedtuples) """ merged_records = [] first_read = 1 for per_rec in read_file(per_rec_file): if first_read == 1: # Skip the header record first_read = 0 continue per_record = person_record(*per_rec) ssn = per_record.ssn emp_record = match_emp_record(emp_rec_file, ssn) upd_record = match_upd_record(upd_rec_file, ssn) veh_record = match_veh_record(veh_rec_file, ssn) # Merge all data into new namedtuple with multiple columns merg_record = merged_record(per_record.ssn, per_record.first_name, per_record.last_name, per_record.gender, \ per_record.language, \ emp_record.employer, emp_record.department,emp_record.employee_id, \ upd_record.updated_date, upd_record.updated_time, upd_record.created_date, \ upd_record.created_time, \ veh_record.vehicle_make, veh_record.vehicle_model, veh_record.model_year) merged_records.append(merg_record) return merged_records def create_merged_records_with_expiry(per_rec_file, emp_rec_file, upd_rec_file, veh_rec_file, exp_yyyy, exp_mm, exp_dd): """ Function: To merge all the records for corresponding SSN stored across multiple files with record expity cut-off Paranms: 4 filenames for set of different parameters but with common SSN Record expiry year, month and day as integer numbers in yyyy,mm and dd format Returns: List of combined records (as namedtuples) """ merged_records = [] first_read = 1 for upd_rec in read_file(upd_rec_file): if first_read == 1: # Skip the header record first_read = 0 continue ssn = upd_rec[0] upd_record = match_upd_record(upd_rec_file, ssn) if upd_record.updated_date.year < exp_yyyy: continue elif upd_record.updated_date.month < exp_mm: continue elif upd_record.updated_date.day < exp_dd: continue # Merge the matching records per_record = match_per_record(per_rec_file, ssn) emp_record = match_emp_record(emp_rec_file, ssn) upd_record = match_upd_record(upd_rec_file, ssn) veh_record = match_veh_record(veh_rec_file, ssn) # Merge all data into new namedtuple with multiple columns merg_record = merged_record(per_record.ssn, per_record.first_name, per_record.last_name, per_record.gender, \ per_record.language, \ emp_record.employer, emp_record.department,emp_record.employee_id, \ upd_record.updated_date, upd_record.updated_time, upd_record.created_date, \ upd_record.created_time, \ veh_record.vehicle_make, veh_record.vehicle_model, veh_record.model_year) merged_records.append(merg_record) return merged_records def find_car_make_groups(merged_rec): mal_car_make_list = dict() fem_car_make_list = dict() for rec in merged_rec: gender = rec.gender make = rec.vehicle_make if gender == 'Male': if make in mal_car_make_list.keys(): mal_car_make_list[make] += 1 else: mal_car_make_list[make] = 1 else: if make in fem_car_make_list.keys(): fem_car_make_list[make] += 1 else: fem_car_make_list[make] = 1 # Find the largest car make group largest_male_car_make_group = max(mal_car_make_list.values()) male_car_gr_name = [key for key in mal_car_make_list.keys() if mal_car_make_list[key] == largest_male_car_make_group] largest_female_car_make_group = max(fem_car_make_list.values()) female_car_gr_name = [key for key in fem_car_make_list.keys() if fem_car_make_list[key] == largest_female_car_make_group] return male_car_gr_name, female_car_gr_name # Test for read_file function() #rows = read_file('personal_info.csv') #for row in islice(rows, 5): # print(row) # Goal-1 Test cases print(f'*** Goal 1: Test cases ***') per_rec_cnt = read_personal_records('personal_info.csv') #print([per_records[i] for i in range(5)]) print(f'No. of records in Personal records: {per_rec_cnt}') print(f'First, Second and Last record in the Personal records') print(per_records[0],'\n', per_records[1],'\n',per_records[-1]) emp_rec_cnt = read_employment_records('employment.csv') #print([emp_records[i] for i in range(5)]) print(f'No. of records in Employment records: {emp_rec_cnt}') print(f'First, Second and Last record in the Employment records') print(emp_records[0],'\n', emp_records[1],'\n',emp_records[-1]) veh_rec_cnt = read_vehicle_records('vehicles.csv') #print([veh_records[i] for i in range(5)]) print(f'No. of records in Employment records: {veh_rec_cnt}') print(f'First, Second and Last record in the Vehicle records') print(veh_records[0],'\n', veh_records[1],'\n',veh_records[-1]) upd_rec_cnt = read_update_records('update_status.csv') #print([upd_records[i] for i in range(5)]) print(f'No. of records in Employment records: {upd_rec_cnt}') print(f'First, Second and Last record in the Update records') print(upd_records[0],'\n', upd_records[1],'\n',upd_records[-1]) # test cases for Goal 2 print(f'*** Goal 2: Test cases ***') mer_data = create_merged_records('personal_info.csv','employment.csv','update_status.csv','vehicles.csv') #print([mer_data[i] for i in range(5)]) print(f'No. of records in merged date: {len(mer_data)}') print(f'First, Second and Last record in the merged records') print(mer_data[0],'\n', mer_data[1],'\n',mer_data[-1]) # test cases for Goal 3 print(f'*** Goal 3: Test case ***') exp_yyyy = 2018 exp_mm = 1 exp_dd = 3 mer_data = create_merged_records_with_expiry('personal_info.csv','employment.csv', 'update_status.csv','vehicles.csv', exp_yyyy, exp_mm, exp_dd) print(f'No. of records beyond expiry date: {len(mer_data)}') print(f'First, Second and Last record in the merged records') print(mer_data[0],'\n', mer_data[1],'\n',mer_data[-1]) #test cases for Goal 4 print(f'*** Goal 4: Test case ***') male_car_gr_name, female_car_gr_name = find_car_make_groups(mer_data) print(f'Largest car make group(s) in Males : {male_car_gr_name}') print(f'Largest car make group(s) in Females : {female_car_gr_name}')
55503730665009447f72e8c61d2e65bbae299772
Lucas130/leet
/376-wiggleMaxLength.py
1,825
3.671875
4
""" 如果连续数字之间的差严格地在正数和负数之间交替,则数字序列称为摆动序列。第一个差(如果存在的话)可能是正数或负数。少于两个元素的序列也是摆动序列。 例如, [1,7,4,9,2,5] 是一个摆动序列,因为差值 (6,-3,5,-7,3) 是正负交替出现的。相反, [1,4,7,2,5] 和 [1,7,4,5,5] 不是摆动序列,第一个序列是因为它的前两个差值都是正数,第二个序列是因为它的最后一个差值为零。 给定一个整数序列,返回作为摆动序列的最长子序列的长度。 通过从原始序列中删除一些(也可以不删除)元素来获得子序列,剩下的元素保持其原始顺序。 示例 2: 输入: [1,17,5,10,13,15,10,5,16,8] 输出: 7 解释: 这个序列包含几个长度为 7 摆动序列,其中一个可为[1,17,10,13,10,16,8]。 """ class Solution: def wiggleMaxLength(self, nums) -> int: n = len(nums) if n < 2: return n ret = 1 start, end = 0, 1 flag = True while end < n: if ret == 1: if nums[end] > nums[start]: ret += 1 flag = False start = end elif nums[end] < nums[start]: ret += 1 flag = True start = end else: if flag and nums[end] > nums[start]: ret += 1 flag = False elif not flag and nums[end] < nums[start]: ret += 1 flag = True start = end end += 1 return ret if __name__ == '__main__': s = Solution() nums = [1,17,5,10,13,15,10,5,16,8] print(s.wiggleMaxLength(nums))
dc033b4e86572d028345be99d3dc0a66861ac913
SenthilKumar009/100DaysOfCode-DataScience
/Python/Programs/no_teen_sum.py
226
3.625
4
def no_teen_sum(a,b,c): return fix_teen(a) + fix_teen(b) + fix_teen(c) def fix_teen(num): if (num >=13 and num <= 14) or (num>16 and num<20): return 0 else: return num print(no_teen_sum(1,13,15))
30153befb1dd7f81d15e84eafc11c7f7f791a044
EduardoArias/Tareas
/Generador de 10000 numeros aleatorios.py
387
3.75
4
'''Este programa busca un elemento en un arreglo de 10.000 numeros aleatorios''' import random def buscar(lista,numero): for i in range(len(lista)): if lista[i] == numero: return i return -1 lista = [random.randint(0,100) for _ in range(10000)] print(buscar(lista,7)) print(buscar(lista,99)) print(buscar(lista,101)) print(buscar(lista,44))
bd0122dedc428144c004106b5b2903772f4c9dbf
JuniorDugue/100daysofPython
/day001/basics.py
938
4.40625
4
# this will print the date and time # import datetime # print (datetime.datetime.now()) # this will print a string with the date & time on 2 different lines # import datetime # print("The date and time is") # print (datetime.datetime.now()) # this will print everything on one line # import datetime # print("The date and time is", datetime.datetime.now()) # variables import datetime mynow = datetime.datetime.now() print(mynow) # different types of variables we can have mynumber = 10 mytext = "Hello" # to print the variables we created above print(mynumber, mytext) # different types of variables we cannot use # - # numbers #simple types: integers, strings and floats x = 10 y = "10" sum1 = x + x sum2 = y + y print(sum1, sum2) # int is short integer # str is short for string # int x = 10 ---> x = 10 # str y = 10 ---> y = "10" sum1 = x + x sum2 = y + y print(sum1, sum2) z = 10.1 print(type(x), type(y), type(z))
661e5418119605ca1142663874ab2c71eed98c37
py2k5/PyGeneralPurposeFunctions
/voice_recognition_tool.py
3,066
3.5
4
import speech_recognition as sr import re import webbrowser from smtplib import SMTP from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText def main(): # enter the name of usb microphone that you found # using lsusb # the following name is only used as an example #mic_name = "USB Device 0x46d:0x825: Audio (hw:1, 0)" mic_name = "Microphone (Realtek High Defini" # Sample rate is how often values are recorded sample_rate = 48000 # Chunk is like a buffer. It stores 2048 samples (bytes of data) # here. # it is advisable to use powers of 2 such as 1024 or 2048 chunk_size = 2048 # Initialize the recognizer r = sr.Recognizer() # generate a list of all audio cards/microphones mic_list = sr.Microphone.list_microphone_names() # the following loop aims to set the device ID of the mic that # we specifically want to use to avoid ambiguity. for i, microphone_name in enumerate(mic_list): if microphone_name == mic_name: device_id = i # use the microphone as source for input. Here, we also specify # which device ID to specifically look for incase the microphone # is not working, an error will pop up saying "device_id undefined" with sr.Microphone(device_index=device_id, sample_rate=sample_rate, chunk_size=chunk_size) as source: # wait for a second to let the recognizer adjust the # energy threshold based on the surrounding noise level r.adjust_for_ambient_noise(source) print("Say Something") # listens for the user's input audio = r.listen(source) try: text = r.recognize_google(audio) print("you said: " + text) if re.search(r'chrome|browser|google', text, re.IGNORECASE): webbrowser.open('www.google.com', new=1) elif re.search(r'youtube', text, re.IGNORECASE): webbrowser.open('www.youtube.com', new=1) elif re.search(r'mail', text, re.IGNORECASE): print("Sending email") mail_notification('test', subject='test', fromAddress='pradip.kumar.k@sap.com', toAddress='pradip.kumar.k@sap.com') # error occurs when google could not understand what was said except sr.UnknownValueError: print("Google Speech Recognition could not understand audio") except sr.RequestError as e: print("Could not request results from Google Speech Recognition service;{0}".format(e)) def mail_notification(body, subject=None, fromAddress=None, toAddress=None): msg = MIMEMultipart() msg['From'] = fromAddress msg['To'] = ','.join(toAddress) msg['Subject'] = subject msg.attach(MIMEText(body)) mailServer = None try: mailServer = SMTP('localhost') mailServer.sendmail(fromAddress, toAddress, msg.as_string()) except Exception as e: print(str(e)) finally: if mailServer != None: mailServer.quit() if __name__ == '__main__': main()
e12dbcc642f75d7f69c96b6d18259f477d0705e6
Long0Amateur/Self-learnPython
/Chapter 6 Strings/Problem/6. A program where uppercase is converted to lowercase and punctuation are ignored.py
283
4.46875
4
# A program asks user to enter string s, # converts s to lowercase, remove all punctuation s = input('Enter a string:') # This will remove the uppercase and convert to lowercase s1 = s.casefold() for c in ',.;:-?!()\'"!': s_new = s1.replace(c,'') print(s_new)
fdb23d46822c4b0ec347ffd967e4eefc8112ee2b
yohanswanepoel/rugbygame
/ball.py
1,875
3.90625
4
# Sprite classes for platform game import pygame from settings import * from rules import * vec = pygame.math.Vector2 class Ball(pygame.sprite.Sprite): def __init__(self, x, y, width, height): pygame.sprite.Sprite.__init__(self) self.height = 0 self.vel_height = 0 self.acc_height = 0 self.image = pygame.Surface((width, height)) self.image.fill(GREY) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y self.player = None self.acceleration = vec(0, 0) self.position = vec(x, y) self.velocity = vec(0, 0) def update(self): if self.player: self.velocity.x = self.player.velocity.x self.velocity.y = self.player.velocity.y self.rect.center = self.player.rect.center self.position.x = self.player.position.x self.position.y = self.player.position.y self.height = 0 else: # self.position = self.rect.center # Adjust the acceleration by friction # The faster you go the more friction applies # Standard equations for motion if self.vel_height > 0 or self.height > 0: self.acc_height = GRAVITY self.acc_height += self.vel_height * BALL_AIR_FRICTION self.vel_height += self.acc_height self.height += self.vel_height self.velocity += (self.velocity * BALL_AIR_FRICTION) else: self.velocity += (self.velocity * BALL_GROUND_FRICTION) # Draw different for now - until figure out how to show flight if self.height > 3: self.image.fill(RED) else: self.image.fill(GREY) self.position += self.velocity self.rect.center = self.position
b7734da68c503bc04c210b2a6b34529d3bc79520
himeshnag/Ds-Algo-Hacktoberfest
/Python/tortois-hare_pointer.py
1,037
4.125
4
#cycle detection #one pointer moving at twice the speed of other #Floyd's cycle finding algorithm #Given a constant array of n elements which contains elements from 1 to n-1, #with any of these numbers appearing any number of times. Find any one of these repeating numbers in #O(n) and using only constant memory space. # element in an array with values in # range from 0 to n-1. # function to find one duplicate def findduplicate(arr, n): # return -1 because in these cases # there can not be any repeated element if (n <= 1): return -1 # initialize fast and slow slow = arr[0] fast = arr[arr[0]] # loop to enter in the cycle while (fast != slow) : # move one step for slow slow = arr[slow] # move two step for fast fast = arr[arr[fast]] # loop to find entry point of the cycle fast = 0 while (slow != fast): slow = arr[slow] fast = arr[fast] return slow # Driver Code if __name__ == "__main__": arr = [1, 2, 3, 4, 5, 6, 3 ] n = len(arr) print(findduplicate(arr, n))
bf17226dc329aff722cd21b027bb9ec82d48d938
srikloud/PyProjects
/List/ret_elemt_indx_frmlist.py
210
3.796875
4
def reteleindfrmlist(): a = [1,2,3,4,5,6,7,8] out=[] for i in range(0,len(a)): print(a[i]) print(i) x = [y for y in range(1, 8) if y%2 == 0] print(x) reteleindfrmlist()
785641ccd8ac9e93667d6d1b921d208f7e4a539b
DaHuO/Supergraph
/codes/CodeJamCrawler/16_0_2_neat/16_0_2_shivank77_yy.py
740
3.890625
4
def reverse(string): #string = string[::-1] string = string.replace('-','=') string = string.replace('+','-') string = string.replace('=','+') return string t = int(input()) for i in range(1,t+1): string = input() p = len(string) s = '' count = 0 c = 0 if string == '+'*p: print("Case #{}: {}".format(i, 0)) elif string=='-'*p: print("Case #{}: {}".format(i, 1)) else : while len(string)>0: if string[-1]=='+': string = string[:-1] else : string = reverse(string) count += 1 print("Case #{}: {}".format(i, count))
67544711035af51be140064ec343936e14cda304
qizongjun/Algorithms-1
/Leetcode/Math/#43-Multiply Strings/main.py
916
4.125
4
# coding=utf-8 ''' Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2. Note: The length of both num1 and num2 is < 110. Both num1 and num2 contains only digits 0-9. Both num1 and num2 does not contain any leading zero. You must not use any built-in BigInteger library or convert the inputs to integer directly. ''' ''' 还是用ASCII码做,Beat 92.97% 公司:Facebook, Twitter ''' class Solution(object): def multiply(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ res, mtcd, mlpl = 0, num1[::-1], num2[::-1] base, count = 0, 1 for s in mtcd: base += ((ord(s) - ord('0')) * count) count *= 10 count = 1 for k in mlpl: res += ((ord(k) - ord('0')) * base * count) count *= 10 return str(res)
eddf2715b7fcebc54884ca5e54dac463ffb4c8e0
ThomasBriggs/python-examples
/Classes/Classes.py
1,599
3.75
4
class Employee: def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + "." + last + "@comapny.com" self.raise_ammount = 4 def __add__(self, other): return self.pay + other.pay def __contains__(self, item): return self.first.contains(item) or self.last.contains(item) def apply_raise(self, different_amount=int(0)): if different_amount == 0: self.pay *= self.raise_ammount else: self.pay *= different_amount def print_details(self): print("Fullname: %s %s" "\nPay: %s" "\nEmail: %s" % (self.first, self.last, self.pay, self.email)) @staticmethod def print_employee(instance): print("Fullname: %s %s" "\nPay: %s" "\nEmail: %s" % (instance.first, instance.last, instance.pay, instance.email)) class Developer(Employee): def __init__(self, first, last, pay, prog_lang): Employee.__init__(self, first, last, pay) self.prog_lang = prog_lang def print_details(self): Employee.print_details(self) print("Programming Language: %s" % (self.prog_lang)) def search_array(input_array, search_item): return search_item in input_array dev_1 = Developer("Thomas", "Briggs", 500000, "Python") dev_1.print_details() # emp_1 = Employee("Thomas", "Briggs", 111) # emp_1.print_details() # Employee.print_details(emp_1) array = [1, 6, 8, 3, 7, 5, 2, 6] print(search_array(array, 99))
644997e6b52dd60a630381f1e8e77091a8dd69cf
chriscarter777/lunarLander
/P2_LunarLander.py
3,528
4.03125
4
# # -------LUNAR LANDER------- # (it's a oldie but a goodie) # def main(): def chooseDifficulty(): difficulty = raw_input("Select a difficulty level (1-5):") try: difficulty = int(difficulty) except ValueError: print "Difficulty level must be a number." chooseDifficulty() if difficulty < 1 or difficulty > 5: print "Difficulty must be between 1 and 5." chooseDifficulty() else: return difficulty def chooseInitial(): defaultVelocity = random.randint(-1000,0) velocity = raw_input("Choose initial velocity or enter to accept random assignment: ") or defaultVelocity try: velocity = int(velocity) except ValueError: print "Initial velocity must be a number." chooseInitial() return velocity def play(altitude, velocity, fuel, threshold): if altitude > 0: print "\n ALTITUDE: ",altitude," VELOCITY: ",velocity," m/s FUEL: ",fuel," lbs" burn = raw_input("How many pounds of fuel do you want to burn? ") if burn.isdigit(): burn = int(burn) #print burn, fuel, type(burn), type(fuel) if burn < 0: print "Burn has to be non-negative, of course!" play(altitude, velocity, fuel, threshold) elif burn > fuel: print "You don't have that much fuel." play(altitude, velocity, fuel, threshold) else: fuel = fuel - burn newVelocity = velocity + burn - gravity altitude = altitude + ((velocity + newVelocity)/2) velocity = newVelocity play(altitude, velocity, fuel, threshold) else: print "Burn rate must be a number." play(altitude, velocity, fuel, threshold) else: if velocity > threshold: print "\nNice Landing! You arrived on the surface with a velocity of ",velocity," m/s and ",fuel," pounds of fuel left." choice=raw_input("Do you want to play again? (y/n)") if choice == "y": main() else: sys.exit else: print "\nCRASH!!! You plowed into the surface with a velocity\ of ",velocity," m/s." choice=raw_input("Do you want to play again? (y/n)") if choice == "y": main() else: sys.exit import sys import random print "\n\n ************************************ " print "\n LUNAR LANDER--An oldie but a goodie! " print "\n ************************************ \n" print "The object is to start at 10,000 feet and arrive at the surface\ \nwith vertical velocity below the damage threshold.\ \nYou will be asked how many pounds of fuel you want to burn\ \nfor each second of flight. \n\n" altitude = 10000 gravity = 10 burn=0 difficulty = chooseDifficulty() threshold = -22 + (difficulty * 4) fuel = 1000-(difficulty * 50) print "Level",difficulty,": Your landing velocity must be greater than ",threshold," m/s.\n\n" velocity = chooseInitial() print "\n\n" play(altitude, velocity, fuel, threshold) if __name__ == "__main__": main()
3599bf4b4cc88af655e9b3a6b22a75e62933bce9
Jonathan-E-Navarro/wallbreakers
/week1/surroundedRegions.py
2,007
3.84375
4
class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ #dfs is going to modify every O that can be reached by another O def dfs(row, col): # if not within boundary or on boundary or not a zero, return if row >= len(board) or col >= len(board[0]) or row < 0 or col < 0: # print("returning") return if board[row][col] != 'O': return # changed every 0 that can be touched by a DFS to a * board[row][col] = '*' dfs(row+1, col) dfs(row-1, col) dfs(row, col+1) dfs(row, col-1) #iterate through board and call DFS when appropriate for row in range(len(board)): for col in range(len(board[0])): if row in {0, len(board)-1} or col in {0, len(board[0])-1} and board[row][col] == 'O': dfs(row,col) #every O seen at this point could not be reached through another O so its a surrounded region, flip it to x #every * can be flipped back to a 0 since it was not surrounded by X's for row in range(len(board)): for col in range(len(board[0])): if board[row][col] == '*': board[row][col] = 'O' elif board[row][col] == 'O': board[row][col] = 'X' """ Thought process: We are going to perform a DFS, Our dfs is going to modify every O that can be reached by another O if not within boundary or on boundary or not a zero, return changed every 0 that can be touched by a DFS to a * iterate through board and call DFS when appropriate every O seen at this point could not be reached through another O so its a surrounded region, flip it to x every * can be flipped back to a 0 since it was not surrounded by X's """
999266d9a8e342a03465da5657c8f37b72039193
Cbkhare/Challenges
/repeated_substr.py
1,887
3.796875
4
#In case data is passed as a parameter from sys import argv import re file_name = argv[1] fp = open(file_name,'r+') contents = [line.strip('\n') for line in fp] #print (contents) for item in contents: junk = list(item) i =2 j =0 stack = [] s = 0 while (i-j)*2 <= len(item) and j < len(item): stat = i #print (junk[j:i],j,i) stat_j = j while (stat+stat-stat_j) <= len(item): #print (junk[j:i],junk[stat:stat+stat-stat_j]) if junk[j:i] == junk[stat:stat+stat-stat_j] and \ len(junk[j:i])*[' '] != junk[j:i] : if len(junk[j:i]) > s: stack= junk[j:i] s = len(junk[j:i]) stat +=1 stat_j +=1 if (i-j)*2 >= len(item)-1: #print (j,i) j +=1 i = j+2 continue i += 1 if stack != []: #print (stack) print (str(stack).replace(', ','').replace('[','').replace(']','').replace('\'','').replace(' ','')) else: print ('NONE') ''' View All Challenges Repeated Substring Challenge Description: You are to find the longest repeated substring in a given text. Repeated substrings may not overlap. If more than one substring is repeated with the same length, print the first one you find.(starting from the beginning of the text). NOTE: The substrings can't be all spaces. Input sample: Your program should accept as its first argument a path to a filename. The input file contains several lines. Each line is one test case. Each line contains a test string. E.g. banana am so uniqe Output sample: For each set of input produce a single line of output which is the longest repeated substring. If there is none, print out the string NONE. E.g. an NONE '''
5fced2357787705619f050793a42f4b18f0e8fb4
ntexplorer/PythonPractice
/PythonForComputation/Week3_Prac/Lab1_4.py
297
4.59375
5
import math def convert_degree_to_radians(x): rad = x / 360 * 2 * math.pi return rad degree = int(input('Enter the degree you want to convert: ')) rad = convert_degree_to_radians(degree) print(degree) print(rad) print("An angle of {} in degrees is {} in radians".format(degree, rad))
71c1763f4620469c143d510b9ddb71432f7d7e8d
DagdiHiman/EDX-Python-Course-6.00.1x-
/PRG2-bob.py
400
3.53125
4
s="Hibob Bobob bo b" count=0 x=0; y=3 length = int(len(s)) while y < length: z=s[x:y] if (z=='bob'): count+=1 else : count+=0 y+=1 x+=1 print("No. of bob =" + str(count)) """ #another method- s="Hibob Bobob bo bob" numBobs = 0 for i in range(1, len(s)): if s[i:i+3] == 'bob': numBobs += 1 print("No. of bob =" + str(numBobs)) """
5b3e9a1ea6e3085f0c315a5729c1c755feb1ce4b
shazam2064/complete-python-developer
/part2/tupples.py
1,369
4.15625
4
# my_tuple = (1, 2, 3, "Stardust Crusaders", ["Star Platinum", "Hierophant Green", "Magician's Red", "Silver Chariot"]) # # print(my_tuple[4]) # # The piece of code below won't work, because a tuple's values can't be modified. # my_tuple = (1, 2, 3, "Stardust Crusaders", ["Star Platinum", "Hierophant Green", "Magician's Red", "Silver Chariot"]) # # my_tuple[3] = "JJBA Part 3 Main Characters Stands" # # print(my_tuple) # # The piece of code below does work, because you are changing the list inside the tupple. # my_tuple = (1, 2, 3, "Stardust Crusaders", ["Star Platinum", "Hierophant Green", "Magician's Red", "Silver Chariot", "Iggy"]) # # my_tuple[4][4] = "The Fool" # # print(my_tuple) # my_tuple = (1, 2, 3, "Stardust Crusaders", ["Star Platinum", "Hierophant Green", "Magician's Red", "Silver Chariot"]) # # count = my_tuple.count("Stardust Crusaders") # # print(count) # my_tuple = (1, 2, 3, "Stardust Crusaders", ["Star Platinum", "Hierophant Green", "Magician's Red", "Silver Chariot"]) # # print(my_tuple[3:6]) # my_tuple = (1, 2, 3, "Stardust Crusaders", ["Star Platinum", "Hierophant Green", "Magician's Red", "Silver Chariot"]) # # str_tuple = my_tuple[3:6] # # print(str_tuple) my_tuple = (1, 2, 3, "Stardust Crusaders", ["Star Platinum", "Hierophant Green", "Magician's Red", "Silver Chariot"]) extracted = my_tuple[4] print(type(extracted))
41b450949ed7bd173fd32997c8fc25b512df24f2
NotAKernel/python-tutorials
/rental_car.py
120
3.5625
4
ask_car = "What car would you like? " car = input(ask_car) print(f"Let me see if we have any {car.title()}'s in stock.")
c77feebb78886fb914540a24ad062e245979fabd
smyang2018/ergatis
/src/python/lgtanalysis.py
10,482
3.671875
4
# This is a program to analyse SAM files for Lateral Genome Transfers. # Ashwinkumar Ganesan. # Date: 01/25/2010 # This module is access os functions, like check if a file exists or not. import os # Class to work with SAM Files. from seqfileparse import SeqFileAnalyse # Class for LGT. # It contains the function to analyse and create statistics for Lateral Genome Transfer. # The two SAM Files are created using the same comparison genome, but reference files for the alignment are different. # SAMFile1 and SAMFile2 are the location of the two sam files which are used to analysing lateral genome transfers. class LGTNode: def __init__(self, SAMFile1, SAMFile2): self.FirstFileLocation = SAMFile1 self.SecondFileLocation = SAMFile2 # 0 index position is for combinations where First File Mate 1 is mapped and Second File Mate 2 is mapped. # 1 index position is for combinations where First File Mate 2 is mapped and Second File Mate 1 is mapped. self.UM_M_UM_M_MapCounter = [0,0] self.M_M_UM_M_MapCounter = [0,0] # This a function to convert a number into binary form. # The number of bits in the number is upto 16. # The function returns the binary value as a list of bit values. def Int2Binary(self, Number): BinaryValue = [] while(Number > 0): Rem = Number % 2 BinaryValue.append(str(Rem)) Number = Number / 2 while(len(BinaryValue) < 16): BinaryValue.append('0') return BinaryValue # This function is to index a file. # The index works only on CSV Type of files. # Index only the first read in the pair. def IndexFile(self, FileName, IndexColumn, DeLimiter): FilePointer = open(FileName, "r") SamAnalyse = SeqFileAnalyse(FileName) ReadDict = {} # Read all the contents of the file and put in an array. while 1: Position1 = FilePointer.tell() FileLine1 = FilePointer.readline() ParsedFileLine1 = SamAnalyse.ParseLine(FileLine1, DeLimiter) # Exit the loop if all the lines in the file are read. if not FileLine1: break pass # Read the other Read-Pair. FileLine2 = FilePointer.readline() # Add the value to Dictionary. Index = ParsedFileLine1[IndexColumn] ReadDict[Index] = Position1 FilePointer.close() return ReadDict # This is a function to find the combinations of mapping amongst sam files for those reads # where one mate is mapped and the other mate is unmapped. # Since the Reads are in a sequence in the SAM file, once a read is found then, searching can continue in from the same location. # U - Unmapped. # M - Mapped. # Paramters: 1. SamFile1FilterOrNot - Flag option to decide, if the SAM File should consider a filtered output or unfiltered output. # 0 - to filter, 1 - Not filter. # e.g - This can be used for Human Genome (req. unfiltered SAM File) to Bacterial compared SAM File which should be filtered. # CreateAlways is a flag - so that the Sam file parsing is done everytime. def Find_UM_UM_Mates(self,SamFile1FilterOrNot, SamFile2FilterOrNot, DeLimiter, CreateAlways): self.UM_M_UM_M_MapCounter = [0,0] Location = self.FirstFileLocation + "_UM_M_UM_M.sam" MappedMatesFile = open(Location,"w") FirstFileLocation = self.FirstFileLocation + "_UM_M.sam" SamAnalysis1 = SeqFileAnalyse(self.FirstFileLocation) # "False" means the file does not exist. Hence create the file. if(os.access(FirstFileLocation, os.F_OK) == 0): SamAnalysis1.OpenFile() SamAnalysis1.ParseOut(DeLimiter,[0,1,1,1],0.8,SamFile1FilterOrNot) SamAnalysis1.PrintStat() SamAnalysis1.CloseFile() SecondFileLocation = self.SecondFileLocation + "_UM_M.sam" SamAnalysis2 = SeqFileAnalyse(self.SecondFileLocation) # "False" means the file does not exist. if(os.access(SecondFileLocation, os.F_OK) == 0 and (CreateAlways == 0)): SamAnalysis2.OpenFile() SamAnalysis2.ParseOut(DeLimiter,[1,1,1,0],0.8,SamFile2FilterOrNot) SamAnalysis2.PrintStat() SamAnalysis2.CloseFile() # Index the Files. FirstFileDict = self.IndexFile(FirstFileLocation, 0, DeLimiter) SecondFileDict = self.IndexFile(SecondFileLocation, 0, DeLimiter) # Once the Files are created, verify the values. FirstMappedFile = open(FirstFileLocation,'r') SecondMappedFile = open(SecondFileLocation,'r') # The DeLimiter has to be the same accross the files. for Key in FirstFileDict: if((Key in SecondFileDict) == 1): # Get the location of the read in the first file. FirstFileReadLocation = FirstFileDict[Key] FirstMappedFile.seek(FirstFileReadLocation, 0) # Read the First File pair. FirstFileMate1 = FirstMappedFile.readline() ParsedFirstFileMate1 = SamAnalysis1.ParseLine(FirstFileMate1, DeLimiter) FirstFileMate2 = FirstMappedFile.readline() # Get the location of the read in the second file. SecondFileReadLocation = SecondFileDict[Key] SecondMappedFile.seek(SecondFileReadLocation, 0) # Read Second File Pair. SecondFileMate1 = SecondMappedFile.readline() ParsedSecondFileMate1 = SamAnalysis2.ParseLine(SecondFileMate1, DeLimiter) SecondFileMate2 = SecondMappedFile.readline() # Using Binary values to check between singletons. FirstFileMate1BinVal = self.Int2Binary(int(ParsedFirstFileMate1[1])) SecondFileMate1BinVal = self.Int2Binary(int(ParsedSecondFileMate1[1])) if(FirstFileMate1BinVal[2] == '1' and SecondFileMate1BinVal[3] == '1'): print(str(FirstFileMate1BinVal) + " " + str(SecondFileMate1BinVal)) self.UM_M_UM_M_MapCounter[0] = self.UM_M_UM_M_MapCounter[0] + 1 MappedMatesFile.write(FirstFileMate1) MappedMatesFile.write(FirstFileMate2) MappedMatesFile.write(SecondFileMate1) MappedMatesFile.write(SecondFileMate2) elif(FirstFileMate1BinVal[3] == '1' and SecondFileMate1BinVal[2] == '1'): print(str(FirstFileMate1BinVal) + " " + str(SecondFileMate1BinVal)) self.UM_M_UM_M_MapCounter[1] = self.UM_M_UM_M_MapCounter[1] + 1 MappedMatesFile.write(FirstFileMate1) MappedMatesFile.write(FirstFileMate2) MappedMatesFile.write(SecondFileMate1) MappedMatesFile.write(SecondFileMate2) MappedMatesFile.close() print str(self.UM_M_UM_M_MapCounter[0]) + " " + str(self.UM_M_UM_M_MapCounter[1]) CounterFile = self.FirstFileLocation + "_UM_M_UM_M_Numbers.txt" CounterFilePointer = open(CounterFile,"w") WriteString = str(self.UM_M_UM_M_MapCounter[0]) + "," + str(self.UM_M_UM_M_MapCounter[1]) CounterFilePointer.write(WriteString) CounterFilePointer.close() # Close the other files. FirstMappedFile.close() SecondMappedFile.close() return 1 # This function looks for the combinations where the first file has a read pair, where both are mapped. def Find_MM_UM_Mates(self,SamFile1FilterOrNot, SamFile2FilterOrNot, DeLimiter, CreateAlways): self.M_M_UM_M_MapCounter = [0,0] Location = self.FirstFileLocation + "_M_M_UM_M.sam" MappedMatesFile = open(Location,"w") FirstFileLocation = self.FirstFileLocation + "_M_M.sam" SamAnalysis1 = SeqFileAnalyse(self.FirstFileLocation) # "False" means the file does not exist. Hence create the file. if(os.access(FirstFileLocation, os.F_OK) == 0): SamAnalysis1.OpenFile() SamAnalysis1.ParseOut(DeLimiter,[1,1,1,1],0.8,SamFile1FilterOrNot) SamAnalysis1.PrintStat() SamAnalysis1.CloseFile() SecondFileLocation = self.SecondFileLocation + "_UM_M.sam" SamAnalysis2 = SeqFileAnalyse(self.SecondFileLocation) # "False" means the file does not exist. if(os.access(SecondFileLocation, os.F_OK) == 0 and (CreateAlways == 0)): SamAnalysis2.OpenFile() SamAnalysis2.ParseOut(DeLimiter,[1,1,1,1],0.8,SamFile2FilterOrNot) SamAnalysis2.PrintStat() SamAnalysis2.CloseFile() # Index the Files. FirstFileDict = self.IndexFile(FirstFileLocation, 0, DeLimiter) SecondFileDict = self.IndexFile(SecondFileLocation, 0, DeLimiter) # Once the Files are created, verify the values. FirstMappedFile = open(FirstFileLocation,'r') SecondMappedFile = open(SecondFileLocation,'r') # The DeLimiter has to be the same accross the files. for Key in FirstFileDict: if((Key in SecondFileDict) == 1): # Get the location of the read in the first file. FirstFileReadLocation = FirstFileDict[Key] FirstMappedFile.seek(FirstFileReadLocation, 0) # Read the First File pair. FirstFileMate1 = FirstMappedFile.readline() FirstFileMate2 = FirstMappedFile.readline() # Get the location of the read in the second file. SecondFileReadLocation = SecondFileDict[Key] SecondMappedFile.seek(SecondFileReadLocation, 0) # Read Second File Pair. SecondFileMate1 = SecondMappedFile.readline() SecondFileMate2 = SecondMappedFile.readline() self.M_M_UM_M_MapCounter[0] = self.M_M_UM_M_MapCounter[0] + 1 MappedMatesFile.write(FirstFileMate1) MappedMatesFile.write(FirstFileMate2) MappedMatesFile.write(SecondFileMate1) MappedMatesFile.write(SecondFileMate2) MappedMatesFile.close() print str(self.M_M_UM_M_MapCounter[0]) + " " + str(self.M_M_UM_M_MapCounter[1]) CounterFile = self.FirstFileLocation + "_M_M_UM_M_Numbers.txt" CounterFilePointer = open(CounterFile,"w") WriteString = str(self.M_M_UM_M_MapCounter[0]) + "," + str(self.M_M_UM_M_MapCounter[1]) CounterFilePointer.write(WriteString) CounterFilePointer.close() # Close the other Files. FirstMappedFile.close() SecondMappedFile.close() return 1 # End Of Class. # End Of Program
1008deb2160d2d6acefed49faae43f493f0fb762
drolleigh/AdventCode
/Day3/day3.py
1,443
3.90625
4
# Author: Dylan Rolleigh # Day: 3 import numpy as np def map_reader(): with open('day3_input.txt', "r") as text_file: policy = text_file.readlines() return policy map = map_reader() # print(map) # Build map in matrix form and pop off '/n' matrix = [] for sub in map: matrix.append(list(sub)) for i in range(len(matrix)): matrix_temp = matrix[i] matrix_temp.pop() matrix[i] = matrix_temp # Dimension of pattern # row = 11 # col = 11 row = 323 col = 31 # Step sizes step_right = 1 step_down = 2 # Calculate matrix size total_step_right = step_right*row pattern_rpt = -(-total_step_right // col) total_col = col*pattern_rpt # creates empty matrix to fill with map elements map_matrix = np.zeros((row, total_col), dtype=str) # Fill empty matrix of string zeroes with elements from map for i in range(row): matrix_row = matrix[i]*pattern_rpt for j in range(total_col): map_matrix[i, j] = matrix_row[j] # print('map_matrix = ', map_matrix) # Check elements in map matrix for # when using step sizes trees = 0 j = step_right for i in range(step_down, row, step_down): map_matrix_line = map_matrix[i] # print('i',i) # print('map_matrix_line', map_matrix_line) # print('map_matrix_line[j]', map_matrix_line[j]) if map_matrix_line[j] == '#': trees = trees + 1 j = j + step_right # print('j', j) print('trees', trees) answer = 70*220*63*76*29 print('answer', answer)
eef2896a9381c7d063dddea9a2ce68eb2cbae7ce
Seremontis/Simple_Projects_in_Python
/python object 2.py
1,826
3.59375
4
class ElementZamowienia: nazwa='' cena=0 liczbaSztuk=0 def __init__(self,nazwa='',cena=0.00,liczbaSztuk=0): self.nazwa=nazwa self.cena=cena self.liczbaSztuk=liczbaSztuk def __str__(self): return '{} {} zł, {} szt., łącznie {} zł'.format(self.nazwa,self.cena,self.liczbaSztuk,self.cena*self.liczbaSztuk) def obliczKoszt(self): wartosc=self.cena*self.liczbaSztuk return [wartosc-(wartosc*self.obliczRabat()),wartosc*self.obliczRabat()] def obliczRabat(self): if self.liczbaSztuk>=5: return 0.1 else: return 0 class Zamowienie: elementy=[] rozmiar=0 maksRozmiar=0 def __init__(self,maksRozmiar): self.maksRozmiar=maksRozmiar def dodaj(self,elZam): if len(self.elementy)<self.maksRozmiar: self.elementy.append(elZam) return True else: return False def obliczKoszt(self): lacznie=0 rabat=0 for el in self.elementy: tmp=el.obliczKoszt() lacznie+=tmp[0] rabat+=tmp[1] return [lacznie,rabat] def pisz(self): print('Zamówienie:') for i in range(len(self.elementy)): print('{0}. {1}, {2} zł, {3} szt., łącznie {4} zł'.format(i+1,self.elementy[i].nazwa,self.elementy[i].cena,self.elementy[i].liczbaSztuk,self.elementy[i].obliczKoszt()[0])) wynik=self.obliczKoszt() print('Koszt całkowity: {} zł \nNaliczony rabat {} zł'.format(wynik[0],wynik[1])) z = Zamowienie(10) z.dodaj(ElementZamowienia("Chleb", 4.0, 2)) z.dodaj(ElementZamowienia("Mleko", 2.5, 1)) z.dodaj(ElementZamowienia("Cukier", 4.0, 5)) z.dodaj(ElementZamowienia("Puszka", 9.0, 1)) z.pisz()
70ad3d1fd9df1a88b3ed77a39ade0876b9b0bdb4
Mantarus/Formal-languages
/Task1/Task1_(not valid).py
2,102
3.578125
4
ADV = "ADV" WIN = "WIN" LOSE = "LOSE" FALSE = "FALSE" A_WON = "A WON" B_WON = "B WON" def main(): string = input("Type input string: ") result = run_det(string) if result: print("Det: Allowed") else: print("Det: Not allowed") result = run_not_det(string) if result: print("Not det: Allowed") else: print("Not det: Not allowed") def run_det(string): F = {A_WON, B_WON} q = (0, 0) for char in string: q = get_next_state_det(q, char) print(char, q) if q == FALSE: return False if q in F: return True return False # def run_not_det(input, init_states): # results = [run_det(input, x) for x in init_states] # for result in results: # if result: # return True # return False def run_not_det(string): F = {A_WON, B_WON} q = {(0, 0)} print(q) X = {'a', 'b'} for char in string: q_next = set() for state in q: if state == FALSE: continue for x in X: q_next.add(get_next_state_det(state, x)) if q_next == {FALSE}: return False q = q_next print(q) for fin in F: if fin in q: return True return False def get_next_state_det(q, x): if q == A_WON or q == B_WON: return FALSE if x == 'a': count = calc_count_det(q[0], q[1]) if count[0] == WIN: return A_WON next_q = count elif x == 'b': count = calc_count_det(q[1], q[0]) if count[0] == WIN: return B_WON next_q = (count[1], count[0]) else: return FALSE return next_q def calc_count_det(w_points, l_points): if w_points == 40 and l_points == 40: return (ADV, 40) if w_points == 40 and l_points == ADV: return (40, 40) if w_points == ADV or w_points == 40 and l_points < 40: return (WIN, LOSE) if w_points == 30: return (40, l_points) return (w_points + 15, l_points) main()
fc51102adca52b8e0d7f8720fedf8fe6cfde6711
burbol/LineTensionPackage
/Analyze_trajectories/Results_Module.py
12,056
3.609375
4
#!/usr/bin/python import matplotlib import matplotlib.pyplot as plt import numpy as np from scipy import stats from fractions import Fraction import math #from scipy.optimize import curve_fit #import os #from scipy.interpolate import interp1d #from matplotlib.font_manager import FontProperties # func is the function of a line, that will be used in the linear fits def func(x, a, b): return a*x + b # endpoint returns the integer "end": the last data point different then "nan" def endpoint(theta): global end for end in range(20, len(theta)): if math.isnan(theta[end]): break return (end-1) # The following functions will be used to calculate the block averages and the errorbars # The function naive_variance will only be used inside the function blockAverage def naive_variance(data): n = 0 Sum = 0 Sum_sqr = 0 for x in data: n = n + 1 Sum = Sum + x Sum_sqr = Sum_sqr + x*x variance = (Sum_sqr - (Sum*Sum)/n)/(n - 1) return variance def blockAverage(datastream, Nblocks): # FIRST WE CREATE AN ARRAY TO STORE THE MEAN VALUES OF THE DATA BLOCKS (blockMean) blockMean = np.zeros(Nblocks) # Nobs is the number of points (observations) in our data Nobs = len(datastream) # BlockSize is the size of each block of data BlockSize = int(Nobs//Nblocks) if Nblocks==1: errorbar = naive_variance(datastream) return errorbar else: # WE CALCULATE IN A LOOP THE MEAN VALUES OF EACH DATA BLOCK (blockMean) for i in range(0,Nblocks-1): ibeg = i*BlockSize iend = (i+1)*BlockSize blockMean[i] = np.mean(datastream[ibeg:iend]) # WE TREAT THE LAST BLOCK SEPARATELY, BECAUSE WE HAVE TO TAKE INTO ACCOUNT THE POSSIBLE REMAINING POINTS # WHEN THE NUMBER OF DATA POINTS ISN'T A MULTIPLE OF THE NUMBER OF BLOCKS ibeg = (Nblocks-1)*BlockSize iend = Nobs blockMean[Nblocks-1] = np.mean(datastream[ibeg:iend]) errorbar = (np.std(blockMean))/math.sqrt(Nblocks -1) #np.std(blockMean) is the standard deviation of blockMean simulavr = np.mean(blockMean) return simulavr, errorbar # best_start SEARCHS FOR THE STARTING POINT (start) OF BIGGEST equilibrated TIME INTERVAL = where the error interval is smaller then the variation of the data # (determined with a line fit of the data) def best_start(theta,t,omitstart,fixend): lastnumber = endpoint(theta) endblocks = lastnumber - fixend error = np.zeros(endblocks-omitstart) #error will be the total error (of all the points taken each time we choose a different set of data to make the blocks) average = np.zeros(endblocks-omitstart) # average is the same, but for the average slope = np.zeros(endblocks-omitstart) intercept = np.zeros(endblocks-omitstart) shift = np.zeros(endblocks-omitstart) goodblocks = [] error = error.tolist() j=0 # Loop for finding the "best" interval to do the block averaging for i in range (omitstart, endblocks): average[j],error[j] = blockAverage((theta[i:lastnumber]),3) slope[j], intercept[j], delete1, delete2, delete3 = stats.linregress(t[i:lastnumber],theta[i:lastnumber]) shift[j] = abs(func(t[i], slope[j], intercept[j]) - func(t[lastnumber], slope[j], intercept[j])) if shift[j] <= (2*error[j]): goodblocks.append(i) j = j+1 if goodblocks==[]: # Not equilibrated yet return None else: print "num of good intervals=", len(goodblocks) start = min(goodblocks) return start #create_pi_labels creates ticks ans labels for plot in radians (script from internet) def create_pi_labels(a, b, step): # next line and .limit_denominator solve issues with floating point precision max_denominator = int(1/step) values = np.arange(a, b+step/10, step) fracs = [Fraction(x).limit_denominator(max_denominator) for x in values] ticks = values*np.pi labels = [] for frac in fracs: if frac.numerator==0: labels.append(r"$0$") elif frac.numerator<0: if frac.denominator==1 and abs(frac.numerator)==1: labels.append(r"$-\pi$") elif frac.denominator==1: labels.append(r"$-{}\pi$".format(abs(frac.numerator))) else: labels.append(r"$-\frac{{{}}}{{{}}} \pi$".format(abs(frac.numerator), frac.denominator)) else: if frac.denominator==1 and frac.numerator==1: labels.append(r"$\pi$") elif frac.denominator==1: labels.append(r"${}\pi$".format(frac.numerator)) else: labels.append(r"$\frac{{{}}}{{{}}} \pi$".format(frac.numerator, frac.denominator)) return ticks, labels # equil_results plots the equilibrated interval and return results # Input: # # Waters: sizes of droplets to loop through # angles: mic. contact angle # pc: SAM's polarity # Nrows: num of rows for the subplots # Ncolumns: num of columns for the subplots # blocksNum: # beg: We leave out the first 5ns<=>10 points # t: array with all the values of the time (0ns, 0.5ns, 1.0ns, 1.5ns, etc) # minblocksize: # The minimum block size is 10ns<=>20 points # mylabel: plot label # pltname: name of output file (plot saved in .jpg file) def equil_results(Waters, angles, pc, Nrows, Ncolumns, blocksNum, beg, t, minblocksize, mylabel, pltname): fig, ax = plt.subplots(Ncolumns, Nrows,figsize=(5,3.5),dpi=400) fig.subplots_adjust(bottom=0.0,top=4.5, left=0., right=2.5, hspace = 0.5) matplotlib.rcParams['legend.handlelength'] = 0 theta = [] # microscopic contact angle of equilibrated system errortheta = [] # error in the microscopic contact angle of equilibrated system equil_theta = [] #equilibrated systems i = 0 for c in Waters: print "for SAM ",pc,"% and ", c, " molecules:" theta2 = np.array(angles[(pc, c)]) end=endpoint(theta2) start=best_start(theta2,t,beg,minblocksize) titletext = r'$\Phi=\ $'+str(pc)+'\%, $n_{W}=\ $'+str(c) if start != None: slope, intercept, delete1, delete2, delete3 = stats.linregress(t[start:end],theta2[start:end]) thetamean, errrorbar = blockAverage((theta2[start:end]),blocksNum) (errortheta).append(errrorbar) (theta).append(thetamean) (equil_theta).append(c) #(start_theta[pc]).append(start) #(end_theta[pc]).append(end) else: print " Not equilibrated!" start = end-40 slope, intercept, delete1, delete2, delete3 = stats.linregress(t[start:end],theta2[start:end]) thetamean, errrorbar = blockAverage((theta2[start:end]),blocksNum) titletext = titletext +': Not equilibrated' ax = plt.subplot(Nrows, Ncolumns, i+1) ax.plot(t[start:end], theta2[start:end],'-',color='orange',linewidth=1.5) ax.plot(t[start:end], func(t[start:end], 0, thetamean+errrorbar),'k-',linewidth=1.5) ax.plot(t[start:end], func(t[start:end], 0, thetamean-errrorbar),'k-',linewidth=1.5) line1, = ax.plot(t[start:end], func(t[start:end], slope, intercept),'b', label=titletext,linewidth=1.5) #We set the ticks size for item in (ax.get_xticklabels() + ax.get_yticklabels()):item.set_fontsize(15) # Labels with symbols ax.set_xlabel(r'$\mathbf{t [ns]}$',fontsize=20) # Labels with names ax.set_ylabel(mylabel,fontsize=23) #titles for each subplot: ax.set_title(titletext,fontsize=20,fontweight='bold') ax.set_xlim([t[start],t[end-1]]) # Create a legend for the first line. #first_legend = plt.legend(loc=1,borderaxespad=0.,borderpad=0.2,fontsize=14) # Add the legend manually to the current Axes. #ax = plt.gca().add_artist(first_legend) i = i + 1 plt.show() fig.savefig('equil_' + pltname + '_t_s' + str(pc) + '.jpg', bbox_inches='tight',dpi=400) return theta, errortheta, equil_theta # Plot whole simulation and return results # Uncomment lines for MiddlePoint/GDS when results are provided def whole_results(Waters, angles_w, angles_m, angles_s, pc, Nrows, Ncolumns, blocksNum, beg, t, minblocksize, mylabel, pltname): # with the 3 interface positions #def whole_results(Waters, angles_w, angles_s, pc, Nrows, Ncolumns, blocksNum, beg, t, minblocksize, mylabel, pltname): # only 2 interface positions # Interface at MiddlePoint/GDS errortheta_m=[] theta_m=[] equil_theta_m=[] # Interface at SAM peak errortheta_s=[] theta_s=[] equil_theta_s=[] fig, ax = plt.subplots(Ncolumns, Nrows,figsize=(5,3.5),dpi=400) fig.subplots_adjust(bottom=0.0,top=4.5, left=0., right=2.5, hspace = 0.5) matplotlib.rcParams['legend.handlelength'] = 1 p=0 i = 0 for c in Waters: print "for SAM ",pc,"% and ", c, " molecules:" ax = plt.subplot(Nrows, Ncolumns, i+1) theta2_w = np.array(angles_w[(pc, c)]) theta2_m = np.array(angles_m[(pc, c)]) theta2_s = np.array(angles_s[(pc, c)]) end=endpoint(theta2_w) start=best_start(theta2_w,t,beg,minblocksize) titletext = r'$\Phi=\ $'+str(pc)+'\%, $n_{W}=\ $'+str(c) # Save results if start != None: # Empty arrays to store averages (for plots) avrg_w = np.ones(end - start) avrg_m = np.ones(end - start) avrg_s = np.ones(end - start) # Arrays with time variables (for plots) t_avrg_w = t[start:end] t_avrg_m = t[start:end] t_avrg_s = t[start:end] # Interface at first water peak (calculated only for plot) thetamean, errrorbar =blockAverage((theta2_w[start:end]),blocksNum) avrg_w = thetamean*avrg_w # Interface at MiddlePoint/GDS thetamean, errrorbar =blockAverage((theta2_m[start:end]),blocksNum) avrg_m = thetamean*avrg_m (errortheta_m).append(errrorbar) (theta_m).append(thetamean) (equil_theta_m).append(c) # Interface at SAM peak thetamean, errrorbar =blockAverage((theta2_s[start:end]),blocksNum) avrg_s = thetamean*avrg_s (errortheta_s).append(errrorbar) (theta_s).append(thetamean) (equil_theta_s).append(c) ax.plot(t_avrg_w, avrg_w,'-',color='orange',linewidth=4) ax.plot(t_avrg_m, avrg_m,'-',color='black', linewidth=4) ax.plot(t_avrg_s, avrg_s,'g-',linewidth=4) p=p+1 else: print " Not equilibrated!" start=end-20 titletext = titletext + ': Not equilibrated' ax.plot(t, theta2_w,'^',label="Water Peak",color='orange',markersize=7.0) ax.plot(t, theta2_m,'h', color='gray',label="GDS",markersize=6.0) ax.plot(t,theta2_s,'s',label="SAM Peak",color='lightgreen',markersize=5.0) ax.set_xlim([t[0],t[end-1]]) #We set the ticks size for item in (ax.get_xticklabels() + ax.get_yticklabels()):item.set_fontsize(15) # Labels with symbols ax.set_xlabel(r'$\mathbf{t [ns]}$',fontsize=20) # Labels with names ax.set_ylabel(mylabel,fontsize=23) #titles for each subplot: ax.set_title(titletext,fontsize=20,fontweight='bold') # Create a legend for the first line. #first_legend = plt.legend(loc=0,borderaxespad=0.,borderpad=0.2) first_legend = plt.legend(loc=0,borderaxespad=0.,borderpad=0.3,fontsize=16,numpoints=1, markerscale=1,handlelength=0.4,handletextpad=0.3) # Add the legend manually to the current Axes. ax = plt.gca().add_artist(first_legend) i = i+1 plt.show() fig.savefig(pltname +'_t_s'+str(pc)+'.jpg', bbox_inches='tight',dpi=400) return theta_m,errortheta_m,equil_theta_m, theta_s,errortheta_s,equil_theta_s #return theta_s,errortheta_s,equil_theta_s
51f09029423d648526adc825f507781f84095b5e
glock3/Learning-
/Alexey/Algorithms/OB_125/sorting/bubble_sort.py
479
3.640625
4
from Alexey.Algorithms.OB_125.sorting.time_decorator import timer def main(): array = [] print(*array) print(sort(array)) @timer def sort(array): try: for i in range(len(array)-1, 0, -1): for y in range(i): if array[y] > array[y + 1]: array[y], array[y + 1] = array[y + 1], array[y] return array except TypeError: raise TypeError('TypeError') if __name__ == '__main__': main()
6a22a98c793f49b38fbbd45a4c00f8e07c6d7d5d
adeak/AoC2015
/day05.py
946
3.578125
4
from collections import Counter def day05(inps, part2=False): if part2: is_nice_fun = is_nice_v2 else: is_nice_fun = is_nice return sum(map(is_nice_fun, inps.strip().split('\n'))) def is_nice(word): counter = Counter(word) if sum(counter[c] for c in 'aeiou') < 3: return False if any(k in word for k in ('ab','cd','pq','xy')): return False for i,k in enumerate(word[:-1]): if word[i] == word[i+1]: return True return False def is_nice_v2(word): for i,k in enumerate(word[:-2]): if word[i] == word[i+2]: break else: return False for i,k in enumerate(word[:-1]): if word[i:i+2] in word[:i] or word[i:i+2] in word[i+2:]: break else: return False return True if __name__ == "__main__": inps = open('day05.inp').read() print(day05(inps)) print(day05(inps, part2=True))
061a3ec0534e3b8bf24352f61201d927574987a3
AnonymnyNikto/PythonProgramovanie
/Edupage/Mocnina.py
159
3.734375
4
cislo = input("Zadajte cislo: ") cislo = int(cislo) tri = cislo ** 3 sest = cislo ** 6 print("Tretia mocnina je ", tri, " a siesta mocnina je", sest)
fd90f1e4accd0f7289e2aef66cdc942cc7d1a439
evandrofranco/curso_python
/8_desafio_5_fatorial.py
121
3.890625
4
 valor = int(input("Digite o valor de n: ")) aux = 1 while (valor > 1): aux *= valor valor -= 1 print(aux)
732672dc221400fad4e444cb77a22c64bd4e7636
PacktPublishing/Mastering-Python-Scripting-for-System-Administrators-
/Chapter03/if_example.py
150
4.15625
4
def check_if(): a = int(input("Enter a number \n")) if (a == 100): print("a is equal to 100") else: print("a is not equal to 100") return a
bf837a6be53dd91bfe837f5e45e3afa4371e42ae
fstahlberg/ucam-scripts
/gnmt/align2csv.py
876
3.59375
4
''' This script converts a line from an alignment file to a csv file ''' import argparse import operator import sys parser = argparse.ArgumentParser(description='Converts a single line of a alignment ' 'text file to csv format.') args = parser.parse_args() weights = {} max_src = 0 max_trg = 0 for pair in ' '.join(sys.stdin.readlines()).split(): if ":" in pair: tmp,weight = pair.split(":") else: tmp = pair weight = "1.0" s,t = tmp.split("-") src_pos = int(s) trg_pos = int(t) max_src = max(max_src, src_pos) max_trg = max(max_trg, trg_pos) if not src_pos in weights: weights[src_pos] = {} weights[src_pos][trg_pos] = weight for src_pos in range(max_src+1): line = weights.get(src_pos, {}) print(' '.join([line.get(trg_pos, "0.0") for trg_pos in xrange(max_trg+1)]))
7e2b2e3b7464bfa2cec6b7844e06d6a8010d7f7f
Yiming-Gao/UIUC-Fall-2017
/CS_446/Homework/HW3/hw3_p2_sol.py
3,593
3.765625
4
import numpy as np import matplotlib.pyplot as plt def rbf_kernel(x1, x2, gamma=100): """ RBF Kernel :type x1: 1D numpy array of features :type x2: 1D numpy array of features :type gamma: float bandwidth :rtype: float """ # Student implementation here diff = x1 - x2 return np.exp(-gamma*np.sum(np.dot(diff, diff))) def w_dot_x(x, x_list, y_list, alpha, kernel_func=rbf_kernel): """ Calculates wx using the training data :type x: 1D numpy array of features :type x_list: 2D numpy array of training features :type y_list: 1D numpy array of training labels where len(x) == len(y) :type alpha: 1D numpy array of int counts :type kernel_func: function that takes in 2 vectors and returns a float :rtype: float representing wx """ # Student implementation here norm_const = max(1, np.sum(alpha)) return np.sum(np.fromiter((y_list[i] * alpha[i] * kernel_func(xi, x) for (i, xi) in enumerate(x_list) if alpha[i] > 0), dtype=float))/(norm_const) def predict(x, x_list, y_list, alpha): """ Predicts the label {-1,1} for a given x :type x_list: 2D numpy array of training features :type y_list: 1D numpy array of training labels where len(x) == len(y) :rtype: Integer in {-1,1} """ wx = w_dot_x(x, x_list, y_list, alpha) return np.sign(wx) def pegasos_train(x_list, y_list, tol=0.01): """ Trains a predictor using the Kernel Pegasos Algorithm :type x_list: 2D numpy array of training features :type y_list: 1D numpy array of training labels where len(x) == len(y) :rtype: 1D numpy array of int counts """ # Alpha counts the number of times the traning example has been selected alpha = np.zeros(len(x_list), dtype=int) for t in range(num_samples_to_train): # Student implementation here rand_i = np.random.randint(len(x_list)) dist = y_list[rand_i]*(w_dot_x(x_list[rand_i], x_list, y_list, alpha)) if dist < tol: alpha[rand_i] += 1 return alpha def accuracy(x_list, y_list, alpha, x_test, y_test): """ Calculates the proportion of correctly predicted results to the total :type x_list: 2D numpy array of training features :type y_list: 1D numpy array of training labels where len(x) == len(y) :type alpha: 1D numpy array of int counts :type x_test: 2D numpy array of test features :type y_test: 1D numpy array of test labels where len(x) == len(y) :rtype: float as a proportion of correct labels to the total """ prediction = np.fromiter((predict(xi, x_list, y_list, alpha) for xi in x_test), x_test.dtype) return float(np.sum(np.equal(prediction, y_test)))/len(y_test) # Student implementation here final_alpha = pegasos_train(x_train, y_train) print(np.sum(final_alpha)) print(accuracy(x_train, y_train, final_alpha, x_test, y_test)) # Plot Countour res = 8 xplot = np.linspace(min(x_train[:, 0]), max(x_train[:, 0]), res) yplot = np.linspace(min(x_train[:, 1]), max(x_train[:, 1]), res) xx,yy = np.meshgrid(xplot, yplot) xy = np.array([[x,y] for x in xplot for y in yplot]) prediction = np.fromiter((predict(xi, x_train, y_train, final_alpha) for xi in xy), x_test.dtype).reshape((res,res)).T plt.contourf(xx,yy,prediction) # Plot data pos_x = np.array([x for i, x in enumerate(x_train) if y_train[i] == 1]) neg_x = np.array([x for i, x in enumerate(x_train) if y_train[i] == -1]) plt.scatter(pos_x[:, 0], pos_x[:, 1], label="+1") plt.scatter(neg_x[:, 0], neg_x[:, 1], label="-1") plt.xlabel("x") plt.ylabel("y") plt.legend() plt.show()
c48949bf4bcf79b5d7fe97f83dd5e573696c60c9
Zahidsqldba07/Python2020
/covid_3.py
550
3.671875
4
#!/bin/python3 class Code(): x = [1, 2, 3, 4, 5] def __init__(self, unicode, task=None): self.unicode = unicode self.task = task def main(self): try: press = int(input("Enter the unicode value [1, 2, 3, 4, 5] :- ")) x = [1, 2, 3, 4, 5] if press in x: return "Your code is right." elif press > 5: return "Enter digit between 1 to 5." else: return "Kindly follow procedures." except Exception as err: return "Enter only digit b/w 1 to 5." if __name__ == "__main__": y = Code("one") z = y.main() print(z)
dedcebab66c1aae3f28007a1a5e5c8fd27da2a44
JokerToMe/PythonProject
/shine/object/demo3.py
645
4.15625
4
# 析构函数:__del()__释放对象时自动调用 class Person(object): def __init__(self,name,age): self.name = name self.age = age def say(self): print('My name is %s,%d years old' % (self.name,self.age)) print(self.__class__) # 在内部创建对象 def createInstance(self): p = self.__class__('inner',0) def __del__(self): print('我是析构函数') p = Person('Shine',18) p.say() # 手动释放对象 del p # 访问p的属性时会报错 # p1 = Person('Nick',18) # p1.say() def func(): p = Person('func',1) print('函数结束时释放对象') func()
afb637fbeca1ec1726c3bfa6bdef6196b604895a
ManasaPola/Coding-Exercise
/Bigram.py
574
3.671875
4
'''Leetcode Contest''' def main(): text = "alice is a good girl she is a good student" first = "a" second = "good" text1 = "we will we will rock you" first1 = "we" second1 = "will" ans = findOccurences(text1, first1, second1) print(ans) def findOccurences(text, first, second): if len(text) == 0: return [] words = text.split(" ") ans = [] for i in range(0, len(words)-2): if words[i] == first and words[i+1] == second: ans.append(words[i+2]) return ans if __name__ == "__main__": main()
194fff3d21a4e6a97da82301943a61303f699178
cosmos-sajal/python_design_patterns
/behavioural/strategy_pattern.py
1,470
4.15625
4
## refernces - https://www.youtube.com/watch?v=MOEsKHqLiBM from abc import ABCMeta, abstractmethod class Movement(metaclass=ABCMeta): @abstractmethod def move(self): pass class Fly(Movement): def move(self): print("I will fly") class Walk(Movement): def move(self): print("I will walk") class Swim(Movement): def move(self): print("I will swim") class Animal(): def __init__(self, name): self.name = name self.movement = "" def get_movement(self): self.movement.move() def set_movement(self, movement): self.movement = movement @abstractmethod def make_sound(self): pass class Dog(Animal): def __init__(self, name): super().__init__(name) def make_sound(self): print("Bhow") class Fish(Animal): def __init__(self, name): super().__init__(name) def make_sound(self): print("no sound") class Eagle(Animal): def __init__(self, name): super().__init__(name) def make_sound(self): print("chi chi") animal_type = int(input( "What kind of animal are you? \n 1. Dog 2. Fish 3. Eagle? ")) if animal_type == 1: animal = Dog("Buzo") animal.set_movement(Walk()) elif animal_type == 2: animal = Fish("fish_name") animal.set_movement(Swim()) else: animal = Eagle("Eagle Name") animal.set_movement(Fly()) animal.get_movement() animal.make_sound()
e9c6dcaf585d7bcc595d08efe42a31657f8e1afe
zyzmoz/python-course
/classes.py
603
3.734375
4
class Dog(): # Class Object Attribute species = "Mammal" def __init__(self, breed, name): self.breed = breed self.name = name # pass mydog = Dog("Pug", "No One") print(mydog.breed) print(mydog.name) print(mydog.species) # mydog.species = "Troll" # print(mydog.species) class Circle(): pi = 3.14 def __init__(self, radius = 1): self.radius = radius def area(self): return self.radius * self.radius * Circle.pi def set_radius(self, radius): self.radius = radius my_circle = Circle(3) my_circle.set_radius(999) print(my_circle.area())
0e9c9ebcc126f1d7c99a8d024ae53d0d78db44b9
vladimir4919/nu8
/bank_account.py
4,601
3.8125
4
""" Программа "Банковский счет" Работа программы: Запускаем программу.На счету -0 Программа предлагает: 1. пополнить счет 2. оплатить покупку 3. вывести историю покупок 4. выход Добавлено сохранение суммы счета в файл. При первом открытии программы на счету 0 После того как мы воспользовались программой и вышли сохраняется история покупок При следующем открытии программы прочитать сумму счета, которую сохранили """ import pickle import os def input_amount(): # функция ввода суммы """ ОБРАБОТКА ИСКЛЮЧЕНИЙ """ try: amount = float(input('Введите сумму:')) except: print('Сумма должна быть числом!') amount = 0 else: if amount < 0: print('Отрицательные суммы не используются!') """ ТЕРНАРНЫЙ ОПЕРАТОР """ amount = amount if amount >= 0 else 0 FILE_NAME = 'history.data' FILE_NAME1= 'account.data' history = [] if os.path.exists(FILE_NAME): with open(FILE_NAME, 'rb') as f: history = pickle.load(f) def replenish_balance(account, history):#Функция пополнения баланса try: replenish_sum = float(input("\nВводим сумму пополнения счета: ")) except: print('Сумма должна быть числом!') replenish_sum = 0 else: if replenish_sum < 0: print('Отрицательные суммы не используются!') """ ТЕРНАРНЫЙ ОПЕРАТОР """ replenish_sum = replenish_sum if replenish_sum >= 0 else 0 return account + replenish_sum, history print(account) def purchase(account,history): #Функция покупки """ ОБРАБОТКА ИСКЛЮЧЕНИЙ """ try: purchase_sum = float(input("\nВводим сумму покупки: ")) except: print('Сумма должна быть числом!') purchase_sum = 0 else: if purchase_sum < 0: print('Отрицательные суммы не используются!') """ ТЕРНАРНЫЙ ОПЕРАТОР """ purchase_sum = purchase_sum if purchase_sum >= 0 else 0 if account - purchase_sum >= 0: purchase_name = input("Вводим название покупки:") if os.path.exists(FILE_NAME): with open(FILE_NAME, 'rb') as f: history = pickle.load(f) history.append(f"Покупка \"{purchase_name}\" на сумму {purchase_sum}") print(f" На счету осталось {account-purchase_sum}") else: print("На счету недостаточно средств") return account, history return account-purchase_sum, history def print_history(history): #Печать истории изменений баланса счета for elem_history in history: print(elem_history) return def bank_account_run(account,history): while True: print('1. пополнение счета') print('2. покупка') print('3. история покупок') print('4. выход') choice = input('Выберите пункт меню:') if choice == '1': account, history = replenish_balance(account, history) print('Состояние счета:', account) elif choice == '2': account, history = purchase(account, history) elif choice == '3': print_history(history) elif choice == '4': if os.path.exists(FILE_NAME1): with open(FILE_NAME1, 'wb') as f: pickle.dump(account, f) if os.path.exists(FILE_NAME): with open(FILE_NAME, 'wb') as f: pickle.dump(history, f) break #if '_name_' == "_main_": account = 0 history = [] bank_account_run(account,history)
43331eb9b79bdf95fd59a81d6b0df758198942b1
ttafsir/100-days-of-code
/code/day21/event.py
1,386
3.828125
4
""" Bert is in charge of organizing an event and got the attendees names, locations and confirmations in 3 lists. Assuming he got all data and being Pythonic he used zip to stitch them together (see template code) but then he sees the output: ('Tim', 'DE', False) ('Bob', 'ES', True) ('Julian', 'AUS', True) ('Carmen', 'NL', False) ('Sofia', 'BR', True) What?! Mike, Kim, and Andre are missing! You heard somebody mention itertools the other day for its power to work with iterators. Maybe it has a convenient way to solve this problem? Check out the module and patch the get_attendees function for Bert so it returns all names again. For missing data use dashes (-). After the fix Bert should see this output: ('Tim', 'DE', False) ('Bob', 'ES', True) ('Julian', 'AUS', True) ('Carmen', 'NL', False) ('Sofia', 'BR', True) ('Mike', 'US', '-') ('Kim', '-', '-') ('Andre', '-', '-') Good luck, Bert will be grateful if you fix this bug for him! By the way, this won't be the last itertools Bite, it is a power tool you want to become familiar with! """ import itertools names = 'Tim Bob Julian Carmen Sofia Mike Kim Andre'.split() locations = 'DE ES AUS NL BR US'.split() confirmed = [False, True, True, False, True] def get_attendees(): for participant in itertools.zip_longest(names, locations, confirmed, fillvalue="-"): print(participant) if __name__ == '__main__': get_attendees()
e40bf8ee37fc3ba8e23642cf9aaf35bc18208846
blanksblanks/Python-Fun
/46-Simple-Ex/ex15.py
475
4.40625
4
from ex13 import max_in_list from ex14 import list_convert def find_longest_word(alist): ''' (list) -> str -> int Defines a function find_longest_word() that takes a list of words and returns the length of the longest one. ''' alist = list_convert(alist) alist = max_in_list(alist) return alist ourzoo = ['cat','snake','lizard','fish','frog', 'dragon', 'gecko'] print 'List of words : ' + str(ourzoo) print 'Longest word length : ' + str(find_longest_word(ourzoo))
92fe4ce79ae9bfb20802452bd33c8b1672ee9720
googlelxhgithub/testgit
/pan7.py
729
3.890625
4
# 最小公倍数是小学五年级的数学课程内容,小学生完成最小公倍数的学习后就可以升学到初中了。 # 如何用程序求出任意两个数的最小公倍数? a = int(input("first: ")) b = int(input("second: ")) # 方法一:先算出最大公约数,在算最小公倍数 # 取最小的那个数 # d = min(a, b) # for i in range(1, d+1): # if a % i == 0 and b % i == 0: # c = i # print(f"{a} and {b} number1 is {c}") # print(f"{a} and {b} number2 is {int(a*b/c)}") # 方法二:遍历,找出能同时被两个数整除的数 c = max(a, b) while True: if c%a == 0 and c%b == 0: break else: c = c + 1 print(f"{a} and {b} number2 is {int(c)}")
139f7a86d16c559b8ec5882594b47a71c33fd405
martin-martin/python-crashcourse
/02_21_thu/string_methods.py
348
4.03125
4
my_string = " hELLo there " # # # lowercase # print(my_string.lower()) # # # uppercase # print(my_string.upper()) # # # # title-case # print(my_string.title()) # # capitalize # print("cap") # print(my_string.capitalize()) # split print(my_string.strip(' h').lower()) # print(my_string.lstrip()) # print(my_string.rstrip()) # # my_string.strip
61d68dfc290133a6ecc916ad3a9aa1044e07d5df
meteozcan06/python
/fonksiyon.py
912
3.578125
4
#dortgen_alan_hesapla_v1 def dikdortgenAlan(genislik, yukseklik): alan = float(genislik) * float(yukseklik) print("Alan :", alan) return alan gen = input("Genişlik : ") yuk = input("Yükseklik : ") dikdortgenAlan(gen, yuk) #daire_alan_hesapla_v1 def daireAlan(yaricap): alan = float(yaricap) * float(yaricap) * 3.14 print("Alan :", alan) return alan r = input("Yarıçapı Gir : ") daireAlan(r) #dortgen_alanı_hesapla_v2 def dikdortgenAlan(genislik, yukseklik): alan = float(genislik) **2 * float(yukseklik) **2 print("Alan :", alan) return alan gen = input("Genişlik :") yuk = input("Yükseklik :") dikdortgenAlan(gen, yuk) #daire_alanı_hesapla_v2 def daireAlan(yaricap): alan = (float(yaricap) * float(yaricap)) **2 * 3.14 print("Alan :", alan) return alan r = input("Yarıçapı Gir : ") daireAlan(r)
279fb47627241a877bac389f22ebc4768846eac1
824zzy/Leetcode
/N_Queue/MonotonicQueue/L1_239_Sliding_Window_Maximum.py
920
3.546875
4
""" https://leetcode.com/problems/sliding-window-maximum/ define a monotonic queue state as (idx, val) and we want to ensure 1. current index is within the window size 2. val is in descending order """ from header import * # heap implementation class Solution: def maxSlidingWindow(self, A: List[int], k: int) -> List[int]: pq = [] ans = [] for i in range(len(A)): while pq and i-pq[0][1]>=k: heappop(pq) heappush(pq, (-A[i], i)) if i>=k-1: ans.append(-pq[0][0]) return ans # deque implementation class Solution: def maxSlidingWindow(self, A: List[int], k: int) -> List[int]: dq = deque() ans = [] for i, x in enumerate(A): while dq and dq[0][0]<=i-k: dq.popleft() while dq and dq[-1][1]<=x: dq.pop() dq.append((i, x)) if i>=k-1: ans.append(dq[0][1]) return ans
d7671875f0293be608d20f559643718fb08cd90d
ovifrisch/Python-Data-Structures
/lists/stack.py
863
3.875
4
class Stack: class Node: def __init__(self, val, next): self.val = val self.next = next def __iadd__(self, i): curr = self while (i > 0): i -= 1 curr = curr.next return curr def __init__(self): self.size = 0 self.head = None def push(self, val): self.head = self.Node(val, self.head) self.size += 1 def pop(self): if (len(self) <= 0): raise Exception("Cannot pop from empty stack") val = self.head.val self.head += 1 self.size -= 1 return val def __len__(self): return self.size def __repr__(self): res = "[" curr = self.head while (curr): res += str(curr.val) + ", " curr += 1 if (len(res) > 1): res = res[:-2] return res + "]" if __name__ == "__main__": stack = Stack() for i in range(10): stack.push(i) print(stack) for i in range(10): stack.pop() print(stack)
1f2b70fac927a8f1a86a47178e6d47f1c70af49b
YaraDeOliveira/CursoemVideo
/ex065.py
466
3.890625
4
n = 'S' x = soma = maior = menor = z = 0 while n in 'Ss': x = int(input('Digite um numero:')) soma += x z += 1 if z == 1: menor = maior = x if x > maior: maior = x if x < menor: menor = x n = str(input('Quer continuar [S/N]')).upper().strip() print('Foram digitados {} numeros' '\na media entre eles eh {:.2f}' '\no maior numero eh {}' '\no menor numero eh {}'.format(z, soma/z, maior, menor))
2825fd6c3ce67deee019741661c8c20013c87f99
jeromehayesjr/University
/512/test.py
184
3.796875
4
def even_nums(lst): # return [x for x in lst if x % 2 == 0] evens = [] for x in lst: if type(x) == int and x % 2 == 0: evens.append(x) return evens
ab5b4ba85b5db3bbbd9dbf1f1fd0faf98096bf4f
suomela/recoloring
/check-tiles.py
2,283
3.578125
4
#!/usr/bin/env python3 import itertools colours = [1, 2, 3, 4] def good_tile(x): a,b,c,\ d,e,f,\ g,h,i = x return a != b != c and \ d != e != f and \ g != h != i and \ a != d != g and \ b != e != h and \ c != f != i def parts(x): a,b,c,\ d,e,f,\ g,h,i = x return [ (a,b, d,e), (b,c, e,f), (d,e, g,h), (e,f, h,i) ] def type(x): if x in [ (1,3,3,2), (2,3,3,1), ]: return "A" elif x in [ (1,3,4,2), (2,1,1,4), (2,1,3,4), (2,3,1,4), (2,3,3,4), (2,3,4,1), (3,1,1,4), (3,2,1,4), (4,1,1,2), (4,1,1,3), (4,1,3,2), (4,2,1,3), (4,3,1,2), (4,3,3,2), ]: return "B" else: return "-" def main(): tiles = 0 pairs = 0 for x in itertools.product(colours, repeat=9): if not good_tile(x): continue tiles += 1 a,b,c,\ d,e,f,\ g,h,i = x for E in colours: y = a,b,c,\ d,E,f,\ g,h,i if x >= y: continue if not good_tile(y): continue pairs += 1 tx = [ type(p) for p in parts(x) ] ty = [ type(p) for p in parts(y) ] p = """ {a} {b} {c} {a} {b} {c} | {x1} {x2} {y1} {y2} {d} {e} {f} -> {d} {E} {f} | {sp} {sp} -> {sp} {sp} {g} {h} {i} {g} {h} {i} | {x3} {x4} {y3} {y4}""" print(p.format( sp=" ", a=a, b=b, c=c, d=d, e=e, E=E, f=f, g=g, h=h, i=i, x1=tx[0], x2=tx[1], x3=tx[2], x4=tx[3], y1=ty[0], y2=ty[1], y3=ty[2], y4=ty[3], )) xa = len([t for t in tx if t == 'A']) xb = len([t for t in tx if t == 'B']) ya = len([t for t in ty if t == 'A']) yb = len([t for t in ty if t == 'B']) da = ya - xa db = yb - xb ea = da % 2 == 0 eb = db % 2 == 0 assert ea == eb print("\nChecked {} tiles, {} pairs.\n".format(tiles, pairs)) main()
e56a702080c5bd6c9c174dcd287517576252d7b9
samims/nptel_python
/week_2/slice.py
179
4.15625
4
a = " hello" print(a[:]) #will print whole string print(a[:3]) #will print upto 3rd index a = a[0:3] +"p!" #creating a new value not modifying it, strings are immutable print(a)
07921bd311c8352637e31e346e5757f655a424f5
mmann964/exercises
/Exercise18.py
1,936
3.78125
4
#!/usr/bin/python import random def generate_number(): #num_str = "" c = range(0, 10) n = random.sample(c, 4) # a list of 4 unique numbers between 0 and 9 return n def get_user_number(): # get a four digit number from the user. # check that it's 4 digits -- length + 0-9 # give them a chance to exit # return number as a string? list of numbers? print "Please guess a 4 digit number. Type bail if you've had enough." while True: res = raw_input(">>>>> ").lower().strip() if res == "bail": print "Thanks for playing! " exit() elif res.isdigit(): if len(res) == 4: num_list = [] for i in res: num_list.append(int(i)) return num_list else: print "Enter 4 digits." else: print "That's not a number!" def eval_nums(tnum, unum): # if a digit in unum is in the same place as in tnum, they get a cow # if a digit in unum is in tnum, they get a bull # return a list: [ cows, bulls ] cows = 0 bulls = 0 for i in range(0, len(unum)): if unum[i] == tnum[i]: cows += 1 elif unum[i] in tnum: bulls += 1 return [ cows, bulls ] def print_results(ans, guess_count): # ans is a list: [ cows, bulls ] # print how many cows and bulls they have # if cows = 4, you're done! print the number of guesses and exit print "{} cows, {} bulls.".format(ans[0], ans[1]) print "" if ans[0] == 4: print "Congratulations! It took you {} guesses." .format(guess_count) exit() if __name__ == "__main__": the_num = generate_number() print the_num guesses = 0 while True: user_num = get_user_number() guesses += 1 answer = eval_nums(the_num, user_num) print_results(answer, guesses)
5fd940cb3e0df6c0d9424f6dde21a5ce41dcc0f3
hguochen/code
/python/questions/ctci/linked_lists/return_kth_to_last.py
2,735
3.984375
4
""" CtCi 2.2 Implement an algorithm to find the kth to last element of a singly linked list. 0 to last -> last element 1 to last -> last second element 2 to last -> last third element """ def kth_to_last(head, k): """ Time: O(n) Space: O(1) where n is the size of the linked list. Make a first pass of the list to count the length. length - k = number of times to traverse to """ if not head: return curr = head last_index = -1 while curr is not None: last_index += 1 curr = curr.next run_times = last_index - k result = head for i in xrange(0,run_times): result = result.next return result.value """ Singly linked list implementation. """ class Node(object): """docstring for Node""" def __init__(self, value, next=None): self.value = value self.next = next class LinkedList(object): """docstring for LinkedList""" def __init__(self, value): self.head = Node(value) def insert_front(self, value): """ Insert node at front of the list """ node = Node(value) node.next = self.head self.head = node return def insert_back(self, value): """ Insert node at back of the list """ curr = self.head while curr.next is not None: curr = curr.next node = Node(value) curr.next = node return def delete(self, value): """ Delete the node which contains the value """ prev = None curr = self.head while curr is not None: if curr.value == value: if prev is None: self.head = self.head.next return prev.next = curr.next del curr break prev = curr curr = curr.next return def get_head(self): return self.head def print_list(self): curr = self.head while curr is not None: print curr.value, curr = curr.next print "" return def find(self, value): curr = self.head while curr is not None: if curr.value == value: return curr curr = curr.next return False if __name__ == '__main__': l_list = LinkedList(1) l_list.insert_back(5) l_list.insert_back(2) l_list.insert_back(4) l_list.insert_back(3) head = l_list.get_head() print kth_to_last(head, 0) # 3 print kth_to_last(head, 1) # 4 print kth_to_last(head, 2) # 2 print kth_to_last(head, 3) # 5 print kth_to_last(head, 4) # 1
dd80aefccbd3840a45ebd62cefc90762106f5f6e
Ljfernando/MovieRecommendation
/MovieRecommendation.py
14,147
4.46875
4
__author__ = 'lancefernando' """This Movie Recommendation program utilizes collaborative filtering to recommend movies the user may enjoy. Data used is original data from MovieLens. It will ask a user to rate 50 random movies on a scale from 0 to 5 where the 0 value means that the user has not seen the movie. The ratings are stored as a vector. This vector is then compared to other user ratings using three different similarity measurements: Cosine similarity, Jaccard similarity and Pearson Correlation Coefficient. The 5 most similar user vectors are then utilized to recommend up to five different movies which are outputted to the console and as a text file. Movies that are recommended must have be rated a 5 by the recorded similar user. """ import random import math """Function reads movie titles from a given movie file and adds each movie title to a list. List of movie titles is then returned.""" def readMovies(filename): moviefile = open(filename, 'r') movieList = [] #creating empty movie list for line in moviefile: line = line.split('|') #using '|' as delimiter to split movieList.append(line[1]) moviefile.close() return movieList """Function uses given list and asks user to rate each movie in list. Each rating is then written to the given filename.""" def profilemaker(filename, movieList): ratingArray = ['0'] * len(movieList) #number of movies randomMovies = random.sample(range(len(movieList)), 50) #Grabbing 50 random movies from list ratingString = '' print("Please create your profile by rating the following movies from 0 to 5 (1 being horrible, 5 being amazing and 0 if not watched):\n") for movie in randomMovies: print(movieList[movie]) rating = raw_input("Enter your rating: ") while(not(rating.isdigit()) or int(rating) not in range(0,6)): rating = raw_input("Please enter a valid rating: ") ratingArray[movie] = str(rating) #ratingString += str(rating) + ' ' print(' ') for each in ratingArray: ratingString += each + ' ' f = open(filename, 'w') f.write(ratingString) f.close() """Function will read given rating profile and returns list of ratings""" def readProfile(filename): f = open(filename, 'r') lines = f.readlines() ratings = lines[0] ratings = ratings.strip(' ') ratings = ratings.split(' ') for i in range(0, len(ratings)): ratings[i] = int(ratings[i]) f.close() return ratings """Function creates a dictionary using given file. Each key is the user and the value is a list of with the movies rated at index 0 and a list of ratings at index 1. This dictionary is then returned.""" def movieRatings(filename): ratingDict ={} ratings = open(filename, 'r') for line in ratings: line = line.strip('\n') line = line.split('\t') if line[0] in ratingDict: #enters this statement if the user has rated #multiple movies templist = [] for x in range(0, len(ratingDict[line[0]])): #loops for the length of the user's rating list templist.append(ratingDict[line[0]][x]) #adds each rating to the temporary list templist.append([int(line[1]), int(line[2])]) #enters the newest rating to temporary list ratingDict[line[0]] = templist #setting the value of the user in dictionary to full rating list else: ratingDict[line[0]] = [[int(line[1]), int(line[2])]] #If user is not in dictionary yet, this will add user #and the user's rating ratings.close() return ratingDict """Takes a vector of ratings (user1) and a list of lists with movie IDs and their respective ratings as user2 and returns the cosine similarity between users.""" def computeCosSim(user1, user2): dotProd = 0 user2Prod = 0 user1Prod = 0 # Computing the dot product between user1 and user2 ratings for i in range(len(user2)): movieID = user2[i][0] rating = user2[i][1] dotProd += rating * user1[movieID - 1] user2Prod += rating **2 #computing the user2 dot product of itself # Computing the user1 dot product of itself for i in range(len(user1)): user1Prod += user1[i] **2 return float(dotProd)/(math.sqrt(float(user1Prod))*math.sqrt(float(user2Prod))) """Takes a vector of ratings (user1) and a list of lists with movie IDs and their respective ratings as user2 returns the jaccard similarity between users.""" def computeJacSim(user1, user2): intersection = 0 union = len(user1) # this is true since len(user1) is the whole sample size of the movie list for i in range(len(user2)): movieID = user2[i][0] rating = user2[i][1] # Values count as intersection when both users rate the same movie as a 3 or greater if user1[movieID - 1] >= 3 and rating >=3: intersection += 1 return float(intersection)/float(union) """Takes a vector of ratings (user1) and a list of lists with movie IDs and their respective ratings as user2 returns the Pearson Correlation Coefficient between users. Calls computeMean in order to """ def computePccSim(user1, user2, user1Mean): dotProd = 0 user2Prod = 0 user1Prod = 0 user2Mean = 0 # Computing the mean of user2s ratings for i in range(len(user2)): rating = user2[i][1] user2Mean += rating user2Mean = float(user2Mean)/float(len(user2)) # Computing the dot product between user1 and user2 ratings for i in range(len(user2)): movieID = user2[i][0] rating = float(user2[i][1]) dotProd += float((rating - user2Mean) * (float(user1[movieID - 1]) - user1Mean)) user2Prod += float((rating - user2Mean) **2) #computing the user2 dot product of itself # Computing the user1 dot product of itself for i in range(len(user1)): user1Prod += float((float(user1[i]) - user1Mean) **2) return float(dotProd)/(math.sqrt(float(user1Prod))*math.sqrt(float(user2Prod))) """Computes the mean of a given vector of ratings and returns this value""" def computeMean(user1): mean = 0 for i in range(len(user1)): mean += user1[i] return(float(mean)/float(len(user1))) """Calls all previous functions and determine movies that the user should watch by comparing their ratings to the ratings of other users. Movies that are recommended must have a rating of 5 by the similar users.""" def computeRecommendation(ratingFile, moviesFile, userFile, recCosFile, recJacFile, recPccFile): ratingDict = movieRatings(ratingFile) movieList = readMovies(moviesFile) profilemaker(userFile, movieList) userRatings = readProfile(userFile) cosFile = open(recCosFile, 'w') jacFile = open(recJacFile, 'w') pccFile = open(recPccFile,'w') #creating empty lists for top 5 compatible users top5ListCos = [] top5ListJac = [] top5ListPcc = [] #creating empty recommended movie lists recommendListCos = [] recommendListJac = [] recommendListPcc = [] #computing mean of client ratings to use for PCC userMean = computeMean(userRatings) #computing cosine and jaccard similarity values between the client and other users' movie ratings for user in ratingDict.keys(): otherUsers = ratingDict[user] cosSim = computeCosSim(userRatings, otherUsers) jacSim = computeJacSim(userRatings, otherUsers) pccSim = computePccSim(userRatings, otherUsers, userMean) top5ListCos.append([cosSim, user]) top5ListJac.append([jacSim, user]) top5ListPcc.append([pccSim, user]) #sorting list in descending order to grab the users that are most similar to the client top5ListCos = sorted(top5ListCos, reverse = True) top5ListJac = sorted(top5ListJac, reverse = True) top5ListPcc = sorted(top5ListPcc, reverse = True) top5ListCos = top5ListCos[0:5] top5ListJac = top5ListJac[0:5] top5ListPcc = top5ListPcc[0:5] #Creating a list of recommended movies from the most similar users based on cosine similarity for sim in range(0, 5): key = top5ListCos[sim][1] movies = ratingDict[key] counter = 1 for i in range(0, len(movies)): if counter <= 5: #allows each user to recommend no more than 5 movies if movies[i][1] == 5 and userRatings[movies[i][0]] == 0: #if the user rated the movie 5 and I have not watched the movie yet movieID = movies[i][0] if movieList[movieID] not in recommendListCos: #If movie title is not in list recommendListCos.append(movieList[movieID]) counter += 1 else: break #Creating a list of recommended movies from the most similar users based on jaccard similarity for sim in range(0, 5): key = top5ListJac[sim][1] movies = ratingDict[key] counter = 1 for i in range(0, len(movies)): if counter <= 5: #allows each user to recommend no more than 5 movies if movies[i][1] == 5 and userRatings[movies[i][0]] == 0: #if the user rated the movie 5 and I have not watched the movie yet movieID = movies[i][0] if movieList[movieID] not in recommendListJac: #If movie title is not in list recommendListJac.append(movieList[movieID]) counter += 1 else: break #Creating a list of recommended movies from the most similar users based on PCC for sim in range(0, 5): key = top5ListPcc[sim][1] movies = ratingDict[key] counter = 1 for i in range(0, len(movies)): if counter <= 5: #allows each user to recommend no more than 5 movies if movies[i][1] == 5 and userRatings[movies[i][0]] == 0: #if the user rated the movie 5 and I have not watched the movie yet movieID = movies[i][0] if movieList[movieID] not in recommendListPcc: #If movie title is not in list recommendListPcc.append(movieList[movieID]) counter += 1 else: break #writing recommended lists to given files for i in range(0, len(recommendListCos)): cosFile.write(recommendListCos[i] + '\n') cosFile.close() for i in range(0, len(recommendListJac)): jacFile.write(recommendListJac[i] + '\n') jacFile.close() for i in range(0, len(recommendListPcc)): pccFile.write(recommendListPcc[i] + '\n') pccFile.close() """Prints movies line by line from a given file to the console.""" def printMoviesFromFile(filename): file = open(filename, 'r') for line in file: print(line) file.close() """Calls printMoviesFromFile() function to print a list of movies based on the similarity metric the client chooses.""" def printRecommendedMovies(file1, file2, file3): print("Based on your ratings and others that have rated similarly we have created three lists of movies in no particular order for you to watch.") print("The three lists of recommendations were computed based on three different similarity metrics. \n") print("Enter C to view movies based on the Cosine-Similarity metric.") print("Enter J to view movies based on the Jaccard-Similarity metric.") simType = raw_input("Enter P to view movies based on the Pearson Correlation Coefficient metric.\n").lower().strip() while simType != "q": if simType == "c": print("Here are your recommendations based on Cosine similarity. \n") printMoviesFromFile(file1) print("Would you also like to view recommended movies based on the other similarity metrics?") print("Enter J to view movies based on the Jaccard-Similarity metric.") print("Enter P to view movies based on the Pearson Corellation Coefficient metric.") simType = raw_input("Enter Q to quit.\n").lower().strip() elif simType == "j": print("Here are your recommendations based on Jaccard similarity. \n") printMoviesFromFile(file2) print("Would you also like to view recommended movies based on the other similarity metrics?") print("Enter C to view movies based on the Cosine-Similarity metric.") print("Enter P to view movies based on the Pearson Corellation Coefficient metric.") simType = raw_input("Enter Q to quit.\n").lower().strip() elif simType == "p": print("Here are your recommendations based on the Pearson Correlation Coefficient.\n") printMoviesFromFile(file3) print("Would you also like to view recommended movies based on the other similarity metrics?") print("Enter C to view movies based on the Cosine-Similarity metric.") print("Enter J to view movies based on the Jaccard-Similarity metric.") simType = raw_input("Enter Q to quit.\n").lower().strip() else: print("Not a valid entry.") print("Enter C to view movies based on the Cosine-Similarity metric.") print("Enter J to view movies based on the Jaccard-Similarity metric.") print("Enter P to view movies based on the Pearson Correlation Coefficient metric.") simType = raw_input("Enter Q to quit.\n").lower().strip() print("Thank you and enjoy!") def main(): computeRecommendation('movieRatings.txt', 'movies.txt', 'profile.txt', 'cosRecommendedMovies.txt', 'jacRecommendedMovies.txt', 'pccRecommendedMovies.txt') printRecommendedMovies('cosRecommendedMovies.txt', 'jacRecommendedMovies.txt', 'pccRecommendedMovies.txt') main()
c2a06c744c6fcbad972670100e8aebfb1837a78b
furkan-kanuga/Multithreaded_Chat_Python
/server_ipv6.py
3,004
3.953125
4
# Chat server where multiple clients can connect to the server. #The server reads the message sent by each lient and broadcasts it to all other connected clients. import socket import select #list of socket descriptors (readable client connections) #Socket descriptors are like file descriptors, in this case used for reading some text which the client sends SOCKET_DESC = [] #Buffer in which messages received from clients are stored RECV_BUFFER = 4096 #port on which chat server will listening PORT = 5000 #creating an INET Stream socket. #Stream sockets transmit data reliably, in order and woth out of band capabilities. serversocket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) # Binds the socket to a host and a port and then listens for incoming connections serversocket.bind(("::", PORT)) serversocket.listen(10) # Add server socket to list of socket descriptors SOCKET_DESC.append(serversocket) print "Chat server running on port " + str(PORT) # function for broadcasting a client's message to all other clients connected to the server def clientbroadcast (sock, message): for socket in SOCKET_DESC: #if the socket is not the client's socket itself or it is not the server's socket, message will be broadcast if socket is not sock and socket is not serversocket: try : socket.send(message) except : socket.close() SOCKET_DESC.remove(socket) while True: # Gets list of readable sockets. These are read using select readsock, writesock, errsock = select.select(SOCKET_DESC, [], []) # case in which a new connection is handled for sock in readsock: if sock is serversocket: # New connection received though serversocket, i.e., a new client has connected to the server. # The connection is accepted using the .accept() method. It returns (connfd, addr) where connfd is a # new socket object used to send/receive data on the connection and sddr is the address bound to the # socket on the other end of the connection connfd, addr = serversocket.accept() # The new client connection is added to the list of connections SOCKET_DESC.append(connfd) print "Client " + str(addr) +" connected" #clientbroadcast function called clientbroadcast(connfd, str(addr) + " entered chat room" + "\n") # case in which some client sends an incoming message else: try: # gets the data stored in the buffer clientdata = sock.recv(RECV_BUFFER) #if some data exists, it means that the client has sent a message # This message is broadcast to others connected to the server if clientdata: clientbroadcast(sock, "\r" + str(sock.getpeername()) + ': ' + clientdata) #when client sends disconnect message if clientdata.split("\n")[0] == "disconnect": clientbroadcast(sock, "Client " + str(addr) + " left chat room!\n") print "Client " + str(addr) + " disconnected" sock.close() SOCKET_DESC.remove(sock) continue except: continue serversocket.close()
c3063f76ba5bf1f9b7370f063df13d8de996c1b2
ansrivas/pyswitcheo
/pyswitcheo/datatypes/fixed8.py
1,451
3.515625
4
# !/usr/bin/env python # -*- coding: utf-8 -*- """Implementation for custom datatypes to interact with the blockchain.""" from decimal import Decimal from pyswitcheo.crypto_utils import reverse_hex import logging logger = logging.getLogger(__name__) class Fixed8(object): """Fixed point representation of a given input number.""" def __init__(self, value): """.""" self.__value = float(Decimal(value).quantize(Decimal("1.00000000"))) def to_hex(self): output = hex(round(self.__value * 1e+8))[2:] return "0" * (16 - len(output)) + output def to_reverse_hex(self): """Get a reverse hex representation of a given Fixed8.""" return reverse_hex(self.to_hex()) @property def value(self): """Return the underlying value of fixed 8.""" return str(self.__value) @staticmethod def num_to_fixed_8(number, size=8): """Convert a given number to Fixed8 representation. Args: number (float/int) : Input which needs to be converted to a Fixed8 representation. Returns: Given number in Fixed8 representation. Raises: TypeError in case size param is not an integer """ if size % 1 != 0: raise TypeError( "size param must be a whole integer. Received {size}".format(size=size) ) return Fixed8(number).to_reverse_hex()[: size * 2]
6159179b88c97cce7471756aff9e939fc2697377
dfridman1/coursera-data-structures-and-algorithms-specialization
/algorithmic-toolbox/assignments/week4/sorting/sorting.py
1,207
3.703125
4
# Uses python2 import numpy as np DEBUG = False def quicksort(xs): def sort(p, r): if p < r: q1, q2 = partition(xs, p, r) sort(p, q1-1) sort(q2+1, r) sort(0, len(xs)-1) def partition(xs, p, r): pivot_idx = np.random.randint(p, r+1) pivot = xs[pivot_idx] swap(xs, pivot_idx, r) i = j = k = p while k < r: if xs[k] == pivot: swap(xs, k, j) j += 1 elif xs[k] < pivot: swap(xs, k, j) swap(xs, j, i) i += 1 j += 1 k += 1 swap(xs, j, r) return i, j def swap(xs, i, j): xs[i], xs[j] = xs[j], xs[i] def stress_test(max_size): while True: xs = list(np.random.randint(-10, 10, size=np.random.randint(1, max_size+1))) sorted_xs = sorted(xs) quicksort(xs) if sorted_xs != xs: print('test failed') raise print('test passed') def main(): if DEBUG: stress_test(max_size=1000) else: raw_input() xs = map(int, raw_input().split()) quicksort(xs) print(' '.join(map(str, xs))) if __name__ == '__main__': main()
e6da329cede060ca836cd6529f3e649304060a4c
Kaitensatsuma/BAN690
/pdf_export.py
391
3.53125
4
import PyPDF2 print("What PDF do you want to scrape text from?") pdf_file = PyPDF2.PdfFileReader(open(str(input()), 'rb')) print("And where do you want to write to?") text_file = str(input()) container = '' iterations = range(pdf_file.numPages) with open(text_file,'w') as file: for x in iterations: container = pdf_file.getPage(x).extractText() file.write(container)
e0e1c8003a6a22bdfcc3be5880d309cff19ac492
yuyeh1212/University
/python/16.py
692
3.796875
4
# 擲骰子6000次並記錄點數出現次數 import random def main(): one = 0 two = 0 three = 0 four = 0 five = 0 six = 0 for i in range(6000): number = random.randint(1, 6) if number == 6: one += 1 elif number == 5: two += 1 elif number == 4: three += 1 elif number == 3: four += 1 elif number == 2: five += 1 else: six += 1 print("1 : {}".format(one)) print("2 : {}".format(two)) print("3 : {}".format(three)) print("4 : {}".format(four)) print("5 : {}".format(five)) print("6 : {}".format(six)) main()
a1b6aa392a2513b82faef555a5c24b837d4f7380
nazhimkalam/Data-Science-Course
/Pandas/Series.py
2,313
4
4
# Series # Series() is a function of pandas class or module import numpy as np import pandas as pd label = ['a','b','c'] # list my_data = [10, 20, 30] # list arr = np.array(my_data) # NumPy array d = {'a':10, 'b':20, 'c':30} # Dictionary # Series will return the data with index # Syntax Series (data, index, dtype, name, copy, fastpath) # Order of the parameter matters unless you define the argument such as data = label # If you pass in a list without an index list it will default use a number list as such [0, 1, 2, 3, 4, 5, .... print(pd.Series(my_data)) print(pd.Series(label)) print('------------------------------------------------------------------------------------------------------------') # You can also index the data elements by a list of your own as a parameter in the Series() function print(pd.Series(my_data,label)) print('------------------------------------------------------------------------------------------------------------') # Order of the data you pass a parameter matters. # Below you will be able to see data and index gets exchanged due to incorrect parameter order print(pd.Series(label,my_data)) print('------------------------------------------------------------------------------------------------------------') # Series can hold any data type object as well print(pd.Series([1,1,2,3],['Nazhim','Nazhim','Abilash','Raveen'])) # we can use "strings" as keys print('------------------------------------------------------------------------------------------------------------') # Accessing Data values using the index value ser = pd.Series([1,2,3,4],['Nazhim','Ravindu','Abilash','Raveen']) # like this you can access the data elements using the string index print(ser['Nazhim']) print('------------------------------------------------------------------------------------------------------------') print(ser['Abilash']) print('------------------------------------------------------------------------------------------------------------') # When adding TWO series it will convert the Integer data into to float number # Only if both the series has the same key then only it will add else, it will return NaN for that key reference ser1 = pd.Series([1,2,3,4],['a','b','c','d']) ser2 = pd.Series([1,2,3,4],['a','b','f','d']) print(ser1 + ser2)
83281d0bd1b6fdf6e338c5412ff728ec17a80cd5
andrefcordeiro/Aprendendo-Python
/Uri/strings/1234.py
1,431
3.734375
4
# Sentença dançante while True: try: str = input() strDancante = [] antIsUp = -1 #anterior está em maiusculo for i in range(0, len(str)): charCode = ord(str[i]) if charCode == 32: #espaco em branco strDancante.append(str[i]) else: if antIsUp == -1: #primeiro caractere diferente de espaço if charCode >= 97: strDancante.append(str[i].upper()) else: strDancante.append(str[i]) antIsUp = 1 elif charCode >= 97: #se estiver em minuscula if antIsUp == 0: #se o char anterior for minusculo strDancante.append(str[i].upper()) antIsUp = 1 else: strDancante.append(str[i]) antIsUp = 0 elif charCode < 97: #se estiver em maiuscula if antIsUp == 0: # se o char anterior for minusculo strDancante.append(str[i]) antIsUp = 1 else: strDancante.append(str[i].lower()) antIsUp = 0 for i in range(0, len(strDancante)): print(strDancante[i], end="") print() except EOFError: break
93a63b34264cc28e6f3d5a72bdcbc6106a4dc41c
frankieliu/problems
/leetcode/python/1121/1121.divide-array-into-increasing-sequences.py
1,146
3.6875
4
# # @lc app=leetcode id=1121 lang=python # # [1121] Divide Array Into Increasing Sequences # # https://leetcode.com/problems/divide-array-into-increasing-sequences/description/ # # algorithms # Hard (52.57%) # Total Accepted: 1.4K # Total Submissions: 2.6K # Testcase Example: '[1,2,2,3,3,4,4]\n3' # # Given a non-decreasing array of positive integers nums and an integer K, find # out if this array can be divided into one or more disjoint increasing # subsequences of length at least K. # # # # Example 1: # # # Input: nums = [1,2,2,3,3,4,4], K = 3 # Output: true # Explanation: # The array can be divided into the two subsequences [1,2,3,4] and [2,3,4] with # lengths at least 3 each. # # # Example 2: # # # Input: nums = [5,6,6,7,8], K = 3 # Output: false # Explanation: # There is no way to divide the array using the conditions required. # # # # # Note: # # # 1 <= nums.length <= 10^5 # 1 <= K <= nums.length # 1 <= nums[i] <= 10^5 # # class Solution(object): def canDivideIntoSubsequences(self, nums, K): """ :type nums: List[int] :type K: int :rtype: bool """
cb73aa75586f0d2a9f0c673152838603ec407c6e
Jordaness/DataStructures
/Stack.py
975
4.15625
4
# Class Representation of a Stack class Stack: def __init__(self): self.collection = list() self.count = 0 def push(self, element): """Adds a element to the top of the Stack""" self.collection.append(element) self.count += 1 return self def pop(self): """Removes an element from the top of the Stack""" if len(self.collection) == 0: return None self.count -= 1 element = self.collection[self.count] del self.collection[self.count] return element def peek(self): """Reveals the element on top of the Stack""" return self.collection[self.count-1] def size(self): """Returns the count of elements on the Stack""" return len(self.collection) def __repr__(self): items = "" for i in range(self.count-1, -1, -1): items += self.collection[i].__repr__() + "\n" return items
6fcc50d7964660ae6ee54f25908c19ce127c8dd4
MountTan/aa
/字典,列表操作一.py
377
3.734375
4
a = {'a': 1, 'b': 2} b = {'c': 3, 'd': 4} c = {**a, **b} print(c) d = a.copy() d.update(b) print(d) # {'a': 1, 'b': 2, 'c': 3, 'd': 4} f = [1, 2] g = [3, 4] h = f + g print(h) # [1, 2, 3, 4] i = ['a', 'b', 'c'] j = [1, 2] k = [1, 2, 3] l = [item * 2 for item in k] print(l) # [2, 4, 6] m = ['a', 'b', 'c'] n = [1, 2] o = zip(m, n) print(list(o)) # [('a', 1), ('b', 2)]
50ae2f6e6febacea9aa58e89702de41dfb0f6b1d
CosmicTomato/ProjectEuler
/eul119.py
1,174
4.09375
4
#Digit power sum #The number 512 is interesting because it is equal to the sum of its digits raised to some power: 5 + 1 + 2 = 8, and 8^3 = 512. Another example of a number with this property is 614656 = 28^4. #We shall define an to be the nth term of this sequence and insist that a number must contain at least two digits to have a sum. #You are given that a2 = 512 and a10 = 614656. #Find a30. #SOLUTION AS WRITTEN IS NOT FAST ENOUGH #PERHAPS START FROM EXPONENTS SOMEHOW? #WOULD HELP TO HAVE FAST WAY TO ORDER EXPONENTS def main( n ): #finds first n numbers in desired list #problem as stated just wants n=30 a_list = [] max_exp = 10 i = 2 #since 1 is not included in the list for problem statement while len( a_list ) < n: #keeps searching until n found exp = 2 i_list = list( str( i ) ) i_sum = 0 for j in i_list: i_sum += int( j ) #finds sum of digits of i while exp <= max_exp: if ( i_sum ** exp ) == i: a_list.append( i ) exp = max_exp + 1 #2nd part is to ensure while loop ends #TEST print('a_list len=',len(a_list)) #TEST else: exp += 1 i += 1 #increments i return a_list
0ddd032fba2bc09e2f749a4a4c8d1e116c654b05
BiswasAngkan/BasicPython
/Conditional_Statement.py
349
4.0625
4
# Angkan Biswas # 23.05.2020 # To use if_else statement '''1st case''' x = input('Insert a Number: ') x = int(x) if x < 5: print('Welcome') if x < 5: print('Welcome') else: print('Please Go Back!!!') '''2nd case''' for i in range(20): if i < 5: print(0) else: print(5) '''3rd case''' x = range(20) y = [0 if a < 5 else 5 for a in x] print(y)
6e2cf37b510e9b6bb1f60e831b55dd719f1fe828
Abdul89-dev/Victor
/types.py
1,124
3.984375
4
#a = 2 #sum = 2.5 #b = sum - a #print(a + b) # name = input ("input your name" ) # print('Hello'+ name) #v = int(input("Введите число от 1 до 10")) #print(v) #s = int(input("Введите число от 1 до 10")) #print(s + 10) #name = input("Enter your name") #print(name) #print (float ('1')) #print(int("2.5")) #print(bool(1)) #print(bool("")) #print(bool(0)) #numbers = [3,5,7,9,10.5] #print(numbers) #numbers.append ('Python') #print(numbers) #print (len(numbers)) #print(numbers[0]) #print(numbers[-1]) #print(numbers[2:4]) #del numbers[-1] #print(numbers) #dictonary = { #'city' : 'Moscow', #'temperature' : '20' #} #print(dictonary ['city']) #print (int(dictonary['temperature'])) #print (int(dictonary['temperature']) - 5) #print(type(dictonary)) #print(dictonary) #print(dictonary.get("namecountry")) #print(dictonary.get("country", "Russia")) #dictonary['date'] = "27.05.2019" #print(len(dictonary)) #def get_sum(one, two, delimiter='&'): #if one == "Learn" and two =="python": #return(one + delimiter + two) #print(get_sum('Learnl', 'python'))
c8d592100685b5acc60be43bc74499c9c8550f56
gabrieleliasdev/python-mentoring
/ex20.py
837
3.5625
4
from sys import argv script, input_file = argv # Aguardo receber (02) parametros: script: python3 e input_file: Caminho do Arquivo def imprime_tudo(f): print(f.read()) def rebobinar(f): f.seek(0) # seek (0): vai mover o cursor para o inicio do arquivo. def imprima_uma_linha(numero_linha, f): print(numero_linha, f.readline()) # readline: ler apenas um arquivo no texto; arquivo_atual = open(input_file) print("Primeiro vamos imprimir todo o arquivo: \n") imprime_tudo(arquivo_atual) print("Agora vamos rebobinar, tipo uma fita cassete") rebobinar(arquivo_atual) print("Vamos imprimir três linhas:") linha_atual = 1 imprima_uma_linha(linha_atual, arquivo_atual) linha_atual = linha_atual + 1 imprima_uma_linha(linha_atual, arquivo_atual) linha_atual = linha_atual + 1 imprima_uma_linha(linha_atual, arquivo_atual)
e4bd12dbb59d30d9141e65807e23f82863ff451c
fangpings/Leetcode
/143 Reorder List/untitled.py
930
3.796875
4
class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def reorderList(self, head): if not head: return cur = head storage = [] while cur: storage.append(cur) cur = cur.next tail = storage.pop() while tail != head and tail != head.next: tail.next = head.next head.next = tail head = head.next.next tail = storage.pop() tail.next = None def new_ll(array): head = ListNode(0) cur = head for num in array: tmp = ListNode(num) cur.next = tmp cur = cur.next return head.next def print_ll(head): while head is not None: print(head.val) head = head.next if __name__ == '__main__': sol = Solution() l = new_ll([1,2]) sol.reorderList(l) print_ll(l)
826c3b13612f83d2fe0dbfaabcf030786f573ea5
chrisx8/Ballzzz
/gameModules/ball.py
4,398
3.765625
4
import math class Ball(object): def __init__(self, color, startX, canvasHeight, canvasMargin): # user-defined color in customization self.color = color # radius is always 5px self.radius = 5 # balls start at where the last ball landed, at the bottom of canvas self.cx = startX self.cy = canvasHeight - canvasMargin - self.radius - 5 # change self.dx = 0 self.dy = 0 self.speed = 5 # return a evaluable string for recreating the object def __repr__(self): return "%s('%s', %d, data.height, data.margin)" % (type(self).__name__, self.color, self.cx) def draw(self, canvas): canvas.create_oval(self.cx-self.radius, self.cy-self.radius, self.cx+self.radius, self.cy+self.radius, fill=self.color) def move(self, angle, quadrant): self.angle = angle self.dx = self.radius * math.cos(angle) self.dy = self.radius * math.sin(angle) * -1 if quadrant == 2: self.dx *= -1 elif quadrant == 3: self.dx *= -1 self.dy *= -1 elif quadrant == 4: self.dy *= -1 def updatePos(self): self.cx += self.dx * self.speed self.cy += self.dy * self.speed def isMoving(self): return self.dx != 0 or self.dy != 0 def collisionWithBorder(self, canvasWidth, canvasHeight, canvasMargin): # top border: reverse vertical direction if self.cy-self.radius <= canvasMargin+10: self.dy *= -1 # left border: change quadrant if self.cx-self.radius <= canvasMargin: # go to quadrant 1 when going up if self.dy < 0: self.move(self.angle, 1) # go to quadrant 4 when going down elif self.dy > 0: self.move(self.angle, 4) # right border: change quadrant elif self.cx+self.radius >= canvasWidth-canvasMargin: # go to quadrant 2 when going up if self.dy < 0: self.move(self.angle, 2) # go to quadrant 3 when going down elif self.dy > 0: self.move(self.angle, 3) # bottom border: return last pos to remove ball elif self.cy+self.radius >= canvasHeight-canvasMargin: return self.cx def isCollisionWithBlock(self, block): return self.cx + self.radius >= block.topLeft[0] and \ self.cx - self.radius <= block.bottomRight[0] and \ self.cy + self.radius >= block.topLeft[1] and \ self.cy - self.radius <= block.bottomRight[1] def collisionWithBlock(self, block): # left border: change quadrant if block.topLeft[0] <= self.cx+self.radius < block.bottomRight[0] and \ self.cx < block.topLeft[0]: # go to quadrant 1 when going up if self.dy < 0: self.move(self.angle, 2) # go to quadrant 4 when going down elif self.dy > 0: self.move(self.angle, 3) # right border: change quadrant elif self.cx-self.radius <= block.bottomRight[0] and \ self.cx > block.bottomRight[0]: # go to quadrant 2 when going up if self.dy < 0: self.move(self.angle, 1) # go to quadrant 3 when going down elif self.dy > 0: self.move(self.angle, 4) # top/bottom border: reverse vertical direction elif (self.cy - self.radius < block.bottomRight[1] or self.cy + self.radius > block.topLeft[1]) and \ block.topLeft[0] < self.cx < block.bottomRight[0]: self.dy *= -1 class SuperBall(Ball): def __init__(self, color, startX, canvasHeight, canvasMargin): super().__init__(color, startX, canvasHeight, canvasMargin) # super balls are twice as big as normal self.radius = 10 self.cy = canvasHeight - canvasMargin - self.radius def draw(self, canvas): super().draw(canvas) canvas.create_text(self.cx, self.cy, text="S") def collisionWithBlock(self, block): # true if collided # destroy itself when colliding with block return True
1ae23ef969c5e2ef9896a295f4d05b87a5d33169
HGNJIT/statsCalculator
/MathOperations/multiplication.py
416
3.578125
4
class Multiplication: @staticmethod def product(multiplier,multiplicand=None): if (isinstance(multiplier,list)): return Multiplication.productList(multiplier) return multiplier * multiplicand @staticmethod def productList (valueList): result = 1 for element in valueList: result = Multiplication.product(result, element) return result
134c3e138b63d260e7bc5b21e102c04e34552247
LiuXPeng/leetcode
/59.py
812
3.5
4
class Solution: def generateMatrix(self, n): """ :type n: int :rtype: List[List[int]] """ number = 1 res = [[None for col in range(n)] for row in range(n)] #每次写数,都把一行/列写满 for k in range(n): #上 for i in range(k, n - k): res[k][i] = number number += 1 #右 for i in range(k + 1, n - k): res[i][n - k - 1] = number number += 1 #下 for i in range(n - k - 2, k - 1, -1): res[n - 1 - k][i] = number number += 1 #左 for i in range(n - k - 2, k, -1): res[i][k] = number number += 1 return res
ae5e53c534c73929158e88aa10d9ef6cf979c14e
19goux/python-eval
/adv_partie-II.py
496
3.5625
4
from codec import TreeBuilder, Codec text = "a dead dad ceded a bad babe a beaded abaca bed" builder = TreeBuilder(text) binary_tree = builder.tree() # on passe l'arbre binaire à un encodeur/décodeur codec = Codec(binary_tree) # qui permet d'encoder encoded = codec.encode(text) # et de décoder decoded = codec.decode(encoded) # si cette assertion est fausse il y a un gros problème avec le code # on affiche le résultat print(f"{text}\n{decoded}") if decoded != text: print("OOPS")
3a53af0caf0a603c5e733ea2c80337e35fa0da0f
Tperm-coder/python-codes
/series and parallel calculations.py
1,600
3.734375
4
import os os.system('color b') os.system('cls') # TOC stands for type of connection pap = True while pap : os.system('color a') os.system('cls') TOC = input('series or parallel ?') if TOC == 'series' : NOR = int(input('what are the number of resistors ?')) # NOR stands for number of resistors SA = range(0,NOR) # SA stands for series array counter = 0 SA2 = [] # SA2 stands for series array number 2 for i in SA : counter = counter + 1 value = int(input('what is the value of resistor number ' + str(counter) + ' in ohm' + ' ?')) SA2.append(value) req = 0 # req stands for equivilant resistance for i in SA2 : req = req + i print('equivilant resistance is ' + str(req) + ' ohm') input() elif TOC == 'parallel' : NOR = int(input('what is the number of resistors ?')) PA = range(0,NOR) counter = 0 PA2 = [] for i in PA : counter = counter +1 voepr=int(input(('what is the value of the resistor number ' + str((counter)) + ' in ohm ?'))) PA2.append(voepr) PA3 = [] for i in PA2 : i = float((1/i)) PA3.append(i) sezo = 0 for i in PA3 : sezo = sezo + i sezo= float(1/sezo) print('equivilant resistance is ' + str(sezo) + ' ohm') input() tap = input('do you want to run again yes or no ?') if tap == 'yes' : pap = True else : pap = False
9feba435621932846974b4de7e8cea0a2a166c51
CoderFemi/AlgorithmsDataStructures
/practice_challenges/python/quick_sort.py
437
4.15625
4
def quickSort(arr) -> list: """Implement quicksort""" pivot = arr[0] left = [] equal = [pivot] right = [] for index in range(1, len(arr)): num = arr[index] if num < pivot: left.append(num) elif num == pivot: equal.append(num) else: right.append(num) sort_list = left + equal + right return sort_list print(quickSort([4, 5, 3, 7, 2]))
dbca8c76f97ddfbe815d0a73ac15eecaf0fdef82
niharikasaraswat/python
/pos_neg.py
197
3.984375
4
# enter series range list1 = [20, -60, 80, 50, -10] for num in list1: if num > 1: print('positive numbers in list', num) else: print('negative numbers in list', num)
656870d4ba887cfd702750093ddb916cbc97eb9c
AnumHassan/Class-Work
/Table.py
95
3.5
4
able = int(input("Enter a No:" )) for i in range(1,11): print(able, "x",i,"=",str(able*i))
0ae7f4d79704b12eb64f7643d1b730d231814204
fernandorunte/SHSU_Assingnments
/Python/Chapter3/chap3_2.py
530
4.0625
4
##areas of rectangles length1=int(input('enter lenght of the first rectangle: ')) width1=int(input('enter the width of the first rectangle: ')) length2=int(input('enter lenght of the second rectangle: ')) width2=int(input('enter the width of the second rectangle: ')) area1= length1*width1 area2= length2*width2 if area1 > area2: print('the first rectangle is bigger') else: if area1 < area2: print('the second rectanble is bigger') else: print('they are the same sise')
40047e93afa0f6cdd8fe2480d006dc0840706a70
IKNL/vertigo
/scripts/auxiliaries.py
2,048
3.5
4
# -*- coding: utf-8 -*- """ auxiliaries.py Auxiliary functions. Created on Mon Mar 18 09:55:09 2019 @author: Arturo Moncada-Torres arturomoncadatorres@gmail.com """ #%% Preliminaries import pandas as pd from sklearn.utils import resample #%% def downsample(X, y, random_state=None): """ Perform class balancing downsampling. Parameters ---------- X: Pandas data frame. Shape (n_samples, n_features) Feature matrix. y: Pandas data frame. Shape (n_samples, 1) Class labels. Rows are instances. random_state: (optional) integer Random seed value. Default is None (which means a np.random is used) Use a fixed value for reproducibility. Returns ------- X_balanced, y_balanced: tuple of Pandas DataFrame. Shape (n_classes*max(n_instances_classes), n_features) and (n_classes*max(n_instances_classes), 1) Class-balanced input/output matrix/vector. """ # Merge dataframe into one. df = pd.concat([X, y], axis=1, sort=False) # Create dataframes (a list of dataframes) for each class. dfs = [] classes = list(y.T.squeeze().unique()) for class_ in classes: df_tmp = df[df[y.columns[0]]==class_] dfs.append(df_tmp) counts = list(map(len, dfs)) # Find the class with less instances. min_value = min(counts) min_index = counts.index(min(counts)) min_class = classes[min_index] # Downsample all the other classes. iteration = 0 for (df_, class_) in zip(dfs, classes): if class_ == min_class: # If the current class is the one with least instances, # do nothing. pass else: # Otherwise, downsample. df_ = resample(df_, replace=False, n_samples=min_value, random_state=random_state) dfs[iteration] = df_ iteration += 1 df_balanced = pd.concat(dfs) X_balanced = df_balanced.iloc[:,0:-1] y_balanced = pd.DataFrame(data=df_balanced.iloc[:,-1], columns=y.columns) return X_balanced, y_balanced
bc733bd3e55880d3b50b8a93540ebf6fa13d886c
developr4u/learning-coding
/python_course/chp_threeEx4.py
186
3.890625
4
user_input = input("Enter a number: ") i = 0 total = 0 length = len(user_input) while length > 0: total = int(user_input[i]) + total length -= 1 i += 1 print(total)
fdb58606849c43e42a4cb9f5a7e8264794f7a761
aakashdinkar/Hackerrank-Series
/CaeserCipher.py
730
3.640625
4
#!/bin/python3 import math import os import random import re import sys # Complete the caesarCipher function below. def caesarCipher(s, k): st = "" for item in s: if item.isalpha(): print(ord(item)+k) if item.isupper(): a = 'A' st += chr(ord(a) + (ord(item) - ord(a) + k) % 26) else: a = 'a' st += chr(ord(a) + (ord(item) - ord(a) + k) % 26) else: st += item return st if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) s = input() k = int(input()) result = caesarCipher(s, k) fptr.write(result + '\n') fptr.close()
a75526c85c9ab5561dbcc1b63814fa5e22378915
kshulgina/codetta
/helper_functions.py
13,539
3.53125
4
import os import sys from subprocess import call, Popen, PIPE import re import numpy as np from ftplib import FTP import datetime def translate(sequence, gct): """ For a DNA sequence, translate it into a sequence of one symbol per codon, following a specific translation table. For example, this could be translating DNA sequence into an amino acid sequence following some genetic code, or it could be mapping the DNA sequence to a sequence of symbols corresponding to each codon. Replaces values not in the translation dict with X's Args: sequence (string): DNA sequence of A, T, G, C characters gc (dict): translation table Returns: string: new sequence of symbols, 1/3 length of DNA sequence """ return ''.join([gct.get(sequence[3*i:3*i+3].upper(),'X') for i in range(len(sequence)//3)]) def replace_stop(sequence): """ For a string, replace all '_' characters with 'X's Args: sequence (string) Returns: string: '_' characters replaced with 'X's """ return sequence.replace('_', 'X') global dna_complements dna_complements = bytes.maketrans(b"AaTtGgCcRrYySsWwKkMmBbVvDdHhNn", b"TtAaCcGgYyRrSsWwMmKkVvBbHhDdNn") def reverse_complement(sequence): """ For a string consisting of valid IUPAC DNA characters, return the reverse complement """ return sequence.translate(dna_complements)[::-1] def validate_file_path(file_path): """ Returns true if the string is a valid UNIX file path and false if not """ unix_safe_name = re.sub(r'[^~/\\.\d\w-]', '_', file_path) if len(file_path) > 0 and unix_safe_name == file_path: return True else: return False def validate_codon_line(line): ''' Validates that line in hmmscan_summary file is valid ''' # check line length (100 chosen somewhat arbitrarily) if len(line) > 100: return False # split into fields info = line.rstrip().split(',') try: dum = int(info[0]) # codon ind dum = float(info[1]) # coded position dum = int(info[3]) dum = int(info[4]) dum = int(info[5]) dum = float(info[7]) dum = int(info[8]) except ValueError: return False if not info[2].isupper(): return False return True def validate_fasta(fasta_file_path): """ Checks that FASTA sequence file, either downloaded genome or provided file, are in correct FASTA format. Arg is file path. Returns True or False. """ # get number of lines that start with > p = Popen('grep "^>" %s | wc' % (fasta_file_path), shell=True, stdout=PIPE) n_header = int(p.communicate()[0].decode().split()[0]) # get number of lines that don't start with > p = Popen('grep -v "^>" %s | wc' % (fasta_file_path), shell=True, stdout=PIPE) n_not_header = int(p.communicate()[0].decode().split()[0]) if n_not_header < n_header: return False # check if any illegal characters present in non-header lines p = Popen('grep -v "^>" %s | grep -i [^acgturykmswbdhvn] | wc' % (fasta_file_path), shell=True, stdout=PIPE) n_illegal_chars = int(p.communicate()[0].decode().split()[0]) if n_illegal_chars > 0: return False return True def validate_hmm_output(hmm_output_lines, piece_name): """ Checks that the content of an hmmscan output are not corrupted. Arg is a list of line-by-line hmmscan outfile file contents. Returns True or False. """ if len(hmm_output_lines) < 20: # somewhat arbitrary return False # check that this is output has info for the right sequence piece if not any('%s ' % piece_name in string for string in hmm_output_lines): return False # always has search summary at the end if not any('Internal pipeline statistics summary:' in string for string in hmm_output_lines): return False return True def extract_hmmscan_output(lines, eval_threshold): """ Reads a single hmmscan output and parses out relevant parts for genetic code inference. Filters domain hits based on E-value threshold. Args: lines (string): line-by-line contents of hmmscan output file eval_threshold (float): threshold for excluding domain hits based on e-value Returns: list of strings: a list of strings for each suitable domain found, with domain and conserved residue information encoded in a string """ # parse output from hmmscan and identify which conserved domains were found y = 0 conserved_regions = list() cr_append = conserved_regions.append # define function locally to speed it up while y < len(lines): line = lines[y] domains = list() if line[0:2] == '>>': domain_name = line.split(' ')[1] y = y+3 line = lines[y] if line[0:2] != '>>': while len(line)>0: # only analyze domains below e-value threshold splits = line.split() dom_eval = splits[5] if float(dom_eval) < eval_threshold: domains.append(splits[0]+","+domain_name+","+dom_eval+","+splits[6]+","+splits[7]+","+splits[9]+","+splits[10]) y = y+1 line = lines[y] y = y+2 line = lines[y] while line[0:2] != '>>': splits2=line.split() if len(splits2) > 0 and splits2[0] == '==': for d, dom in enumerate(domains): dom_info = dom.split(",") if dom_info[0] == splits2[2]: try: hmm_ali = lines[y+1].split()[2] que_ali = lines[y+3].split()[2] post_ali = lines[y+4].split()[0] y = y + 1 amt_add = 5 except IndexError: try: hmm_ali = lines[y+2].split()[2] que_ali = lines[y+4].split()[2] post_ali = lines[y+5].split()[0] y = y + 2 amt_add = 6 except IndexError: hmm_ali = lines[y+3].split()[2] que_ali = lines[y+5].split()[2] post_ali = lines[y+6].split()[0] y = y + 3 amt_add = 7 line = lines[y] while int(line.split()[3]) < int(dom_info[4]): y = y + amt_add line = lines[y] hmm_ali = hmm_ali + line.split()[2] que_ali = que_ali + lines[y+2].split()[2] post_ali = post_ali + lines[y+3].split()[0] # turn into numpy arrays so can mask hmm_ali = np.frombuffer(hmm_ali.encode(), dtype='a1') que_ali = np.frombuffer(que_ali.encode(), dtype='a1') post_ali = np.frombuffer(post_ali.encode(), dtype='a1') # now transform this into pairs of hmm and query index that have no gaps and pass # alignment posterior quality filter mask1 = hmm_ali != b'.' mask2 = que_ali != b'-' mask3 = post_ali == b'*' mask = mask1 & mask2 & mask3 hmm_inds = np.ones(len(hmm_ali), dtype=int) hmm_inds[~mask1] = 0 que_inds = np.ones(len(que_ali), dtype=int) que_inds[~mask2] = 0 hmms = np.cumsum(hmm_inds)-1+int(dom_info[3]) hmms = hmms[mask] que = np.cumsum(que_inds)-1+int(dom_info[5]) que = que[mask] if len(hmms) == 0: continue region = np.empty((hmms.size + que.size,), dtype=int) region[0::2] = hmms region[1::2] = que region = ','.join(region.astype(str)) cr_append("%s,%s,%s,%s,%s" % (dom_info[1], dom_info[2], dom_info[5], dom_info[6], region)) y = y+1 if y >= len(lines): break line = lines[y] else: y = y+1 return conserved_regions def genome_download(species_id, type_download, database_dir, download_output_file): """ For a given species ID, function will attempt to download a genome Args: species_id : species ID that will be matched to genomes in GenBank type_download ('a' or 'c'): specifying is ID is GenBank assembly or accession number Returns: Nothing """ # database files genbank_file = '%s/assembly_summary_genbank.txt' % database_dir # try to download from genbank genbank_res = download_genbank(species_id, genbank_file, type_download, download_output_file) return genbank_res def update_genbank(genbank_file): ''' Updates the assembly_summary file from GenBank, used to download assembly accessions ''' # get modification time of local copy of GenBank database file (in UTC) UTC_OFFSET = datetime.datetime.utcnow() - datetime.datetime.now() if os.path.isfile(genbank_file): local_time = int((datetime.datetime.fromtimestamp(os.path.getmtime(genbank_file)) + UTC_OFFSET).strftime("%Y%m%d%H%M")) else: local_time = 0 # get modification time of database file on GenBank ftp server (in UTC) ftp = FTP('ftp.ncbi.nlm.nih.gov') ftp.login() ftp.cwd('./genomes/ASSEMBLY_REPORTS') genbank_time = ftp.sendcmd("MDTM assembly_summary_genbank.txt") if genbank_time[:3] == "213": genbank_time = int(genbank_time[3:-2].strip()) # if local version of file is younger than the GenBank version, download new version if local_time < genbank_time: print('Downloading updated version of GenBank assembly reference file') with open(os.devnull, "w") as f: dum = call('wget -O %s ftp.ncbi.nlm.nih.gov/genomes/ASSEMBLY_REPORTS/assembly_summary_genbank.txt' % (genbank_file), shell=True, stdout=f, stderr=f) def download_genbank(species_id, genbank_file, type_download, download_output_file): ''' Downloads nucleotide sequence from GenBank, either assembly accession or nucleotide accession. Returns either the ftp URL from which the file was downloaded OR a 1 if failed ''' # deal with case where species id is a GenBank genome assembly ID if type_download == 'a': # see if newer versions of genome database file is available, if so download update_genbank(genbank_file) # get urls p = Popen("awk -F'\t' -v OFS='\t' '$1 == \"%s\" {print $20}' %s" % (species_id, genbank_file), shell=True, stdout=PIPE) info = p.communicate()[0].decode().split('\n')[:-1] # if species id does not exist in GenBank if len(info) == 0: return 1 # if multiple entries exist, just pick the first one u = info[0] prefix = u.split('/')[-1] download_url = '%s/%s_genomic.fna.gz' % (u, prefix) # check if sequence is being downloaded into a directory that exists download_dir = os.path.dirname(download_output_file) if download_dir != '' and not os.path.isdir(download_dir): sys.exit('ERROR: the path leading up to prefix has not been created') # download the genome! genome_path = '%s.gz' % download_output_file with open(os.devnull, "w") as f: dum = call('wget -O %s %s' % (re.escape(genome_path), download_url), shell=True, stdout=f, stderr=f) # unzip os.system('gunzip -f %s' % (re.escape(genome_path))) return download_url # deal with case where species id is a GenBank accession number elif type_download == 'c': # check if sequence is being downloaded into a directory that exists download_dir = os.path.dirname(download_output_file) if download_dir != '' and not os.path.isdir(download_dir): sys.exit('ERROR: the path leading up to prefix has not been created') download_url = 'https://www.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nuccore&id=%s&rettype=fasta&retmode=text' % species_id wget_command = "wget -q -O %s '%s'" % (download_output_file, download_url) with open(os.devnull, "w") as f: dum = call(wget_command, shell=True, stdout=f, stderr=f) return download_url
10166a92e26316e1182a17528bfa73e88f4364e4
eloghin/Python-courses
/LeetCode/contains_duplicate.py
703
4.1875
4
# Given an array of integers that is already sorted in ascending order, find two numbers such that # they add up to a specific target number. # Given an array of integers, find if the array contains any duplicates. # Your function should return true if any value appears at least twice in # the array, and it should return false if every element is distinct. """"" SOL 1 """"" dict_duplicates = {} for item in nums: if item in dict_duplicates: return True else: dict_duplicates[item] = 1 return False """"" SOL 2 """"" # num = list(set(nums)) #To remove duplicates # if len(num) == len(nums): # return False # return True
d3dda9a06c0a019523e27239420bb5a5df18de03
sourabbanka22/Competitive-Programming-Foundation
/HackerEarth/Math/Number Theory/Basic Number Theory-2/isPrime.py
204
3.890625
4
def isPrime(number): if number<2: return False idx = 2 while idx*idx <= number: if number%idx == 0: return False idx += 1 return True print(isPrime(1))