blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
fd606068c480f06130cc7a5793099376fa086631 | owoshch/Cracking_the_coding_interview_5 | /chapter_8_recursion/8_3_magic_index_distinct_numbers.py | 617 | 4.21875 | 4 | def find_index(array, left, right):
"""
array - sorted array of distinct integers
If magical index is not presented in the array,
return -1
"""
if left <= right:
mid_index = left + (right - left) // 2
if array[mid_index] > mid_index:
# search left
return f... |
5ecae442221c1cf3ad5a338671106d0eefacc8a8 | fagnercandido/codes | /python/NPerfeitos.py | 1,511 | 3.734375 | 4 | '''
Sintese :
Objetivo : Determinar os numeros perfeitos
Entrada : n valores
Saida : Numeros que se enquadram na condicao
Autor :
f_Candido
@fagner_candido
fagner7777777@gmail.com
'''
import time
class NPerfeitos:
def __init__(self):
self.totalSomatorio = 0
self.valorInicial = 30
self.co... |
0a1a26ccbc5d7b05703cef742c7bb4bbe2db1fc8 | fagnercandido/codes | /python/paridade.py | 352 | 4.0625 | 4 | #! /usr/bin/python
#Autor: Fagner Candido
#Objetivo : Verifica paridade de Numeros
#Entrada : Um inteiro
#Saida : A paridade do numero
#Leitura do Valor
numero = int(raw_input("Informe o Valor : "))
#O condicional verifica: Caso o modulo de zero, e par
if ((numero % 2) == 0):
print 'O numero e par'
#Caso contrario e... |
48f1a2a018ed65ce3be600e7cdb0a7fd01af4513 | chatsdude/Data-Structure-Implementations | /BST.py | 1,354 | 3.953125 | 4 | class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BST(object):
def __init__(self, root):
self.root = Node(root)
def insert(self, new_val):
return self.insert_help(self.root,new_val)
def insert_he... |
de1b0dc2df98f1730e83fa3a9c3cf88b870fe06f | vara0257/python-practise | /lambda.py | 705 | 4.5 | 4 | # A lambda function is small anonymous function
# A lambda function can take any number of arguments, but can only have one expression.
# Synatax
# lambda arguments : expression
# Single argument
x = lambda x: x+10
print(x(5))
# Two arguments
x = lambda a, b : a * b
print(x(5,6))
# Multiple arguments
x = lambda a,... |
ccea3e85fde1879de986ddb061b9aaa8cffa164d | AbdallahAhmed1999/WDMM-1402 | /chapter6/string_comparison.py | 245 | 4.28125 | 4 | # string comparison (alphabetic order)
word1 = 'banana'
word2 = input('enter a word: ')
if word2 > word1:
print(word2, 'is after', word1)
elif word2 < word1:
print(word2, 'is before', word1)
else:
print(word2, 'is the same', word1)
|
881eec715c251218e98c840aefabfda3d47fa639 | AbdallahAhmed1999/WDMM-1402 | /chapter3/calc1.py | 416 | 4.40625 | 4 | '''
write a program that asks the user to enter two
numbers and the operator (*, /), and compute the result
according the operator.
'''
number1 = float(input('enter 1st number:'))
number2 = float(input('enter 2nd number:'))
op = input('enter operator: ')
# addition
if op == '+':
print(number1 + number2)
# subtracti... |
9010c6dac1df57e55d03314a5ecfe1fc56facc35 | AbdallahAhmed1999/WDMM-1402 | /chapter2/types_conversions3.py | 65 | 3.53125 | 4 | s = '123'
print(s + '1') # concat
print(int(s) + 1) # addition
|
e98d680c3d4aa80ed68b2635b307cd8b9fafc717 | AbdallahAhmed1999/WDMM-1402 | /chapter3/freelancer_payment.py | 656 | 4.1875 | 4 | '''
1) write a program to compute the payment for a freelancer.
The program asks the user to enter hours and rate.
The payment will be 1.5 times the hourly rate for
hours worked above 40 hours.
2) rewrite the program using try and except so that your
program handles non-numeric input.
'''
try:
hours = float(input... |
4905483e15bdfd666e71a42b696792c43ced0a3f | AbdallahAhmed1999/WDMM-1402 | /chapter5/friends.py | 187 | 4.09375 | 4 | # a list of strings
friends = ['Joseph', 'David', 'Sally']
print('list:', friends)
print('size:', len(friends))
for friend in friends:
print('Happy New Year:', friend)
print('Done!')
|
301b6f7ea24bd98e77516791668b774e0e730272 | AbdallahAhmed1999/WDMM-1402 | /chapter1/statements.py | 153 | 4 | 4 | x = 1
print(x)
x = x + 10
print(x)
x = 10
if x >= 10:
print("bigger")
print("x is bigger than 10")
if x < 10:
print('smaller')
print('done')
|
d7101e25f8ad72d9afb55f06f8f28a410a59186b | AbdallahAhmed1999/WDMM-1402 | /chapter6/find_words_starts_consentants_ends_vowels1.py | 601 | 4.09375 | 4 | '''
اكتب برنامج لعد الكلمات في نص بحيث تبدأ بحرف m وتنتهي بحرف متحرك (a e i o u ) سواء كان الحرف كبير ام صغير
'''
text = ''' Hi , my name is Ahmed , and
I like banana , Orange ,
and apple fruits - but I do not like
APPLE COMPANY !!!
I love Python , and python is cool ! :)
I AM A PYTHON PROGRAMMER ! OK
please share... |
a4c3d2830dd0a71652500bf73a074194adbd64b4 | AbdallahAhmed1999/WDMM-1402 | /chapter2/pretty_print_vars.py | 121 | 3.515625 | 4 | a = 10
b = 20
c = 30
print(a, b, c) # print in one line
# pretty print
print('value of a:', a)
print('value of b:', b)
|
0e5a0cb174873de5a86b5be6d4968c8c1d387503 | AbdallahAhmed1999/WDMM-1402 | /chapter2/input_name.py | 137 | 4.03125 | 4 | # call function and assignment
name = input('enter your name: ')
print('welcome ' + name + ' :)') # concat
print('welcome', name, ':)')
|
1dd455b17c9fd23d71be67e424a6aa185d364394 | AbdallahAhmed1999/WDMM-1402 | /chapter5/addition4multiplication_for_loop.py | 140 | 3.953125 | 4 | A = int(input('enter A: '))
B = int(input('enter B: '))
result = 0
for i in range(B):
result = result + A
print(A, '*', B, '=', result)
|
00ea8a9428d1221fd584cd604b054c8f0bfacb63 | AbdallahAhmed1999/WDMM-1402 | /chapter3/ifelse.py | 191 | 4.125 | 4 | x = 4
if x > 2:
print('Bigger')
else:
print('Smaller')
print('All done')
# the same with else keyword
if x > 2:
print('bigger')
if x <= 2:
print('smaller')
print('all done!')
|
6ea993809ae18d8c5a27bb33cfe90b88da59d2b4 | ramona-2020/Python-OOP | /06. Iterators and Generators/02. Dictionary Iterator.py | 493 | 3.75 | 4 | class dictionary_iter:
def __init__(self, dictionary):
self.dictionary = dictionary
self.pairs = list(dictionary.items())
self.idx = 0
def __iter__(self):
return self
def __next__(self):
if self.idx == len(self.pairs):
raise StopIteration
idx = ... |
597c4af412171451c2d88f7974f92c53e7914170 | ramona-2020/Python-OOP | /07. Decorators/Lab_03. Even Numbers.py | 274 | 3.609375 | 4 | def even_numbers(function):
def wrapper(numbers):
result = list(filter(lambda x: x % 2 == 0, numbers))
return function(result)
return wrapper
@even_numbers
def get_numbers(numbers):
return numbers
print(get_numbers([1, 2, 3, 4, 5, 10, 11]))
|
e02a23793cfb86089e12460c641a37c061616b03 | ramona-2020/Python-OOP | /05. Polymorphism/demo.py | 1,271 | 4.21875 | 4 | from abc import ABC, abstractmethod
from math import pi, sqrt
class Shape(ABC):
def __str__(self):
return f'Area: {self.area()}; Perimeter: {self.perimeter()}'
@abstractmethod
def area(self): pass
@abstractmethod
def perimeter(self): pass
class Circle(Shape):
def __init__(self, radi... |
955a943f9cdd7d8e20ddb5c3072cd4474133d3df | ramona-2020/Python-OOP | /04. Inheritance/diamond_demo.py | 320 | 3.625 | 4 | class A:
def f(self):
print('A')
class AA(A):
def f(self):
print('AA')
super(AA, self).f()
class AB(A):
def f(self):
print('AB')
super(AB, self).f()
class C(AA, AB):
def f(self):
print('C')
super(C, self).f()
# AB.f(self)
c = C()
c.f() |
5daaba3fa06d510d8820894fa53fde7cb463b5b3 | twscode/GroceryList | /sample_output.py | 1,274 | 3.921875 | 4 | def main():
print('=======================Grocery List Generator=======================\n')
grocery_message()
print ('\nHere is the food you currently have: \n' + '\n*print contents from current_ingredients txt file here* ')
get_current_diet()
print('\nHere are some popular recipes for you to try: ... |
9372c85f15f353d2c5ac8a64304e4e3b8c908527 | asanteb/CSC-3320 | /python/animals.py | 1,900 | 4.25 | 4 | ## In Class assignment
## Asante Buil,
## Me and my team used https://www.python-course.eu/python3_inheritance.php to brush up on class implementation
## Because we couldn't get python working on the command line we then used an online compiler, https://repl.it/languages/python3,
## to start debugging
class Animals:
... |
d49f881e7c8178c9e04cdce607617972264c51e0 | Valuebai/awesome-python-io | /run_test_code/map-info/get_coordinates_by_imap_gaode.py | 1,471 | 3.640625 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''=================================================
@IDE :PyCharm
@Author :LuckyHuibo
@Date :2019/7/13 13:28
@Desc :利用高德地图查询对应的地铁站经纬度信息,下面的key需要自己去高德官网申请
Passed,可以直接拿来用
=================================================='''
import requests
def get_longitude_latitud... |
85f81a4f53e8057439a460116d01587c393b7761 | Valuebai/awesome-python-io | /run_leetcode/002_Add_Two_Num.py | 2,269 | 3.671875 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''=================================================
@IDE :PyCharm
@Author :LuckyHuibo
@Date :2019/9/22 23:21
@Desc :leetcode-02 2个数相加
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开... |
fd69746afde938a7fa1185e328fb97069ff81003 | Valuebai/awesome-python-io | /run_leetcode/run_EightQueen.py | 1,659 | 3.96875 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''=================================================
@IDE :PyCharm
@Author :LuckyHuibo
@Date :2019/6/22 16:00
@Desc :
《图解算法 使用Python》中的代码调试
=================================================='''
global queen
global number
EIGHT = 8 # 定义堆栈最大的容量
queen = [None] * 8 # ... |
74f6c9c50ff058de8d309560f12e0a80bb8da948 | ebsiqueira/Poo2 | /exe1/e21.py | 532 | 3.859375 | 4 | soma = 0
quantidade = 0
total = 0
maior = 0
menor = 9999999999999999
while True:
valor = float(input('Digite o valor: '))
if(valor == 0):
break
quantidade += 1
soma += valor
total += valor
if(valor > maior):
maior = valor
if(valor < menor):
menor = valor
pr... |
d3bd7780cf84d227ad7a364e69df5aeae7a5fce9 | ebsiqueira/Poo2 | /Listas/5.py | 250 | 3.75 | 4 | vetor = []
par = []
impar = []
for i in range(20):
num = int(input('Digite um numero: '))
vetor.append(num)
if(num%2 == 0):
par.append(num)
else:
impar.append(num)
print(vetor)
print(par)
print(impar) |
dcaa0d8b2b6523f3d454e84f0ae58edf0cf46262 | ebsiqueira/Poo2 | /exe1/e14.py | 268 | 4.0625 | 4 | n = int(input('Digite um número: '))
m = int(input('Digite um número: '))
valorFor = 1
l = 0
valorWhile = 1
# for
for k in range(m):
valorFor *= n
# while
while(l<m):
valorWhile *= n
l += 1
print('For: %d' % valorFor)
print('While: %d' % valorWhile)
|
e8a318fe7cd58178a6a9522649fcac5a58e78f5a | ebsiqueira/Poo2 | /Listas/18.py | 1,072 | 3.59375 | 4 | votos = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
camisa = 0
k = 0
maior = 0
segundoMaior = 0
terceiroMaior = 0
camisaMaior = 0
camisaSegundoMaior = 0
camisaTerceiroMaior = 0
while True:
n = int(input('Digite o numero do melhor jogador: '))
if (n == 0):
break
votos[n... |
bbda2b020b45c3a81d806e230cc03e0ad50cabe5 | ebsiqueira/Poo2 | /Listas/4.py | 211 | 3.921875 | 4 | vetor = ['a','b','c','d','e','f','g','h','i','j']
for letras in vetor:
if(letras == 'a' or letras == 'e' or letras == 'i' or letras == 'o' or letras == 'u'):
vetor.remove(letras)
print(vetor) |
51abdd15019e8a2c6456ac2c43e3e16353e9f954 | ebsiqueira/Poo2 | /Listas/3.py | 189 | 3.890625 | 4 | notas = []
valor = 0
for i in range(4):
nota = float(input('Digite a nota do aluno: '))
notas.append(nota)
for val in notas:
valor += val
print(notas)
print(valor/4) |
730a1e3eebec4eff8b93f905a0ac5aae4c64bd0a | ebsiqueira/Poo2 | /exe1/e19.py | 173 | 3.890625 | 4 | total = 0
cont = 0
while True:
val = float(input('Digite os valores de energia: '))
if(val == 0):
break
total += val
cont += 1
print(total / cont) |
4f48e9474756577e9d3e65da44e1ec97f404d8a9 | ebsiqueira/Poo2 | /exe1/e8.py | 176 | 3.9375 | 4 | n = int(input('Insira um numero maximo: '))
m = 0
for k in range(1,n):
if(k%3 == 0) or (k%5 == 0) or (k%7 == 0):
m += k
if(k%8 == 0):
m -= k
print(m)
|
5d0806025740660ee57d4ff399746a14b32e033d | jorgearanda/katas | /diamond/diamond.py | 847 | 3.828125 | 4 | from string import ascii_uppercase
def print_diamond(last_letter):
diamond = [
make_line(letter, last_letter)
for letter in letters_up_to(last_letter)
]
return diamond + lower_half_of(diamond)
def letters_up_to(last_letter):
return ascii_uppercase[:index(last_letter) + 1]
def make... |
8db03eb7c7a13c215b1600790688aff11e3605a1 | QuantumNovice/PyMathematics | /Ackerman Fucnction.py | 200 | 3.53125 | 4 | def ackerman(m,n):
global x,y
x.append((m,n))
y.append(n)
if m==0:
return n+1
elif m>0 and n==0:
return ackerman(m-1, 1)
return ackerman(m-1, ackerman(m, n-1))
|
d3721294bc8b0913542f1f8e76902927fb9a81d3 | ciurca/PracticePython | /02OddOrEven.py | 2,174 | 4.125 | 4 | def yesNo():
while True:
try:
yesorno = str(input("Do you want to try another program? Enter yes or no: "))
if yesorno == "yes":
whichOne()
else:
break
except ValueError:
print("You need to enter yes or no.")
def basic()... |
c2bcbd679f28efc303749926b032a4c94252c8a4 | Tarun-19/SPOJ-Soutions | /GCD2.py | 167 | 3.5625 | 4 | # GCD2 - GCD2
# Author: Tarun Kumar
# E-mail: tarunkumar281200@gmail.com
import math
t=int(input())
while(t>0):
t=t-1
a,b=map(int,input().split())
a=math.gcd(a,b)
print (a)
|
2914bd8bcedb099ef14506b56b2e4430b6852301 | Tarun-19/SPOJ-Soutions | /GEOPROB.py | 173 | 3.5 | 4 | # GEOPROB - One Geometry Problem
# Author: Tarun Kumar
# E-mail: tarunkumar281200@gmail.com
t=int(input())
while (t>0):
t=t-1
x,y,z=map(int,raw_input().split())
x=2*y-x-z
print x
|
a50363dcb3a9b451987e31805f46cdd86326a368 | ConnorAustin/ProgrammingCompetition | /NNHappyPrimes.py | 715 | 3.671875 | 4 | import sys, math
is_prime = [True] * 10000
def gen_primes(n):
for i in range(2, int(math.sqrt(n))):
for j in range(i*i, n, i):
is_prime[j] = False
gen_primes(10000)
def digit_square_sum(num):
s = 0
for c in num:
s += int(c) ** 2
return str(s)
for num in map(lambda l: l.str... |
99bb5ed73176ff7bf7ec958d205a5b7ce3c507d0 | esmadurmaz/Python | /Practice/Calculator.py | 637 | 3.96875 | 4 | print(""""""*********
Hesap Makinesi Programı
İşlemler
1.Toplama İşlemi
2.ÇIıkarma işlemi
3.Çarpma İşlemi
4.Bölme İşlemi
*********
"""""")
a = int(input("Birinci Sayı:"))
b = int(input("İkinci sayı:"))
işlem = input("İşlem Giriniz:")
if işlem == "1":
print("{}ile {} in toplamı {} dır.".format(a,b,a+b... |
f3822dcfbb01a0bf8303eda1e6134f47d54a731a | parthrathod1994/PythonPractical | /bigExponant.py | 335 | 3.609375 | 4 | import time
a = int(input())
b = int(input())
ans = 1
start = time.clock()
while True:
q = int(b/2)
r = int(b % 2)
if r == 1:
ans = ans*a
if q == 0:
break
b = q;
a = a*a;
stop = time.clock()
current_microsec_time = int(round((stop - start) * 1000000))
print(current_microsec_tim... |
7779806cacc45b2a7c1549801b4facd6857804d8 | parthrathod1994/PythonPractical | /prettyprintingdynamic.py | 1,872 | 3.53125 | 4 | import math
def cost(list_word,i,j):
sum = 0
for k in range(i,j):
sum = sum + len(list_word[k])
return sum
def dynamic(list_word,length):
n=len(list_word)
cost_mat = []
min_cost = []
result = []
for i in range(0,n):
cost_mat.append([])
min_cost.append(0)
... |
c014c57cda396d6a3e70fc46f52d8fc7794dd965 | diegoami/datacamp-courses-PY | /cleaning/clean_3.py | 454 | 3.75 | 4 | # Import matplotlib.pyplot
import matplotlib.pyplot as plt
# Import pandas
import pandas as pd
# Read the file into a DataFrame: df
df = pd.read_csv('../data/job_applications_2.csv',low_memory=False)
df['Initial Cost'] = df['Initial Cost'].apply(lambda x: pd.to_numeric(x[1:],errors='coerce'))
print(df.info())
import ... |
1d59293b8ec34b05e11de3ff5f2917683d3422dc | diegoami/datacamp-courses-PY | /nnetworks/fw_8.py | 828 | 3.78125 | 4 |
import numpy as np
input_data = np.array([1, 2, 3])
weights = np.array([0, 2, 1])
target = 0
# Set the learning rate: learning_rate
learning_rate = 0.01
def get_slope(input_data, target, weights):
# Calculate the predictions: preds
preds = (weights * input_data).sum()
# Calculate the error: error
er... |
70534482f25dc5803c99760c0cbcd1739f350061 | diegoami/datacamp-courses-PY | /pandas_9/pandas9_1.py | 255 | 3.53125 | 4 | import pandas as pd
users = pd.read_csv('../data/users.csv',index_col = 0)
# Pivot the users DataFrame: visitors_pivot
visitors_pivot = users.pivot(index='weekday', columns = 'city', values='visitors')
# Print the pivoted DataFrame
print(visitors_pivot)
|
f8a2af786b441d9f0ff321380f32043999591370 | diegoami/datacamp-courses-PY | /pandas_4/pandas4_2.py | 423 | 4 | 4 | from data.cars import cars_df as df
from data.cars import sizes
import matplotlib.pyplot as plt
# Create a list of y-axis column names: y_columns
# Generate a scatter plot
df.plot(kind='scatter', x='hp', y='mpg',s=sizes)
# Add the title
plt.title('Fuel efficiency vs Horse-power')
# Add the x-axis label
plt.xlabel('Ho... |
ff84aed25b3213c1d2cbf3c7e406135800e7f2cc | diegoami/datacamp-courses-PY | /pandas_10/pandas10_8.py | 669 | 3.53125 | 4 | import pandas as pd
# Read the CSV file into a DataFrame and sort the index: gapminder
gapminder_2010 = pd.read_csv('gapminder_2010.csv')
# Import zscore
from scipy.stats import zscore
# Group gapminder_2010: standardized
# Import zscore
from scipy.stats import zscore
# Group gapminder_2010: standardized
standardized... |
dbe7fe8aaf3a8c71a7005fc7e920be08139e8051 | diegoami/datacamp-courses-PY | /pandas_12/pandas12_14.py | 509 | 3.671875 | 4 |
import pandas as pd
medal_types = ['bronze', 'silver', 'gold']
medals = []
for medal in medal_types:
# Create the file name: file_name
file_name = "%s_top5_2.csv" % medal
# Read file_name into a DataFrame: df
medal_df = pd.read_csv("../data/"+file_name,index_col='Country')
print(medal_df)
#... |
5de70d8d70e04c32831298281ebf7ef4813fddd7 | diegoami/datacamp-courses-PY | /pandas_11/pandas11_3.py | 454 | 3.53125 | 4 | import pandas as pd
medals = pd.read_csv('../data/medals.csv',index_col = 0)
# Construct the pivot table: counted
counted = medals.pivot_table(index='NOC',values='Athlete',columns='Medal',aggfunc='count')
# Create the new column: counted['totals']
counted['totals'] = counted.sum(axis='columns')
# Sort counted by the... |
91111e0fc4793c105de769aaaa5aa37adc42254c | diegoami/datacamp-courses-PY | /supervised/grid1.py | 855 | 3.515625 | 4 | import numpy as np
import pandas as pd
# Import necessary modules
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
# Read the CSV file into a DataFrame: df
df = pd.read_csv('../data/diabetes.csv')
X = df.drop('diabetes', axis=1).values
y = df['diabetes']
df_columns =... |
aa15ca5cede6603a9177b6d8244c6a8ee3d15a5e | diegoami/datacamp-courses-PY | /sql/sql_8.py | 867 | 3.8125 | 4 |
from sqlalchemy import *
# Reflect census table from the engine: census
# Create an engine to the census database
engine = create_engine('postgresql+psycopg2://'+
'student:datacamp'+
'@postgresql.csrrinzqubik.us-east-1.rds.amazonaws.com'+
':5432/census')
# Use the .table_names() method on the engine to print the ta... |
dbe9fd36e195f25177dd208cc3dce08ba0a29a3e | diegoami/datacamp-courses-PY | /numpy/numpy_5.py | 392 | 4.03125 | 4 | # height and weight are available as a regular lists
# Import numpy
import numpy as np
height = [170,156,190]
weight = [72,59,84]
# Store weight and height lists as numpy arrays
np_weight = np.array(weight)
np_height = np.array(height)
# Print out the weight at index 50
print(np_weight[2])
# Print out sub-array of ... |
47a7233a201883bf2c47bfad1ad9843aa7acdd02 | diegoami/datacamp-courses-PY | /st_python/st_python_19.py | 643 | 3.890625 | 4 |
# Import plotting modules
import matplotlib.pyplot as plt
from datacamp.lib import *
# Seed random number generator
np.random.seed(42)
# Initialize the number of defaults: n_defaults
n_defaults = np.empty(1000)
# Compute the number of defaults
for i in range(1000):
n_defaults[i] =perform_bernoulli_trials(100... |
15943fa4d4289db828ddda45cff96960a27f2b40 | diegoami/datacamp-courses-PY | /pandas_12/pandas12_10.py | 774 | 3.515625 | 4 | # Import pandas
import pandas as pd
# Load 'sales-jan-2015.csv' into a DataFrame: jan
jan = pd.read_csv('../data/sales-jan-2015.csv',parse_dates=True,index_col='Date')
# Load 'sales-feb-2015.csv' into a DataFrame: feb
feb = pd.read_csv('../data/sales-feb-2015.csv',parse_dates=True,index_col='Date')
# Load 'sales-mar... |
1fcfbb317c0a798995f4c864fa5c0fc21cb99eb4 | diegoami/datacamp-courses-PY | /cleaning/clean_2.py | 317 | 3.5 | 4 | # Import matplotlib.pyplot
import matplotlib.pyplot as plt
# Import pandas
import pandas as pd
# Read the file into a DataFrame: df
df = pd.read_csv('../data/job_applications.csv')
# Plot the histogram
df['Existing Zoning Sqft'].plot(kind='hist', rot=70, logx=True, logy=True)
# Display the histogram
plt.show()
|
f27a9649c4bfae2cb11a9737e32f1759a2cab22a | adriabaquero/phyton2018 | /calculo-areas.py | 854 | 3.953125 | 4 | #coding:utf8
#Adrià Baquero
#02/03/2018
import os
os.system ("clear")
from math import pi
print """
Pulsa la tecla T si quieres calcular el área de un triángulo.
Pulsa la tecla C si quieres calcular el área de un círculo.
"""
figura=raw_input("Que quieres calcular? ")
if(figura=="T" or figura=="t"):
base=in... |
495de04b5f14af7d0048c13e0a104c733c13bb14 | adriabaquero/phyton2018 | /ejercicio-mayor_menor.py | 229 | 4.03125 | 4 | #coding:utf8
#Adrià Baquero
#09/02/2018
valor1=input ("Introduce el valor 1: ")
valor2=input ("Introduce el valor 2: ")
valor3=input ("Introduce el valor 3: ")
if (valor1=valor2) and (valor3!=valor1):
print "Los 3 son iguales"
else
|
b6eac2c62ecca3cd7b36c3c869a0b2890daaf31d | tomoyoshi-0104/python_study | /2.基礎編/20.rangeとxrange/test20.py | 196 | 4.125 | 4 | for i in range(10):
print(i)
print()
for i in range(2,10):
print(i)
print()
for i in range(-2,10):
print(i)
print("xrangeはpython3にて廃止")
# for i in xrange(10):
# print(i)
|
0ffb25ea3fe0b9601ae18472dc42c94852c05c7d | sundongjian/algorithm | /stack/char6.py | 1,887 | 3.640625 | 4 | # 迷宫的递归求解
dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)] # 四个方向
def mark(maze, pos): # 给迷宫maze的位置表上pos表示到过了
maze[pos[0][pos[1]]] = 2
def passable(maze, pos):
return maze[pos[0][pos[1]]] == 0
def find_path(maze, pos, end):
mark(maze, pos)
if pos == end:
print('pos:', pos, end=' ')
retu... |
325aa930214b04cc0b0c9e58db7e6df41abd5689 | sundongjian/algorithm | /stack/char5.py | 1,216 | 4.03125 | 4 | '''
队列,先进后出
ADT Queue:
Queue(self)
is_empty(self)
enqueue(self,elem)
dequeue(self)#删除最早
peek(self)#查看最早
'''
# 循环顺序表
class QueueUnderflow(ValueError):
pass
class SQueue:
def __init__(self, init_len=8):
self._len = init_len
self._elems = [0] * init_len
self._head = ... |
eb328caf719b0a3172bf125898436120baacc411 | crmacd/adventofcode | /2020/day1.py | 723 | 3.90625 | 4 |
def subset_sum(numbers, target, partial=[]):
s = sum(partial)
# check if the partial sum is equals to target
if s == target:
print(f"sum({partial})={target} *2={partial[0]*partial[1]}")
if len(partial) == 3:
print(f"*3={partial[0]*partial[1]*partial[2]}")
if s >= target:
... |
72e188408828bb0de9b4960fd56de02d36b1f636 | sxnys/learning_for_future | /D&A/heap.py | 2,007 | 3.90625 | 4 | '''
堆排序(以最小堆为例)
heap[int] 为维护的堆,堆编号从1开始
lst[] 为需要排序的数组
'''
import random
heap = [None]
n = 0 # 堆需要维护的最大长度
## shiftup 和 shiftdown 是建堆和维护堆的基本操作
# 向上调整,维护堆结构
def shiftup(i):
while i > 1:
father_i = i // 2
if heap[i] < heap[father_i]:
heap[i], heap[father_i] = heap[father_i], heap[i]
... |
1464f13c5a56f4be7f51abe35d13ac05c5ce046d | thortun/raspberrypi | /Server/classes.py | 5,608 | 3.65625 | 4 | import socket # To use sockets
import hashlib # For some hashing
import json # JSON usability
import random as rand # Generating random numbers. NOT CRYPTO SECURE!!!! Change to something secure
import _globals # Global variables
import serverUtilities as su # Server utilities
import cryp... |
be289394b776691afa2966abb7a9f7a299bcb720 | Tiseno/ud120-projects | /svm/svm_author_id.py | 1,791 | 3.5 | 4 | #!/usr/bin/python
"""
This is the code to accompany the Lesson 2 (SVM) mini-project.
Use a SVM to identify emails from the Enron corpus by their authors:
Sara has label 0
Chris has label 1
"""
import sys
from time import time
sys.path.append("../tools/")
from email_preprocess import preprocess
### ... |
815d193174c04098234854b0c74d508f820de815 | PrashantShivajiBhapkar/PythonPractice | /Dictionaries.py | 983 | 3.734375 | 4 | # DICTIONARY
# key: value pairs, UNORDERED
tel = {'jack': 1234, 'sape': 7895}
print(tel)
tel['Dannial'] = 9876
print(tel)
tel['Dannial'] = 7777
print(tel) # Dannial's valus updated
del(tel["Dannial"])
print(tel)
print('Sachin' in tel)
print('jack' in tel)
print(sorted(tel.keys(), reverse=1))
print(sorted(tel.keys()))... |
2b7e6bd366fd85dc36b301ae302ee97f699b3ec1 | hkyopreston/Election_Analysis | /PyPoll_Challenge.py | 4,758 | 4.0625 | 4 | # The data we need to retrieve.
# 1. The total number of votes cast
# 2. A complete list of candidates who received votes
# 3. The percentage of votes each candidate won
# 4. The total number of votes each candidate won
# 5. The winner of the election based on popular vote.
# 6. The voter turnout for each county
# 7. T... |
023bd24542331e398219df8b98f5cdd446626ec7 | rodrigovaldes/newsproject | /code/analysis_and_plotting/plot_pred.py | 1,281 | 3.796875 | 4 | import matplotlib.pyplot as plt
def build_plot(df):
'''
Builds a plot from a dataframe of dates, actual prices, & predicted prices.
Inputs:
df (pandas dataframe): A dataframe with three columns: dates, actual
prices, and predicted prices.
Outputs:
fig (m... |
828b184602fddf079ef62a2107bafce7abb9d71a | aolite/ProgSemWeb | /chapter2/chapter2.py | 2,115 | 3.75 | 4 | from myTripleStore import SimpleGraph
if __name__=="__main__":
print "Chapter 2 examples"
print "Creating a simple Graph..."
movie_graph = SimpleGraph()
print "Adding blade runner triples..."
movie_graph.add(('blade_runner', 'name', 'Blade Runner'))
movie_graph.add(('blade_runner', 'directed... |
14d1ac091d68d503ac9eac1808e0a1763c4b0af6 | ikvibhav/DSA_Fundamentals | /data_structures/python/trees/tree.py | 2,918 | 3.875 | 4 | class TreeNode:
def __init__(self, data):
self.data = data
self.left = None #leaf node termination
self.right = None
def insert(self, data):
if data > self.data:
if self.right is None:
self.right = TreeNode(data)
else:
... |
beb821c2fa9e8fb98e09b8fe46cb9962d03f0125 | hyeryn/Natural-Language | /chapter03/03_5 edit_distance_calculator.py | 592 | 3.515625 | 4 | from nltk.metrics.distance import edit_distance
def my_edit_distance(str1, str2):
m = len(str1)+1
n = len(str2)+1
#배열의 테이블 만들고 행과 열 초기화
table = {}
for i in range(m): table[i,0]=i
for j in range(n): table[0,j]=j
for i in range(1,m):
for j in range(1,n):
cost = 0 if str1... |
02887c632b1917adc4b6ce501c7749e952123534 | BanisharifM/Training | /Neural Network/Coursera/W2A1_Python Basics with Numpy/Exercise 7 - softmax.py | 958 | 4.09375 | 4 | # GRADED FUNCTION: softmax
import numpy as np
def softmax(x):
"""Calculates the softmax for each row of the input x.
Your code should work for a row vector and also for matrices of shape (m,n).
Argument:
x -- A numpy matrix of shape (m,n)
Returns:
s -- A numpy matrix equal to the softmax o... |
eb322ad0c32b2231c0490a1391bf730a9209622a | vtemian/interviews-prep | /cracking-the-code-interview/trees/09-bst-sequence.py | 2,470 | 3.515625 | 4 | """
2, 3, 1, 4, 5, 6, 7
"""
from typing import List
from tree import Node, BinarySearchTree
# 1. get all tree's nodes
# 2. weave list
def _generate_weaved_nodes(root: Node) -> List[Node]:
if not root:
return []
if not root.nodes:
return [root.val]
left = _generate_weaved_nodes(root.no... |
71cdf88966fcfcac511bd6cf82fc7c7ebd37f11c | vtemian/interviews-prep | /leetcode/medium/validate-bst.py | 655 | 3.90625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
def valid(node, lower=float('-inf'), upper=float('inf')):
if not node:
... |
9a8999a7c787c34f5a41c5c8d945b584a0d38aa8 | vtemian/interviews-prep | /leetcode/easy/cousins-in-binary-tree.py | 853 | 3.703125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
parents = {}
def dfs(node, depth=0, parent=None):
... |
59449afcff942c8efb59200e4dcb33cc051f7891 | vtemian/interviews-prep | /elements-of-programming-interviews/16.1-tower-hanoi.py | 518 | 3.953125 | 4 | from typing import List
def hanoi(n: int):
rods = [[i for i in range(n, 0, -1)], [], []]
def _hanoi(moves: int, from_rod: int, to_rod: int, aux_rod: int):
if not moves:
return
_hanoi(moves - 1, from_rod, aux_rod, to_rod)
print(from_rod, rods[from_rod])
rods[to_r... |
3b2865d6393359b4c0809f186a0508e764711c2b | vtemian/interviews-prep | /leetcode/easy/n-ary-tree-level-order-traversal.py | 550 | 3.515625 | 4 | """
# Definition for a Node.
class Node:
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution:
def levelOrder(self, root: 'Node') -> 'List[List[int]]':
levels = []
def dfs(root, level):
if not root:
return
... |
5a9f4b099518dd32e848425af71e12d71f928132 | vtemian/interviews-prep | /leetcode/easy/second-minimum-node-in-a-binary-tree.py | 687 | 3.53125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def findSecondMinimumValue(self, root: TreeNode) -> int:
answer = 999999999999999999
min = root.val
def dfs(node... |
a1453669912d1cca6e80015157698909c8f59f9d | vtemian/interviews-prep | /elements-of-programming-interviews/5.1-parity.py | 994 | 3.546875 | 4 | def no_ones(number: int) -> int:
"""
nr: 101010
nr - 1: 101001
nr & (nr - 1) == 101000
"""
ones = 0
while number:
ones += 1
number = number & (number - 1)
return ones
def solve_ok(number: int) -> int:
""" O(k) complexity, where k == no ones """
r... |
ec7fc1a2e819c4b3ffae06ee6ececf5db9a503f0 | vtemian/interviews-prep | /cracking-the-code-interview/stacks/02-stack-min.py | 1,356 | 3.78125 | 4 | """
stack: [4, 5, 1, 2, 7]
min: 1
"""
from typing import Union
class Stack:
def __init__(self, size: int = 100):
self.size = size
self.store = []
def pop(self) -> Union[int, None]:
if self.is_empty():
return None
return self.store.pop()[0]
def peek(s... |
49e825b6096b99b616e495df2e40399101548f56 | vtemian/interviews-prep | /leetcode/easy/increasing-order-search-tree.py | 1,597 | 3.953125 | 4 | """
Given a tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree,
and every node has no left child and only 1 right child.
Example 1:
Input: [5,3,6,2,4,null,8,1,null,null,null,7,9]
5
/ \
3 6
/ \ \
2 4 8
/ / \
1 7 9
Ou... |
65bdc80001d8401fee7dceb40879bdae334042c9 | vtemian/interviews-prep | /leetcode/trees/serialize-deserialize.py | 1,280 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
... |
7b9ce1ecb92cb329540dab481ecf9d1aca264ca3 | vtemian/interviews-prep | /elements-of-programming-interviews/10.0-balanced-binary-tree.py | 1,265 | 3.828125 | 4 | from typing import List, Tuple, Optional
class Node:
def __init__(self, val: int, left: 'Node' = None, right: 'Node' = None):
self.val = val
self.left = left
self.right = right
def is_balanced(tree: Node) -> bool:
def balanced(node: Optional[Node], current_depth: int = 0) -> Tuple[in... |
9342893c3cff1eecf466a1f3af6096d1ec0514b4 | vtemian/interviews-prep | /leetcode/easy/projection-area-of-3d-shapes.py | 1,120 | 4.125 | 4 | """
On a N * N grid, we place some 1 * 1 * 1 cubes that are axis-aligned with the x, y, and z axes.
Each value v = grid[i][j] represents a tower of v cubes placed on top of grid cell (i, j).
Now we view the projection of these cubes onto the xy, yz, and zx planes.
A projection is like a shadow, that maps our 3 dimen... |
73ec2b4a08af4b1840b7bc44d8a9d3dc69ed07a6 | vtemian/interviews-prep | /leetcode/easy/palindrome-permutation.py | 326 | 3.53125 | 4 | from collections import Counter
class Solution:
def canPermutePalindrome(self, s):
store = Counter(s)
is_odd = False
for no_letter in store.values():
if no_letter % 2 == 1:
if is_odd:
return False
is_odd = True
return... |
e4812ecc75be5ed3fd831640595a104940d70cb6 | vtemian/interviews-prep | /cracking-the-code-interview/stacks/04-queue-via-stacks.py | 1,764 | 3.828125 | 4 | from typing import Union
class Stack:
def __init__(self, size: int = 100):
self.size = size
self.store = []
def pop(self) -> Union[int, None]:
if self.is_empty:
return None
return self.store.pop()
def peek(self) -> Union[int, None]:
if self.is_empty:
... |
e1a3c66fc9d3be5ade44fba15a0b872504fe2d39 | vtemian/interviews-prep | /cracking-the-code-interview/heaps/heap.py | 2,737 | 3.890625 | 4 | from typing import Union
class Heap:
def __init__(self, size: int = 100):
self.size = size
self.store = []
def insert(self, item: int) -> bool:
if len(self.store) == self.size:
return False
self.store.append(item)
self._swap_up()
@property
def pee... |
2e9e404633ba79a8bd02b1e69c41959fab20295b | vtemian/interviews-prep | /leetcode/easy/strobogrammatic-number.py | 404 | 3.625 | 4 | class Solution:
def isStrobogrammatic(self, num: str) -> bool:
strobogrammatic = {
'1': '1',
'0': '0',
'6': '9',
'9': '6',
'8': '8'
}
for idx, digit in enumerate(num):
if digit not in strobogrammatic or strobogrammatic[... |
41a1debc8d9bc1e395c8728b46afbd222b3babac | vtemian/interviews-prep | /leetcode/easy/rotate-image.py | 646 | 3.59375 | 4 | class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
q = 0
m = len(matrix) - 1
while q < len(matrix) // 2:
c = 0
while c < len(matrix) - 1 - q * 2:
n... |
9a5da6bb3c2b10457d8f77eaa1dfffb27e9b3e3d | vtemian/interviews-prep | /leetcode/easy/count-primes.py | 565 | 3.734375 | 4 | from math import sqrt
class Solution:
def countPrimes(self, n: int) -> int:
primes = [
True
for _ in range(n)
]
for idx, is_prime in enumerate(primes):
if not is_prime or idx < 2:
continue
maybe_prime = idx + idx
... |
5225a638787af540c03c2243d5943cf11db74c5e | vtemian/interviews-prep | /cracking-the-code-interview/stacks/03-stack-of-plates.py | 3,556 | 3.640625 | 4 | from typing import Union
class Stack:
def __init__(self, size: int = 100):
self.size = size
self.store = []
def pop(self) -> Union[int, None]:
if self.is_empty:
return None
return self.store.pop()
def peek(self) -> Union[int, None]:
if self.is_empty:
... |
2bfb88c6d7df9ee454a4d9d5678d61836464b9f8 | msebi/problem-solving | /hackerrank/angle-mbc.py | 266 | 3.96875 | 4 | import math
ab = int(input())
bc = int(input())
# ac = (ab ** 2 + bc ** 2) ** (1/2)
# sin_val = ab / ac
#
# eps = 0.5
#
# print('angle: ' + str(math.asin(sin_val) * 180 / math.pi - eps))
print(str(round(math.degrees(math.atan2(ab, bc)))) + '°')
|
9cf8fe828a96610232ef1789f4a9e880b84ca7f4 | nurul-ds/Data-Mining-and-Prediction--Crude-Oil-Price | /Milestone 1/Web Scraping - News Article/newscrawl - The Guardian Daily Mail The Star/2) News Article Web Scraping - online news websites.py | 6,808 | 3.734375 | 4 | #!/usr/bin/env python
# coding: utf-8
import requests
from bs4 import BeautifulSoup
import numpy as np
import pandas as pd
from datetime import datetime
import uuid
# ### Working out which pages to scrape
#
# Obtain list of news from the one of the popular news article website, The Guardian websites. Website: https... |
fce168b5379150d827d704200445f8291b8e0386 | MikhailErofeev/a3200-2015-algs | /classic-algs/lab10/Grushitcyna/pifagor.py | 833 | 3.703125 | 4 | from sys import stdin
from sys import stdout
def find_triples(arr):
n = len(arr)
square = [0 for i in range(n)]
counter = 0
for i in range(n):
square[i] = arr[i] ** 2
square.sort()
a = len(square)
j = 0
while j < a:
origin = square[j]
i = j + 1
while i <... |
2c1a523fe769f6070c5ea726dcf9884a1854bbcc | MikhailErofeev/a3200-2015-algs | /classic-algs/lab8/Grushitcyna/tests_q.py | 1,779 | 3.515625 | 4 | import unittest
import Queue
class TestQueue(unittest.TestCase):
def test_simple(self):
queue = Queue.StacksQueue()
queue.push(10)
queue.push(1)
queue.push(31)
res = queue.pop()
expected = 10
self.assertEquals(expected, res)
def test_empty(self):
... |
b32cdc437d86bf072bb319722c5e8659e37eb530 | MikhailErofeev/a3200-2015-algs | /classic-algs/lab3/Yakunin/3.py | 370 | 3.53125 | 4 | from sys import stdin
def change(cur, money):
if money != 0:
if money < 0 or len(cur) == 0:
return 0
else:
return change(cur[1:len(cur)], money) + change(cur, money - cur[0])
else:
return 1
money = int (stdin.readline())
curList = stdin.readline()
print(cha... |
b4e75e3a27929093dd49bd2148f5a7663efd7a61 | MikhailErofeev/a3200-2015-algs | /classic-algs/lab6/Morozov/radix_sort.py | 1,294 | 3.59375 | 4 | import sys
__author__ = 'vks'
# get i-th digit of a number
def ith_digit(number, i):
return (number % (10 ** (i + 1))) // (10 ** i)
# count sort by digits at k-th position
def count_sort(a, b, k):
digits = [0 for i in range(10)]
for i in a:
index = ith_digit(i, k)
digits[index] += 1
... |
cf0b39a138729a81524cc9c2f5cf591a07a240b7 | MikhailErofeev/a3200-2015-algs | /classic-algs/lab17/Rybkin/union_find.py | 684 | 3.53125 | 4 | __author__ = 'Nikita Rybkin'
class UnionFind:
def __init__(self):
self.parent = dict()
self.rank = dict()
def creation(self, obj):
self.parent[obj] = obj
self.rank[obj] = 0
def search(self, obj):
if obj == self.parent[obj]:
return obj
self.pare... |
905d5ea8871d387e32a898cac2ba800b17a3d5e3 | MikhailErofeev/a3200-2015-algs | /classic-algs/lab10/Grushitcyna/tests_pif.py | 962 | 3.578125 | 4 | import unittest
import triples
class TestPithagoras(unittest.TestCase):
def test_example_from_exercises(self):
arr = [23, 247, 19, 96, 264, 265, 132, 181]
res = triples.find_triples(arr)
expected = 2
self.assertEqual(expected, res)
def test_empty(self):
arr = []
... |
a184e9a5b03ae4d6aef950f9da4af9150b8463ea | fwchj/cursoJavaAbm2018S2 | /ejemplosClase/python/EjemploIfElse2.py | 333 | 3.984375 | 4 | ## Definimos las variables
mujer = True
mex = False
## Python require más detalle para manejar los boolean
if mujer and mex:
print("Es una mujer de México")
elif not mujer and mex:
print("Es un hombre de México")
elif mujer and not mex:
print("Es una mujer de otro pais")
else:
print("Es un hombre de ot... |
8e57a4deacffd81fb69ad8a87d09ef681ea81273 | OzRhodes/pentesting | /portscanner.py | 297 | 3.6875 | 4 | vial port scanner
import socket
ip = input(" Enter the IP Address: ")
port = int(input("Enter a port number : "))
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if socket.connect_ex((ip, port)):
print("Port " , port, " is closed")
else:
print("Port " , port, " is open")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.