blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
20232de9b92db6f52870607fb3092cfcd42d49a2 | AndrasHacks/learn-python | /003.fibo.py | 172 | 4.03125 | 4 | def fibo(n):
curr = 1
next = 1
k = 3
while k <= n:
curr, next = next, next + curr
k = k + 1
return curr
n = 8
print('The', n, 'th fibonacchi number is:', fibo(n))
|
e7c5bfcc2d088df9c9541e70f6ff93145848a33d | ProgrammerDan/acronym-phrase | /phraseit.py | 678 | 3.6875 | 4 | import argparse
import json
import string
from random import randrange
parser = argparse.ArgumentParser(description='Turn an acronym into a random phrase')
parser.add_argument('acronym', nargs=1)
parser.add_argument('iters',nargs='?',default=2,type=int)
args = parser.parse_args()
acronym=args.acronym[0]
print('input:... |
058bebc669e9f7ad702012a2bb7e70dcae26edcc | rasmuserlemann/Projecteuler-Foobar | /112.py | 359 | 3.53125 | 4 | import numpy as np
def monotonic(x):
dx = np.diff(x)
return np.all(dx <= 0) or np.all(dx >= 0)
def bouncy(n):
dig = [int(d) for d in str(n)]
if not monotonic(dig):
return 1
S = 1
sum = 0
ratio = 0
prop = 0.99
while ratio < prop:
if bouncy(S)==1:
sum = sum + 1
ratio = sum/... |
f8f5a2c200ab166fe88e01f1ba439343374e4de0 | rasmuserlemann/Projecteuler-Foobar | /64.py | 907 | 3.53125 | 4 | import math
def is_square(integer):
root = math.sqrt(integer)
return integer == int(root + 0.5) ** 2
def CF(n):
if is_square(n):
return [int(math.sqrt(n))]
ans = []
step1_num = 0
step1_denom = 1
while True:
nextn = int((math.floor(math.sqrt(n)) + step1_num) / step1_denom)
ans.append(int(nextn))
s... |
4357288b586959b6eafb20f83a23148d24e1f70d | Paulvitalis200/Data-Structures | /BinaryTrees/binary_search.py | 325 | 3.828125 | 4 | def binary_search(nums, target):
l = 0
r = len(nums) - 1
while l <= r:
mid = (l + r) // 2
if target > nums[mid]:
l = mid + 1
elif target < nums[mid]:
r = mid - 1
else:
return mid
return -1
print(binary_search([-1, 0, 3, 5, 9, 12],... |
a0eb08e1e120a89d55285a1a5fdb98a94ee988b1 | Paulvitalis200/Data-Structures | /Arrays/LeetCode/longest_repeating_character_replace.py | 1,265 | 3.953125 | 4 | # You are given a string s and an integer k. You can choose any character of the string
# and change it to any other uppercase English character. You can perform this operation at most k times.
# Return the length of the longest substring containing the same letter
# you can get after performing the above operations.... |
ba5ab5edaf9b9f85d5b95bc454e418d7cfc0cc6c | Paulvitalis200/Data-Structures | /Sorting/sort_list.py | 1,641 | 4.125 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.nex... |
299330f418abb7e0b7541146fd2c4834750a8ebb | Paulvitalis200/Data-Structures | /Dictionaries/dict_comprehension.py | 493 | 3.65625 | 4 | import random
names = ["James", "Alicia", "Frost", "John", "Grace", "Wambui"]
my_dict = {customer:random.randint(1, 100) for customer in names}
days = ["Sunday", "Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
temp_C = [30.5,32.6,31.8,33.4,29.8,30.2,29.9]
dates = {day:temp for (day, temp) in zip(days... |
80be098433bf1b7d3593d26da520306209cc1ea6 | akhilrazdan/cryptopals | /src/set1/challenge_8.py | 640 | 3.671875 | 4 | from Crypto.Cipher import AES
def detect_ecb(cipher_text: bytes, keysize=AES.block_size):
assert len(cipher_text) % keysize == 0, "length of cipher text should be a multiple of blocksize"
num_blocks = len(cipher_text) // keysize
blocks = [cipher_text[(i * keysize): ((i + 1) * keysize)] for i in range(0, ... |
6cb33df130f60fb58866642d8aa598be9b76128f | valefaraz/computacion1 | /58018-valentin-faraz/clase06/gng.py | 920 | 3.703125 | 4 | class Game():
def __init__(self):
self.is_playing = True
def finish(self):
self.is_playing = False
class HumanAgainstComputerGame(Game):
def __init__(self):
#self.is_playing = True (se borra porque creamos una clase en comun)
super __init__() #hereda el init de la clase bas... |
1c2c0d3f4c38325ae7e56add9c5379708efefe09 | caizhenzhen2010/Python3 | /Test/src/MemberCounter.py | 387 | 3.75 | 4 | class MemberCounter:
members=0
def init(self):
#MemberCounter.members+=1
self.members+=1
m1=MemberCounter()
m1.init()
print MemberCounter.members
print m1.members
print MemberCounter.members
m2=MemberCounter()
m2.init()
print MemberCounter.members
print m2.members
print m1.members
m1.members="... |
0f1e181d5efed829f609c6d444a50cb02772f6f0 | caizhenzhen2010/Python3 | /Squish/src/objects.py | 2,713 | 3.671875 | 4 | #! /usr/bin/env/python
#! -*- encoding: utf-8 -*-
import pygame,config,os
from random import randrange
"这个模块包括Squish的游戏对象"
class SquishSprite(pygame.sprite.Sprite):
"""
Squish 中所有的子图形的泛型超类。构造函数负责载入图像,设置自图形的rect和area属性,
并且允许它在指定区域内进行移动。area由屏幕的大小和六百决定。
"""
def __init__(self,image):
pygame.... |
e8114baa8df6626669f9a1597bdc90e8ab1d96c9 | caizhenzhen2010/Python3 | /Test/src/Fibs.py | 391 | 3.625 | 4 | class Fibs:
def __init__(self):
self.a=0
self.b=1
def next(self):
self.a,self.b=self.b,self.a+self.b
return self.a
def __iter__(self):
return self
fibs=Fibs()
for fib in fibs:
print fib
print '\n'
if fib>10000:
break
it=iter([... |
fd5a7183baa217488eef9e8525f4abfddc1bfca7 | panpan31415/wzr | /exercise4.py | 2,073 | 3.8125 | 4 |
def interpret_request(request):
operators_symbols = ["+", "-", "*", "/"]
operators = []
for index, symbol in enumerate(request):
if symbol in operators_symbols:
operators.append({"index": index, "symbol": symbol})
elements = []
start = -1
for index, operator in enumerate(ope... |
c61dddf1054699633a51777fb86544e2296b4f79 | leonmelein/ba_thesis | /machinelearning/featurizers/surface/fiveletterwordsratio.py | 1,355 | 4 | 4 | #!/usr/bin/python
# Five letter words ratio - Léon Melein, s2580861
def generate(tweets, debug=False):
"""
Generates the ratio of words longer than 5 characters to the amount of all words per user (S_5CH).
:param tweets: a List containing a list of tokens per tweet.
:param debug: a Bool indicating ... |
a8560b6ee364cc9ad5edfcc21124971bc08b1779 | nervaishere/DashTeam | /python/HOMEWORK/6th_Session/Answers/Class/7/T7.py | 73 | 3.5 | 4 | a=input("Enter your number:")
a=a[::-1]
mynum = int(a)
print(mynum)
|
330c57407072ece38bf6ebdfb5f643cf9f964dc3 | nervaishere/DashTeam | /python/9th_session/14dict.py | 344 | 3.515625 | 4 | thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(x)
print('*****')
for y in thisdict:
print(thisdict[y])
print('*****')
for y in thisdict.values():
print(y)
print('*****')
for z in thisdict.keys():
print(z)
print('*****')
for key , value in thisdict.items(... |
cecb11d22c90ce7f2453c5848f13f4168cda59db | nervaishere/DashTeam | /python/5th_session/9Tamrin2.py | 109 | 3.53125 | 4 | a, b, c= map(int, input().split())
if a%2==0 or (b%2==0 and c%2==0):
print('good')
else:
print('bad') |
2424c86b54d5ca4f07c4d54a15e01f86b9e00c3d | nervaishere/DashTeam | /python/HOMEWORK/6th_Session/Answers/Class/4/soale 4.py | 300 | 4.09375 | 4 | x = int(input("Enter a number: "))
if x>=0:
if x==0:
print("0")
else:
for x in range(0,x):
count = 0
while count <= x:
print('*', end =' ')
count = count+1
print()
else:
print("not valid")
|
dac5fafe987537af89c7c2ae817e8935448e545b | nervaishere/DashTeam | /python/HOMEWORK/3rd-4th_Session/Answers/Class/4/soale 4 sum&multi.py | 86 | 3.53125 | 4 | x = int(input())
y = int(input())
print('sum:' + str(x+y) + '\tmulti:' + str(x*y))
|
783baa95357f68bfd54d8de1f7a78e0eb040e477 | nervaishere/DashTeam | /python/HOMEWORK/3rd-4th_Session/Answers/Class/1/T-1.py | 54 | 3.5 | 4 | x=input("Enter first Number:")
print(int(float(x)))
|
ce39b97f2b6d7e216c0ea677ece6b3e7488d2adb | nervaishere/DashTeam | /python/HOMEWORK/8th_Session/Answers/Class/1/soale 1.py | 130 | 3.921875 | 4 | def even(a):
if a%2==0:
return(a+2)
else:
return(a+1)
print(even(int(input("Enter a number: "))))
|
8c28d29aeb819d4fb34e5d0ad52699ace9e44ee2 | nervaishere/DashTeam | /python/HOMEWORK/5th_Session/Answers/Class/1/T_1.py | 259 | 3.75 | 4 | a,b,c=map(int,input("Enter some number: ").split())
t="\t"
if max(a,b,c)==a:
print(max(a,b,c),t,max(b,c),t,min(b,c))
elif max(a,b,c)==b:
print(max(a,b,c),t,max(a,c),t,min(a,c))
else :
print(max(a,b,c),t,max(b,a),t,min(b,a))
|
af64002c70d91b508e0c30a54911ba36835f99ec | nervaishere/DashTeam | /python/HOMEWORK/7th_Session/Answers/Correct/1.py | 169 | 3.84375 | 4 | n , m = map(int,input("Enter two integers as m and n: ").split())
counter = int()
for i in range(1,n+1):
text=input()
counter += text.count("*")
print(counter)
|
23c876ef2bb70e31da995413e3a77708024b07ce | nervaishere/DashTeam | /python/HOMEWORK/5th_Session/Answers/Correct/2.py | 128 | 4.125 | 4 | a = float(input("Enter a number: "))
b = float(input("Enter a number: "))
if a>b:
div = a/b
else:
div = b/a
print(div)
|
02e2a1de809c9bfba2233dc5ac4aa7db2c63f9d2 | nervaishere/DashTeam | /python/9th_session/test.py | 264 | 3.859375 | 4 | n=int(input("enter your number: "))
m=0
p=1
if n<1:
print("not valid")
elif n==1:
print(0)
elif n==2:
print(0,1)
elif n>2:
print(0, 1, sep=" , " , end=" , ")
for n in range(2,n):
f=m+p
print(f, end=" , ")
m=p
p=f |
2c214217179d0e6501e1773eee6c970bab02ab03 | nervaishere/DashTeam | /python/HOMEWORK/6th_Session/Answers/Class/12/6.12.py | 91 | 3.515625 | 4 | a,b=map(float,input("enter 2 float:").split())
p=a*b
g=p/3.1415
print(format(g,".5f"))
|
bb268ab7adafb29018bf5dd97dff0d2ed204dfa0 | nervaishere/DashTeam | /python/HOMEWORK/6th_Session/Answers/Class/1/kkjfjg.py | 163 | 4 | 4 | x=float(input("x before swapping:" ))
y=float(input("y before swapping:" ))
x=x+y
y=x-y
x=x-y
print("x after swapping:" + x)
print("y aftee swapping:" + y)
|
3f703dde97ff625e920e0b8a27757e495add0c3f | nervaishere/DashTeam | /python/HOMEWORK/7th_Session/Answers/Class/3/3.py | 377 | 3.796875 | 4 | a=int(input("enter your number: "))
x=a
count=0
number=str(a)
evencount=0
while x>0:
count+=1
if x%2==0:
evencount+=1
x=x//10
if count%2==0:
print(count, evencount, sep="\n")
newcount=0
if count%2==1:
for i in range(0,count):
if int(number[i])<6:
newcoun... |
ed1fbca08c4cbd77e93e46a3973c1f27457e24a3 | nervaishere/DashTeam | /python/HOMEWORK/3rd-4th_Session/Answers/Correct/3.py | 122 | 3.625 | 4 | text1 = input("Enter a text: ")
text2 = input("Enter a text: ")
print(text1,text2)
print(list(text1))
print(list(text2))
|
6ccf7ab345cede75c72156ef9d342450ef96a104 | einstein13/wl_soldiers_exact | /soldiers.py | 1,650 | 3.515625 | 4 | from fractions import Fraction
import stats
class Soldier():
attack_min = 0.0
attack_max = 0.0
defense = 0.0
evade = 0.0
health = 0.0
tribe = 0
def set_tirbe(self, tribe_name):
if tribe_name == "barbarians" or tribe_name == "Barbarians":
self.tribe = 1
elif tri... |
9f43dcd19ca484594a4c8502a8b5fe4abb4915ef | MauricioCarreon/AprendaPython | /Entrada.py | 672 | 3.9375 | 4 | entrada=input()
print(type(entrada))
#la variable booleana contiene el resultado de verificar
#si lo capturado es digito y si no se encuentra un punto
# en lo capturado lo que indicara se que trata de un
#numero con decimales es decir float. si find retorna -1
#quiere decir que lo buscado en este caso un punto decimal
... |
1d832b811d66f77a573dea16d711b330cfbc9826 | txmoose/pythonprojects | /fuzzles.py | 185 | 3.828125 | 4 | #!/usr/bin/env python
print 'Will you club Mr. Fuzzles now?'
answer = raw_input().lower()
if "no" in answer or answer == "n":
print "Thank you!"
else:
print "You monster :("
|
647aa11df89057f0d43e3b1f875c32c51fda6a01 | jtdevore/pythonRepos | /namegame.py | 242 | 3.78125 | 4 | def namegame():
name = input('Enter a name!')
print (name +', '+ name+ ', ' + 'bo-b'+name[1:])
print ('banana-fana fo-f' + name[1:])
print ('fee-fi-mo-m' + name[1:])
print (name + '!')
while True:
namegame()
|
d49542512e69447d3ae89765a9b5c8591f4f3702 | brbisheng/ProgrammingFoundations | /Final_stage/Titanic_final_Sheng_BI_IPND_1st_modification.py | 49,100 | 3.625 | 4 |
# coding: utf-8
# ## Programming Fundation (Udacity) - Final Project: Exploring Titanic Data.
# ### 1. Description of the dataset:
# The data could be downloaded from the Kaggel (https://www.kaggle.com/c/titanic), a website for learning data analytics. The raw data consists of 891 observations and 12 variables
#
# ... |
c17f301d0bec644be350d553feb39690972f65ab | coderCadu/Python-Training-for-the-test | /ex2.py | 180 | 4.125 | 4 | num = int(input("Digite quantos números deseja: "))
i = 0
numeros = []
while len(numeros) < num:
if i % 2 != 0 and i > 0:
numeros.append(i)
i+=1
print(numeros)
|
75002616d1d2c463e9d82297da74cc6862fc7b40 | iricchi/Project1_ML | /code/SUBMISSION/standard.py | 517 | 3.859375 | 4 | # Standardize dataset
import numpy as np
def standardize(x):
"""Standardize the original data set."""
# get the vector of means (for each feature)
mean_x = np.mean(x, axis = 0)
# pair wise substraction of those means in each feature space
x = x - mean_x
# get the vector of stand... |
c215649e5193309d5d0a9259db8c02df6bbd5255 | Graunarmin/Little_Python_Games | /GuessTheNumber.py | 1,489 | 3.9375 | 4 | """
Little "Guess the number" game from "Invent your own computer games with python" by Al Sweigart
(Given rules but my own code)
"""
import random
# --------- STATIC FUNCTIONS ----------
def greetings():
print("Hello there. What's your name?")
user_name = input()
print("Hello ", user_name, ". I am think... |
00e24e8f4dca427fc08ea66ad50cc0aad1fb1e28 | jounaidr/jr-nlp-sandbox | /normalise_text.py | 728 | 3.71875 | 4 | import re
import nltk
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
#nltk.download('stopwords')
#nltk.download('punkt')
input = 'I like go walking! I was interested in dancing.'
out = input.lower() #lower case everything
print(out)
out = re.sub(r'[^\w\s]', '', out) #remove punctuation (could... |
e145093930caccaf4be437b705669090604fa42d | JairoLedezma/ParallelProcess | /Parallel_Example/main.py | 850 | 3.78125 | 4 | import multiprocessing as mp
print("Number of processors: ", mp.cpu_count())
import numpy as np
from time import time
def howmany_within_range(row, minimum, maximum):
"""Returns how many numbers lie within `maximum` and `minimum` in a given `row`"""
count = 0
for n in row:
if minimum <= n <= maxi... |
c4c3fce06c5dfa787620f2f3d7dad2f11b67625a | ConorFlanagan/210CTCW | /Week3/Q3_RemoveVowels.py | 541 | 4.03125 | 4 | def removeVowels(word, count=0):
vowels = ["a","e","i","o","u"]
if count == len(vowels):
print(''.join(word))
elif count < len(vowels):
if vowels[count] in word: #Check if vowel in word
word.remove(vowels[count])
removeVowels(word, count)
else:
... |
9710556b7eeef69c1e734fff5bef2b1432c21a50 | alineat/python-exercicios | /desafio041.py | 712 | 4.0625 | 4 | # A confederação nacinal d natação precisa d um progrma q leia o ano de nasciemnto d um atleta e mostre sua categoria
# de acordo c/ a idade:até 9 anos: mirim.até 14 anos: infantil; até 19 anos: junior; até 20 anos: sênior; acima: master.
from datetime import date
nasc = int(input('Em que ano você nasceu? '))
idade = ... |
478d9de956991af1d1cffea20ca6ac0302a28e1f | alineat/python-exercicios | /desafio012.py | 297 | 3.71875 | 4 | # Faça um algoritmo que leia o preço de um produto e mostre seu novo preço, com 5% de desconto.
preco = float(input('Qual o preço do produto? R$'))
desc = preco - (preco * 5 / 100)
print('O preço normal do produto é R${:.2f}. Com o desconto de 5% ele custa R${:.2f}.'.format(preco, desc))
|
795f17a270c5a7956e70f89eee404dd41f7cc1b3 | alineat/python-exercicios | /desafio060.py | 467 | 4 | 4 | #from math import factorial
#n = int(input('Digite um nº p/ calcular seu fatorial: '))
#f = factorial(n)
#print('O fatorial de {} é {}.'.format(n, f))
#OU
n = int(input('Digite um nº p/ calcular seu Fatorial: '))
c = n #contador começa c/ n q é o numero q queremos fatorar
f = 1
print('Calculando {}! = '.format(n), end... |
d4259713f468a2051014f1b86d53de5905837f16 | alineat/python-exercicios | /desafio066.py | 193 | 3.71875 | 4 | s = cont = 0
while True:
n = int(input('Digite um nº: '))
if n == 999:
break
s = s + n
cont = cont + 1
print(f'Foram digitados {cont} nºs e a soma entre eles é {s}.') |
7fff7cf3e06878c965fe5f2675b8f01142d9c4a4 | alineat/python-exercicios | /desafio074.py | 451 | 3.921875 | 4 | # programa q vai gerar 5 nºs aleatorios e colocar em uma tupla. Dpois disso, mostre a listagem de nºs gerados e tbm
# indique o menor e o maior valor q estão na tupla.
from random import randint
n = (randint(1,10), randint(1,10), randint(1,10), randint(1,10), randint(1,10))
""" OU
n = [randint(1,10) for numero in ran... |
993439d6246b23ac944ecadff41dd227efccb284 | alineat/python-exercicios | /desafio078.py | 1,252 | 3.8125 | 4 | # programa q leia 5 valores numéricos e guarde-os em uma lista. Mostre qual foi o maior e o menor valor digitado e as
# suas respectivas posições na lista
"""
#solucao incompleta, para fzer um loop q qndo houver mais de um numero igual imprima tdas as posições
lista = []
cont = 0
for numero in range(0,5):
numeros =... |
14ef5f788b4da81b9c338268dd2959736af3ef0c | alineat/python-exercicios | /desafio098.py | 1,311 | 3.953125 | 4 | # Faça um programa que tenha uma função chamada contador(), que receba 3 parâmemtros: início, fim e passo. Seu programa
# tem que realizar 3 contagens através da funçãao criada: a) de 1 até 10, de 1 em 1. b) de 10 até 0, de 2 em 2.
# c) uma contagem personalizada.
from time import sleep
def contador(inicio, fim, passo... |
2db5ebe52b4e8512b8ae76e6f89165aa6a9cd095 | alineat/python-exercicios | /desafio085.py | 563 | 4.21875 | 4 | # Crie um programa onde o usuário possa digitar sete valores numéricos e cadastre-os em uma lista única que mantenha
# separados os valores pares e ímpares. No final, mostree os valores pares e ímapres em ordem crescente.
num = [[], []]
#valor = 0
for c in range(1, 8):
valor = int(input(f"Digite o {c}º valor: "))
... |
1aea3573add2b7839784dba4194e9b0b7f0246fd | alineat/python-exercicios | /desafio061.py | 306 | 3.78125 | 4 | print('=-' * 6, '10 termos de uma PA', '-=' * 6)
primeiro = int(input('Primeiro termo: '))
razao = int(input('Razão da PA: '))
termo = primeiro
cont = 1 #contador começa c/1 p/mostrar os 10 primeiros termos
while cont <= 10:
print(f'{termo} ->', end='')
termo += razao
cont += 1
print('Fim')
|
711429106919ef18c8cfbd15ba416f5e30f130a9 | alineat/python-exercicios | /desafio082.py | 638 | 3.890625 | 4 | # leia variso nºs e coloque-os em uma lista. Dpois, crie duas listas extras q vão conter apenas os valores pares e os
# valores ímpares digitados, respectivamente. Ao fim, mostre o conteúdo das três listas geradas.
num = list()
pares = list()
impares = list()
while True:
num.append(int(input("Digite um nº: ")))
... |
c1b078b9850c0de800e1cad090aa70b8e74330d2 | alineat/python-exercicios | /desafio031.py | 485 | 4.03125 | 4 | # Desenvolva um programa que pergunte a distância de uma viagem em Km. Calcule o preço da passagem, cobrando R$0,50 por
# Km para viagens de até 200Km e R$0,45 parta viagens mais longas.
distancia = float(input('Qual a distância da viagem? '))
if distancia <= 200:
preço = 0.5 * distancia
else:
preço = 0.45 * d... |
a523b8a1a4cd0a77e2f1ee5ddf373e4d2c1bef3a | HerikaOlmedo/Clases | /persona.py | 931 | 3.703125 | 4 | #Crear una carpeta que se llame clases y dentro poner los archivos dino.py y persona.py
#Crear una clase persona() en el archivo persona.py que tenga como atributos
# nombre, edad y profesion
#Al instanciar la clase tiene que saludar igul que el dino diciendo sus
#atributos
class Persona:
def __init__(self, un_n... |
ecc31c6871822b937eed2f4b835de1896af4ab73 | maqueredkop/Bioinformatics_Specialization_Coursea_Exercise | /bioinfo_sec1/week1/No8_reverse_complement.py | 435 | 3.90625 | 4 |
dna = 'TGTTGGCATCCTTCAGGAACTTAACACAAGCCTACTAGTGAATTCTGCTCCACGTTAATTTATATGATGGCAGGATAGTTCGCAATGAGAGTCTTGACTATT'
base_comple = {'A':'T', 'C':'G', 'G':'C', 'T':'A'}
def reverse_complement(dna):
dna_comple = ''
for i in dna:
i_comple = base_comple[i]
dna_comple = dna_comple + i_comple
dna_re... |
be00cb90b0ac35cf167762a3b2c82992d5e713b7 | maqueredkop/Bioinformatics_Specialization_Coursea_Exercise | /bioinfo_sec1/week2/No5_neighbors_modified.py | 918 | 3.609375 | 4 |
def hamming_distance(text1, text2):
distance = 0
for i in range(len(text1)):
if text1[i] != text2[i]:
distance = distance + 1
return distance
pattern = 'TACTTCCC'
def neighbors(pattern, d):
if d == 0:
return set(pattern)
if len(pattern) == 1:
return set(['A',... |
74d04a7bf3e559b0660a391868cc476d72c3ec93 | n17/python_audio_demo | /spectrogram.py | 427 | 3.5625 | 4 | """
Compute and display a spectrogram.
Give WAV file as input
"""
import matplotlib.pyplot as plt
import numpy as np
import sys
from audio_demo import spectrogram, display_spectrogram, read
if __name__ == "__main__":
if len(sys.argv) != 2:
print "Usage: python spectrogram.py wavfile.wav"
sys.exit(1)
... |
20cb8f53226940b8b42a70cc1d524d2a37e1d1e8 | Ornella-KK/password-locker | /user_test.py | 1,841 | 4.125 | 4 | import unittest
from user import User
class TestUser(unittest.TestCase):
def setUp(self):
self.new_user = User("Ornella")#create user object
def test_init(self):
'''
test_init test case to test if the object is initialized properly
'''
self.assertEqual(self.new_user.us... |
011a2d9e2737c7650caaf6efa0565397a0eb748f | ryanskeller48/Advent-of-Code-2018 | /Day 7/tasks.py | 3,133 | 3.625 | 4 | # Ryan Keller
#
# AoC Day 7 Problem 1
#
from sets import Set
def get_data(line): # get data from txt input
words = line.split(" ")
dependency = words[1]
dependent = words[7]
return [dependency, dependent]
def make_dependencies(filename):
# make a hashmap of tasks that require other ... |
48da9e15e2446d88f90d92ff68ca106052f013e8 | zhiqixu/structlinks | /DataStructures/Matrix/Matrix.py | 15,017 | 3.703125 | 4 | """This file contains the Matrix object."""
from __future__ import annotations
from typing import Union, Callable
import copy
class Matrix:
"""A matrix
Instance Attributes:
- shape: shape of the matrix
Private Instance Attributes:
- _row_count: The number of rows
- _col_count: The number of... |
c33ebab9cb7a83e78b7374d3f3c1e44e4e9898f7 | theyoucheng/scbmc | /src/common.py | 3,145 | 3.5625 | 4 | import argparse
import re
import sys
import string
import os
def remove_comments(string):
pattern = r"(\".*?\"|\'.*?\')|(/\*.*?\*/|//[^\r\n]*$)"
# first group captures quoted strings (double or single)
# second group captures comments (//single-line or /* multi-line */)
regex = re.compile(pattern, re.M... |
731ef374fda68c76f3fc82091b093fdcad72cf64 | phuocquoc/pdl_5 | /capter.py | 944 | 3.515625 | 4 | import cv2
# 1.creating a video object
video = cv2.VideoCapture(0)
# 2. Variable
a = 0
# 3. While loop
while True:
a = a + 1
# 4.Create a frame object
check, frame = video.read()
# Converting to grayscale
#gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
# 5.show the frame!
cv2.imshow("Captur... |
998f75f7d0fb5dfc53b2d4df451b484638ca8d19 | HakobAtanesyan/Snake | /snake.py | 4,499 | 3.59375 | 4 | from tkinter import *
import random
root = Tk()
root.title("Snake game in PYTHON")
root["bg"] = ("black")
root.resizable(width=False, height=False)
photo = PhotoImage(file = "voice.png",height= 110, width = 127)
WINDOW_HEIGHT = 800
WINDOW_WIDTH = 800
BACKGROUND_COLOR = "black"
SNAKE_COLOR = "blu... |
f8316c78eaf144b15ba430fd88b445b923f0f14a | bullud/pyray | /polyhedron.py | 10,077 | 3.890625 | 4 | '''
All kinds of polyhedra. Like Platonic solids, Archimedean solids, Tetartoids, etc.
'''
import numpy as np
from scipy.spatial import ConvexHull
from misc import *
from rotation import *
from color import *
# A global variable used for investigating the angles the faces of polyhedons make with a light source. This ... |
1250e6335b7cfcdb8131d285d18d82aa0250a804 | ssxssx/cancelable-fingerprint | /rsolomon2.py | 5,239 | 3.5 | 4 | from utils import *
import reedsolomon as rdsolomonlib
import random
__all__ = ['Rsolomon']
"""
rs.Codec(n, k)
n is the total number of symbols per codeword, including data
and parity.
k is the number of data symbols per codeword.
symsize is max 8, so n should be less than 2 ** symsize - 1 < 256,
if ... |
36627a1d6b86a918624faa3f5f3ad609c9b17635 | sharfuz95/DataMining | /dataset_analysis/tags_analysis.py | 2,958 | 3.90625 | 4 | #Resource followed for the analysis
#https://www.kaggle.com/jneupane12/analysis-of-movielens-dataset-beginner-sanalysis
import pandas as pd # pandas is a data manipulation library
import numpy as np #provides numerical arrays and functions to manipulate the arrays efficiently
import random
import matplotlib.pyplot as ... |
564db3e5e03d18e980107ed59fa9dab7bfe0bfca | RizwanAliQau/Python_Practice | /try_excep_example.py | 274 | 4.125 | 4 | try:
num = int(input(" enter a number"))
sq_num = num * num
print(sq_num)
num1= int(input("enter second number of division"))
b = num / num1
except ValueError:
print('invalid number')
except ZeroDivisionError:
print("num2 can't be zero") |
0a55931b8fe4870389c8392e3a311d2d4d38b387 | DerrickChanCS/Leetcode | /637.py | 1,404 | 3.859375 | 4 | """
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
Example 1:
Input:
3
/ \
9 20
/ \
15 7
Output: [3, 14.5, 11]
Explanation:
The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].
... |
d5a1064642d886d3f325359688313fc5b4f44efd | DerrickChanCS/Leetcode | /687.py | 818 | 3.9375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def longestUnivaluePath(self, root):
"""
:type root: TreeNode
:rtype: int
"""
sel... |
ba7389bd2476a80e1bd31936abce463963884f4d | DerrickChanCS/Leetcode | /426.py | 1,837 | 4.34375 | 4 | """
Let's take the following BST as an example, it may help you understand the problem better:
We want to transform this BST into a circular doubly linked list. Each node in a doubly linked list has a predecessor and successor. For a circular doubly linked list, the predecessor of the first element is the last e... |
8b33e5666e7044c4b077a82eb85e6c8647d489bf | hsyy673150343/PythonCoreProgramming | /GUI编程/tkhello4.py | 602 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding:utf8 -*-
# @TIME :2019/4/20 16:48
# @Author : 洪松
# @File : tkhello4.py
from tkinter import *
def resize(ev=None):
label.config(font='Helvetica -%d bold' % scale.get())
top = Tk()
top.geometry('250x150')
label = Label(top, text='Hello World!', font='Helvetica -12 bo... |
faba4e82273713708ef75dfdd1abcef225a7079a | KomarovaEkaterina/GeekBrains | /python_base/homework_3/task_6.py | 960 | 3.859375 | 4 | def int_func(word):
return word.title()
while True:
str_of_words = input("\nВведите слово или строку из слов в маленьком регистре латинскими буквами: ")
arr_of_words = str_of_words.split()
res = ''
flag = 0
for word in arr_of_words:
for letter in word:
if ord(letter) > 122 ... |
801bb293b8c448129b9ffe77590ccda91dcda11c | KomarovaEkaterina/GeekBrains | /python_base/homework_2/task_6.py | 2,881 | 3.625 | 4 | # я не очень поняла идею с аналитикой, если честно.
# Там нужно было зановсить в списки по ключам только уникальные значения?
# Или нужно было сделать так, чтобы при совпадерии наименования товара суммировались цены и количества совпавших товаров?
# Сделала так, чтобы просто не добавлялись одинаковые значения в аналити... |
0b794b1c61ce171fe8516cbf1951db68f5e1fcba | KomarovaEkaterina/GeekBrains | /python_base/homework_6/task_3.py | 1,304 | 3.75 | 4 | class Worker:
def __init__(self, name, surname, position, wage, bonus):
self.name = name
self.surname = surname
self.position = position
self._income = {"wage": wage, "bonus": bonus}
class Position(Worker):
def get_full_name(self):
full_name = self.surname + " " + self... |
7176e9b90860d3657a9eced24708d2ac56897f56 | drone-comp/SNOOTY | /src/SNOOTY/__init__.py | 5,718 | 3.75 | 4 | """
Python package `SNOOTY`: smoothing and evaluation for data analysis.
"""
import rpy2.robjects.numpy2ri as numpy2ri
import rpy2.robjects. pandas2ri as pandas2ri
from rpy2.robjects.packages import STAP
import rpy2.robjects as ro
import pandas as pd
def smooth(data, smooth_size, before, after):
"""
Eac... |
918f91915f814d1dcb6785b67689008ad399f075 | DDMAL/barlineGroundTruth | /gtruth_zoom.py | 4,151 | 4.1875 | 4 | '''
Abstract from this class to enable zooming.
'''
import abc
class Zoomer:
'''
A class that supports zooming, granted the object that subclasses it has the
methods:
self.SetWidth()
self.SetHeight()
self.SetPosition()
Sublassing this will allow you to zoom instances of the class
'''
... |
224a738ee98d7f86d59ae5e64f090038c74861eb | anna-reirl/Numerical-Methods-Solving-Nonlinear-Equations | /Newton's method.py | 451 | 4.03125 | 4 | def naive_Newton(f, dfdx, x, eps):
x1 = x+eps*2
while abs(x1-x) > eps: # пока не достигнута точность 0.000001 определяет достигнута ли необходимая точность
x1 = x
x = x - float(f(x))/dfdx(x) #первое приближение
return x
def f(x):
return x**2 - 9
def dfdx(x): # производная функции
return 2*x
print(n... |
7aae09c1ae307367d999e28fba2c359ba108e221 | MehdiSv/Python-Euler-Project | /20.py | 191 | 3.5625 | 4 | n = 100
def factorial(number):
if number == 1:
return 1
res = number * factorial(number - 1)
return res
res = factorial(n)
print reduce(lambda x, y: x + y, [int(i) for i in str(res)]) |
768452e4a21704ffec9d87f81c10b0b3b271fbc6 | berthin/cuscontestX | /problem-set/testcase-generator/genString.py | 949 | 3.671875 | 4 | import sys
from random import randint
if len(sys.argv) == 3:
testinfile = open(sys.argv[1], 'w')
testoutfile = open(sys.argv[2], 'w')
else:
print 'the program received one parameter'
print './program <test.in> <test.out>'
T = 100
testinfile.write(str(T) + '\n')
max_chrs = 0
with open('text.in', 'r') a... |
43ce00fb1f3da7c60644030122ba14453fee58d6 | sryklief/python-mySQLdb | /admin.py | 705 | 3.75 | 4 | def menu():
select = input("""Please select one of the following options:
1. Register user
2. Delete user
3. Register
4. Show sign in and sign out tables
5. Upgrade/Downgrade privileges
Choose Option: """)
try:
option = int(select)
if option == 1:
... |
1afd209ff82d985882b7631f6fd3f4fa7cf68d72 | KiLJ4EdeN/ObjectDetection_WithoutAI | /ObjectDetection_WithoutAI/sci_utils.py | 1,647 | 3.578125 | 4 | def get_iou(bb1, bb2):
"""
Calculate the Intersection over Union (IoU) of two bounding boxes.
Parameters
----------
bb1 : dict
Keys: {'x1', 'x2', 'y1', 'y2'}
The (x1, y1) position is at the top left corner,
the (x2, y2) position is at the bottom right corner
bb... |
da5d8cfb4befeadad03271b6c80165ca9400cc55 | samerkr/python-homework | /Project/FizzBuzz.py | 319 | 3.984375 | 4 | ##BASIC
mylist =list(range(1,101))
##print(mylist)
for i in mylist:
if (i % 5 == 0) and (i % 3 == 0): print(F" {i} is Multiples of three and five --FizzBuzz")
elif i%3 ==0: print(F" {i} is Multiples of three --Fizz")
elif i % 5 == 0: print(F" {i} is Multiples of five --Buzz")
else: print(" "+str(i))
|
815ade9232c33c6f022de92984b1ee011c532657 | aditi27mahajan/python | /table.py | 136 | 3.96875 | 4 | num = int(input("enter the value of the table:-"))
print("the value is=", num)
for i in range(1, 11):
print(num,'x',i,'=',num*i)
|
ecb0eccada394ea46d4449de067c6090712946ab | ksanman/ev_route_planner_v2 | /Cars/battery.py | 1,177 | 3.625 | 4 | class Battery:
kwh_to_watt_hour_conversion_factor = 1000
lion_battery_efficiency = .90
def __init__(self, batteryCapacityKwh, systemVoltage):
"""
Creates a new instance of the Car object.
"""
self.batteryCapacityKwh = batteryCapacityKwh
self.systemVoltage = systemVo... |
ee2eb479db94644efdd0bcf23faea75cbec3216d | zafaralam/python_tute | /lpp_2nd_edition/chapter_1/bike.py | 523 | 4.03125 | 4 | # bike.py
# let's define the class Bike
class Bike:
def __init__(self, color, frame_material):
self.color = color
self.frame_material = frame_material
def brake(self):
print("Braking!")
# let's create a couple of instances
red_bike = Bike("Red", "Carbon fiber")
blue_bike = Bike("Blue"... |
8d4774c5da31af3a962999d98b4007b127e09f8e | aej/vending_machine | /transaction.py | 2,580 | 3.71875 | 4 | from exceptions import NoStockException, InsufficientFundsForPurchase, CalculateChangeError
class VendingAction:
"""Actions that can be made on a vending machine.
Args:
vending_machine: An instantiated vending machine
"""
def __init__(self, vending_machine):
self.vending_machine = v... |
2c744471177e3aae6bb8b21f12401a235cc3e223 | aej/vending_machine | /products.py | 448 | 3.75 | 4 | from abc import ABC
class Product(ABC):
"""A generic product object. A product has a price, in pence."""
price = None
def __init__(self):
if self.price is None:
raise AttributeError
class Candy(Product):
price = 10
class Snack(Product):
price = 50
class Nuts(Product):
... |
2997ce656ad7ca5e9abc1edf00ee5b0aa9edeff3 | sushmeetha31/BESTENLIST-Internship | /Day 7/Day 7 task.py | 2,419 | 4 | 4 | #DAY 7 TASK
#1)Create a python module with list and import the module in another .py file and change the value in list
import my_module as mm
print(mm.my_list)
mm.my_list[0] = 6
print(mm.my_list)
#2)Install pandas package (try to import the package in a python file)
#Installed successfully
Collecting pa... |
164ab46dfc6364b49b06b0bd442fe5e85bd6ca37 | sushmeetha31/BESTENLIST-Internship | /Day 3 task.py | 1,042 | 4.40625 | 4 | #DAY 3 TASK
#1)Write a Python script to merge two Python dictionaries
a1 = {'a':100,'b':200}
a2 = {'x':300,'y':400}
a = a1.copy()
a.update(a2)
print(a)
#2)Write a Python program to remove a key from a dictionary
myDict = {'a':1,'b':2,'c':3,'d':4}
print(myDict)
if 'a' in myDict:
del myDict['a']
print(myD... |
77720fc7dc475bbda16ca990f03eb2077ffec474 | enterprise-analytics-id/RWID_Yap | /fund_1.py | 515 | 3.96875 | 4 | # KONSTRUKSI DASAR PYTHON
# SEQUENTIAL: Eksekusi berurutan
print('Hello World')
print('by Enterprise Analytica')
print('30 Juni 2021')
print('-' * 10)
# PERCABANGAN: Eksekusi terpilih
ingin_cepat = True
if ingin_cepat:
print('jalan lurus saja')
else:
print('Jalan lain')
print('-' * 4)
# PERULANGAN
jumlah_kar... |
8ce3306a608dc5175c067f0d1e34ee21b0f94d31 | minsub0302/project | /calc.py | 525 | 3.59375 | 4 | import random as r
def calc():
a = r.randint(1,100)
b = r.randint(1,100)
c = r.randint(1,3)
if c == 1:
k = '+'
elif c == 2:
k = '-'
elif c == 3:
k = '*'
I = str(a)+k+str(b)
return I
D = input("What's your name?")
print('Hello '+D+'!!!!!!!!!!!!!!!!!!!!!!!!!')
B = True
while B:
A = str(calc())
mes... |
125eaf98db6359cb6d899c8e6aea55556c6c99f3 | DKumar0001/Data_Structures_Algorithms | /Bit_Manipulation/Check_Power2.py | 366 | 4.4375 | 4 | # Check wheather a given number is a power of 2 or 0
def Check_pow_2(num):
if num ==0:
return 0
if(num & num-1) == 0:
return 1
return 2
switch ={
0 : "Number is 0",
1 : "Number is power of two",
2 : "Number is neither power of 2 nor 0"
}
number = int(input("Enter a Number"))
... |
27f146b3dc51b7c9d2ebc1bd7780d7f2e5e27ebf | huseynakifoglu/Tic-Tac-Toe | /Problems/Particles/test.py | 576 | 4.09375 | 4 | # put your python code here
first_num = float(input())
second_num = float(input())
operator = input()
if operator == "+":
print(first_num + second_num)
elif operator == "-":
print(first_num - second_num)
elif operator == "*":
print(first_num * second_num)
elif operator == "pow":
print(first_num ** secon... |
bdf6935bfdb95419052cc858238a5f18964025eb | huseynakifoglu/Tic-Tac-Toe | /Problems/snake_case/task.py | 241 | 3.984375 | 4 | text = input()
text_ = list(text)
output = ""
for i in range(len(text_)):
if text_[i].islower():
output += text_[i]
elif text_[i].isupper():
text_[i] = text_[i].lower()
output += "_" + text_[i]
print(output)
|
ce6def55b48b8bfe66998bf6ce937cda07e33d3f | kbedan/python_basic | /Tuple.py | 8,171 | 4.90625 | 5 | #TUPLE
# ORDERED COLLECTION OF ITEMS WHICH ARE iMMUTABLE (cannot be altered)
"""A tuple in Python is similar to a list.
The difference between the two is that we cannot change the elements of a tuple
once it is assigned whereas we can change the elements of a list."""
=================... |
ff61137fb930d6a2b211d8eeb1577ca67ec64924 | YammerStudio/Automate | /CollatzSequence.py | 490 | 4.28125 | 4 |
import sys
'''
Rules:
if number is even, divide it by two
if number is odd, triiple it and add one
'''
def collatz(num):
if(num % 2 == 0):
print(int(num/2))
return int(num/2)
else:
print(int(num * 3 + 1))
return int(num*3 + 1)
print('Please enter a number and the Collatz seque... |
7ff53e6234d754040baec4278d8487acdb23d2d1 | koder-ua/python-classes | /examples/tasks/minilisp/evaluate.py | 897 | 3.703125 | 4 | #!/usr/bin/env python
# -*- coding:utf8 -*-
from nodes import to_nodes
def evaluate_procedural(parsed_prog):
if isinstance(parsed_prog, (int, str)):
return parsed_prog
assert isinstance(parsed_prog, tuple), "Program should be a tuple"
assert len(parsed_prog) > 0, "Program should not be empty"
... |
5e5a554e3e72a51a2d39b58bffe230eb4941a97a | koder-ua/python-classes | /examples/lazy.py | 759 | 3.71875 | 4 | #!/usr/bin/env python
# -*- coding:utf8 -*-
import functools
def lazy(func):
@functools.wraps(func)
def closure(*args, **kwargs):
return Lazy(func, args, kwargs)
return closure
class Lazy(object):
def __init__(self, func, args, kwargs):
self.func = func
self.args = args
... |
4b856c2caa43bc3714867662d3246b869a59a5a9 | mizanurriyadh/Python | /Pattern/simple piramid.py | 315 | 3.765625 | 4 | def pypart(n):
# outer loop to handle number of rows
for i in range(0, n):
# inner loop to handle number of column
for j in range(0, i+1):
# printing stars
print("* ", end="")
# ending line after each row
print("\r")
# Driver Code
n = 5
pypart(n) |
d1b19c5581bfbb8f7f9e7cdb70083a6012d82ee2 | oreo0701/openbigdata | /01_jumptopy/chap05/239.py | 210 | 3.625 | 4 | from copy import copy
a=3
print(id(3))
print(id(a))
b=a
print(id(b))
c=copy(a)
print(c)
print(id(c))
d= copy(3)
print(d)
print(id(d))
l1=[1,2,3]
l2=l1
l3=copy[l1]
print(id[l1])
print(id[l2])
print(id[l3]) |
a9adeb482a3e3926b3ec8ed8d97902ab8b7df149 | oreo0701/openbigdata | /01_jumptopy/chap03/133_range.py | 109 | 3.515625 | 4 | #my_range = range(10)
my_range = range(1,11)
sum = 0
for num in my_range:
sum = sum + num
print(sum)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.