blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
2213e27af6af0016ae88f618b3168f44ff5b8d83
melissabica/whats-up
/tweet_classify.py
7,487
3.71875
4
def hasRepeats(document): """Returns True if more than 3 consecutive letters are the same in document.""" previous = '' two_previous = '' for letter in document: if letter == previous == two_previous: return True two_previous = previous previous = letter return False # features for the classifier # all features should return a boolean all_features = { 'hasGood': lambda document: any(word in ['good', 'awesome', 'wonderful'] for word in document.split()), 'hasBad': lambda document: any(word in ['bad', 'terrible', 'horrible'] for word in document.split()), 'hasHappy': lambda document: 'happy' in document or 'happi' in document, 'hasSad': lambda document: 'sad' in document, 'hasLove': lambda document: 'love' in document or 'loving' in document, 'hasHate': lambda document: 'hate' in document, 'hasSmiley': lambda document: any(word in [':)', ':-)', ':D', '(:', '=)', '(='] for word in document.split()), 'hasWinky': lambda document: any(word in [';)', ';D'] for word in document.split()), 'hasFrowny': lambda document: any(word in [':(', ':-(', '):', 'D:', ':.('] for word in document.split()), 'hasBest': lambda document: 'best' in document, 'hasWorst': lambda document: 'worst' in document, 'hasDont': lambda document: any(word in ['dont','don\'t','do not','does not','doesn\'t'] for word in document.split()), 'hasExclamation': lambda document: '!' in document, 'hasRepeats': lambda document: hasRepeats(document), 'hasHeart': lambda document: any(word in ['<3', '&lt;3'] for word in document.split()), 'hasCant': lambda document: any(word in ['cant','can\'t','can not'] for word in document.split()), 'hasExpense': lambda document: any(word in ['expensive', 'expense'] for word in document.split()), 'hasFavorite': lambda document: 'favorite' in document, 'hasFantastic': lambda document: 'fantastic' in document, 'hasFuck': lambda document: 'fuck' in document or 'f*ck' in document, 'hasFriend': lambda document: any(word in ['bff', 'friend'] for word in document.split()), 'hasAche': lambda document: any(word in ['ache', 'aching'] for word in document.split()), 'hasLol': lambda document: any(word in ['lol', 'lmao'] for word in document.split()), 'hasHaha': lambda document: 'haha' in document, 'hasGreat': lambda document: 'great' in document, 'hasNo': lambda document: 'no' in document.split(), 'hasYes': lambda document: 'yes' in document.split(), 'hasCold': lambda document: 'hot' in document.split(), 'hasHot': lambda document: 'cold' in document.split(), 'hasFree': lambda document: 'free' in document, 'hasImprove': lambda document: 'improve' in document, 'hasFail': lambda document: 'fail' in document, 'hasSweet': lambda document: 'sweet' in document, 'hasSuck': lambda document: 'suck' in document, 'hasCool': lambda document: 'cool' in document, 'hasPay': lambda document: 'pay' in document, 'hasFast': lambda document: 'fast' in document, 'hasCheap': lambda document: 'cheap' in document, 'hasPlay': lambda document: 'play' in document, 'hasIdiot': lambda document: 'idiot' in document, 'hasUgh': lambda document: 'ugh' in document, 'hasWtf': lambda document: 'wtf' in document, 'hasNew': lambda document: 'new' in document.split(), 'hasSmell': lambda document: 'smell' in document, 'hasAss': lambda document: 'ass' in document.split(), 'hasCurse': lambda document: 'curse' in document, 'hasFunny': lambda document: any(word in ['funny', 'hilarious', 'silly'] for word in document.split()), 'hasLoss': lambda document: any(word in ['lost', 'loss', 'lose'] for word in document.split()), 'hasWin': lambda document: any(word in['win', 'won'] for word in document.split()), 'hasOpportunity': lambda document: 'opportunity' in document, 'hasAwesome': lambda document: 'awesome' in document, 'hasConfident': lambda document: 'confident' in document, 'hasFun': lambda document: 'fun' in document, 'hasSuper': lambda document: 'super' in document, 'hasSmile': lambda document: 'smile' in document, 'hasWow': lambda document: 'wow' in document, 'hasScary': lambda document: 'scary' in document.split(), 'hasHurt': lambda document: 'hurt' in document, 'hasThanks': lambda document: any(word in ['thanks', 'thank you'] for word in document.split()), 'hasLike': lambda document: 'like' in document.split(), 'hasDislike': lambda document: 'dislike' in document.split(), 'hasSave': lambda document: 'save' in document, 'hasRocks': lambda document: any(word in ['rocks', 'rocked'] for word in document.split()), 'hasExcited': lambda document: any(word in ['excited', 'exciting'] for word in document.split()), 'hasRidiculous': lambda document: 'ridiculous' in document, 'hasCool': lambda document: 'cool' in document, 'hasHate': lambda document: 'hate' in document or 'hating' in document, 'hasDisgusting': lambda document: 'disgusting' in document or 'disgust' in document or 'ew' in document or 'gross' in document, 'hasHorrible': lambda document: 'horrible' in document or 'terrible' in document, 'hasStupid': lambda document: 'stupid' in document or 'dumb' in document, 'hasIgnorant': lambda document: 'ignorant' in document, 'hasShallow': lambda document: 'shallow' in document or 'superficial' in document, 'hasFail': lambda document: 'fail' in document or 'failed' in document or 'failure' in document, 'hasFlunk': lambda document: 'flunk' in document, 'hasUgly': lambda document: 'ugly' in document or 'hideous' in document, 'hasUnfair': lambda document: 'unfair' in document, 'hasDirty': lambda document: 'dirty' in document, 'hasDreadful': lambda document: 'dreadful' in document, 'hasDepressing': lambda document: 'depressing' in document, 'hasUnwise': lambda document: 'unwise' in document, 'hasUpset': lambda document: 'upset' in document, 'hasRude': lambda document: 'rude' in document or 'mean' in document, 'hasCruel': lambda document: 'cruel' in document, 'hasClumsy': lambda document: 'clumsy' in document, 'hasRocks': lambda document: any(word in ['rocks', 'rocked'] for word in document.split()), 'hasExcited': lambda document: any(word in ['excited', 'exciting'] for word in document.split()), 'hasRidiculous': lambda document: 'ridiculous' in document, 'hasScary': lambda document: 'scary' in document.split(), 'hasHurt': lambda document: 'hurt' in document, 'hasThanks': lambda document: any(word in ['thanks', 'thank you'] for word in document.split()), 'hasLike': lambda document: 'like' in document.split(), 'hasDislike': lambda document: 'dislike' in document.split(), 'hasSave': lambda document: 'save' in document, 'hasWin': lambda document: any(word in['win', 'won'] for word in document.split()), 'hasOpportunity': lambda document: 'opportunity' in document, 'hasConfident': lambda document: 'confident' in document, 'hasFun': lambda document: 'fun' in document, 'hasSuper': lambda document: 'super' in document, 'hasSmile': lambda document: 'smile' in document, 'hasWow': lambda document: 'wow' in document } def extract_features(document): features = {} for feature, function in all_features.items(): features[feature] = function(document.lower()) return features
523d3c3eab34a3fa8b4ee657661b741688165385
derickdeiro/curso_em_video
/aula_22-modulos-pacotes/desafio_110-reduzindo-ainda-mais-seu-programa.py
359
3.53125
4
from utilidadescev import moeda """ Adicione ao módulo moeda.py criado nos desafios anteriores, uma função chamada resumo(), que mostre na tela algumas informações geradas pelas funções que já temos no módulo criado até aqui. """ valor = float(input('Digite um valor: ')) p = float(input('Digite um percentual: ')) moeda.resumo(valor, p)
6542dac8bffdcdd3dc71ebbe849d4e4e230ec374
ferreret/python-bootcamp-udemy
/36-challenges/ex122.py
441
3.9375
4
''' find_the_duplicate([1,2,1,4,3,12]) # 1 find_the_duplicate([6,1,9,5,3,4,9]) # 9 find_the_duplicate([2,1,3,4]) # None ''' def find_the_duplicate(numbers): duplicates = [num for num in numbers if numbers.count(num) > 1] return duplicates[0] if len(duplicates) > 0 else None print(find_the_duplicate([1, 2, 1, 4, 3, 12])) # 1 print(find_the_duplicate([6, 1, 9, 5, 3, 4, 9])) # 9 print(find_the_duplicate([2, 1, 3, 4])) # None
8548c0a9e45c998638964b041981ba2719cc9348
joetechem/cs_python
/cs_python/foundations/functions_and_loops/greeter_v3.py
729
4.3125
4
# Python 2.7 # USING A FUNCTION WITH A WHILE LOOP # Let's use the get_formatted_name() function we looked at earlier # Only this time, we'll throw in a while loop to greet users more formally. def get_formatted_name(first_name, last_name): """Return a full name, neatly formatted.""" full_name = first_name + ' ' + last_name return full_name.title() while True: print("\nPlease tell me your first name:") print("(enter 'q' at any time to quit)") f_name = raw_input("First name: ") if f_name == 'q': break l_name = raw_input("Last name: ") if l_name == 'q': break formatted_name = get_formatted_name(f_name, l_name) print("\nHello, " + formatted_name + "!")
85aec4f07ff69396d9e296d0de5ba44dd0dc2db2
DanAyala/TAPfinal
/prime_threading.py
1,657
3.609375
4
#!/usr/bin/env python3 import concurrent.futures import multiprocessing import time def primos(inicio, fin): numeros_primos = list() for num in range(inicio,fin + 1): if (num > 1): for i in range(2,num): if (num % i) == 0: break else: #print(num) numeros_primos.append(num) return numeros_primos def main(numero, hilos): #threads = [] rango = int( numero / hilos ) start = 0 end = 0 futures = [] pool = concurrent.futures.ThreadPoolExecutor(max_workers=hilos) for x in range(hilos): end = (start + rango - 1) futures.append(pool.submit(primos, start, end)) start = start + rango for x in concurrent.futures.as_completed(futures): print(x.result()) def procesa(inicio, final, hilos): numero = final - inicio rango = int( numero / hilos ) start = 0 end = 0 futures = [] pool = concurrent.futures.ThreadPoolExecutor(max_workers=hilos) for x in range(hilos): end = (start + rango - 1) futures.append(pool.submit(primos, start, end)) start = start + rango primes_sum = 0 for x in concurrent.futures.as_completed(futures): print("abajo va algo") print(x.result()) primes_sum = primes_sum + len( x.result) print("numeros primos entre %d y %d : %d" % (inicio,final,primes_sum)) if __name__ == "__main__": start_time = time.time() cores = multiprocessing.cpu_count() #main(20,cores) procesa(0,100000,cores+4) duration = time.time() - start_time print("Tiempo en segundos:%f" % duration) #[17, 19] #[2, 3] #[5, 7] #[11, 13]
0d93361de78939022811722fef37f7fe4f0cb3a0
ttomchy/LeetCodeInAction
/tree/q543_diameter_of_binary_tree/solution.py
1,007
3.6875
4
#!/usr/bin/env python # -*- coding:utf-8 -*- """ FileName: solution.py Description: Author: Barry Chow Date: 2020/11/18 4:03 PM Version: 0.1 """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def diameterOfBinaryTree(self, root: TreeNode) -> int: #返回树的最大深度,和经过该节点的最大直径 def tree_depth_diam(root,depth): if root is None: return depth,0 else: left_depth,left_diam = tree_depth_diam(root.left,depth) right_depth,right_diam = tree_depth_diam(root.right,depth) depth = max(left_depth,right_depth)+1 diam = max(left_depth+right_depth,left_diam,right_diam) return depth,diam if not root: return 0 else: depth,diam = tree_depth_diam(root,0) return diam
050d1a40cd52edbaa112f07caaf261aa4b1d929b
tedtedted/Project-Euler
/004.py
569
4.25
4
""" A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. """ palindromes = [] def is_palindrome(num): string = str(num) first = string[:] last = string[::-1] return string[:] == string[::-1] for i in range(100, 1000): for j in range(100, 1000): if is_palindrome(i * j): palindrome = i * j palindromes.append(palindrome) print("The largest palindrome is:", sorted(palindromes)[-1])
af0d0f111416a1c47748e522211d81cf9ecb1b46
vagerasimov-ozn/python18
/contin.py
117
4
4
number = 0 while number < 15: number+= 1 if number % 3 == 0: continue else: print(number)
b9a17467eb7e05a864b2a8999abea888f89ac17a
luckmimi/leetcode
/LC79.py
904
3.65625
4
class Solution: def exist(self, board: List[List[str]], word: str) -> bool: for row in range(len(board)): for col in range(len(board[0])): if self.backtrack(board, row, col, word): return True return False def backtrack(self,board,row, col, word): if len(word) == 0 : return True if row < 0 or row > len(board) - 1 or col < 0 or col > len(board[0]) - 1 or board[row][col] != word[0]: return False ret = False board[row][col] = '#' for dx , dy in ((0,1),(0,-1),(-1,0),(1,0)): ret = self.backtrack(board, row + dx, col + dy,word[1:]) if ret: break board[row][col] = word[0] return ret
afa93a0d1ea8e998cc5efedd0862b9db584e4446
4mayet21/COM404
/3-decision/2-if-else/bot.py
235
3.90625
4
#asking for input print("what activity would you like me to perform?") activity = str(input()) if activity == "calculate": print("performing calculations...") else: print("performing activity...") print("activity completed!")
67c309bee7acb56ac1d5de2c902af9afe0bb5995
Dilmer-R/Python-POO
/Ejercicio 4/Ejercicio_4--Herencia--Walter_Diaz.py
3,980
4.09375
4
class Productos(): def __init__(self,nombre,costo,tipo): self.nombre=nombre self.costo=costo self.tipo=tipo def informe(self): print(f""" ---INFORME DEL PRODUCTO--- Nombre: {self.nombre} Costo: {self.costo} Tipo: {self.tipo} """) class Herramientas(Productos): def garantia(self): marca=input("Ingresar nombre de la marca: ",) if marca == "Stanley" or marca == "STANLEY" or marca == "stanley": garantiaP = 12 else: garantiaP = 6 print(f"-La garantia es de {garantiaP} meses") class Maquinas(Herramientas): def consumo(self): print("--Para calcular el consumo en KWH de la maquina ingrese los siguientes datos--\n") potencia=int(input("Potencia: ",)) horas_uso=int(input("Horas de uso promedio: ",)) cons= potencia*horas_uso print(f"\n-La consumo de KWH de la maquina es : {cons}") class Otros(Productos): def descripcion(self): descrip=input("Ingrese descripcion del producto: ",) print("\n\n",descrip) def salir (): desicion="p" while desicion != "N" and desicion != "n": desicion=input("Desea seguir ingresando datos(Y/N): ",) if desicion == "Y" or desicion == "y": menu() elif desicion == "N" or desicion == "n": print("\n\n-----Gracias por usar el programa-----\n\n") def menuMaquina(producto,costo,tipo): obj=Maquinas(producto,costo,tipo) print("""\n\n 1-Ver datos del producto 2-Calcular garantia 3-Calcular consumo 4-Volver al menu 5-Salir del programa """) desicion=int(input()) if desicion == 1: obj.informe() menuMaquina(producto,costo,tipo) elif desicion == 2: obj.garantia() menuMaquina(producto,costo,tipo) elif desicion == 3: obj.consumo() menuMaquina(producto,costo,tipo) elif desicion == 4: menu() else: pass def menuHerramienta(producto,costo,tipo): obj=Herramientas(producto,costo,tipo) print("""\n\n 1-Ver datos del producto 2-Calcular garantia 3-Volver al menu 4-Salir del programa """) desicion=int(input()) if desicion == 1: obj.informe() menuHerramienta(producto,costo,tipo) elif desicion == 2: obj.garantia() menuHerramienta(producto,costo,tipo) elif desicion == 3: menu() else: pass def menuOtro(producto,costo,tipo): obj=Otros(producto,costo,tipo) print("""\n\n 1-Ver datos del producto 2-Agregar una descripcion 3-Volver al menu 4-Salir del programa """) desicion=int(input()) if desicion == 1: obj.informe() menuOtro(producto,costo,tipo) elif desicion == 2: obj.descripcion() menuOtro(producto,costo,tipo) elif desicion == 3: menu() else: pass def menu(): print("\n\n************FERETERIA LA TUERCA************\n\n") producto=input("-Ingresar nombre del producto: ",) tipo=input("\n-Ingresar tipo de producto(maquina/herramienta/otro): ",) costo=int(input("\n-Ingresr costo del producto: ")) if tipo == "maquina" or tipo == "Maquina": menuMaquina(producto,costo,tipo) elif tipo == "herramienta" or tipo == "Herramienta": menuHerramienta(producto,costo,tipo) elif tipo == "otro" or tipo == "Otro": menuOtro(producto,costo,tipo) else: print("\n\n--DATOS MAL INGRESADOS--\n\n") salir() menu()
652a69f3019e6890b3fb4963e987ea49326cf08b
santiagovasquez1/Curso-python
/programa 007.py
988
4.125
4
#Pedir informacio al usuario #Usano iput #Usando raw input #Al escribir cadenas hay que ponerlas con "" """ nombre = input ("Dame tu nombre ") base_=input ("Dame la base " ) altura= input ("Dame la altura ") area = base_*altura perimetro = 2*(base_+altura) #print "Hola %s el area es %.2f y el perimetro es %.2f" %(nombre,area,perimetro) print "Hola ", nombre," el area es ",area, " y el perimetro es ",perimetro """ #Usando el raw_input mas recomendado """ nombre=str(raw_input("Dame tu nombre: ")) base=float(raw_input ("Dame la base : " )) altura=float(raw_input("Dame la altura: ")) area = base*altura perimetro = 2*(base+altura) print "Hola %s el area es %.2f y el perimetro es %.2f" %(nombre,area,perimetro) """ #Funcion type, nos indica el tipo del objeto, cuando se use raw es mejor usar el constrructor para el ingreso de las variables print "Con input" a=input ("Un valor ") print (a,type(a)) print "Ahora raw_input" b=raw_input("mismo valor ") print (b,type(b))
1353797e71e0f5b851088c1430f3bca2b4b0ee75
wjj8795/learngit
/出租计费.py
372
3.578125
4
i = 1 while i == 1: km = int(input()) if km <= 0: print ("请输入正确的公里数进行计算,程序结束") elif km > 0 and km <=2: money = 8 print (money) elif km >2 and km <=12: money = 8 + (km - 2) * 1.2 print (money) elif km > 12: money = 8 + 10 * 1.2 + (km - 12) * 1.5 print (money)
5489a44fcb5098d1cf65d91ca1bb9fbd09c8ce46
deepthi93k/icta-calicut-fullstack
/python/reverse.py
289
4.09375
4
num=int(input("Enter a number")) rev=0 while(num>0): rem=num%10 rev=rev*10+rem num=num//10 print(rev) def reverse(n): rev=0 rem=0 while(n>0): rem=num%10 rev=rev*10+rem num=num//10 return rev num=int(input("number is")) result=reverse(num) print(result)
30a690ce5f9b126d0bb19eb4005bf105a752830f
mouyleng2508/VS_Code
/Cryptography Algorithm/tempCodeRunnerFile.py
345
3.578125
4
from string import maketrans rot13trans = maketrans('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm') # Function to translate plain text def rot13(text): return text.translate(rot13trans) def main(): txt = "ROT13 Algorithm" print (rot13(txt)) if __name__ == "__main__": main()
135cccba85a1f12348d73cceff34be2ed66e54d9
nhuntwalker/code-katas
/src/find_smallest_int.py
458
4.1875
4
"""Find the smallest integer in the array (7 kyu). Given an array of integers your solution should find the smallest integer. For example: Given [34, 15, 88, 2] your solution will return 2. Given [34, -345, -1, 100] your solution will return -345. You can assume, for the purpose of this kata, that the supplied array will not be empty. """ def find_smallest_int(arr): """Return the integer with the lowest value in arr.""" return sorted(arr)[0]
0f6e5338306385788ba860aec11ecc22577a0947
GlebovAlex/2020_eve_python
/Lasya_Homework/vowel.py
753
4.40625
4
''' 1) count the number of each vowel in a string using dictionary and list comprehension. ''' # created a vowel list with all the vowel alphabets as elements vowel = ['a','e','i','o','u'] vowel_Counts = dict() userInput = input('Enter your string input here: ').lower() ''' iterated through the user provided string char by char if a char is a vowel then add that to a dictionary vowel_counts with vowel as key and count as value ''' for i in userInput: if i in vowel and i not in vowel_Counts: vowel_Counts[i] = 1 elif i in vowel and i in vowel_Counts: vowel_Counts[i] +=1 print(vowel_Counts) for alphabet,counts in vowel_Counts.items(): print(alphabet,'is repeated',counts,'times in given string')
1c9402fc06021cce1f6cde783fd33a49e21a3e31
perfsonar/pscheduler
/python-pscheduler/pscheduler/pscheduler/filestring.py
835
4.25
4
""" Functions for retrieving strings from files """ import os def string_from_file(string, strip=True): """ Return an unaltered string or the contents of a file if the string begins with @ and the rest of it points at a path. If 'strip' is True, remove leading and trailing whitespace (default behavior). """ if not isinstance(string, str): raise ValueError("Argument must be a string") if not string: # Easy case. No need to strip, either. return string if (string[0] != "@"): if string.startswith("\\@"): value = string[1:] else: value = string else: path = os.path.expanduser(string[1:]) with open(path, 'r') as content: value = content.read() return value.strip() if strip else value
bca56c6463631c1c898b73b57faa1dec1877a54a
rvcevans/adventofcode
/2015/advent5.py
1,318
3.59375
4
import os, requests strings = requests.get('http://adventofcode.com/day/5/input', cookies=dict(session=os.environ['ADVENT_SESSION'])).content.strip().split('\n') vowels = {'a', 'e', 'i', 'o', 'u'} disallowed_strings = {'ab', 'cd', 'pq', 'xy'} def vowel_count(word): count = 0 for vowel in vowels: count += word.count(vowel) return count def contains_repeated_letter(word, offset): for i in xrange(len(word) - 1 - offset): if word[i] == word[i + 1 + offset]: return True return False def contains_disallowed(word): for s in disallowed_strings: if s in word: return True return False def repeated_pair(word): for i in xrange(len(word) - 3): for j in xrange(i + 2, len(word) - 1): if word[i: i + 2] == word[j: j + 2]: return True return False def nice1(word): return vowel_count(word) >= 3 and contains_repeated_letter(word, 0) and not contains_disallowed(word) def nice2(word): return contains_repeated_letter(word, 1) and repeated_pair(word) nice1_count, nice2_count = 0, 0 for word in strings: nice1_count += nice1(word) nice2_count += nice2(word) print("Nice words for part 1: %s, Nice words for part 2: %s" % (nice1_count, nice2_count))
28c7bcdf0fb860381989b7a0af378ae36e6c94b4
ptwd/MSU_REU_ML_course
/_build/jupyter_execute/notebooks/day-4/Day_4-What_is_Tuning_and_Validation.py
4,009
3.59375
4
#!/usr/bin/env python # coding: utf-8 # # What is Tuning and Validation? # # ## 1. What have done so far? # # Thus far we have talked about two kinds of supervised machine learning problems: regression and classification. Fairly broad definitions of these two are below: # # * **Regression**: Using a set of input data to predict an outcome on some continuous scale. # * **Classification**: Using a set of input data to predict the class associated with data. # # We have used `sci-kit learn` to begin to investigate how we can model data to solve one or the other problems. We have not talked in detail as to how these models work. That is important to understand if you are going to use particular models, but beyond the scope of this short course. # # ## 2. Tuning and Validation # # Instead, we will talk about the last pieces of supervised machine learning that are needed to understand your model: tuning and validation. Broad definitions are given below: # # * **Tuning**: The process of finding the right model and hyperparamters to build an accurate model. # * **Validation**: The process by which you build confidence in your model. # # We will make use of `sci-kit learn`'s built in tools for tuning and validation. We will introduce those tools in class and we will focus on classifiers. For now, there are several useful videos to conceptually understand what we are trying to do. # ## 3. Example with a Classifier # # We will focus on classifiers because the process of tuning and validating them is a bit easier to understand at first. As we have seen we start our work with a classifier as follows: # # 1. Read in the data # 2. Clean/Transform data # 3. Select model and parameters # 4. Fit model # 5. Evaluate model with confusion matrix # # The message we want to convey is that parts 3, 4, and 5 often are part of a cyclkic process to adjust and change your model slightly to get a better prediction. *In fact, part 2 can come back also if you have to clean, encode, or impute your data differently.* # # Because all the work we are doing relies on understanding the Confusion Matrix we will start there. # ### 3.1 The Confusion Matrix # # Watch the video below. # In[1]: from IPython.display import YouTubeVideo YouTubeVideo("Kdsp6soqA7o",width=640,height=360) # ### 3.2 ROC # # We can extract additional information about the quality of our model by varying the prediction threshold. That is, we allow the model to change the probability cutoff between predicting a positive (1) and negative (0) case. These resulting Receiver Operator Curve (ROC) can offer additional evidence as to the quality of your model beyond accuracy. In the video below, ROCs are described. # In[2]: from IPython.display import YouTubeVideo YouTubeVideo("4jRBRDbJemM",width=640,height=360) # ### 3.3 Leveraging randomness # # As you might recall, we performed a data splitting when we started our modeling. That split was randomly done. So the Accuracy, ROC, and AUC were all deteermined for a single test set. What if we ran the model again? With a new random split? Would the results be similar our different? By how much? # # You can see that there's a problem with running a single model and making a claim aboout it. Because our data was randomly split, our model produces results based on that split. If that split is representative of all possible splits then maybe it is ok to trust it. But if not it is better to build a bunch of models based on a bunch of random splits. Then you will get a disrtibution of results. That can give you some confidence in the predictions the model makes with a statistical uncertainty. # # The video below talks about cross validation as one form of this. We will introduce this form and the [Monte Carlo](https://towardsdatascience.com/cross-validation-k-fold-vs-monte-carlo-e54df2fc179b) form. # # Watch the video below. # In[3]: from IPython.display import YouTubeVideo YouTubeVideo("fSytzGwwBVw",width=640,height=360) # In[ ]:
5fb31ef827e45e6e52581c11e81a6071151abc3b
DaisyKoome/Python_Scripts
/Py101.py
182
3.96875
4
name=input('Please enter your name: ') age=input('Please enter your age: ') print("The name of the person is",name,"and the age of the person is",age) input("Press enter to quit")
b71da885208f93e6ecf17c0946322a125dc4e08d
kawai-sk/Competition_programming-Python3-
/Slim_Span.py
1,082
3.53125
4
# coding: utf-8 # Slim Span,https://onlinejudge.u-aizu.ac.jp/#/problems/1280 # 右、奥 # 最小全域木の全探索です。重さ順にエッジをソートし, # 最初に繋ぐ辺として選ぶものを軽い方から順に調べます。 def root(x): r = [] while P[x] != x: r.append(x) x = P[x] for u in r: P[u] = x return x def unite(x,y,n): a = root(x) c = root(y) if a != c: if a == x: P[x] = c else: P[c] = a n += 1 return n while True: n,m = map(int,input().strip().split(" ")) if n == 0:break d = [] for _ in range(m): d.append(list(map(int,input().strip().split(" ")))) d.sort(key=lambda e:e[2]) w,s = -1,0 while s <= m - n + 1: P = [i for i in range(n+1)] t,j,v = 1,s,d[s][2] while t < n and j < m: p,q = d[j][:2] t = unite(p,q,t) if t == n:v = d[j][2]-v j += 1 if t == n and (w > v or w == -1): w = v s += 1 print(w)
59e3386bacca956914b27d45991184ef6788a976
Gilb03/bouncer
/app.py
318
4.125
4
age = input("How old are you: ") if age != "": age = int(age) if age >= 18 and age < 21: print("You can enter but need wristband") elif age >= 21 : print("You can enter and drink!") else: print("You cant come in little dude =(") else: print("Please enter an age!")
3d316938ac872e43bec981709f797c994e83be60
yandexdataschool/Practical_RL
/week04_[recap]_deep_learning/mnist.py
2,505
3.703125
4
import sys import os import numpy as np __doc__ = """taken from https://github.com/Lasagne/Lasagne/blob/master/examples/mnist.py""" def load_dataset(): # We first define a download function, supporting both Python 2 and 3. if sys.version_info[0] == 2: from urllib import urlretrieve else: from urllib.request import urlretrieve def download(filename, source='http://yann.lecun.com/exdb/mnist/'): print("Downloading %s" % filename) urlretrieve(source + filename, filename) # We then define functions for loading MNIST images and labels. # For convenience, they also download the requested files if needed. import gzip def load_mnist_images(filename): if not os.path.exists(filename): download(filename) # Read the inputs in Yann LeCun's binary format. with gzip.open(filename, 'rb') as f: data = np.frombuffer(f.read(), np.uint8, offset=16) # The inputs are vectors now, we reshape them to monochrome 2D images, # following the shape convention: (examples, channels, rows, columns) data = data.reshape(-1, 1, 28, 28) # The inputs come as bytes, we convert them to float32 in range [0,1]. # (Actually to range [0, 255/256], for compatibility to the version # provided at http://deeplearning.net/data/mnist/mnist.pkl.gz.) return data / np.float32(256) def load_mnist_labels(filename): if not os.path.exists(filename): download(filename) # Read the labels in Yann LeCun's binary format. with gzip.open(filename, 'rb') as f: data = np.frombuffer(f.read(), np.uint8, offset=8) # The labels are vectors of integers now, that's exactly what we want. return data # We can now download and read the training and test set images and labels. X_train = load_mnist_images('train-images-idx3-ubyte.gz') y_train = load_mnist_labels('train-labels-idx1-ubyte.gz') X_test = load_mnist_images('t10k-images-idx3-ubyte.gz') y_test = load_mnist_labels('t10k-labels-idx1-ubyte.gz') # We reserve the last 10000 training examples for validation. X_train, X_val = X_train[:-10000], X_train[-10000:] y_train, y_val = y_train[:-10000], y_train[-10000:] # We just return all the arrays in order, as expected in main(). # (It doesn't matter how we do this as long as we can read them again.) return X_train, y_train, X_val, y_val, X_test, y_test
116945196336be265fec1553109af3ce10b88e01
hevalhazalkurt/codewars_python_solutions
/6kyuKatas/Which_are_in.py
189
4
4
def in_array(array1, array2): arr = [] for a2 in array2: for a1 in array1: if a1 in a2 and a1 not in arr: arr.append(a1) return sorted(arr)
c9066581c2b67d35404fdfafbacb4ef76074f277
KocUniversity/comp100-2021f-ps0-ER-Mustafa
/main.py
195
3.859375
4
import math x = int(input("Enter number x: ")) y = int(input("Enter number y: ")) result = x**y print("x**y = " + str(result)) print("log(" + str(x) + ") = " + str(math.log2(x))) print("76742")
ce54bdfbd0ba728265689328bc2e08d42b5d3374
flightdutch/Python-HomeTasks
/L7.Theory/2Person.py
1,360
4.25
4
""" Person Class """ class Person: max_age = 120 # Создает объект alex - екземпляр класса Person alex = Person() # Созадем атрибуты объекта (переменные) alex.name = 'Alex' alex.age = 17 # class работает по принципу словаря: # - если чего то нет - добавить # - если это уже есть - изменить kate = Person() kate.name = 'Kate' kate.age = 16 print('Kate', kate) print(kate.name, 'is', kate.age) print(alex.name, 'is', alex.age) print(kate.name, 'is: ', kate.age, 'max: ', kate.max_age) print(alex.name, 'is: ', alex.age, 'max: ', alex.max_age) # Проверка - оба производных класса ссылаються на один и тотже атрибут одного и того же класса print(kate.max_age is alex.max_age) # Атрибуты экземпляра kate.a = 'test' # сначала атрибут ищется в текущем экземпляре класса print(kate.a) # если в текущем экземпляре класса его нет - поиск поднимается на ступень выще в производный класс print(kate.max_age) kate.max_age = 130 print(kate.max_age) # атрибуты - разные print(kate.max_age is alex.max_age)
b5ef98c5a2afa1ba5fa5dbe2b2e0e7432a0c4ee1
BarbierJeremy/ProjetS3
/SCRIPTS/Others/Methode_1/Parse_And_Filter_Sjcount.py
2,154
3.5625
4
#!/usr/bin/python3 # -*- coding: Utf-8 -*- ## For now, only keep + strand def Analyze_Count(Count) : #Open file f = open(Count, "r") Fini = False #Dictionary to get Positions Positions = {} # Loop to iterate on each line while not Fini : line = f.readline() if line == "" : Fini = True else : Line = line.split() # First Column = Position # Second = Idk # Third = Idk # Fourth = Number of reads supporting # Need to get first and last # The position of the Junction Position = Line[0][:-2] #The count of reads without the junction Support = int(Line[3]) # Put that in dictionnary Positions[Position] = Support return Positions def Analyze_Junction(Junction, Counts, Treshold, Output) : f = open(Junction, "r") g = open(Output, "w") g.write("Chromosome\tFirst Position of Junction\tSecond Position of Junction\tReads with Junction\tRead overlapping without Junction\n") Fini = False while not Fini : line = f.readline() if line == "" : Fini = True else : Line = line.split() Position = Line[0][:-2] Support = int(Line[3]) if Support > Treshold : # Get Chromosome, Position 1 and 2 of the junction Pos = Position.split("_") Chr = Pos[0] Pos1 = Pos[1] Pos2 = Pos[2] # Search for Pos1 in dictionnary To_Search = Pos[0] + "_" + Pos[1] Count = Counts[To_Search] To_Print = Chr + "\t" + Pos1 + "\t" + Pos2 + "\t" + str(Support) + "\t" + str(Count) + "\n" g.write(To_Print) def main(): import argparse parser = argparse.ArgumentParser() parser.add_argument("-ssj", "--Junction", help = "Junction file") parser.add_argument("-ssc", "--Count", help = "Count file") parser.add_argument("-t", "--treshold", help = "Beyond this treshold, we keep the junction") parser.add_argument("-o", "--output", help = "output file") args = parser.parse_args() # Test base Count = args.Count Junction = args.Junction Treshold = int(args.treshold) Output = args.output Counts = Analyze_Count(Count) Analyze_Junction(Junction, Counts, Treshold, Output) if __name__ == '__main__': main()
28cd1d7b988323094c27bcd71cffa4b369d21526
LoopSun/PythonWay
/PythonLearn/Python Basic/HelloWorld.py
402
3.6875
4
#!/user/bin/python3 #^.^ coding=utf-8 ^.^# def cute_split_line(): print("*"*20) class hello_world(): def __init__(self, want_to_say = "Hello, World"): self.want_to_say = want_to_say def __str__(self): return self.want_to_say def say(self): print("{0}.".format(self.want_to_say)) if __name__ == "__main__": human = hello_world("Hi, Mama") human.say()
25ae4dff28b7563438847248872138a24ccebfb5
Luca2460/Imeneo-Leetcodes-Solutions-in-Python
/98. Validate Binary Search Tree.py
776
4.03125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isValidBST(self, root: Optional[TreeNode]) -> bool: printed = [] def inOrder(root): if not root: return True left = inOrder(root.left) if printed: if root.val <= printed[-1]: return False printed.pop() printed.append(root.val) right = inOrder(root.right) return left and right return inOrder(root) # TIME complexity: O(N) has to visit every node # SPACE complexity: O(N) due to recursion stack
7d7079a1aa2c644574ed0d6f8428bf0f4a23b9f5
969452199/pythonproject
/day03/day03_class05.py
174
3.515625
4
i = 0 sum = 0 for i in range (0,100): i = i+1 sum = sum + i print(sum) a = 0 sum1 = 0 for a in range (0,101): if a%2 ==0: sum1 = sum1 + a print(sum1)
11014699b05e0df50b73a4c86647c90379d2e868
m0rtal/GeekBrains
/Введение в высшую математику/дз3-2.py
1,957
4.125
4
""" 1. Задание (в программе) Нарисуйте график функции: y(x) = k∙cos(x – a) + b для некоторых (2-3 различных) значений параметров k, a, b """ from math import cos, sin import matplotlib.pyplot as plt import numpy as np from random import randint x = np.linspace(-np.pi, np.pi, 101) for i in range(3): k = randint(1, 5) a = randint(1, 5) b = randint(1, 5) y = k * np.cos(x - a) + b plt.plot(x, y, label=f"y{i}") plt.legend() plt.grid(True) plt.show() plt.close() """ Напишите код, который будет переводить полярные координаты в декартовы. """ def convert_polar_to_decart(r, a): return round(r * cos(a), 2), round(r * sin(a), 2) """ Напишите код, который будет рисовать график окружности в полярных координатах. """ r = 3 a = np.linspace(0, 2 * np.pi, 100) x = r * np.cos(a) y = r * np.sin(a) plt.figure(figsize=(r * 2, r * 2)) plt.polar(x, y) plt.show() plt.close() """ Напишите код, который будет рисовать график отрезка прямой линии в полярных координатах""" x = np.linspace(0, 5, 101) y = 2 * x + 1 plt.polar(x, y) plt.show() plt.close() """ Решите систему уравнений exp(x) + x*(1 – y) = 1 y = x^2 – 1 """ from scipy.optimize import fsolve def equations(p): x, y = p return np.exp(x) + x * (1 - y) - 1, x ** 2 - y - 1 x1, y1 = fsolve(equations, (1, 1)) print(x1, y1) """ Решите систему уравнений exp(x) + x*(1 – y) - 1 > 0 y = x^2 – 1 """ def equations(p): x, y = p if np.exp(x) + x * (1 - y) - 1 > 0: return np.exp(x) + x * (1 - y) - 1, x ** 2 - y - 1 else: return None, x ** 2 - y - 1 x1, y1 = fsolve(equations, (1, 1)) print(x1, y1)
848a5804c1fb296e305b0df67d901a1b8bce5769
q-riku/Python3-basic2
/04 面向对象编程-类/Cat.py
900
4.34375
4
""" 类的创建语法: class 类名: 《代码块》 备注:类名命名规则不能以数字开头,尽量以大写字母开头; 驼峰式命名法 helloworld HelloWorld 类的调用:变量名 = 类名([是否带参]) 叫对象; 对象能干么? 答:能够调用类中所有的属性和方法; """ class Cat: def __init__(self, color, legs): #构造方法 self.color = color self.legs = legs felix = Cat("ginger", 4) rover = Cat("dog-colored", 4) stumpy = Cat("brown", 3) # print("felix:",felix.__dict__) #dict是用来存储对象属性的一个字典,其键为属性名,值为属性的值. # print("rover:",rover.__dict__) # print("stumpy:",stumpy.__dict__) class AAA: def __init__(self,name,age): self.name = name self.age = age print(str(name)+" "+str(age)) a = AAA('黄老师','18')
00cb98d470ac8ed6cc90af4498f4927108a69722
LucasKetelhut/cursoPython
/desafios/desafio036.py
598
3.953125
4
casa=float(input('Insira o valor da casa: R$')) salario=float(input('Insira o salário do comprador: R$')) anos=int(input('Em quantos anos ele irá pagar: ')) meses=anos * 12 gasto=casa/meses if (gasto > (0.3 * salario)): print('O gasto mensal será de R${:.2f} durante os próximos {} meses\nIsso é superior a 30% do seu salário!'.format(gasto,meses).replace('.',',')) print('Impossível fincanciar a casa.') else: print('O gasto mensal será de R${:.2f} durante os próximos {} meses'.format(gasto,meses).replace('.',',')) print('Você tem a opção de financiar esta casa!')
78a522aa22f3da6cc938e708c06330d7ff5b3bc2
deepatmg/toolkitten
/summer-of-code/week-01/love.py
1,114
3.953125
4
# #love affair # name = "Rebecca Fillier" # result = "" # print('result: ' + result) # # print(name[1]) # # i = 1 # # print(name[1]) # # for i in range(0,15): # # print(name[i]) # # print(len("Rebecca Fillier")) # for i in range(0, len(name)): # # print(name[i]) # if i % 2 == 0: # print(name[i]) # result = result + name[i] # print('result just changed to: ' + result) # print('The final result for all even indexed letters in name is: ' + result + '! Drumroll please!!! Thank you. I would like to thank the Academy. (Little bow)') # # "X" land, "o" water # world = "X" # # count 1 # world = "o" # # print('result is: ' + result) # # print(name[-1]) # # What happens with the other negative numbers? # # What happens if you are out of range? # # print(name[7]) # # print(name[-7]) # my_birth_month = "August" # my_birth_day = 3 # print(my_birth_month + my_birth_day) # Angry Boss print("Angry boss's reply") print("\nAngry Boss: What do you want??\n") answer = input("\nYour answer: ") reply = "WHADDAYA MEAN \""+ answer.upper() + "\"?!? YOU'RE FIRED!!" print("\nAngry Boss replied, "+ reply)
2175a11a9db96fc58f0567b1bb32e9afec9ded19
browngirlangie/Unit-4-Lesson-4
/Lesson 4/Problem 5/problem5.py
311
3.875
4
from turtle import * kitkat = Turtle() kitkat.color("green") kitkat.pensize(12) kitkat.speed(10) kitkat.shape("turtle") screen = Screen() screen.bgcolor("yellow") kitkat.forward(80) kitkat.right(50) kitkat.forward(200) kitkat.left(150) kitkat.forward(50) kitkat.circle(25) kitkat.backwards(300) mainloop()
5ee421fd43933f7ae179fdccdd4819156a67f9e3
janarqb/Week2_Day4_Logic
/Task2.py
247
4.125
4
given_number = int(input("Please insert the number:")) if given_number % 5 == 0 and given_number % 3 == 0: print('HahaHoo') elif given_number % 3 == 0: print("Haha") elif given_number % 5 == 0: print("Hoo") else: print("Aaaaa")
2670e9f33e5a6e57129b5286d289ddf68564057e
sunnysidesounds/InterviewQuestions
/amazon/longest_substring_wo_repeats.py
1,117
4.21875
4
""" Given a string, find the length of the longest substring without repeating characters. Example 1: Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: "012345" Input: "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring. """ def longest_substring_without_duplication(string): last_seen = {} longest_sub_str = [0, 1] start_index = 0 for index, char in enumerate(string): if char in last_seen: start_index = max(start_index, last_seen[char] + 1) if (longest_sub_str[1] - longest_sub_str[0]) < index + 1 - start_index: longest_sub_str = [start_index, index+1] last_seen[char] = index return string[longest_sub_str[0]:longest_sub_str[1]] if __name__ == '__main__': string = 'abcabcbb' results = longest_substring_without_duplication(string) print(results)
44bb844f9b3e20ff6710808749eaf942aefe98af
faten20/Python-Programming-1
/Week_12/TryExceptExample-1.py
208
3.8125
4
''' divide by zero error using try and axcept ''' try: x=int(input('Enter first number')) y=int(input('Enter second number')) a=x/y print(a) except : print ('divide by zero error')
a49a410103c0136ed3fe02f69e89b5c4e7aa6860
juechen-zzz/LeetCode
/python/0017.Letter Combinations of a Phone Number.py
899
4.0625
4
''' Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. Example: Input: "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. ''' class Solution: def letterCombinations(self, digits: str) -> List[str]: dt = {'1':'', '2':'abc', '3':'def', '4':'ghi', '5':'jkl', '6':'mno', '7':'pqrs', '8':'tuv', '9':'wxyz', '0':''} if len(digits) == 0: return [] elif len(digits) == 1: return [s for s in dt[digits[0]]] elif len(digits) == 2: return [a+b for a in dt[digits[0]] for b in dt[digits[1]]] else: str_list = self.letterCombinations(digits[1:]) return [a+b for a in dt[digits[0]] for b in str_list]
bb146e8cbb6f96eea4fdd8dee411ebefe1108d58
github188/note-1
/算法/merge3.py
658
4.125
4
#!/usr/bin/env python def qsort3(alist, lower, upper): print(alist) if lower >= upper: return pivot = alist[lower] left, right = lower + 1, upper while left <= right: while left <= right and alist[left] < pivot: left += 1 while left <= right and alist[right] >= pivot: right -= 1 if left > right: break # swap while left <= right alist[left], alist[right] = alist[right], alist[left] # swap the smaller with pivot alist[lower], alist[right] = alist[right], alist[lower] qsort3(alist, lower, right - 1) qsort3(alist, right + 1, upper) unsortedArray = [8,7,6,5,4,3,2,1] print(qsort3(unsortedArray, 0, len(unsortedArray) - 1))
020abbf176f7a8c33ee8cb5c46897f356de34214
Alapont/PythonConBetsy
/Gente/discoteca.py
799
3.5
4
# Discoteca unts unts class Discoteca: # Constructor por parametros def __init__(self, nombre="club momentos",aforoMaximo=100): self.nombre = nombre self.aforoMaximo=aforoMaximo self.dinero=0 self.colaEntrada=[] self.genteDentro=[] def añadirColaEntrar(self, persona): self.colaEntrada.append(persona) def intentarPasar (self): if ( len (self.genteDentro) < self.aforoMaximo): siguiente=self.colaEntrada.pop(0) if (siguiente.colorDeCalcetines != "blanco"): self.genteDentro.append(siguiente) else : # print("heute leider nicht +siguiente.nombre) print("Que te jodan "+siguiente.nombre) else: print("no hay mas hueco")
3afb658ff6b19fc1d4e17575b5a881fc94c34b3f
immzz/leetcode_solutions
/maximum product subarray.py
511
3.5625
4
class Solution(object): def maxProduct(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 current_min = nums[0] current_max = nums[0] res = nums[0] for num in nums[1:]: current_max,current_min = max(num,current_max*num,current_min*num),min(num,current_max*num,current_min*num) res = max(res,current_max) return res sol = Solution() print sol.maxProduct([-4,-3,-2])
62d20720385771bc21718bc47c13fe20d1cb8f40
PraveenMPKumar/ENG_Thesaurus
/Theasaurus_local.py
1,436
3.890625
4
import json from difflib import get_close_matches #Storing data from json file data = json.load(open("data.json")) closest_words = [] #Function to fetch the meaning def get_meaning(word): w = word.lower() if w in data: return data[w] elif w.title() in data: return data[w.title()] elif w.upper() in data: return data[w.upper()] elif if_close_match_exists(w): yn = input( "Did you mean %s instead ?, If Yes enter y, else No enter n : " % closest_words[0]) if yn == "y" or yn == "Y": return get_meaning(closest_words[0]) elif yn == "n" or yn == "N": return "The word doesn't exist, Please double check !" else: return "Invalid input, Please Try Again !" else: return "Word doesn't exists. Please double check !" #Function to check close match if typo from user def if_close_match_exists(w): closest_words.extend(get_close_matches(w, data.keys(), 5, 0.8)) return len(closest_words) > 0 print("English Theasaurus CLI App") while True: user_input = input("Enter a word :") closest_words.clear() output = get_meaning(user_input) if type(output) == list: for word in output: print(word) else: print(output) to_continue = input("Press q to quit or any other key to continue:") if to_continue == "q" or to_continue == "Q": break
b22d07e4520da41da60a2ef93c606afbc743c2cf
ClodaghMurphy/dataRepresentation
/Week3/PY03readOurFile.py
649
3.6875
4
from bs4 import BeautifulSoup with open("../Week2/carviewer2.html") as fp: soup = BeautifulSoup(fp,'html.parser')#fp = file pointer #print (soup.tr) #above command is commented out but it finds the first instance of a tr rows = soup.findAll("tr")#find all of the elements called tr for row in rows: #print("-------") #print(row)# the 3 preceeding lines would print out every instance of tr tags in turn dataList = []#tostore in a list #note the first line is an empty pair of brackets! cols = row.findAll("td") #command to find all the td tags for col in cols: dataList.append(col.text) print (dataList)
12ba0e1694347c069cbe7c0363e7f4899290ac50
natty2012/Python4Bioinformatics2020
/Notebooks/write_to_file.py
1,125
3.6875
4
def write2file(gene_list, out_file): """ Takes a gene list and writes the output to file """ with open(out_file, 'w') as outfile: outfile.write('\n'.join(gene_list)) def remove_empty(gene_list): """ Given a gene list, removes items that start with dash (empty) """ tag = True while tag: try: gene_list.remove('-') except ValueError: tag = False return gene_list def clean_genes(input_file, out_file): """ Given a chromosome annotation file, extract the genes and write them to another file """ gene_list = [] tag = False with open(input_file, 'r') as humchrx: for line in humchrx: if line.startswith('Gene'): tag=True if line == '\n': tag = False if tag: gene_list.append(line.split()[0]) #clean the gene list gene_list.pop(2) gene_list[0] = gene_list[0]+"_"+gene_list[1] gene_list.pop(1) gene_list = remove_empty(gene_list) ## Writing to file write2file(gene_list, out_file)
8042d2a6917b1ab30dac6e46160bdb1070f8c9f7
hopkeinst/Diplomado_Uniminuto_Python_2021
/041_Listas_2/041_DosListas.py
1,743
3.953125
4
import os import sys sistema_operativo = sys.platform if sistema_operativo.startswith('win'): os.system("cls") else: os.system("clear") print("LISTAS - TRABAJO CON 2 LISTAS") print("Se van a trabajar 2 listas para guardar datos de productos y cantidades.") print("\nVas a ingresar los productos a medida que se le solicite.\nSi no desea ingresar más productos ingrese 'NO' cuando se le solicite el producto.\n") productos = [] p = "" while p != "no": p = input("-> Producto: ") if p.lower() != "no": productos.append(p) cantidades = [] print("\nAhora vas a ingresar las cantidades para cada producto") for i in productos: cnt = None while cnt == None: try: str_input = input("Ingrese la cantidad para el producto {:s}: ".format(i)) cnt = int(str_input) except ValueError: try: cnt = float(str_input) except ValueError: print("-- ERROR -- Ingresaste un valor no numérico (entero o con decimales).\n\tInténtelo de nuevo.\n") cnt = None cantidades.append(cnt) print() for i in range(len(productos)): print("El producto {:s} tiene {} existencias".format(productos[i], cantidades[i])) print("\nMÍNIMAS EXISTENCIAS") minimo = 0 while minimo <= 0: try: minimo = int(input("Ingrese la cantidad mínima para todos los productos: ")) if minimo <= 0: print("-- ERROR -- Ingresaste un valor menor o igual que cero.\n\tInténtelo de nuevo.\n") except ValueError: print("-- ERROR -- Ingresaste un valor dato no numérico (entero o con decimales).\n\tInténtelo de nuevo.\n") for i in range(len(productos)): if cantidades[i] <= minimo: print("El producto {:s} debe revisarse porque tiene menos de {:d} productos (actualmente {} cantidad).".format(productos[i], minimo, cantidades[i])) print()
9677ad4975192e4904d1ed15d32ac3b631eedfc8
pukkapies/geninterp
/geninterp/factors.py
13,406
3.96875
4
__author__ = 'Kevin Webster' import copy def prime_factors(n): """ Factors n into primes :param n: An integer :return: A list of prime factors of n. If n = 1, return [] """ assert n >= 1 if n == 1: return [] else: i = 2 factors = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(i) if n > 1: factors.append(n) return sorted(factors) def prime_factors_list(alist, sort=True): """ Factors each element of alist into primes :param alist: a list of positive integers :param sort: option to sort the return list :return: a list containing all prime factors of all elements in alist """ assert isinstance(alist, list) if len(alist) == 0: return [] else: return_list = [] for item in alist: return_list.extend(prime_factors(item)) if sort: return sorted(return_list) else: return return_list def gcd(a, b): """ Return greatest common divisor using Euclid's Algorithm. :param a: a nonzero integer :param b: a nonzero integer """ assert a != 0 and b != 0 a_temp = abs(a) b_temp = abs(b) while b_temp: a_temp, b_temp = b_temp, a_temp % b_temp return a_temp def gcdd(*args): """ Return gcd of args :param args: A number of integers :return: gcd of args. If args is only 1 element, return that element """ templist = [] for arg in args: templist.append(arg) assert len(templist) >= 1 if len(templist) == 1: return abs(templist[0]) else: answer = gcd(templist[0], templist[1]) for index in range(2, len(templist)): answer = gcd(answer, templist[index]) return answer def lcm(a, b): """ Return lowest common multiple. :param a: an integer :param b: an integer """ return a * b // gcd(a, b) def lcmm(*args): """Return lcm of args.""" answer = 1 for arg in args: answer = lcm(answer, arg) return answer """ print('gcdd(21,6,12) = ', gcdd(21,6,12)) print('gcdd(*[40, 24, 36, 112]) = ', gcdd(*[40, 24, 36, 112])) alist = [2, 330, 1420012, 42, 80] print('alist = ', alist) print('all prime factors (sorted) = ', prime_factors_list(alist)) print('') alist[2:3] = prime_factors(alist[2]) print('3rd element factored: ',alist) """ def prod_div_quotient_rem(alist, divisor): """ Calculates the quotient and remainder from dividing the product of elements in alist with divisor The method used does not actually multiply out the elements of alist - the function is intended to be used for situations where the product is very large :param alist: a list of nonnegative integers :param divisor: an integer :return: a list of two elements, the quotient and remainder. """ assert isinstance(alist, list) for element in alist: assert element >= 0 if len(alist) == 0: return [0, 0] elif len(alist) == 1: return [alist[0] // divisor, alist[0] % divisor] else: answer = [0, 0] quotient1 = alist[0] // divisor remainder1 = alist[0] % divisor for i in range(1, len(alist)): quotient2 = alist[i] // divisor remainder2 = alist[i] % divisor answer[0] = (quotient1 * quotient2 * divisor) + (quotient1 * remainder2) + ( quotient2 * remainder1) + ((remainder1 * remainder2) // divisor) answer[1] = (remainder1 * remainder2) % divisor answer[0] += answer[1] // divisor quotient1 = answer[0] remainder1 = answer[1] return answer def prod_div_rem(alist, divisor): """ Calculates the remainder from dividing the product of elements in alist with divisor The method used does not actually multiply out the elements of alist - the function is intended to be used for situations where the product is very large :param alist: a list of nonnegative integers :param divisor: an integer :return: the remainder """ assert isinstance(alist, list) for element in alist: assert element >= 0 if len(alist) == 0: return 0 elif len(alist) == 1: return alist[0] % divisor else: answer = 0 remainder1 = alist[0] % divisor for i in range(1, len(alist)): remainder2 = alist[i] % divisor answer = (remainder1 * remainder2) % divisor remainder1 = answer return answer """ # Example alist = [7,8,5] print(prod_div_quotient_rem(alist, 3)) # [93, 1] print(prod_div_rem(alist, 3)) # 1 alist2 = [2,3,7,8,9,8,9,10,11,13,17,23] print(prod_div_quotient_rem(alist2, 29)) # [4197870918, 18] print(prod_div_rem(alist2, 29)) # 18 """ def prod_sum_divisible(list_of_lists, divisor): """ Calculates if sum of products in list_of_lists is divisible by divisor, without multiplying out product terms (intended for large numbers) :param list_of_lists: Each sublist represents a product :param divisor: an integer :return: Boolean """ assert isinstance(list_of_lists, list) lol_copy = copy.deepcopy(list_of_lists) remainder = 0 for l in lol_copy: # First check if all elements are nonnegative sign = 1 for index in range(len(l)): if l[index] < 0: sign *= -1 l[index] *= -1 if sign == 1: remainder += prod_div_rem(l, divisor) else: remainder -= prod_div_rem(l, divisor) remainder = remainder % divisor return remainder == 0 """ # Example lol = [[7,8,5], [8, 10, -1], [10]] print(prod_sum_divisible(lol, 6)) # True print(prod_sum_divisible(lol, 8)) # False lol2 = [[9,10,11,16], [10,11,-48], [11, 96, 1], [96, -1, 1]] print(prod_sum_divisible(lol2, 90)) # True print(prod_sum_divisible(lol2, 7)) # False lol3 = [[15,14,13,12,11,384], [15,14,13,12,-1920], [15,14,13,7680], [15,14,-23040], [15,46080], [-46080], []] print(prod_sum_divisible(lol3, 15*14*13*12*11)) # True print(prod_sum_divisible(lol3, 49)) # False """ def prod_sum_divide(list_of_lists, divisorlist): """ Divides sum of products in list_of_lists by divisor, without multiplying out products !!!Assumes that sum of products in list_of_lists is divisible by prod(divisor)!!! :param list_of_lists: a list of lists of integers :param divisorlist: a list of positive divisors to divide into list_of_lists :return: a list of lists that is equal to sum([prod(sublist) for sublist in list_of_lists]) / prod(divisor) """ assert isinstance(list_of_lists, list) lol_copy = [] # First convert all sublists into prime factors. Any products that are negative get -1 at the beginning # Any empty sublists are removed for sublist in list_of_lists: sign = 1 zero_flag = 0 # To catch any zeros in sublists new_sublist = [] for index in range(len(sublist)): if sublist[index] < 0: sign *= -1 if sublist[index] == -1: pass # -1 will be appended later because sign = -1 else: new_sublist.extend(prime_factors(-sublist[index])) elif sublist[index] == 0: zero_flag = 1 else: if sublist[index] == 1: new_sublist.extend([1]) else: new_sublist.extend(prime_factors(sublist[index])) if len(sublist) == 0: continue if sign == -1: new_sublist.append(-1) new_sublist.sort() if not zero_flag: lol_copy.append(new_sublist) # Now divide each sublist by divisor #print('lol_copy = ', lol_copy) divisorlist = prime_factors_list(divisorlist) for divisor in divisorlist: assert divisor > 0 if divisor == 1: continue appended_lists = [] # Extra lists to add to lol_copy single_remainders = 0 # Take care of remainders for this divisor for sublist in lol_copy: if divisor in sublist: if len(sublist) > 1: sublist.remove(divisor) else: sublist[0] = 1 elif len(sublist) == 0: continue elif sublist[-1] < 0: if (-sublist[-1] // divisor) != 0: appended_lists.append([-(-sublist[-1] // divisor)]) single_remainders -= -sublist[-1] % divisor sublist.pop() else: while len(sublist) > 1: rem = sublist[-1] % divisor sublist[-1] = sublist[-1] // divisor if sublist[-1] != 0: appended_lists.append(list(sublist)) sublist.pop() sublist[-1] *= rem # Now sublist has length 1 if sublist[0] < 0: if (-sublist[0] // divisor) != 0: appended_lists.append([-(-sublist[0] // divisor)]) elif sublist[0] // divisor != 0: appended_lists.append([sublist[0] // divisor]) if sublist[0] < 0: single_remainders -= -sublist[0] % divisor else: single_remainders += sublist[0] % divisor sublist.pop() lol_copy.extend(appended_lists) assert not single_remainders % divisor if single_remainders: lol_copy.append([single_remainders // divisor]) # Clean up - remove any empty lists, single digit lists and 1's from lists for ind1 in range(len(lol_copy)): if len(lol_copy[ind1]) == 0: continue all_ones = 1 any_one = 0 one_indices = [] for ind in range(len(lol_copy[ind1])): if lol_copy[ind1][ind] != 1: all_ones = 0 else: any_one = 1 one_indices.append(ind) if all_ones == 1: lol_copy[ind1] = [1] elif any_one == 1: for ind in reversed(one_indices): lol_copy[ind1].pop(ind) remove_indices = [] single_digits = 0 for ind in range(len(lol_copy)): if lol_copy[ind] == []: remove_indices.append(ind) if len(lol_copy[ind]) == 1: remove_indices.append(ind) single_digits += lol_copy[ind][0] for ind in reversed(remove_indices): lol_copy.pop(ind) if single_digits: if single_digits == 1: lol_copy.append([single_digits]) elif single_digits < 0: if single_digits == -1: lol_copy.append([single_digits]) else: lol_copy.append([-1] + prime_factors(-single_digits)) else: lol_copy.append(prime_factors(single_digits)) return lol_copy def prod_sum_eval(list_of_lists): """ Evaluates sum of products of sublists :param list: list of lists of numbers :return: sum of product of sublist elements """ assert isinstance(list_of_lists, list) total = 0 for sublist in list_of_lists: assert isinstance(sublist, list) if len(sublist) > 0: prod = 1 for item in sublist: prod *= item total += prod return total """ # Example lol = [[1,7,8,5],[8,-10],[], [10, 1]] print(prod_sum_divide(lol, [6])) print('total = ', prod_sum_eval(prod_sum_divide(lol, [6]))) print('\n********************************************\n') lol2 = [[9,10,11,16],[10,11,48,-1],[11,96,-1,1,-1], [96,-1,1]] print(prod_sum_divide(lol2, [8,9,5])) print('total = ', prod_sum_eval(prod_sum_divide(lol2, [8,9,5]))) print('\n********************************************\n') lol3 = [[],[10,11,1,1],[11,14,1],[96,1,1]] print(prod_sum_divide(lol3, [8,9,5])) print('total = ', prod_sum_eval(prod_sum_divide(lol3, [8,9,5]))) print('\n********************************************\n') lol4 = [[15,14,13,12,11,0], [15,14,13,12,7], [15,14,13,126], [15,14,1422], [15,10872], [46080]] print(prod_sum_divide(lol4, [15,14,13,12,11])) print('total = ', prod_sum_eval(prod_sum_divide(lol4, [15,14,13,12,11]))) #print(prod_sum_divide(lol4, [15,14,13,12,11,10])) # Throws an error since lol4 is not divisible by this print('\n********************************************\n') lol5 = [[2, 2, 5, 7, 11], [-1, 2, 3, 7, 11], [2, 2, 3, 7], [-1, 7]] print(prod_sum_divide(lol5, [5])) print('total = ', prod_sum_eval(prod_sum_divide(lol5, [5]))) print('\n********************************************\n') lol6 = [[3, 7, 11, 11, 2], [3, 7, 11, 6], [3, 7, 6], [3, 4], [-1, 2, 2, 3, 7, 11, 2], [-1, 2, 2, 3, 7, 6], [-1, 2, 2, 3, 4], [-1, 2], [3, 7, 11, 2], [3, 7, 6], [3, 4], [-1, 2, 3, 7, 2], [-1, 2, 3], [-1, 2], [3, 2], [1]] print('total before dividing: ', prod_sum_eval(lol6)) print(prod_sum_divide(lol6, [11])) print('total = ', prod_sum_eval(prod_sum_divide(lol6, [11]))) """
936a33418e02ae427e0b2aaecbb89069c2b6e7e1
cramer4/Python-Class
/Chapter_11/homework_11_3.py
391
3.859375
4
class Employee: def __init__(self, first, last, salary): self.first_name = first self.last_name = last self.salary = salary def raise_salary(self, money=""): if money: self.salary += money else: self.salary += 5000 print(self.salary) jj = Employee("jordan", "jamsey", 5000) jj.raise_salary()
ba1164c174eeb0a25f119c217480d6753e71bf0a
EricSchles/phd_algorithms
/cuny_gc/chapter2/find_sum.py
550
3.640625
4
def binary_search(arr, value): if len(arr) == 1 and arr[0] != value: return False if arr[0] == value: return True mid_point = len(arr)//2 if value < arr[mid_point]: return binary_search(arr[:mid_point], value) else: return binary_search(arr[mid_point:], value) def find_sum(s, x): for elem in s: value = x - elem if binary_search(s, value): return 1 return -1 if __name__ == '__main__': s = list(range(1000)) x = 1500 print(find_sum(s, x))
ee1ee956a4ac929a80bcae9dde91aae39b79e371
manuel-garcia-yuste/ICSR3U-4-02-Python
/Whileloop2.py
482
4.28125
4
#!/usr/bin/env python3 # Created by: Manuel Garcia Yuste # Created on : October 2019 # This program do a while loop def main(): # variables answer = 1 counter = 1 # input number = int(input("Enter a number to loop it and add its results: ")) # process & output while counter <= number: answer = answer * counter counter = counter + 1 print("The multiplication of all the numbers is {}".format(answer)) if __name__ == "__main__": main()
17b943b3a445113135d3995d736d95b231bfed5f
arthurcorreiasantos/pi-web-full-stack
/01 - Coding Tank/01 - Exercícios/12 - Aula/3 - até 0.py
198
3.890625
4
lista = [] num = int(input('Digite um número inteiro: ')) while num != 0: lista.append(num) num = int(input('Digite outro número inteiro: ')) print('Você digitou', len(lista), 'números')
cf241538ba1dd67e65a0586ed8d9b95b2699103d
IndraSigicharla/Python-Code
/Small_Code/sorting_algos/selection_sort.py
254
3.640625
4
a = [int(input()) for _ in range(10)] def sorter(lst): for i in range(len(lst)): mn = i for j in range(i+1, len(a)): if lst[mn] > lst[j]: mn = j lst[i], lst[mn] = lst[mn], lst[i] sorter(a) print(a)
e494609dd7cf28d3203b8a68932acdca644d1250
Howmuchadollarcost/INF1100
/ball_table1.py
700
3.625
4
g = 9.81 v_0 = 5 n = 5 stop = 2*v_0/g #last dt = stop/n #uniformally spaced interval print("For loop:") print("----------------------") print("V0 : t") for i in range(0,n+1): t = i*dt y = v_0*t - 0.5*g*t**2 print("....................") print("%.2f : %.2f" %(t,y)) print("|----------------------|") i=0 print("While Loop:") print("----------------------") print("V0 : t") while(i < n+1): t= i*dt y = v_0*t - 0.5*g*t**2 print("....................") i+=1 print("%.2f : %.2f" %(t,y)) print("|----------------------|") """ or t = 0 eps = 1e-10 while t<t_stop+eps: y = v_0*t - 0.5*g*t**2 print("%.2f : %.2f" %(t,y) t+=dt """
4e5c07813377bb71c3ed7b4afef1f58e0170940e
Nanutu/python-poczatek
/module_2/zad_58/homework/main.py
868
3.796875
4
# Zabezpiecz listę pozycji w zamówieniu i łączną wartość zamówienia przed utratą spójności. # # W tym celu: # # Zamień listę pozycji w zamówieniu na zmienną prywatną. # Zamień również metodę obliczającą łączny koszt zamówienia na prywatną. # Dodaj metodę publiczną umożliwiającą dodanie nowego produktu do zamówienia # (potrzebne będą informacje o produkcie i ilości). # Pamiętaj wywołać ponownie przeliczenie łącznej wartości zamówienia. from shop.order import generate_order, Order from shop.product import Product def run_homework(): first_order = generate_order() print(first_order) cookies = Product(name="Cookies", category_name="Food", unit_price=5) first_order.add_product_to_order(cookies, quantity=10) print(first_order) if __name__ == '__main__': run_homework()
bfb12b34b42e08e6ad746a4e1cfdd9a6792ca387
Liveo123/base64Hack
/base64.py
1,412
3.765625
4
# Description: Convert base64 to ASCII based on the RFC 3528 scheme # Author: Paul Livesey # Usage: base64.py filename import pdb # Function to convert a single base64 character to it's # numeric equivalent def cnvtToAsc(letter): for i in range(0, len(b64Table)-1): if b64Table[i] == letter: return i # if letter is not found, return -1 return -1 # Create base64 character data structure charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' pad = '=' # Take each character and add to array. b64Table = [] counter = 0 pdb.set_trace() for letter in charset: b64Table.append(letter) counter += 1 pdb.set_trace() print('b64Table[63] = ' + b64Table[63]) # Loop through characters 4 letters at a time... # For now just get 1st 4 quartet = 'abdr' # Take 1st of 4, get base 64 conversion, and shift left 2. letter1Code = cnvtToAsc(quartet[0]) letter1Code = letter1Code << 2 pdb.set_trace() # Take 2nd of 4, get base64 conversion, AND final 2 bits out, shift to lowest places and OR with 1st temp = cnvtToAsc(quartet[1]) twoBits = temp & 192 #11000000 twoBits = twoBits >> 6 letter1Code = letter1Code | twoBits # Take 2nd conversion again, AND out lowest 4 bits and shift 4 to the left # Take 3rd of 4, get base64 conversion, AND final 4 bits out, shift to lowest places and OR with 2nd # Take 3rd conversion again, AND out lowest 4 bits and shift
b834c14861457187b272ca8b02bce828a0c51f03
patdriscoll61/Practicals
/Practical01/Workshop02/taskThree.py
368
4.125
4
# Discount Calculator DISCOUNT_PERCENT = .20 # .2 is 20% def main(): full_price = float(input("Enter Full Price: ")) discounted_price = calculate_discount(full_price) print("Discounted Price: ", discounted_price) def calculate_discount(full_price): discounted_price = full_price - full_price * DISCOUNT_PERCENT return discounted_price main()
6e106e60b4350f1c6e97e97bf740d5d1492f19d1
ahmetakcan/python_proj
/defloraiton.py
116
3.765625
4
x = 0 for i in range(0, 10): x = x + i print(x) # i ve 1 ile ayrıca dene farkı gör # 0,1,2,3,4,5,6,7,8,9
23da1fede8f5d21d16b0728bda41ca1e6250f80c
pimoroni/scroll-phat
/examples/count.py
656
3.546875
4
#!/usr/bin/env python import sys import time import scrollphat if(len(sys.argv) == 1): print(""" Scroll pHAT - Count Counts up to <number> Usage: {} <number> Number should be under 999. """.format(sys.argv[0])) sys.exit(-1) val = int(sys.argv[1]) if(val > 999): print("Number must be under 999 to fit on screen") sys.exit(-1) scrollphat.set_brightness(7) print(""" Scroll pHAT - Count Counting up to {} Press Ctrl+C to exit! """.format(val)) for x in range(1, val + 1): try: scrollphat.write_string(str(x)) time.sleep(0.35) except KeyboardInterrupt: scrollphat.clear() sys.exit(-1)
d0979f20e0940d7a2d5e7215d458ab8a3d1190a6
Austin-Buchanan/MealGeneratorApp
/mealApp.py
2,526
4.0625
4
import random print("Welcome to Austin's Meal App!") mealList = [] done = False # load data from mealData.txt to mealList inFile = open('mealData.txt') for line in inFile: mealList.append(line.strip()) inFile.close() def suggestMeal(mealList): "This suggests a random meal in the meal list to the console." index = random.randint(0, len(mealList) - 1) print("This app suggests " + mealList[index] + "\n") return def addMeal(mealList): "This adds a user-selected meal to the meal list." newMeal = input("Please enter the name of the new meal.\n") mealList.append(newMeal) print("Added " + mealList[len(mealList) - 1] + " to the meal list.\n") return def viewMeals(mealList): "This prints the current meals in the meal list to the console." for meal in mealList: print(meal) print('') return def editMeals(mealList): "This allows user to remove or rename meals in list." badMeal = input("Please enter the name of the meal you want to edit.\n") if not badMeal in mealList: print("Could not find " + badMeal) return else: choice = input("Please enter the number of your choice: 1. Rename 2. Remove\n") choice = int(choice) if choice == 1: goodMeal = input("Please enter the new name for " + badMeal + "\n") for meal in mealList: if badMeal == meal: mealList[mealList.index(meal)] = goodMeal print("Renamed " + badMeal + " to " + meal + '.\n') return elif choice == 2: for meal in mealList: if badMeal == meal: mealList.remove(meal) print("Removed " + badMeal + '.\n') return else: print("Something went wrong.\n") return def save(mealList): file = open('mealData.txt', 'w') for meal in mealList: file.write(meal + '\n') file.close() while not done: selection = input('Please enter the number of your selection: 1. Get a Suggestion 2. Add a Meal 3. View Meals 4. Edit Meals 5. Save and Exit\n') selection = int(selection) if selection == 1: suggestMeal(mealList) elif selection == 2: addMeal(mealList) elif selection == 3: viewMeals(mealList) elif selection == 4: editMeals(mealList) elif selection == 5: save(mealList) done = True else: print("something went wrong")
635067cd98830099abb2e1c7aa6d839e788794d9
qaidjohar/PythonCourse
/23_sqlite/2_createTable.py
927
3.9375
4
import sqlite3 from sqlite3 import Error def create_connection(db_file): """ create a database connection to a SQLite database """ conn = None try: conn = sqlite3.connect(db_file) print(sqlite3.version) except Error as e: print(e) return conn def create_table(conn, create_table_sql): try: c = conn.cursor() c.execute(create_table_sql) except Error as e: print(e) if __name__ == '__main__': conn = create_connection("pythonsqlite.db") table_query = """ CREATE TABLE IF NOT EXISTS customers ( id INT AUTO_INCREMENT PRIMARY KEY, name text, address text); """ # create tables if conn is not None: # create projects table create_table(conn, table_query) else: print("Error! cannot create the database connection.")
f8719ddb784837a42ca37088b2ae87c5faa4df75
ipeksargin/data-structures-algorithms
/arrays/convertAsci.py
373
3.921875
4
#Asci numaralarına gore harfleri buyukten kucuge siralar. def sort_str(s): s = list(s) print(s) arr = [] secondArr = [] for i in range(len(s)): x = ord(s[i]) arr.append(x) arr.sort() #print(arr) for k in range(len(arr)): char = chr(arr[k]) secondArr.append(char) print(secondArr) sort_str("hello")
eb62193d81298342a620c5a4019c6efbc1c55b72
GeoffreyRe/python_exercices
/exercice_utilisation_objet_par_un_objet/utilisation_objet.py
1,221
4.09375
4
# Réalisation d'un petit exercice d'un objet de la classe "Rectangle" qui utilise un objet de la classe "Point". #Création des deux classes class Point(object): "définition d'un point géométrique" class Rectangle(object) : "définition d'une classe de rectangle" # instanciation de la classe Rectangle + attributs "largeur", "hauteur" et "coin" boite = Rectangle() boite.largeur = 50.0 boite.hauteur = 35.0 boite.coin = Point() # coin inférieur gauche ( = instanciation d'un objet à l'intérieur d'un autre objet) boite.coin.x = 12.0 # attribut x de l'objet coin de la classe Point boite.coin.y = 27.0 # attribut y de l'objet coin de la classe Point # définition d'une fonction qui "retourne" un objet de la classe Point et qui prend en paramètre un objet de la classe Rectangle # cet objet "p" n'est rien d'autre que le centre de l'objet de la classe rectangle def trouver_centre(box): p = Point() p.x = box.coin.x + box.largeur/2 p.y = box.coin.y + box.hauteur/2 return p p = trouver_centre(boite) # on capture cet objet dans une variable "p" print("le point au centre du rectangle se trouve aux coordonnées (",p.x ,",", p.y, ")") # affichage des coordonnées du centre du rectangle
531f016a5492c3e425f49862eab6ce7d9e3fe93d
fefa4ka/schema-library
/analog/current/Gain/__init__.py
3,552
3.5
4
from bem.abstract import Electrical, Network from bem.analog.voltage import Divider from bem.basic import Resistor from bem.basic.transistor import Bipolar from bem import Net, u, u_Ohm, u_V, u_A class Base(Electrical(), Network(port='two')): """**Emitter-Follower** Common-Collector Amplifier The circuit shown here is called a common-collector amplifier, which has current gain but no voltage gain. It makes use of the emitter-follower arrangement but is modified to avoid clipping during negative input swings. The voltage divider (`R_s` and `R_g`) is used to give the input signal (after passing through the capacitor) a positive dc level or operating point (known as the quiescent point). Both the input and output capacitors are included so that an ac input-output signal can be added without disturbing the dc operating point. The capacitors, as you will see, also act as filtering elements.” * Paul Scherz. “Practical Electronics for Inventors, Fourth Edition """ V = 10 @ u_V # I_load = 0.015 @ u_A # R_load = 1000 @ u_Ohm I_in = 0 @ u_A R_e = 0 @ u_Ohm Beta = 100 pins = { 'v_ref': True, 'input': ('Signal', ['output']), 'gnd': True } def willMountbunt(self): """ R_in -- `1/R_(i\\n) = 1/R_s + 1/R_g + 1 / R_(i\\n(base))` R_e -- `R_e = V_e / I_(load)` V_je -- Base-emitter built-in potential V_e -- `V_e = V_(ref) / 2` V_b -- `V_b = V_e + V_(je)` I_in -- `I_(i\\n) = I_(load) / beta` R_in_base_dc -- `R_(i\\n(base),dc) = beta * R_e` R_in_base_ac -- `R_(i\\n(base),ac) = beta * (R_e * R_(load)) / (R_e + R_(load))` """ self.load(self.V) def circuit(self): R = Resistor() is_ac = 'ac' in self.mods.get('coupled', []) is_compensating = 'compensate' in self.mods.get('drop', []) self.V_e = self.V / 2 self.R_e = self.V_e / self.I_load if is_compensating: self.R_e = self.R_e * 2 amplifier = Bipolar( type='npn', common='emitter', follow='emitter')( emitter = R(self.R_e) ) self.V_b = self.V_e + amplifier.V_je self.I_in = self.I_load / amplifier.Beta self.R_in_base_dc = amplifier.Beta * self.R_e self.R_in_base_ac = amplifier.Beta * ((self.R_e * self.R_load) / (self.R_e + self.R_load)) stiff_voltage = Divider(type='resistive')( V = self.V, V_out = self.V_b, Load = self.I_in ) stiff_voltage.gnd += self.gnd self.R_in = R.parallel_sum(R, [self.R_in_base_ac if is_ac else self.R_in_base_dc, stiff_voltage.R_in, stiff_voltage.R_out]) if is_compensating: compensator = Bipolar( type='pnp', common='collector', follow='emitter')( emitter = R(self.R_e) ) compensator.v_ref += self.v_ref compensator.gnd += self.input_n or self.gnd compensated = Net('CurrentGainCompensation') rc = self.v_ref & stiff_voltage & self.input & compensator & compensated self.output = compensated else: rc = self.v_ref & stiff_voltage & self.input amplified = Net('CurrentGainOutput') amplifier.v_ref += self.v_ref amplifier.gnd += self.input_n or self.gnd gain = self.output & amplifier & amplified self.output = amplified
f9fad04ebfa6d0709e481ff98b44b5028431aca2
graalumj/CS362-HW4
/Q2/test_average.py
586
3.578125
4
import unittest import average class test_average(unittest.TestCase): # Test whole number average def test_avg_whole(self): self.assertEqual(average.avg([2,2,2,2]), 2) # Test floating point average def test_avg_floating(self): self.assertEqual(average.avg([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 5.5) # Test string list def test_avg_string(self): self.assertEqual(average.avg(['a', 'b', 'c', 'd', 'e']), 'f') # Test empty list def test_avg_empty(self): self.assertEqual(average.avg([]), 0) if __name__ == '__main__': unittest.main()
6c365caa2b276fdeff09dd5e1c9d11674e47ce3b
jefftoppings/wizard-scorekeeper
/play_in_console.py
2,026
3.703125
4
from player import * from game import * from hand import * from calculate import * if __name__ == '__main__': print("*** Welcome to Wizard Scorekeeper! ***\n") # obtain the number of players valid_input = False num_players = 0 while not valid_input: num_players = int(input("How many players will be playing? ")) if 3 <= num_players <= 6: valid_input = True else: print("Wizard requires 3-6 players.") # obtain names of players and create list of player objects player_list = [] for x in range(num_players): name = input("Enter Player " + str(x + 1) + "'s Name: ") player_list.append(Player(name)) # initialize the game game = Game(player_list) print() game_over = False while not game_over: print("Hand", game.current_hand, "of", game.number_of_hands) print() # obtain bids from everyone bids = [] for player in game.players: bid = int(input("Enter Bid for " + player.name + ": ")) bids.append(Hand(player, bid)) # determine who was correct correct = [] print() print("Input '0' for Correct, or the Number of Tricks Missed By") for player in game.players: c = int(input(player.name + ": ")) correct.append(c) # update scores game.update_scores(bids, [int(x) for x in correct]) # print summary of scores print() print("*** SCORE UPDATE ***") print(game, end="") print("********************") print() # determine if game is over if game.current_hand > game.number_of_hands: print() winner = None max_score = 0 for player in game.players: if player.score > max_score: max_score = player.score winner = player.name print("The winner is", winner + "!") game_over = True
3ee8bc93193fbbae19489913246bf3df9a1100a2
gbvsilva/algorithm_toolbox
/week3_greedy_algorithms/3_car_fueling/myCar_fueling.py
455
3.6875
4
# python3 import sys def compute_min_refills(distance, tank, stops): # write your code here min_refills = 0 last_stop = 0 stops.append(distance) for i in range(len(stops)-1): if stops[i] + tank < stops[i+1]: return -1 if tank + last_stop < stops[i+1]: min_refills += 1 last_stop = stops[i] return min_refills if __name__ == '__main__': d, m, _, *stops = map(int, sys.stdin.read().split()) print(compute_min_refills(d, m, stops))
1d1553e3a91c46c61410294da6e2e40c2a989f29
satishr1999/slide-show-presentation
/main.py
2,174
3.578125
4
# Slide-Show Presentation #importing cycle from itertools library from itertools import cycle #importing Tkinter library as tk import tkinter as tk #importing Image from PIL library from PIL import Image #importing ImageEnhance from PIL library from PIL import ImageEnhance #defining slides class class slides(tk.Tk): def __init__(self, image_files, x, y, delay): tk.Tk.__init__(self) self.geometry('+{}+{}'.format(x, y)) self.delay = delay self.pictures = cycle((tk.PhotoImage(file=image), image) for image in image_files) self.picture_display = tk.Label(self) self.picture_display.pack() def show_slides(self): img_object, img_name = next(self.pictures) self.picture_display.config(image=img_object) self.title(img_name) self.after(self.delay, self.show_slides) self.title("Slides") def run(self): self.mainloop() #inserting effects image = Image.open('1.jpg') image.save('1.gif') enhancer = ImageEnhance.Brightness(image) brighter_image = enhancer.enhance(2) darker_image = enhancer.enhance(0.5) brighter_image.save('x1.gif') darker_image.save('y1.gif') image = Image.open('2.jpg') image.save('2.gif') enhancer = ImageEnhance.Brightness(image) brighter_image = enhancer.enhance(2) darker_image = enhancer.enhance(0.5) brighter_image.save('x2.gif') darker_image.save('y2.gif') image = Image.open('3.jpg') image.save('3.gif') enhancer = ImageEnhance.Brightness(image) brighter_image = enhancer.enhance(2) darker_image = enhancer.enhance(0.5) brighter_image.save('x3.gif') darker_image.save('y3.gif') image = Image.open('4.jpg') image.save('4.gif') enhancer = ImageEnhance.Brightness(image) brighter_image = enhancer.enhance(2) darker_image = enhancer.enhance(0.5) brighter_image.save('x4.gif') darker_image.save('y4.gif') a = ['1.gif', 'y1.gif', 'x2.gif', '2.gif', 'y2.gif', 'x3.gif', '3.gif', 'y3.gif', 'x4.gif', '4.gif', 'y4.gif'] delay = 800 x = 100 y = 50 display = slides(a, x, y, delay) display.show_slides() display.geometry("600x400") display.run()
40877a380f403dcfb92b5359021b2b248cead2f0
rafaelperazzo/programacao-web
/moodledata/vpl_data/148/usersdata/264/86629/submittedfiles/testes.py
250
3.78125
4
# -*- coding: utf-8 -*- #COMECE AQUI ABAIXO n= int(input('Digite o número de temos:')) numerador=1 denominador=1 soma=0 i=1 while (i<=n): if (i%2)==0: soma= soma- (i)/(i*i) else: soma= soma+ (i)/(i*i) print ('%.5f' %soma)
54abdf15a0b388f1d0233681c5f5251968b0fe2f
dccdis/riga
/prototype.py
1,086
3.71875
4
#!/usr/bin/python ''' Usage: argv[1] = accounts file argv[2] = max password length to iterate ''' import sys import string from hashlib import md5 def passwdgenerator(maxlength): validchars = string.printable[:94] if (maxlength == 0): yield tuple() return for x in validchars: for y in passwdgenerator(maxlength-1): yield tuple(x)+y def parseaccounts(accountfile): accounts = [] for line in open (accountfile, 'r'): (username, salt, hashvalue) = line.split('|') accounts.append((hashvalue.strip(), str(int(salt, 16)), username)) return accounts accounts = parseaccounts(sys.argv[1]) pwmaxlen = 1 + int(sys.argv[2]) for length in range (0, pwmaxlen): for i in passwdgenerator(length): password = ''.join(i) for nextuser in accounts: (hashvalue,salt,username) = nextuser h = md5() h.update(password) h.update(salt) if (h.hexdigest() == hashvalue): print "Found password: \t" + username + "/" + password
a04d9779f9635ca9551eb6b3d9bb10e04398cc9c
EllaAurora/Learning1
/Computer.py
683
3.609375
4
global ratel, rate5, rate15 rate1 = 5.57 rate5 = 11.75 rate15 = 28.49 function parcelCost(weight) overWeight = "Too Heavy, parcel rates do not apply" underWeight = "Send as package, not parcel" if weight >= 20 then theCost = overWeight elseif weight >=15 then theCost = str(rate5) elseif weight >= 1 then theCost = str(rate1) else theCost = underWeight endif return theCost end function //main program parecelWeight = float(input("Enter parecl weight: ") while parcelWeight != 0: print("Postage cost: ", parcelCost(parcelWeight)) parcelWeight = float(input("Enter parcel weight: ")) endwhile.
f777e02cdcb43748441b3d1213b0e8b78222101e
akashadr/Albanero-Hackweek
/Q37.py
361
3.84375
4
def Decimal_To_Binary(DN): if(DN==0 or DN==1): return DN else: BN="" while(DN>0): BN=str(DN%2)+BN DN=DN//2 return int(BN) if __name__=="__main__": N = int(input()) L = list() for i in range(N+1): X=Decimal_To_Binary(i) Y=str(X).count('1') L.append(Y) print(L)
d0e2ffeb6c25c5c0b00536b6d28ad4839ab5fa9e
satishkhanna/feature_selection_project
/q04_select_from_model/build.py
593
3.71875
4
# Default imports from sklearn.feature_selection import SelectFromModel from sklearn.ensemble import RandomForestClassifier import pandas as pd import numpy as np data = pd.read_csv('data/house_prices_multivariate.csv') np.random.seed(9) def select_from_model (df): X, y = df.iloc[:,:-1], df.iloc[:,-1] model = RandomForestClassifier() sfm = SelectFromModel(model) sfm.fit(X,y) featurelist = sfm.get_support(indices=True) full_set = X.columns.values temp = full_set[featurelist] feature_name = temp.tolist() return feature_name # Your solution code here
8cf555f48ea97e4dda0df737cbeb389c11449274
eddarmitage/enigma
/tests/mappings_test.py
1,297
3.640625
4
from string import ascii_uppercase import codecs from enigma.mappings import IDENTITY, ROT13, AsciiMapping ROT13_OUTPUT = [codecs.encode(c, 'rot13') for c in ascii_uppercase] def test_identity_mapping(): """Ensure IDENTITY mapping maps every uppercase ASCII letter to itself""" assert_mappings(IDENTITY, ascii_uppercase, ascii_uppercase) def test_rot13_mapping(): """Ensure ROT13 mapping works, and is symmetric""" assert_mappings(ROT13, ascii_uppercase, ROT13_OUTPUT) assert_mappings(ROT13, ROT13_OUTPUT, ascii_uppercase) def test_ascii_mapping(): """Test the AsciiMapping using a ROT13 output encoding""" mapping = AsciiMapping(ROT13_OUTPUT) assert_mappings(mapping, ascii_uppercase, ROT13_OUTPUT) assert_mappings(mapping, ROT13_OUTPUT, ascii_uppercase) def assert_mappings(mapping, input_sequence, output_sequence): """ Ensure that map mapping works as expected. For every character in the input sequence, ensure that map_forward produces the corresponding character in output_sequence. Also ensure that map_back produces the correct result when mapping characters from output_sequence. """ for i, o in zip(input_sequence, output_sequence): assert mapping.map_forward(i) == o assert mapping.map_back(o) == i
8929fcded77d164176277d6073f4e6254d11b7f7
at3103/Leetcode
/139_Word Break_mock_interview.py
1,267
4.125
4
""" Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words. For example, given s = "leetcode", dict = ["leet", "code"]. Return true because "leetcode" can be segmented as "leet code". UPDATE (2017/1/4): The wordDict parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes. """ class Solution(object): def wordBreak(self, s, wordDict): """ :type s: str :type wordDict: List[str] :rtype: bool """ if not s: return False word_set = set(wordDict) word_set.add("") n = len(s) is_possible = [False for i in range(n)] is_possible[0] = s[0] in word_set for i in range(1, n): if (s[:i+1] in word_set): is_possible[i] = True continue for j in range(i): if (is_possible[j] and s[j+1:i+1] in word_set): is_possible[i] = True break return is_possible[n-1]
c0798e79659109948a2535425b6a4a9dbb9e6b72
Eslam-Mohamed78/python-data-structures-and-algorithms
/algorithms/sorting/bubble-sort.py
555
4
4
def bubble_sort(alist): n = len(alist) for i in range(n - 1 , 0 , -1): for j in range(i): if alist[j] > alist[j + 1]: alist[j] , alist[j + 1] = alist[j + 1] , alist[j] def smart_bubble_sort(alist): n = len(alist) for i in range(n - 1 , 0 , -1): exchanges = False for j in range(i): if alist[j] > alist[j + 1]: alist[j] , alist[j + 1] = alist[j + 1] , alist[j] exchanges = True if not exchanges: break
534f062b268e709dda52d2e5ed866eeca6565ae4
EricMontague/Leetcode-Solutions
/easy/problem_1122_relative_sort_array.py
3,208
3.859375
4
"""My solution to Problem 1122: Relative Sort Array.""" from heapq import heappush, heappop class Solution: def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]: heap = [] arr2_positions = {} arr2_length = len(arr2) for index, num in enumerate(arr2): arr2_positions[num] = index for num in arr1: if num in arr2_positions: heappush(heap, (arr2_positions[num], num)) else: heappush(heap, (arr2_length, num)) output = [] while heap: item = heappop(heap) output.append(item[1]) return output #Overall time complexity: O(nlogn), where n is the number of elements in the first array #Explanation: The first for loop take O(m) time where m is the number of elements in the #second array. The second loop takes O(nlogn), because you have to loop through all n #elements in the second array, you perform an insert operation on each loop. Inserting into #a min heap is O(logn). Finally, you loop through all n elements in the heap, popping each #one off and adding the element to the list, which is also O(nlogn). This makes the time complexity #O(2nlogn + m), but since we drop coefficients and lower order terms, this is reduced to O(nlogn). #space complexity: O(n) #Explanation: The size of arr2_positions will be O(m), and between output and heap, the #space complexity will be O(n). Thus, the space comeplexity will be O(n + m). But, #since m is upper bounded by n, in the worst case this could be said to be O(n). ################################################### #Below is a more objected oriented and modularized solution #Overall time and space complexities are the same. ################################################### from heapq import heapify, heappop from collections import deque class QueueItem: def __init__(self, key, data): self.key = key self.data = data def __lt__(self, other): if self.key == other.key: return self.data < other.data return self.key < other.key class Solution: def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]: arr2_positions = self.build_dictionary(arr2) priority_queue = self.build_queue(arr1, arr2, arr2_positions) return self.extract_items(priority_queue) def build_dictionary(self, arr2): arr2_positions = {} for index, num in enumerate(arr2): arr2_positions[num] = index return arr2_positions def build_queue(self, arr1, arr2, arr2_positions): arr2_length = len(arr2) priority_queue = [] for num in arr1: if num in arr2_positions: priority_queue.append(QueueItem(arr2_positions[num], num)) else: priority_queue.append(QueueItem(arr2_length, num)) heapify(priority_queue) return priority_queue def extract_items(self, priority_queue): output = [] while priority_queue: item = heappop(priority_queue) output.append(item.data) return output
c863419770af866136bd1b6e785871d9dc6af4ba
felipegt56/O_poder_da_Tataruga
/formatos_em_loop.py
345
3.5
4
speed(1) shape("turtle") #PENTAGONO for count in range(5): color('red') forward(100) left(72) penup() backward(200) pendown() #HEXAGONO for count in range(6): color('blue') forward(100) left(60) penup() backward(150) pendown() #CIRCULO for count in range(360): color('black') forward(1) left(1) done()
9820852ddc166f6601214eae40dd55568292bd48
bsofcs/interviewPrep
/findOccurenceOfKeys.py
834
3.578125
4
def firstOccurence(arr,low,high,val,n): if low>high: return mid=low+(high-low)//2 if (mid==0 or arr[mid-1]<val) and arr[mid]==val: return mid elif arr[mid]>val: return firstOccurence(arr,low,mid-1,val,n) else: return firstOccurence(arr,mid+1,high,val,n) def lastOccurence(arr,low,high,val,n): if low>high: return mid=low+(high-low)//2 if (mid==n-1 or arr[mid+1]>val) and arr[mid]==val: return mid elif arr[mid]>val: return lastOccurence(arr,low,mid-1,val,n) else: return lastOccurence(arr,mid+1,high,val,n) def findOccurenceOfKeys(arr,val): if arr is None or val is None: return None if val not in arr: return(-1,-1) low,n=0,len(arr) firstOcc=firstOccurence(arr,low,n-1,val,n) lastOcc=lastOccurence(arr,low,n-1,val,n) return(firstOcc,lastOcc) arr=[1,2,3,3,4,5] print(findOccurenceOfKeys(arr,0))
411ff775b0b10a5d9f4855ec7febf9180da27611
xiam220/UdemyCourses
/Python/StringMethods.py
1,179
4.28125
4
String Functions greet = 'hellloooo' print(len(greet)) #Output: 9 print(greet[0:len(greet)]) #Output: hellloooo Formatted Strings name = 'Johnny' age = 55 print(f'Hi {name}. You are {age} years old.') #Output: Hi Johnny. You are 55 years old. """ Alternative: print('Hi ' + name + '. You are ' + str(age) + ' years old.') """ String Methods quote = 'to be or not to be' #str.upper() #Modifies entire str to uppercase print(quote.upper()) #Output: TO BE OR NOT TO BE #str.capitalize() #Capitalizes first character in str print(quote.capitalize()) #Output: To be or not to be #str.find('x') #Returns position of x if it exists print(quote.find('be')) #Output: 3 #str.replace(old, new) #Replace all occurrences of old with new print(quote.replace('be', 'me')) #Output: to me or not to me print(quote) #Output: to be or not to be """ When we use methods, we are creating a new String We never modify the original String We are not assigning it to anything """
0ee32d84074e515f81571ccdea79ddb2f2e7a40d
16030IT028/Daily_coding_challenge
/InterviewBit/013_counting_Triangles.py
1,007
3.5
4
# https://www.interviewbit.com/problems/counting-triangles/ """ You are given an array of N non-negative integers, A0, A1 ,…, AN-1. Considering each array element Ai as the edge length of some line segment, count the number of triangles which you can form using these array values. Notes: You can use any value only once while forming each triangle. Order of choosing the edge lengths doesn’t matter. Any triangle formed should have a positive area. Return answer modulo 109 + 7. For example, A = [1, 1, 1, 2, 2] Return: 4""" class Solution: # @param A : list of integers # @return an integer def nTriang(self, A): M = 1e9 + 7 count = 0 A.sort() for end in range(len(A)-1, -1, -1): start = 0 k = end -1 while start < k: if A[start] + A[k] <= A[end]: start += 1 else: count += k - start k -= 1 return int(count % M)
0a5e1d9153b934f56dd65244f2a13c105ad63005
jimbrunop/brunoperotti
/Exercicios-Python/DecisaoExercicio1.py
577
4.0625
4
#Faça um Programa que peça dois números e imprima o maior deles. primeiro_numero = float(input("Informe o primeiro numero: ")) segundo_numero = float(input("Informe o segundo numero: ")) def valida_numero(primeiro_numero, segundo_numero): if primeiro_numero < segundo_numero: return print("o segundo numero é o maior: " + segundo_numero) elif primeiro_numero == segundo_numero: return print("os números são iguais") else: return print("o primeiro numero é o maior: " + primeiro_numero) valida_numero(primeiro_numero, segundo_numero)
831158c2ad8e65d667ea07ca4cbfc5e96e5acbde
aniagut/ASD-2020
/Zadania grafy/dwudzielnosc.py
1,154
3.625
4
#kolorujemy bfsem-jesli ktorys juz pokolorowany na inny niz powinien byc, to graf nie jest dwudzielny class Queue: def __init__(self): self.head=0 self.tail=-1 self.size=0 self.q=[] def enqueue(self,v): self.q.append(v) self.tail+=1 self.size+=1 def dequeue(self): result=self.q[self.head] self.head+=1 self.size-=1 return result def is_empty(self): return self.size==0 def BFScol(G): n=len(G) colour=[0]*n colour[0]=1 q=Queue() q.enqueue(0) while not q.is_empty(): v=q.dequeue() for i in range(n): if G[v][i]==1: if colour[i]==0: if colour[v]==1: colour[i]=2 else: colour[i]=1 q.enqueue(i) else: if colour[i]==colour[v]: return False return True G=[[0,1,0,1,1,1],[1,0,1,1,0,0],[0,1,0,0,1,1],[1,1,0,0,1,1],[1,0,1,1,0,0],[1,0,1,1,0,0]] print(BFScol(G))
9fe4432f7ed0190b051d3e7d1d1b97b331b2b6d7
basti-shi031/LeetCode_Python
/Ex9_PalindromeNumber.py
769
3.640625
4
import time class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ # 时间 O(n) # 空间 O(n) x_str = str(x) length = len(x_str) middle_index = int(length / 2) for index in range(0, middle_index): if x_str[index] != x_str[-1 - index]: return False return True def isPalindrome2(self, x): # 时间 O(n) # 空间 O(1) if x < 0: return False p, res = x, 0 while p: res = res * 10 + p % 10 p /= 10 return res == x solution = Solution() start1 = time.time() print(solution.isPalindrome(123321)) print(solution.isPalindrome2(123321))
b171f3977de3a104220a8cd84339c810e6c5dc1b
mgbo/My_Exercise
/Дистанционная_подготовка/Программирование_на_python/8_функция_рекурсия/zadacha_C.py
233
3.765625
4
''' Принадлежит ли точка квадрату - 1 ''' x = float(input()) y = float(input()) def IsPointInSquare(x, y): return -1 <= x <=1 and -1 <= y <=1 if IsPointInSquare(x, y): print ('YES') else: print ("NO")
632ccd7c28a1127700add8da88abe0abe169fb50
pixlalchemy/lpthw
/lpthw/ex17.py
1,494
4
4
# imports argument variable from sys from sys import argv # imports exists from os.path from os.path import exists # Takes the arguments entered from the command line, # and stores them in their own variables script, from_file, to_file = argv # Prints the string "Copying from %s to %s" and takes the values stored # in from_file and to file and formats it into the string. print "Copying from %s to %s" % (from_file, to_file) # We could do these two on one line too, how? # opens the file stored in the from_file and stores it in the in_file in_file = open(from_file) # Stores the read file and stores it in the indata variable indata = in_file.read() # Prints the string "The input file is %d bytes long" and takes length # of value stored in indata and formats it into the string print "The input file is %d bytes long" % len(indata) # Prints the string "Does the output file exist? %r" and takes the True # or False values that were returned from the exists functions and formats it # into the string print "Does the output file exist? %r" % exists(to_file) # Prints the string "Ready, hit return to continue, CTRL-C abort." print "Ready, hit Return to continue, CTRL-C to abort." # Takes a users input raw_input() # Opens the file stored in the to_file in write mode and stores it in the out # file out_file = open(to_file, 'w') # writes the read file stored in indata in the out_file out_file.write(indata) print "Alright, all done." # Closes the files out_file.close() in_file.close()
4b2431d634a0505ecea4a9698003379fb2866496
DuNG-bot/nguyenthedung-fundamental-C4EP35
/Lesson2/homework/moreturtle.py
551
4.03125
4
# from turtle import* # shape('turtle') # color('red','red') # left(120) # for i in range (4): # right(150) # forward(80) # left(60) # forward(80) # left(120) # forward(80) # left(60) # forward(80) # mainloop() n = int(input('Enter the number of shapes: ')) from turtle import* shape('turtle') for x in range (3,n+1): for i in range (x): if x%2==1: color('red','red') else: color('blue','blue') forward(100) left(360/x) mainloop()
ebd06b52e2f9526e995645a961aca3315777cdc6
LiquidityC/aoc
/2021/day_09/main.py
1,394
3.609375
4
from collections import defaultdict import sys def get_neighbors(point): x, y = point return { (x+1,y), (x-1,y), (x,y+1), (x,y-1) } def measure_basin(start, area): checked = {start} neighbors = get_neighbors(start) size = 1 while len(neighbors) > 0: n = next(iter(neighbors)) neighbors.remove(n) checked.add(n) v = area[n] if v < 9: size += 1 new_neighbors = get_neighbors(n) neighbors = neighbors | new_neighbors.difference(checked) return size if __name__ == "__main__": with open("input.txt") as fh: rows = [map(int, list(l.strip())) for l in fh.readlines()] area = defaultdict(lambda: defaultdict(lambda: sys.maxsize)) for y, r in enumerate(rows): for x, v in enumerate(r): area[(x,y)] = v total = 0 low_points = [] for y, r in enumerate(rows): for x, v in enumerate(r): if all(map(lambda h: v < area[h], get_neighbors((x, y)))): low_points.append((x, y)) total += 1 + v print("Part 1: %d" % total) basin_area = 0 basin_sizes = [measure_basin(p, area) for p in low_points] basin_sizes.sort() basin_sizes.reverse() answer = 1 for size in basin_sizes[:3]: answer *= size print("Part 2: %d" % answer)
fde822f751958cc09d1c9f69432730d6b38ef47c
tushar-rishav/Algorithms
/Archive/Contests/Codechef/Contest/Others/Infiloop/zeroes.py
248
3.578125
4
#! /usr/bin/env python def main(): t=input() while t: n_5=0 n=input() for i in range(1,n+1): j=i while not (j%5): j/=5 n_5+=i print n_5 t-=1 if __name__=="__main__": main()
2e1d1044b02a8d204ffc40192c400e6f392ad945
frankieliu/problems
/leetcode/python/971/971.flip-binary-tree-to-match-preorder-traversal.py
1,821
3.984375
4
# # @lc app=leetcode id=971 lang=python3 # # [971] Flip Binary Tree To Match Preorder Traversal # # https://leetcode.com/problems/flip-binary-tree-to-match-preorder-traversal/description/ # # algorithms # Medium (41.88%) # Total Accepted: 3.8K # Total Submissions: 9K # Testcase Example: '[1,2]\n[2,1]' # # Given a binary tree with N nodes, each node has a different value from {1, # ..., N}. # # A node in this binary tree can be flipped by swapping the left child and the # right child of that node. # # Consider the sequence of N values reported by a preorder traversal starting # from the root.  Call such a sequence of N values the voyage of the tree. # # (Recall that a preorder traversal of a node means we report the current # node's value, then preorder-traverse the left child, then preorder-traverse # the right child.) # # Our goal is to flip the least number of nodes in the tree so that the voyage # of the tree matches the voyage we are given. # # If we can do so, then return a list of the values of all nodes flipped.  You # may return the answer in any order. # # If we cannot do so, then return the list [-1]. # # # # # Example 1: # # # # # Input: root = [1,2], voyage = [2,1] # Output: [-1] # # # # Example 2: # # # # # Input: root = [1,2,3], voyage = [1,3,2] # Output: [1] # # # # Example 3: # # # # # Input: root = [1,2,3], voyage = [1,2,3] # Output: [] # # # # # Note: # # # 1 <= N <= 100 # # # # # # # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def flipMatchVoyage(self, root, voyage): """ :type root: TreeNode :type voyage: List[int] :rtype: List[int] """
8a54a8c97f2721d3a6fb3bffa5846d5d3bb088ae
TetianaSob/Python-Projects
/ex-22.py
358
3.6875
4
answer = [num for num in range(1,101) if num % 12 == 0] print(answer) # [12, 24, 36, 48, 60, 72, 84, 96] # answer = [val for val in range(1,101) if val % 12 == 0] # answer = [char for char in "amaizing" if char not in "aeiou"]) answer2 = [char for char in "amazing" if char not in ["a", "e", "i", "o", "u"]] print(answer2) # ['m', 'z', 'n', 'g']
6de127f4d187cd31341b4b0a47c63b6c08a31302
Cjhome/python
/python-learn/进程和线程区别.py
1,629
3.625
4
""" 进程 能够完成多任务 运行多个软件 线程 能够完成多任务 软件中运行多个窗口 同一进程间的不同线程可以共享全局变量 不同进程间不能共享全局变量 一个程序至少有一个主进程 一个主进程里至少有一个主线程 线程不能够独立运行,必须依赖于进程 线程和进程在使用上各有优缺点 线程执行开销小,但不利于资源的管理和保护;而进程正相反 """ import os,threading,multiprocessing from multiprocessing import Queue """ 进程共享全局变量 需要传参 队列的使用 """ n = 100 def test(): global n n += 1 print('{}n的值是{}'.format(os.getpid(), hex(id(n)))) def demo(): global n n += 1 print('{}n的值是{}'.format(os.getpid(), hex(id(n)))) def producer(): for i in range(10): print('生产了+++pid{}{}'.format(os.getpid(), i)) def consumer(): for i in range(10): print('消费了+++pid{}{}'.format(os.getpid(), i)) # t1 = threading.Thread(target=test) # t2 = threading.Thread(target=demo) if __name__ == '__main__': # 创建队列时,可以指定最大长度 默认0 代表不限 q = Queue(5) # 不同进程各自保存一份全局变量,不会共享全局变量 # t1 = multiprocessing.Process(target=test) t1 = multiprocessing.Process(target=producer, args=(q, )) # t2 = multiprocessing.Process(target=demo) t2 = multiprocessing.Process(target=consumer, args=(q, )) # 同一个主进程里的两个子进程, 线程之间可以共享同一个进程的全局变量 t1.start() t2.start()
aebc2c942ffd9864ec6e73eb5b9780904e85f76d
WillianVieira89/Python_Geek_University
/Script_Python/Estudos/Exercicios de fixação/Exercicios_Secao5/exercicio_10.py
278
3.734375
4
altura = float(input("Digite sua altura: ")) sexo = input("Digite seu sexo: ") homem = (72.7 * altura) - 58 mulher = (62.1 * altura) - 44.7 if sexo == "masculino": print(f"Seu peso ideal é: {homem:.2f} quilos") else: print(f"Seu peso ideal é: {mulher:.2f} quilos")
dfbce0ee1c23522c8e209183fab54142e6829f44
seojpark91/HackerRank_dailycoding
/appendAndDelete.py
623
3.5
4
def appendAndDelete(s, t, k): s_length = len(s) t_length = len(t) if s_length + t_length < k: return "Yes" same = 0 for letter_s, letter_t, in zip(s,t): if letter_s == letter_t: same +=1 else: break extra_s = s_length - same extra_t = t_length - same difference = extra_s + extra_t if difference <= k and difference%2 == k%2: return "Yes" return "No" appendAndDelete('zzzzz', 'zzzzzzz',4, appendAndDelete('ashley', 'ash', 2), appendAndDelete('abc', 'def', 6), appendAndDelete('hackerhappy','hackerrank', 9)
faf19f8aa672f9a58e9685bfb572ed5f6a32d2a5
stollcri/UA-3460-560-P2
/nltk/util_wordfreq.py
626
3.671875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys, nltk def process_file(file_name): dictionary = {} dict_strg = open('/usr/share/dict/words', 'r').read() dict_list = dict_strg.split() for word in dict_list: dictionary[word.lower()] = 1 dict_list = [] dict_strg ="" file_string = open(file_name, 'r').read() file_list = file_string.split() word_freq = nltk.FreqDist(file_list) word_list = list(word_freq) odd_words = [] for word in word_list: if dictionary.get(word, 0) == 0: odd_words.append(word) print odd_words if __name__ == "__main__": if len(sys.argv) >= 2: process_file(sys.argv[1])
194f33c2588803e3c10be65a707357343d8800a4
stressisboucard/par-apr-2019-prework
/temperature.py
1,065
3.65625
4
import matplotlib.pyplot as plt %matplotlib inline temperatures_C = [33,66,65,0,59,60,62,64,70,76,80,69,80,83,68,79,61,53,50,49,53,48,45,39] minimun = min(temperatures_C) print("le minimun est de ",minimun) maximum = max(temperatures_C) print("le maximum est de",maximum) somme = sum(temperatures_C) mean = somme/len(temperatures_C) print("la moyenne est de",mean) temperatures_C = [33,66,65,0,59,60,62,64,70,76,80,69,80,83,68,79,61,53,50,49,53,48,45,39] temperature_hot = 0 for i in temperatures_C: if i>70: temperature_hot = i+=1 print("il y a",i,"elements superieur à 70°") for i in temperatures_C: if i==0: i == sum(i-1,i+1)/2 temperatures_C.append(i) print("la nouvelle liste:",temperatures_C) # axis x, axis y y = [33,66,65,0,59,60,62,64,70,76,80,81,80,83,90,79,61,53,50,49,53,48,45,39] x = list(range(len(y))) # plot plt.plot(x, y) plt.axhline(y=70, linewidth=1, color='r') plt.xlabel('hours') plt.ylabel('Temperature ºC') plt.title('Temperatures of our server throughout the day') fahrenheit = [((i*1.8)+32), for i in temperatures_C]
0909ca80c69156bacf45723e6fcbdc3f62051beb
Victorkme/PythonProjects
/areEquallyStrong.py
423
3.734375
4
# -*- coding: utf-8 -*- """ Created on Mon Apr 15 15:04:02 2019 @author: User1 """ yourLeft = 10 yourRight = 15 friendsLeft = 10 friendsRight = 15 def areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight): return (max(yourLeft,yourRight) == max(friendsLeft,friendsRight) and min(yourLeft,yourRight) == min(friendsLeft,friendsRight)) print(areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight))
58f090743070729e37d95f4d8deb1340cef83313
tonysulfaro/CSE-331
/Lecture/Lecture06-Sorting/binary_search.py
756
4.09375
4
"""Return True if target is found in indicated portion of a Python list. The search only considers the portion from data[low] to data[high] inclusive. """ def recBinarySearch(data, target, low, high): if low > high: return False else: mid = (low + high) // 2 if target == data[mid]: return True elif target < data[mid]: return recBinarySearch(data, target, low, mid - 1) else: return recBinarySearch(data, target, mid + 1, high) #sorted list alist = [17, 20, 26, 31, 44, 54, 55, 77, 93] #sorted list #alist = [26,44,47] #empty list #alist=[] low=0 high=len(alist)-1 #target =77 target=78 if recBinarySearch(alist,target,low,high): print("Target value found") else: print("Target value not found")
3f6f9e15159d59f84f9cf9f938b65bd07bb9f13a
YusufVolkan/25.12.2020-globalaihub-hw-teslim
/just homework 25.12.2020.py
1,844
4
4
name=input("enter your name:") surname=input("enter your surname:") deneme=3 failed=0 while True: if deneme==0: print("please try again later..") break if name=="Yusuf" and surname=="Volkan": print("Welcome {} {}".format(name,surname)) deneme-=1 break if name=="Yusuf" and surname!="Volkan": print("Soyadınızı doğru giriniz lütfen..") deneme-=1 elif name!="Yusuf" and surname=="Volkan": print("İsminiz yanlış, lütfen isminizi doğru giriniz..") deneme-=1 else: print("isminiz ve soyadınız yanlış....") deneme-=1 """ DERSLER 1.MAT 2.kimya 3.software 4.biology 5.fizik """ ders1=input("ders1 seçiniz:") ders2=input("ders2 seçiniz:") ders3=input("ders3 seçiniz:") ders4=input("ders4 seçiniz:") ders5=input("ders5 seiçini:") dersler=[ders1,ders2,ders3,ders4,ders5] print("seçtiğiniz dersler:",dersler) midterm=0 final=0 project=0 while True: midterm_grade=int(input("midterm notunuzu giriniz:")) midterm=midterm_grade*0.3 print("midterm orlamanız is:",midterm) final_grade=int(input("final notunuz:")) final=final_grade*0.5 print("final ortalamanız:",final) project_grade=int(input("proje puanınınz:")) project=project_grade*0.2 print("proje ortalamanız:",project) notlar={"midterm":midterm_grade,"final":final_grade,"proje":project_grade} print(notlar) grades=midterm+final+project print(grades) if grades>=90: print("AA") elif 90>grades>70: print("bb") elif 70>grades>50: print("cc") elif 30<grades<50: print("dd") else: print(" YOU FAILED!! 'FF' ")
35dd6e5d1c13f3be929e8275e9522e34e76ae569
acrius/path_to_mordor
/ptm/adventure_managment/spells/implementations/utils.py
851
3.5
4
''' Module contains secondary functions for spells. ''' from os import makedirs from os.path import exists, join, isdir def make_package(package_path: str): ''' Create python package with package_path path. :param package_path: path of new package :type package_path: string ''' if not exists(package_path) or not isdir(package_path): makedirs(package_path) make_module(join(package_path, '__init__.py')) def make_module(module_path: str): ''' Create python module. :param module_path: path of new module :type module_path: string ''' if not exists(module_path): with open(module_path, 'w+'): pass def apply(function, iterator): ''' Apply function for all values from iterator. ''' for value in iterator: function(value)