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 |
|---|---|---|---|---|---|---|
c1e0c2d2ecd602dbe6fd8d022e678f7b1329a76f | hubieva-a/lab3 | /individual2.py | 947 | 3.953125 | 4 | # Даны цифры двух двузначных чисел, записываемых в виде a2a1, b2b1, где a1, b1 – число
# единиц, a2b2 – число десятков. Получить цифры числа, равного сумме заданных чисел
# (известно, что это число двузначное). Слагаемое – двузначное число и число-результат не
# определять; условный оператор не использовать.
#!/u... |
d9a26b05590ee4c5512e2a057443fe8dfdc355aa | Jeffresh/zookeeper | /zookeeper.py | 767 | 3.8125 | 4 | import animals as an
class Zoo:
def __init__(self, animals=None):
if animals and type(animals) == list:
self.animals = animals
else:
self.animals = []
def check_animals(self):
habitat = input('Which habitat # do you need?\n')
while habitat != 'exit':
... |
31f6f4032e451f0e784c6c4a7ce5d7a6090bd438 | Lalesh-code/PythonLearn | /String Operation.py | 1,739 | 4.15625 | 4 | name = 'Lalesh'
print(name)
name = "Garud"
print(name)
name = str("Welcome")
print(name)
#id function to get the memory location ID:
name1="welcome"
name2="python"
print(id(name1)) # 16157312
print(id(name2)) # 16157376
name3 = name2 + "my area"
print(id(name3)) # 15764880
# Operations on Strings: + for addition... |
a32fa47fe2f8e571a862e53e89d76ab67efebc21 | Lalesh-code/PythonLearn | /Oops_Encapsulation.py | 1,484 | 4.4375 | 4 | # Encapsulation: this restrict the access to methods and variables. This can prevent the data from being get modified accidently or by security point of view. This is achived by using the private methods and variables.
# Private methods denoted by "__" sign.
# Public methods can be accessed from anywhere but Private me... |
5f93f75d936bf7b2b14fedecb31313b2f734c3f5 | Lalesh-code/PythonLearn | /Numbers Opearation.py | 237 | 3.71875 | 4 | # Numbers are immutable
x=10
print(x)
print(float(x))
print(type(float(x)))
print(int(x))
print(type(int(x)))
# Built in functions - max(), min()
large = max(1,10,50,100)
print(large) # 100
small = min(1,10,50,100)
print(small) # 1
|
fdf2b4e519451e8e552d3be317ed3138edb184bf | joon0505/MoneyBot_Algorithm_Trading | /Practice.py | 1,286 | 3.640625 | 4 | def solution(numbers):
answer = 0
temp = [] #문자열 값의 정수변환 및 정렬을 위한 list 선언
max_str = '' # 주어진 numbers로 조합할 수 있는 max 숫자의 str 타입 형
max_int = 0 # 주어진 numbers로 조합할 수 있는 max 숫자의 int 타입 형
# numbers의 값들을 temp list 에 정수변환 하여 넣음
for i in range(len(numbers)):
temp.append(int(numbe... |
1fc17817c57ca5e8208492c95632133e442f6d31 | alemaan15/First-repo | /game.py | 674 | 3.515625 | 4 | game = [[2, 0, 2],
[1, 2, 0],
[2, 2, 0],]
#Diagonal
diag = []
for ix in range(len(game)):
diag.append(game[ix][ix])
diags = []
for i in reversed(range(len(game))):
diags.append(game[len(game)-i-1][i])
if diag.count(diag[0])==len(diag) and diag[0]!=0:
print("Diagonal Winnerrr")
if diags.count(diags[0])=... |
053f444dc31bf4631f3f1681451156eb24c9e5ff | gitsirihub/pythonclass | /GuessANumber.py | 234 | 4.09375 | 4 | '''
Created on Apr 24, 2018
@author: sisinga
'''
print ('Guess a number')
a = input ('Please input a number')
a = int (a)
if a < 50:
print ('Your number is less than 50')
else: print ('Your number is more than 50')
|
727e053dc981ef5fd028a66db297d7f7dfad5387 | xueyes/python3 | /loop.py | 276 | 3.796875 | 4 | # for every_letter in 'Hello, I love you':
# print(every_letter)
# for num in range(1,11):
# print(str(num) + ' + 1 =' , num + 1 )
count = 0
while True:
print ('Repeat the line 1 !')
count = count + 1
if count == 5:
#continue
break |
251d2647bb2279aa620b8d28af45c32ad0df3c06 | nickyrayray/IntroPythonProj | /Player.py | 2,464 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat May 16 08:50:23 2015
@author: nfalba
"""
import random;
class Player:
def __init__(self, name):
self.name = name;
self.pokemon = [];
def addPokemon(self, p):
self.pokemon.append(p);
def checkIfFull(self):
if len(self.pok... |
1e4c125103938aa1655d17f716250d65bf5c6d4f | SebastianMM-96/deepLearning-Keras | /firstNeuralNetwork/compiling/nn.py | 618 | 3.671875 | 4 | # Import's
from keras.models import Sequential
from keras.layers import Dense
# Create a new sequential model
model = Sequential()
# Add and input and dense layer
model.add(Dense(2, input_shape=(3, ), activation="relu"))
# Add a final 1 neuron layer
model.add(Dense(1))
# Summarize the model
model.summary()
# Compili... |
b80edc3ace2cb209e56e05289a01037b1b45d49a | DTerrell77/Machine-Learning | /Filling between the lines.py | 2,064 | 3.8125 | 4 | # CSC-356 ML
# Dylan Terrell
# Jan 21, 2021
# Multi-line comment is ctrl+ '+' +'/'
# Example 1
# Fill in Area Between Two Horizontal Lines
# import matplotlib.pyplot as plt
# import numpy as np
# #define x and y values
# #np.arrange(start, stop, step)
# x = np.arange(0, 10, 0.1)
# y = np.arange(10, ... |
68f80af66522f743b780687a6073d03e435b4692 | dquiroga10/CS141 | /Project1/leagues_to_feet.py | 213 | 3.921875 | 4 | leagues = float(input("How many leagues? "))
leagues_to_feet = leagues * 18228.3 #converstion from leagues to feet by multiplying a constant
print("There are" , leagues_to_feet , "feet in" , leagues , "leagues.")
|
ef5561afcbbc1228d08e4cff566f4ac8c21b7bbd | emma-rose22/practice_problems | /leet_twosum.py | 944 | 3.9375 | 4 | '''given an array of integers, return indices of the two numbers such that they add up to a specific problem
given nums = [2, 7, 11, 15], target = 9
because nums[0] + nums[1] = 2 + 7 = 9
return [0, 1]
'''
#this is a great time to use a hash table
#class Solution(object):
def twoSum(nums, target):
index_mapping... |
b9104f7316d95eaa733bbbd4926726472855046e | emma-rose22/practice_problems | /HR_arrays1.py | 247 | 4.125 | 4 | '''You are given a space separated list of nine integers. Your task is to convert this list into a 3x3 NumPy array.'''
import numpy as np
nums = input().split()
nums = [int(i) for i in nums]
nums = np.array(nums)
nums.shape = (3, 3)
print(nums)
|
c0a36bf1705c76d41b34d6fd033336237e3db6f4 | cmkishores/100DaysOfCode | /Guess.py | 332 | 4 | 4 | import random
i = True
x = random.randint(1,101)
while i:
guess = int(input ("Enter a number: "))
if (guess<x):
print(" Guess is less than the number")
elif (guess>x):
print(" Guess is greater than the number")
elif(guess == x):
print ("You Won! That was a correct guess")
... |
eb913d2753a8d15fe3ad916320e0c3959b264cc0 | SZkristof/tictactoe | /mainfunc.py | 732 | 3.546875 | 4 | from design import *
from inputs import *
def isWinner(bo, le):
return (
(bo[7] == le and bo[8] == le and bo[9] == le) or
(bo[4] == le and bo[5] == le and bo[6] == le) or
(bo[1] == le and bo[2] == le and bo[3] == le) or
(bo[7] == le and bo[4] == le and bo[1] == le) or
(bo[8... |
076560b0b8a64a5a2afeb9d5f7f27842d25ceafb | TedCassirer/Coursera | /python_data_science/week2/ass2.py | 2,698 | 3.5625 | 4 | import pandas as pd
df = pd.read_csv('olympics.csv', index_col=0, skiprows=1)
for col in df.columns:
if col[:2] == '01':
df.rename(columns={col: 'Gold' + col[4:]}, inplace=True)
if col[:2] == '02':
df.rename(columns={col: 'Silver' + col[4:]}, inplace=True)
if col[:2] == '03':
df.re... |
310c7ee2eff93ef5e6e0f023293993e9cfe5eae1 | matthewacha/YummyRecipes | /flask_app/test/test_recipe.py | 8,910 | 3.5 | 4 | """Module containing all the tests for Recipe class"""
import unittest
from app.models import Database, User, RecipeCategory,\
Recipe, RecipeStep
from app import utilities
class RecipeTest(unittest.TestCase):
"""All tests for the Recipe class"""
def setUp(self):
"""Initiates variables to be use... |
72a864f7453a5dfc875c64221f1a6f18f39414f5 | keltin13/Salvation | /Button.py | 2,130 | 3.671875 | 4 | ############################
## Keltin Grimes ##
## kgrimes@andrew.cmu.edu ##
## ##
## Term Project: ##
## Salvation ##
## - ##
## Button Class ##
############################
import pygame
# Generic button class for GUI
... |
aa4554e20572752a994e0bd2487e84820259a392 | 3wnbr1/TD-Informatique-ECAM | /SUP/TD1_correction/Euler_Problem_5.py | 563 | 3.515625 | 4 | from time import time
d=time()
nb = 1
for i in range(1, 21):
print("Solution pour", i,"entiers :")
min = nb # on repart du résultat précédent
while nb % i > 0: #si le résultat précédent ne se divise pas par l'entier suivant on entre dans la boucle
print("Résultat négatif pour", nb)
... |
d317e170af07805bbb536fc4b2fc08d7b556ce5b | 3wnbr1/TD-Informatique-ECAM | /SUP/TD1_correction/exercice_6.py | 222 | 3.890625 | 4 | T = float(input("Donner la température de l'eau : "))
if T < 0:
print("L'eau est sous forme de glace.")
elif T<100:
print("L'eau est sous forme liquide.")
else:
print("L'eau est sous forme de vapeur.")
|
bb9e854404404e2474b7c05449b5f36a95307b19 | 3wnbr1/TD-Informatique-ECAM | /SUP/TD2_codes/exercice2.py | 399 | 3.671875 | 4 | # -*- coding: utf-8 -*-
ma_liste = 6*[0] # indispensable de créer une liste de 6 éléments au préalable !
# ou ma_liste = list(range(6))
ma_liste[0]="a"
ma_liste[1]="e"
ma_liste[2]="i"
ma_liste[3]="o"
ma_liste[4]="u"
ma_liste[5]="y"
print(ma_liste)
#OU
ma_liste2 = list()
voyelles = "aeiouy"
for lett... |
f7ea02c93478207294e222ddc64158f29e916993 | 3wnbr1/TD-Informatique-ECAM | /SUP/TD1_correction/exercice_5.py | 223 | 3.59375 | 4 | prix = float(input("Donnez le prix HT d'un article :"))
nb = int(input("Donnez le nombre d'articles :"))
tva = float(input("Donnez le taux de TVA (en %) :"))
print("Le prix total TTC est de",prix*(tva/100+1)*nb,"€.")
|
f227d64bec225f4476dfdfdd131a88d184be6b9c | 3wnbr1/TD-Informatique-ECAM | /SUP/Resolution_numeriques/3.py | 243 | 3.578125 | 4 | import scipy.optimize as sc
import numpy as np
import matplotlib.pyplot as plt
plt.close()
def f(x):
return x**3+2*x**2-x-2
x = np.linspace(-2.5, 1.5, 1000)
print("Les zeros sont :",np.roots([-1,2,-1,-2]))
plt.plot(x,f(x))
plt.show()
|
baaf7154362bde518977d0be8d00baddae1dc223 | 3wnbr1/TD-Informatique-ECAM | /SUP/TD1_correction/exercice_13.py | 164 | 3.890625 | 4 | somme = 0
nb=int(input("Donner un nombre entier non nul : "))
for i in range(1,nb+1):
somme+=i
print("La somme des entiers jusqu'à",nb,"est",somme,"\b.")
|
71f04eddf5fae54214dee52bdcaa36a8bf2c7e46 | 3wnbr1/TD-Informatique-ECAM | /SUP/TD1_correction/exercice_20.py | 276 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 4 20:54:20 2015
@author: Pierre
"""
a = int(input("Entrer une année :"))
if a%4 == 0 and (a%100 != 0 or a%400 == 0):
print(a,"est une année bissextile.")
else:
print(a,"n'est pas une année bissextile.")
|
9cb69efcf9e95a55ce3df1f2fef2640a17ab72fe | 3wnbr1/TD-Informatique-ECAM | /SUP/TD2_codes/exercice15.py | 232 | 3.53125 | 4 | # -*- coding: utf-8 -*-
ma_liste = ["D","E","C","A","L","A","G","E"]
print(ma_liste)
prem = ma_liste[0]
for i in range(1,len(ma_liste)):
ma_liste[i-1]=ma_liste[i]
ma_liste[len(ma_liste)-1]=prem
print(ma_liste)
|
4d6f5bc1489b9285e5eb563bc5dbdeb82856a13b | 3wnbr1/TD-Informatique-ECAM | /SUP/TD3/capitales_v1.py | 729 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from random import choice
#Loding Data :
score = 0
datalist = list()
data = open('jeu_donnees.txt','r')
for line in data:
datalist.append(line.strip('\r\n').split(';'))
#Start_UI
print('='*48)
print("Bienvenue au jeu des capitales. v1")
print('='*48)
n = int(input(... |
044e361e733aefcf255f56396e2b23f417201063 | 3wnbr1/TD-Informatique-ECAM | /SUP/TD1_correction/exemple3.py | 264 | 3.84375 | 4 | x =float(input("Donner la valeur de x :"))
a = x >= 3
b = x < 10
if a and b:
print("x dans l'intervalle [3, 10[.")
elif not(a):
print("x trop petit pour être dans l'intervalle.")
else:
print("x trop grand pour être dans l'intervalle.")
|
48eb1e03ddcae01b657bbe4f409108def42d2c7a | Just-YH/Python | /Topic02_Hurynovich/Python2/PurchaseMoneyCalculation.py | 313 | 4.03125 | 4 | """Program to calculate Total cost of items."""
DOLLAR_PART = input("Input dollar part of item cost:\n")
CENTS_PART = input("Input cents part of item cost:\n")
QUANTITY = input("Input quantity of items:\n")
TOTAL_COST = DOLLAR_PART*QUANTITY + CENTS_PART*QUANTITY/100.0
print "Total cost: {0}$".format(TOTAL_COST)
|
848cc1bc3214e02277577627e5c6fe4284deec30 | TheOneTAR/tiffany_devCamp | /Python Intro /pre-project-stuff/dice.py | 832 | 3.8125 | 4 | from random import randint
class Die(object):
"""A class for making dice of different sizes
and rolling them."""
diceRolls = []
def __init__(self, numSides):
self.numSides = numSides
self.currentValue = 1
self.color = "white"
def roll(self):
self.currentValue = randint(1, se... |
65d4549dde309adfd36b4fa530186d044f7487bc | TheOneTAR/tiffany_devCamp | /Python Intro /Angry_MVC/angry_view_mobile.py | 661 | 3.671875 | 4 | __author__ = 'TheOneTAR'
class AngryMobileView:
"""Ideal view for smaller screen sizes, such as Mobile screens."""
def show_instructions(self):
text = "Welcome to Angry Dice! Roll the 2 dice until you win\n" \
"Stage 1 – 1 & 2\n" \
"Stage 2 – ANGRY & 4\n" \
"Stag... |
706de4742658894cc29bd061d5c99acdd2318634 | TheOneTAR/tiffany_devCamp | /Python Intro /Connect4Assignment/Connect4/tests/test_add_player.py | 1,386 | 3.5625 | 4 | __author__ = 'joecken'
import unittest
from connect4_game import Player, Game
class Connect4AddPlayerTest(unittest.TestCase):
"""Tests the add_player method of the Game"""
def setUp(self):
self.game = Game()
def tearDown(self):
del self.game
def test_with_first_player(self):
... |
833241787a82e908fa401665c040bfe3124a8ada | lbbruno/Python | /Exercicios_1/ex012.py | 157 | 3.65625 | 4 | p = float(input('Digite o preço que receberá o desconto: '))
print('O novo valor com desconto é: {:.2f} | Foi descontado {:.2f}'.format(p*0.95, p*0.05))
|
e9f59f8662139961e5c7381a78886c12896c7b01 | lbbruno/Python | /Exercicios_1/ex041.py | 543 | 3.984375 | 4 | from datetime import datetime
frame = '*' * 60
print(frame)
print('{:*^60}'.format(' Confederação Nacional de Natação '))
print(frame)
anoAtual = datetime.now().year
anoNasc = int(input('Informe o ano de nascimento do atleta: '))
idade = anoAtual - anoNasc
categoria = str('')
if idade < 10:
categoria = 'Mirim'
el... |
2999f9e4d710e206774ed039911fab9fa5c9627a | lbbruno/Python | /Exercicios_1/ex054.py | 390 | 3.875 | 4 | from datetime import datetime
anoatual = int(datetime.now().year)
maior = 0
menor = 0
for i in range(1, 8):
nasc = int(input('Digite o ano de nascimento da {}° pessoa:'.format(i)))
idade = anoatual - nasc
if idade >= 18:
maior += 1
else:
menor += 1
print('''Existem {} pessoas menores de... |
16501836a54fdc7ceba149779d2c811d2ecab37c | lbbruno/Python | /Exercicios_1/005_Formatando_Strings_1.py | 106 | 4.0625 | 4 | n = int(input('Digite um número:'))
print('O antecesso de {} é {} e o sucessor é {}'.format(n,n-1,n+1)) |
d49cdfb4e1ef68e0239ffff7d02d683d8c3657e1 | lbbruno/Python | /Exercicios_1/006_Formatando_Strings_2.py | 133 | 3.90625 | 4 | n = int(input('Digite um valor:'))
print('Valor Digitado:{} | Dobro:{} | Triplo:{} | Raiz quadrada:{} |'.format(n,n*2,n*3,n**(1/2)))
|
64492ca7c08b35175af73641940d6bdde595dac0 | lbbruno/Python | /Exercicios_1/ex036.py | 1,187 | 3.921875 | 4 | print('=' * 30, 'Emprestimo Bancário', '=' * 30)
casaVlr = float(input('Primeiramente informe o valor do imóvel a ser comprado:'))
salario = float(input('Informe o seu salário:'))
vlrMaximoParcela = salario * 0.3 # Calcula 30% do salário que não deve ser excedido
minimoParcelas = casaVlr // vlrMaximoParcela + 1
numP... |
5abcf5f032e02d2e686f800fc9cfbf6b47a7f10e | lbbruno/Python | /Exercicios_1/ex043.py | 952 | 3.8125 | 4 | frame = '*' * 60
print(frame)
print('{:*^60}'.format(' Cálculo IMC '))
print(frame)
peso = float(input('Informe o peso: ')) # Recebe o peso pelo usuário
altura = float(input('Informe a altura: ')) # Recebe Alatura pelo usuário
imc = (peso / (altura * altura)) # Calculo do IMC
situacao = ''
pesoMax = (24.99 * (altur... |
ae994f7fa77601e04861ec8b87c87693e1b32eda | lbbruno/Python | /Exercicios_1/ex018.py | 164 | 3.734375 | 4 | import math
a = float(input('Informe o ângulo: '))
sen = math.sin(a)
cos = math.cos(a)
tan = math.tan(a)
print('sen: {} || cos: {} || tan:{}'.format(sen,cos,tan))
|
5c7c0fd1001729c89c9d81b14b8e0a44fbfb045d | lbbruno/Python | /Exercicios_1/ex073.py | 519 | 3.84375 | 4 | div = ('='*40)
times = ('', 'São Paulo', 'Internacional', 'Atletico-MG', 'Flamengo', 'Grêmio', 'Palmeiras',
'Palmeiras', 'Fluminense', 'Santos', 'Ceará', 'Corinthians',)
print(f'Lista de times do Brasileirão\n{times[1:]}')
print(div)
print(f'Os 5 primeiros são:')
print(f'{times[1:6]}')
print(div)
print('Os 4 ú... |
18c035e7917e335bf2785a1b611e887c69581857 | lbbruno/Python | /Exercicios_1/ex065.py | 606 | 3.953125 | 4 | n = cont = soma = maior = menor = media = 0
repetir = 'S'
while repetir == 'S':
n = int(input('Digite um número: '))
if cont == 0:
maior = n
menor = n
else:
if n > maior:
maior = n
if n < menor:
menor = n
soma = soma + n
media = float(s... |
16bf6b92df5d1b54ac11a8185109a9d44f45f0b9 | oldboy123/oldboy_practice | /test_repr_str.py | 602 | 3.953125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""By xuzhigui"""
class Book(object):
def __init__(self, author, title, price):
self.author = author
self.title = title
self.price = price
def __repr__(self):
print("repr is called")
return "{0} - {1}".format(self.author, ... |
38a70f45f1c09b2b63e7551b86a7ed00af8390cc | tphene/test2- | /maxbin.py | 832 | 3.5 | 4 | class TreeNode:
def __init__(self,value):
self.val = value
self.left = None
self.right = None
def constructMaximumBinaryTree(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
def construct(nums,l,r,node):
node = TreeNode(max(num... |
5c1f47c22fda4516b79ba8022460563fe986c836 | xkortex/pstruct | /pstruct/core.py | 2,604 | 3.578125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import Mapping
from pstruct.validity import is_invalid_key, InvalidKeyName
class Pstruct(dict):
"""
A dict-compatible data structure with attributes defined by slots.
"""
__slots__ = ["_pstruct"]
def __init__(self, *args, **kwargs):
... |
f51375d9a8f3f61c219ca98d983cfb7fa572e343 | cp-helsinge/eksempler | /fibonacci.py | 244 | 3.625 | 4 | # En lykke der beregner fibronacci tal
# beregning: Et hvert tal, er lig med summen af de to forudgående tal, startende med 1.
# Eksempel: 1 1 2 3 5 8 13
a=1
b=1
for n in range(1,10):
print(a, end =" "),
c=a+b
a=b
b=c
print("")
|
2530c028c5bc17bd73db55bd2743a9396f033889 | cp-helsinge/eksempler | /simon.py | 701 | 3.875 | 4 | # -*- coding: utf-8 -*-
# testing ground
class Test1:
def __init__(self):
self.a =1
self._d=4
self.__e=5
class Test2(Test1):
def __init__(self):
Test1.__init__(self)
self.b = self.a+1
class Test3(Test2,Test1):
def __init__(self):
Test1.__init__(self)
... |
805c540dbf1cd32ba3d5e54247b6bdee331cf2ed | cp-helsinge/eksempler | /l3_2_turtle.py | 197 | 3.609375 | 4 | import turtle
# Color and size
# turtle.pencolor((0.5,0,1))
# turtle.pensize(5)
turtle.speed(0)
# the power of for loops
for n in range(1,320):
turtle.left(15)
turtle.forward(n/5)
input()
|
ff1b018004afb7c4c3beadb07dc5267211b23167 | mahammadmansur95/python | /oops_durga.py | 4,435 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 1 19:22:14 2020
@author: acre
"""
class student:
def __init__(self,name,roll,marks): #constructor
self.name = name
self.roll = roll #instance variable
self.marks=marks
def display(self): #method
... |
9d243347f5c329b7e4cf68ee58a6347baf92b6b3 | mahammadmansur95/python | /regularexp.py | 652 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 2 15:15:19 2020
@author: acre
"""
"""regular exprections"""
import re
count = 0
matcher = re.finditer('ab','abaaaabaaba')
for match in matcher:
count +=1
print(match.start(),"....",match.end(),"....",match.group())
print("the number of occurren... |
9fab85249e7c862131ab337f1dd6aca06f6d9ba9 | neerajkulk/solar_refraction | /atmos_refrac.py | 13,905 | 3.609375 | 4 | #!/usr/bin/env python
# coding: utf-8
# ## atmospheric_refraction.pro
#
# ### Purpose:
# Calculate the refraction of the Sun at different wavelengths.
#
# ### Explanation:
# This program calculates the refractivity of the air for a given set of atmospheric conditions and the position of the Sun for an array of inp... |
28b4fac84b8fb63c83e2db30695fcc519b0158af | qimanchen/Algorithm_Python | /Chapter6/discrete_event_system.py | 8,673 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
离散事件模拟:
行为特征:
1、系统运行中可能不断发生一些事件(带有一定的随机性)
2、一个事件在某个时刻发生,其发生可能导致其他事件在未来发生
通用模拟框架:
"""
from random import randint
from priority_queue import PrioQueue
class QueueUnderflow(ValueError):
"""判断队列为空是,异常类"""
pass
class SQueue(object):
"""队列实现数据结构"""... |
0aa336fc2a8e018a6a75d7366d6fac2076ab73e1 | qimanchen/Algorithm_Python | /Chapter3/stack_by_list.py | 580 | 3.9375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
class TestQueue(object):
def __init__(self, elems=None):
self._queue = []
def is_empty(self):
return len(self._queue) == 0
def in_queue(self, elem):
self._queue.append(elem)
def out_queue(self):
return self._queue.pop()
def print_queue(self):
... |
33ba46d849eec7e9d1021641558606a24904b40a | qimanchen/Algorithm_Python | /python_interview_program/合并两个有序序列.py | 779 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
合并两个有序列表
"""
def recursion_merge_sort(l1, l2, tmp):
"""
:param l2: list
:param l1: list
:param tmp: sorted list
:return: list
"""
if len(l1) == 0 or len(l2) == 0:
tmp.extend(l1)
tmp.extend(l2)
return tmp
else:
if l1[0] < l2[0]:
tmp.append(l1[0])
... |
1835749cfdd89680d79881e8b0290b92ec6b7a61 | qimanchen/Algorithm_Python | /Chapter2/class_static_limit_success.py | 546 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
静态约束
就是,在谁里面,就谁做主
动态约束
x = C() # 实例类C
x.f() # f 为虚函数
实际调用流程:
1、先检查类C中是否有方法f
2、若没有,则检查它的基类B中是否有相应的方法
3、执行B中的f,但是其 self属性还是表示C的
谁实例化,self就代表谁
"""
class B(object):
def f(self):
self.g()
def g(self):
print('B.g called.')
class C(B... |
0d17c10f02dfa0efed8c780f6d19620675261334 | Adi-Deshmukh/Scientific-Calculator-using-python | /Scientific Calculator/main.py | 5,655 | 3.765625 | 4 |
#scientific Calculator
# imports
from tkinter import *
import parser
import math
# MAIN SCREEN
root = Tk()
root = root
root.title("Calculator")
root.geometry("308x535")
root.configure(bg="black")
root.resizable(20,20)
# The all Values and Functions
i = 0
def get_value(num):
global i
... |
5ef57d686450c3f248ae64b1b62d4674f91799d6 | parth18356/Hackerrank-Python | /gradingstudents.py | 952 | 3.828125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'gradingStudents' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts INTEGER_ARRAY grades as parameter.
#
def gradingStudents(grades):
i=0
for i in range(grad... |
f4e0cd1f22c515f21afb7a0ba4f73ace58702864 | Andrey-Rogov/snake-game | /snake.py | 4,179 | 3.75 | 4 | from turtle import Turtle, Screen
from time import sleep
from random import randint
START_POSITION = [(0, 0), (-20, 0), (-40, 0)]
MOVE_DISTANCE = 30
UP = 90
DOWN = 270
LEFT = 0
RIGHT = 180
FONT = ("Courier", 15, "normal")
screen = Screen()
screen.setup(600, 600)
screen.bgcolor("black")
screen.title("My S... |
6950ab377a7b09b923a55bf88e977f996ea74aec | Tulmot/TFG_DietaPorDientes | /src/proyecto/analisis/estadisticas/Estadistica.py | 7,881 | 3.734375 | 4 | import math
from proyecto.analisis.diccionario.Diccionario import Diccionario
class Estadistica():
"""
Clase que se encargara de calcular las estadisticas de una conjunto de rectas dadas
dependiendo de esto las agrupara y calculara sus atributos como distancia , numero de cada
tipo o angulo de cada rec... |
0f71c08b312080cae70fee385626f4837073ab5b | nishantiwari-iitg/EE524-1 | /Assignment1/204102316_Sqn_Ldr_Nishan_Tiwari/EE524_ASST1_Ques6 decending list.py | 481 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 18 11:51:40 2020
@author: NISHAN TIWARI
"""
list1=[]
n=15
for i in range (0,n):
e=int(input("Enter the elements\n"))
list1.append(e)
print ("The numbers before sorting are\n",list1)
for j in range (0,n-1):
for k in range (0,n-j-1):
if l... |
639515d5edc0de1366b79d044c629cc599a57b7e | nishantiwari-iitg/EE524-1 | /Assignment1/204102316_Sqn_Ldr_Nishan_Tiwari/EE524_ASST1_Ques2.py | 385 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 18 11:48:54 2020
@author: NISHAN TIWARI
"""
a=int(input("Enter first number\n"))
b=int(input("Enter second number\n"))
c=a+b
d=a-b
e=a*b
f=a/b
g=a%b
print("first number is ",a,"\nsecond number is ",b,"\nthere sum is ",c,"\nthere difference is ",d,"\nthere m... |
0c54b81762859a014fd818b948e3d81a52865bc1 | samlanka/Algorithms | /Graphs/DFS.py | 319 | 3.71875 | 4 | #Depth-first-search graph traversal
#Author: Sameera Lanka
def dfs(graph, start):
visited, stack = [], [start]
while stack:
node = stack.pop()
if node not in visited:
visited.append(node)
for neighbour in graph[node]:
stack.append(neighbour)
return vi... |
82c27e750058b6853bafc75b05a4e73503b8518f | EshrakK/py_func | /email_regex.py | 236 | 3.71875 | 4 | # Regex for email address
import re
emails = '''
timothy145@gmail.com
geofry.hinton@university.edu
max-321-payne@my-work.net
'''
pattern = re.compile(r'[a-zA-Z0-9.-]+@[a-zA-Z-]+\.(com|net|edu)')
matches = pattern.finditer(emails)
for match in matches:
print(match)
|
f9f1c93c718757455569fcce64b95250ef77f8bd | rouleau/gamepicker | /gamepicker/utilities/budget.py | 295 | 3.609375 | 4 | """ Budget planner """
from random import choice, choices
budget = 100
bet_amounts = [2, 3, 4, 5]
bets = []
while budget > 2:
bet = choice(bet_amounts)
if bet <= budget:
bets.append(bet)
budget = budget - bet
print("Bets:", bets)
print("Number of Bets:", len(bets))
|
e4150c9a8c2bc41995315a2a095dc781dcda4aed | radhigulati/jsandpy | /array_partition_i.py | 2,592 | 4 | 4 | # Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.
class Solution(object):
def arrayPairSum(self, nums):
nums.sort()
res = 0
for i in... |
cb7118a415776c30ee4f4fa46ca9e1c8a4c32a86 | joannalew/networks | /proj1/chatserver.py | 2,255 | 3.953125 | 4 | #!/bin/python
# Joanna Lew
# 7-30-17
# OSU CS372 Project 1
# Descrip: Using TCP Protocol and Socket API, create a
# simple chat system between a client and a server.
# Python Server Example: https://docs.python.org/2/library/socket.html#example
import sys
import socket
# Send server name to client; get client nam... |
b8d56fba7b098bfb4dcffe7436013ed11c62326f | Freesensei/Sanity | /NPC.py | 4,165 | 3.65625 | 4 | from sys import exit
import time
Running = False
i = 0, 1, 2, 3, 4, 5, 6
##################
class NPC:
raise_amt = 1.05
num_npc_amount = 0
def __init__(self, first, last, pay, position):
self.first = first
self.last = last
self.pay = pay
self.position = position
... |
2a3d35b1bbe23070068a27771a73db334c8ea745 | jjcc/scrapybots | /generalbot/crpytojson_process.py | 706 | 3.59375 | 4 | import json
'''process json file generated by cryptobot
for now, output the list of interest coins by print
'''
def process(file):
fp = open(file,"rb");
data = json.load(fp)
for c in data:
coininfo = c['coininfo']
rank = coininfo['Rank']
#print coininfo['Name']
if "extrainfo" in... |
4239aaee9e02cf22c29b61d6e60efabf702abcb5 | asiapiorko/Introduction-to-Computer-Science-and-Programming-Using-Python | /Unit 1 Exercise 1.py | 1,616 | 4.1875 | 4 | """
In this problem you'll be given a chance to practice writing some for loops.
1. Convert the following code into code that uses a for loop.
prints 2
prints 4
prints 6
prints 8
prints 10
prints Goodbye!
"""
# First soultion
for count in range(2,11,2):
print(count)
print("Goodbye!")
# F... |
78a1a1d2d9f6afebcdc69c1e8a7fb2b321983a7e | siddhant68/Data-Structures-Python | /Sort.py | 1,878 | 3.5 | 4 | # Selection Sort
l = [10, 7, 8, 9, 1, 5]
for i in range(len(l)):
ind = i
for j in range(i+1, len(l)):
if l[ind] > l[j]:
ind = j
if i != ind:
l[i], l[ind] = l[ind], l[i]
print(l)
# Bubble Sort
l = [10, 7, 8, 9, 1, 5]
for i in range(len(l)):
flag = 0
for j i... |
f5c927eb7c5bda3f22de135a71d4d8ae284a281c | VitthalMagdum0104/python_problems | /dec_to_binary.py | 333 | 3.96875 | 4 | # def compute_binary(num):
# if num == 0:
# return 0
# if num >= 1:
# return str(compute_binary(num//2))+str(num % 2)
# print(compute_binary(8))
def compute_binary(num):
if num >= 1:
compute_binary(num // 2)
print(num % 2, end='')
compute_binary(8)
# print(bin(8).replac... |
6cb08d4104436385ac63661b45766d94d2ec177d | JCanedaG/Proyecto4enRaya | /cuatro_en_raya.py | 3,649 | 3.578125 | 4 | # -*- coding: utf-8 -*-
#Imports
import os
import time
from ./jaime_bot_1 import JaimeBot1
# Definición de funciones
def pintar_tablero(matriz_juego):
for i in range(len(matriz_juego)):
texto_fila = ''
for j in range(len(matriz_juego[i])):
texto_fila += '|'
if matriz_juego[len(matriz_jue... |
833c8f8fb45c49c735a19e53eff2ae6aa9321adb | ha-usth/WingLanmarkPredictor | /iMorph_src/point.py | 656 | 3.625 | 4 | class Point:
def __init__(self,x_init,y_init):
self.x = x_init
self.y = y_init
def shift(self, x, y):
self.x += x
self.y += y
def force_in_range (self, w, h):
self.x = max(self.x,0)
self.x = min(self.x,w)
self.y = max(self.y,0)
self.y = min(se... |
094baaccde095dcd8b0e932a094c87f372851bc2 | daniel-afana/coding-roblems | /reverse-iterable.py | 237 | 3.84375 | 4 | def reversed_iterable(s):
u"""Reverses a sequence using a built-in function
:param s: iterable with a __reversed__() method or
_getitem__() and __len__() methods
:return: reversed sequence
"""
return reversed(s)
|
84fce63f043d3b48c019739dce5d9a58df6c0198 | arcstarusa/prime | /StartOutPy4/CH7 Lists and Tuples/drop_lowest_score/main.py | 678 | 4.21875 | 4 | # This program gets a series of test scores and
# calculates the average of the scores with the
# lowest score dropped. 7-12
def main():
# Get the test scores from the user.
scores = get_scores()
# Get the total of the test scores.
total = get_total(scores)
# Get the lowest test scores.
lowest... |
e2106e1e3de96fe8890528d6069989c6e703b87e | arcstarusa/prime | /TheQuickPythonBook2ndVernonL/if-elif-else-statement.py | 388 | 3.921875 | 4 | #The block of code after the fist true condition (of an if or an elfif ) is executed.
# If none of the condition is true, the block of code after the else is exceuted.
x = 5
if x < 5:
y = -1 #python uses indentation to delimit blocks
z = 5
#elif and else clauses are optional
elif x > 5:
y = 1
z = 11
el... |
18c597902f1fa9e14de3506f2cce0d357af647b0 | arcstarusa/prime | /StartOutPy4/CH12 Recursion/fibonacci.py | 457 | 4.125 | 4 | # This program uses recursion to print numbers from the Fibonacci series.
def main():
print('The first 10 numberss in the ')
print('Fibonacci series are:')
for number in range(1,11):
print(fib(number))
# The fib function returns returns the nth number
# in the Fibonacci series.
def fib(n):
if n... |
272ba928131e12b772e60c737e791d7fdb3031bd | arcstarusa/prime | /StartOutPy4/CH4 Repitition Structures/simple_loop2.py | 174 | 4.5 | 4 | # This program also demonstrates a simple for
# loop that uses a list of numbers.
print('I will display the odd numbers 1 through 9.')
for num in [1,3,5,7,9]:
print(num) |
1684ed5ced8288e821c464db286a72f0c1098b0a | arcstarusa/prime | /StartOutPy4/CH8 Strings/validate_password.py | 420 | 4.15625 | 4 | # This program gets a password from the user and validates it. 8-7
import login1
def main():
# Get a password from the user.
password = input('Enter your password: ')
# Validate the password.
while not login1.valid_password(password):
print('That password is not valid.')
password = in... |
c7199516daccdae79abbefd6321f96392159d5e4 | screamff/Hello-Python | /thread_intro/08-iter.py | 541 | 3.59375 | 4 | # coding:utf-8
from collections import Iterable
class Classmate(object):
def __init__(self):
self.names = list()
def add(self, name):
self.names.append(name)
# 拥有iter方法即是可迭代对象
# 拥有iter和next方法即迭代器,可用作生成(return)可迭代对象
def __iter__(self):
"""使其成为可迭代对象"""
pass
class... |
7996a3fd503168a8203e9a72499ae231f2203ce4 | screamff/Hello-Python | /thread_intro/09-iter-next.py | 850 | 3.921875 | 4 | #! python3
# coding:utf-8
from collections import Iterable
class Classmate(object):
def __init__(self):
self.names = list()
self.current_num = 0
def add(self, name):
self.names.append(name)
# 拥有iter方法即是可迭代对象
# 拥有iter和next方法即迭代器,可用作生成(return)可迭代对象
def __iter__(self):
... |
9f564b6a687e39159827eafc341b9a1ade7c49a5 | lavaniab/harvest-melons | /harvest.py | 2,818 | 3.5625 | 4 | ############
# Part 1 #
############
class MelonType(object):
"""A species of melon at a melon farm."""
def __init__(self, code, first_harvest, color, is_seedless, is_bestseller,
name):
"""Initialize a melon."""
self.pairings = []
self.code = code
self.fi... |
79a710e89307661f01f31dce8844c34daddcd179 | akhuh213/hangman-challenge | /hangman.py | 2,007 | 3.84375 | 4 | import random
words = ['banana', 'tree', 'plate', 'mirror', 'chair']
# def shuffle(ls):
# random.shuffle(ls)
# return display_word(random_word)
# print(shuffle(word))
def wrong_answer(count):
if count == 1:
print( "|-\ \n| 0 \n| \n| \n try again!")
elif count == 2:
print( "|-... |
46cba8a43cb65ece9a372e4c99c46b987d88dbd7 | LesterAGarciaA97/OnlineCourses | /08. Coursera/01. Python for everybody/Module 1/Week 06/Code/4.6Functions.py | 1,004 | 4.4375 | 4 | #4.6 Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Pay should be the normal rate for hours up to 40 and
#time-and-a-half for the hourly rate for all hours worked above 40 hours. Put the logic to do the computation of pay in a function called computepay() and use
#the... |
cf972c29dece8fd4506d33cdb0fa2ced0915987a | LesterAGarciaA97/OnlineCourses | /08. Coursera/25. Big-O time complexity in Python code/Module 1/Week 01/Program/PythonBigO/task4.py | 630 | 3.875 | 4 | from plot import plot
from linear_search import linear_search
import random
# Task 4: Create and analyze the linear search function
arr = [ 2, 3, 4, 10, 40, 60, 80, 100]
x = 100
# Function call
size = []
iters = []
for i in range(10):
result,count = linear_search(arr, x)
iters.append (count)
size.ap... |
ffedac6bf30d341ff0676ca272ba5f6d76e2fe33 | LesterAGarciaA97/OnlineCourses | /08. Coursera/27. Python data structures/Module 1/Week 01/Program/PythonDS/quiz3.py | 591 | 3.5 | 4 | import random
def get_word_and_definition(rastring):
word, definition = rawstring.split(',', 1)
return word, definition
#Import the file, read the file, put the content in a list and print the list
fh = open("Vocabulary_list.csv", "r")
wd_list = fh.readlines()
wd_list.pop(0) #Remove the first entry in the l... |
0bdf4a37a6389b9ea23c715b119f019ac12a46e7 | AmandaMurray/Machine-Learning-For-Virginia | /ML.py | 5,425 | 3.53125 | 4 | #Hey look we have an ML Document where we can maybe probably understand WTF is happening :)
#Because we need all these ALL THE FUCKING TIME
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import os
#For data cleaning+Processing+Discovery
from sklearn.model_selection import tra... |
b665a17acf96488ddc809dd135d462c8bb82831f | lucasmonteirobandtec/python-ex | /manipuling-text/6.py | 131 | 3.828125 | 4 | name = str(input('Digite seu nome inteiro: '))
li = name.split()
print('Primeiro nome {}, último nome {}'.format(li[0], li[-1])) |
3c8c79249d33ee147d20ddbb3336f5f875e1337c | lucasmonteirobandtec/python-ex | /for/8.py | 263 | 4.09375 | 4 | p = str(input('Digite uma frase: '))
p = p.replace(' ', '')
p = p.upper()
ip = p[::-1]
ip = ip.upper()
if p == ip:
print('As palavras {} e {} são um Pálindromo'.format(p, ip))
else:
print('As palavras {} e {} não são um Pálindromo'.format(p, ip))
|
7144251e22477f9a4568acc9803bd710fdecd84a | lucasmonteirobandtec/python-ex | /while/1.py | 254 | 3.953125 | 4 | sex = str(input('Sexo: [M]/[F] ')).strip()[0]
while sex not in 'MnFf':
sex = str(input('Digite novamente... [M]/[F] ')).strip()[0]
if sex in 'Mn':
sex = 'masculino'
else:
sex = 'feminino'
print('Sexo {} registrado com sucesso'.format(sex)) |
383f5cae2df3c048244861fbcd42ccdf597709c8 | lucasmonteirobandtec/python-ex | /while/2.py | 221 | 4.03125 | 4 | from random import randint
num = int(input('Digite um numero de 1 a 10: '))
num2 = randint(0, 10)
while num != num2:
num2 = randint(0, 10)
num = int(input('Digite um numero de 1 a 10: '))
print('Você acertou') |
ba73e6da1844ea7982997002ef3d74fc2b67a67a | lucasmonteirobandtec/python-ex | /manipuling-text/3.py | 157 | 3.8125 | 4 | city = str(input("Digite o nome de sua cidade: "))
city = city.lower()
if("santo" in city[:5]):
print("tem Santo")
else:
print("não tem santo")
|
fb810fc8ebb1648992503d73685b61474c97a077 | oransimhony/nand2tetris | /06/Assembler/code.py | 2,032 | 3.578125 | 4 | class Code(object):
def dest(self, mnemonic):
if mnemonic == 'null':
return "000"
elif mnemonic == 'M':
return "001"
elif mnemonic == 'D':
return "010"
elif mnemonic == 'MD':
return "011"
elif mnemonic == 'A':
return "100"
elif mnemonic == 'AM':
return "101"
elif mnemonic == 'AD':
re... |
fa13866c67266b10d08bda687f86d5c7196d0f8a | Lvchaoyi/Leetcode | /data_structure/trie.py | 4,268 | 3.609375 | 4 | #! usr/bin/env python
# -*- coding: utf-8 -*-
"""
trie.py
~~~~~~~~~~~~~~~~~~~~~~~
208. 实现 Trie (前缀树)
:author: jacklv :)
:copyright: (c) 2018, Tungee
:date created: 19-7-9 下午8:56
:python version: 3.5
"""
class Node:
def __init__(self, val):
"""
Initialize a node.
... |
06258d00d6cc9d026e3637b8d04925c05cbda561 | tyosssss/python3.5-demo | /build.in.type/string/string.func.encode.py | 311 | 3.53125 | 4 | # -*- coding:utf-8 -*-
FILE = 'unicode.txt'
CODEC = 'utf-8'
str_out = u'你好 Python\n'
bytes_out = str_out.encode(CODEC)
with open(FILE, "wb") as fp:
fp.write(bytes_out)
with open(FILE, "rb") as fp:
bytes_in = fp.read()
str_in = bytes_in.decode(encoding='utf-8')
print('from file : ', str_in)
|
51f914c9a4f404d46aac066e3e37970c4adc1fe1 | tyosssss/python3.5-demo | /generator/gen.fib.py | 238 | 3.71875 | 4 | # -*- coding:utf-8 -*-
# 使用生成器实现 , 菲波那切数列数列
def create_fib_gen(n):
f1 = 0
f2 = 1
for i in range(0, n):
yield f2
(f1, f2) = (f2, f1 + f2)
print([x for x in create_fib_gen(10)])
|
c32191d419a6456a514b91b8a3f73106d158007c | tyosssss/python3.5-demo | /build.in.type/dict/fromkeys.py | 171 | 3.734375 | 4 | # -*- coding:utf-8 -*-
lst = ['a', 'b', 'c']
tpl = ['1', '2', '3']
d = {"a": 1, "b": 2, "c": 3}
print(dict.fromkeys(lst, 1))
print(dict.fromkeys(tpl, 2))
print(iter(d))
|
39482b226b8b4bd5c2b20f02bf139e7d3e22d4d9 | tyosssss/python3.5-demo | /build.in.type/dict/key.missing.py | 340 | 3.578125 | 4 | # -*- coding:utf-8 -*-
# 1. 第一种处理key缺失的方法
class Counter(dict):
def __missing__(self, key):
self[key] = 0
return self[key]
counter1 = Counter()
counter1['red'] += 1
print(counter1)
# 2 . 第二种处理key缺失的方法
counter2 = dict()
counter2['red'] = counter2.get('red') + 1
print(counter2)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.