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 |
|---|---|---|---|---|---|---|
546133fee38aec413b24f85177232de067ed00f7 | paul-cruz/Python | /MostRequestedRoom/main.py | 918 | 3.765625 | 4 | def most_requested(rooms):
number_of_requests = {}
for room in rooms:
if room[0] == '+':
if room in number_of_requests.keys():
number_of_requests[room] += 1
else:
number_of_requests[room] = 1
return max(number_of_requests, key=number_of_request... |
1ebb8fe7ca85d3bc9a9b3d46624976655e5e18fe | paul-cruz/Python | /HeightOfBinaryTree/main.py | 1,700 | 3.9375 | 4 | class Node:
def __init__(self,value):
self.value = value
self.left = None
self.right = None
def get_height(root):
if root is None:
return 0
left_height = get_height(root.left)
right_height = get_height(root.right)
return(max(left_height,right_height)+1)
if __name... |
9c39c5f7af9b7982b359b194face3a6a3e54b176 | paul-cruz/Python | /LinkedList/LinkedList.py | 1,992 | 3.84375 | 4 | from Node import Node
class LinkedList:
def __init__(self):
self.first = None
self.last = None
def empty(self):
return self.first == None
def add(self, data):
if self.empty():
self.first = self.last = Node(data)
else:
self.last.next = self.... |
5a6581df1fe39f85ced914b58254e2b3c49ee944 | ZarahShibli/Data-Science-Bootcamp | /Python/Week 1/Weekend Project_Movie theater.py | 4,454 | 4.25 | 4 | # simulating the total revenue earned each day for a movie theater
# import libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math
# In[2]:
def one_sample(low, high):
"""
Generates a random sample of visitors: adults, children and seniors
parameters
---------... |
a619e27cef04c63ae346f70f6ac3880fc532382c | b1gb4dw0lf/8-puzzle-search | /Search/SupervisedTreeSearch.py | 3,371 | 3.5625 | 4 | from Tree.QuadrupleTree import QuadrupleTree
import heapq
class GreedyBestSearch(QuadrupleTree):
def add_neighbours_to_frontier_queue(self, node, state_counter):
# Store the coordinates of the blank tile AKA 0
blank_x, blank_y = node.blank_coordinates
for position in [0, 1]:
fo... |
f9382e2fa2f64c7f7aa3ed6048d9f5bb173f6674 | holen/Python | /raw_inputTest/raw_inputTest.py | 431 | 3.53125 | 4 | #-* coding:UTF-8 -*
#!/usr/bin/env python
while True:
flag = raw_input("There are affect %s rows on messages:%s and last_rt_id=%s, are you when to continue [y/n]:")
if flag == 'y':
print "y"
break
elif flag == 'n':
print "Nothing is dode !"
break
else: ... |
2031ac55003c4859790886ded867a9d3e6fd64ec | holen/Python | /timeTest/timestr.py | 463 | 3.734375 | 4 | #-* coding:UTF-8 -*
#!/usr/bin/env python
from time import strftime
from time import time, localtime
day = 24 * 60 * 60
print day
# 86400
yesterday = localtime(time() - day)
print yesterday
# time.struct_time(tm_year=2014, tm_mon=5, tm_mday=20, tm_hour=15, tm_min=33, tm_sec=13, tm_wday=1, tm_yday=140, tm_isdst=0)
pri... |
45a238310072e446a6b56489735a8e7c7cb8a2b0 | holen/Python | /design_pattern/test_self_cls.py | 589 | 3.625 | 4 | class A(object):
a = 'a'
@staticmethod
def foo1(name):
print('hello {}'.format(name))
print(A.a)
# print(A.foo2("foo2")) # TypeError: unbound method foo2() must be called with A instance as first argument (got str instance instead)
print("foo1 end")
def foo2(self, name)... |
3a2043ced613cab40e3644f13db712a388922c7c | shegg59/files_python | /index.py | 624 | 3.828125 | 4 | import os
directory = input("Введите путь к файлу: ") # Вводится путь к файлу и записывается в переменную Name
print("Подтвердите путь", directory) # Выводит просьбу подтвердить путь
input("Нажмите Enter для продолжения") # Заставляет прогу ждать ввода Enter
if os.path.exists(directory):
files = os.listdir(dire... |
2eedd41e2bf978844b8d2c877f43214797853ef7 | ryo219/vscode_Python | /GradientMethod.py | 851 | 3.984375 | 4 | # 勾配法
import random
import math
def sum_of_squares_gradient(x):
return [2 * x_i for x_i in x]
def step(x, direction, step_size):
return [x_i + step_size * direction_i for x_i, direction_i in zip(x, direction)]
def sum_of_squares(x):
return sum(x_i ** 2 for x_i in x)
def vector_subtract(x... |
16aab7f61a6b651ea68640742efa7d8888689769 | ryo219/vscode_Python | /PCA.py | 718 | 3.6875 | 4 | #主成分分析
#今回は sklearnの irisデータを使用
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.datasets import load_iris
# データ読込み
dataset = load_iris()
features = dataset.data
targets = dataset.target
# PCA実行
model = PCA(n_components=4) # irisデータでは特徴... |
711c5ecff995e4ecb0827bac3d29e744300fa7f0 | swetakum/Algorithms | /DataStructures/SuffixTrie.py | 451 | 3.703125 | 4 | def xyz(t):
""" Make suffix trie from t """
t += '$' # terminator symbol
root = {}
for i in range(len(t)): # for each suffix
cur = root
print("i = ", i)
print(t[i:])
for c in t[i:]: # for each character in i'th suffix
print("c = ",c)
if c not in... |
fac82c434af25d041592681988052ed024a2dd5b | swetakum/Algorithms | /DynamicProgramming/CoinChange.py | 337 | 3.796875 | 4 | def coinChange(coins, total):
dp = [float('inf') for i in range(0, total+1)]
dp[0]=0
for sum in range(1, total+1):
for value in coins:
print(sum,value)
if value<=sum and dp[sum-value]<dp[sum]:
dp[sum]=dp[sum-value]+1
print(dp)
return dp[total]
coinCha... |
df5bf5226c1fe6331bf651b5c7c1e0d4e3fc4a3d | swetakum/Algorithms | /DynamicProgramming/LongestCommonSubstring.py | 832 | 3.640625 | 4 | def lcs(word1,word2):
m = len(word1)
n = len(word2)
maxi = 0
matrix = [[0 for _ in range(n+1)] for _ in range(m+1)]
for i in range(m+1):
matrix[i][0] = 0
for j in range(n+1):
matrix[0][j] = 0
for i in range(1, m+1):
for j in range(1, n+1):
if word1[i-1] ==... |
e034286bfc69c7d7497052b152d1163ee58f205c | yanxuceo/IT-Automation-Python | /src/count_occurrences.py | 646 | 3.96875 | 4 | #!/usr/bin/env python3
fruit_list = ["apple", "pear", "banana", "kiwi", "watermelon", "carrot", "carrot", "apple", "apple", "apple", "pear","banana"]
# Method 1: using set() to get identical entry, then loop through to count
count_dic = {}
for fruit in set(fruit_list):
count_dic[fruit] = fruit_list.count(fruit)
... |
dd2e7f14b4061e46164b5919a88fcfab48c671c2 | Kacper-Pionka/Python_practice | /10-List_Overlap_Comprehensions.py | 290 | 3.5625 | 4 | # -*- coding: utf-8 -*-
import random
def rand_a():
return list(random.sample(range(1,30),7))
def rand_b():
return list(random.sample(range(1,30),12))
a = rand_a()
b = rand_b()
print(str(a) + '\n' + str(b))
list_boi = set([x for x in a for z in b if x == z])
print(list_boi)
|
2c2718429f88d74fd3b29cccefb72fc564dd6c69 | Kacper-Pionka/Python_practice | /06-String_Lists.py | 106 | 3.953125 | 4 | # -*- coding: utf-8 -*-
str_1 = input('Type in string: ')
for i in range(len(str_1)):
print(str_1[i])
|
f06d9691eacac126bce06951be5b91244b4fe4b1 | NJIT-CS490-SP21/johnTICTACTOE | /models.py | 403 | 3.515625 | 4 | """This module is used to create the table inside of our database"""
from app import DB
class Player(DB.Model):
"""This class is the creation of our database table schema"""
id = DB.Column(DB.Integer, primary_key=True)
username = DB.Column(DB.String(100), unique=True, nullable=False)
score = DB.Column... |
59fbe36424c259eb75e7651004933564f6527f9c | satoshi-eric/URI | /iniciante/coordenadas_de_um_ponto.py | 537 | 3.78125 | 4 | def get_coords():
x, y = map(float, input().split())
return x, y
def get_quadrant(x, y):
if x == y == 0:
return 'Origem'
elif x == 0:
return 'Eixo Y'
elif y == 0:
return 'Eixo X'
elif x > 0 and y > 0:
return 'Q1'
elif x < 0 and y > 0:
return 'Q2'
... |
136c6059b1525b7718d883f00a777c784b64df7a | satoshi-eric/URI | /iniciante/triangulo.py | 725 | 3.625 | 4 | def verifica_triangulo(lado1, lado2, lado3):
return not (lado1 + lado2 == lado3 or lado1 + lado3 == lado2 or lado2 + lado3 == lado1)
def calcular_perimetro_triangulo(lado1, lado2, lado3):
return lado1 + lado2 + lado3
def calcular_trapezio(base1, base2, altura):
return ((base1 + base2) / 2) * altur... |
75be30c4ec25b4372a2f224b82ceab9061fb1531 | Ketaki09/File-Consistency | /file_server.py | 3,905 | 3.6875 | 4 | import socket
import time
all_connections = []
all_address = []
# Create a Socket ( connect two computers)
def create_socket():
try:
global host
global port
global s
host = ""
port = 9999
s = socket.socket()
except socket.error as msg:
print("Socket cre... |
a9054d443ce55b49eadfaddbfb9c8319708e9e8d | jaysonzhao/pythonmisc | /test.py | 129 | 3.9375 | 4 | int_list = [1, 2, 3, 4, 5, 6]
sum = 0
for iter in int_list:
sum -= iter
print("Sum =", sum)
print("Avg =", sum/len(int_list)) |
aa07108baa2c97ccfb8f5983c99570fe96aadea3 | marcelocastilho/Python | /PythonForAllProject/src/pythonclasses/chapter06/exercises.py | 369 | 3.890625 | 4 | '''
Created on Aug 1, 2018
@author: marcelo
'''
#6.5 Write code using find() and string slicing (see section 6.10) to extract the number at the end of the line below.
#Convert the extracted value to a floating point number and print it out.
text = "X-DSPAM-Confidence: 0.8475";
index = text.find('0')
text = text... |
6e15416f29bee9f1564c5559f0588edc9412fc35 | marcelocastilho/Python | /PythonForAllProject/src/pythonclasses/chapter12/exercises.py | 2,142 | 4.0625 | 4 | '''
Created on Aug 7, 2018
@author: marcelo
'''
#Scraping Numbers from HTML using BeautifulSoup In this assignment you will write a Python program similar to http://www.py4e.com/code3/urllink2.py. The program will use urllib to read the HTML from the data files below, and parse the data, extracting numbers and compute... |
31d8b5465c9cc59b507317f0cf26c5e049cc4aaa | TairikJohnny/CURSO-PYTHON3-PRIMEIRO-MUNDO | /aula07/exercicio014.py | 176 | 3.8125 | 4 | graus = float(input("Informe a temperatura em C°: "))
conversao = ((9 * graus) / 5) + 32
print("A temperatura de C° {:.2f}, equivale a {:.2f} °F".format(graus, conversao)) |
71d86d1b41d4e23a1e133d9b00ad9ff392a37357 | TairikJohnny/CURSO-PYTHON3-PRIMEIRO-MUNDO | /aula07/exercicio011.py | 348 | 3.921875 | 4 | largura = float(input("Informe a largura da parede: "))
altura = float(input("Informe a altura da parede: "))
area = largura * altura
print("A dimensão da sua parede é de {} X {} e a sua área é de {:.2f}m²".format(largura, altura, area))
tinta = area / 2
print("Para pintar a sua parede você precisara de {:.2f}L de ... |
d986b0b30adc57f2eb7219a166e42f922a181d16 | TairikJohnny/CURSO-PYTHON3-PRIMEIRO-MUNDO | /aula08/exercicio017.py | 374 | 3.96875 | 4 | from math import hypot
cateto_oposto = float(input("Digite o valor do comprimento do cateto oposto: "))
cateto_adjacente = float(input("Digite o valor do comprimento do cateto adjacente: "))
# hipotenusa = (cateto_oposto ** 2 + cateto_adjacente ** 2) ** (1/2)
hipotenusa = hypot(cateto_oposto, cateto_adjacente)
prin... |
722018932a09a778a59dddc72f7a91784e78c5e3 | TairikJohnny/CURSO-PYTHON3-PRIMEIRO-MUNDO | /aula07/exercicio012.py | 208 | 3.734375 | 4 | produto = float(input("Digite o preço do produto: R$ "))
desconto = produto - (produto * 5 / 100)
print("O produto que custava R$ {}, agora custa R$ {:.2f} com o desconto de 5%".format(produto, desconto))
|
dee6b1aeb342f546c9725ec8fbcc88a16bf3355d | emy3210/Primeiro-repo | /Jogo NIM.py | 2,163 | 4.0625 | 4 | def jogo():
print("Bem vindo ao jogo do NIM! Escolha \n \n 1- Para jogar uma partida \n 2- Para jogar uma melhor de três")
esc=int(input("O que você escolhe?"))
if esc==1:
print("Você escolheu jogar uma partida!")
partida()
elif esc==2:
print("Você escolheu jogar um campeonato!"... |
17527b96f68133e608f17ff34cf5ce3cd210bb9e | Nabil-almrstani/SkillApp | /skillApp.py | 3,570 | 3.90625 | 4 | import sqlite3
import os
db = sqlite3.connect("skillapp.db")
cr = db.cursor()
def Login():
global username
username = input("enter your username: ")
cr.execute("SELECT * FROM users WHERE name = ?", [(username)])
result = cr.fetchall()
if result:
#print it after the password
pass
... |
bc3a3abbdd38fb71f52e5894a57fc17c16a40a65 | matiasimc/RedesNeuronales | /ejercicio2/learning_perceptron.py | 624 | 3.75 | 4 | import math
class LearningPerceptron:
def __init__(self, bias = 2, w1 = 2, w2 = 2, C = 0.01):
self.bias = bias
self.w1 = w1
self.w2 = w2
self.C = C
def perceptron_output(self,x1,x2):
return x1*self.w1+x2*self.w2 + self.bias >= 0
def sigmoid_output(self,x1,x2):
... |
0206af95337ab9e64444dcc6563d37c74f51dde4 | bermetkaa/homeworks | /lesson5.py | 2,810 | 3.890625 | 4 | # length=10
# width=7
#
# print(length+width)
#
# def cube(length=3,width=2):
# length=int(input("Enter length"))
# print(length*width*height)
# a=cube(2,4)
# print(type(a))
#
# def cube_return(length, height=7, width=2):
# length = int(input("Enter length"))
# return length*width*height
# # a=cube_retu... |
143d7c0fc68a826c80208d0543be0957af71458f | ignasa007/Algorithms | /Median Maintenance/heapFunctions.py | 6,504 | 3.984375 | 4 | #OPERATIONS
#Find-max (or Find-min): find a maximum item of a max-heap, or a minimum item of a min-heap, respectively (a.k.a. peek)
def findMax(maxHeap):
return maxHeap[0]
def findMin(minHeap):
return minHeap[0]
#Insert - adding a new key to the heap (a.k.a., push)
def insertMaxHeap(maxHeap... |
bb71e17a67684f9c776bff9af5c9634ebfda37a8 | ignasa007/Algorithms | /Karger Random Contraction Algorithm/Karger Random Contraction Algorithm.py | 2,666 | 3.9375 | 4 | '''
Karger's minimum cut algorithm is a randomized algorithm used to calculate the minimum cut of a connected graph, i.e., the
minimum number of edges that can be removed to obtain two disjoint set of vertices.
The algorithm predicts the correct number of minimum cuts with a probability 1/(nC2) = 2(n(n-1)), where... |
9507c820c47413d89571fbf39ff64d0d1c5f490b | JiungChoi/Baekjoon | /baekjoon_1181.py | 176 | 3.6875 | 4 | ary = []
for i in range(int(input())):
pre_in = input()
if [len(pre_in),pre_in] not in ary: ary.append([len(pre_in),pre_in])
ary.sort()
for i in ary:
print(i[1])
|
0ff8ed761e5629853d1bc82533d895c1842a0bee | mjneri/pipelined-RV32IMC | /assembler/assembler.py | 22,843 | 3.546875 | 4 | import sys
from argparse import ArgumentParser
from registers import register_dict
from instructions import instruction_dict
from re import split
argparser = ArgumentParser()
argparser.add_argument('input_file', help='Input filename')
argparser.add_argument('output_file', help='Output filename')
argparser.add_argument... |
d9a40b8c822dad0d919c65f8a1a55b844fe7a42b | kvahid/OCW-6.0001 | /ps1/ps1c.py | 1,932 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 23 19:23:08 2019
@author: Vahid Karimi
Problem SET 1
Part C: Finding the right amount to save away
"""
#assumptions
semi_annual_raise = 0.07
r = 0.04
portion_down_payment = 0.25
total_cost = 1000000.0
epsilon = 100.0
#initialization
lower_guess ... |
e3297d9b58ea3b64f007a5fd642cd824572be42e | mckoss/codejam-2013 | /alien-language.py | 1,604 | 3.6875 | 4 | #!/usr/bin/env python
# https://code.google.com/codejam/contest/32016/dashboard#s=p0
import re
import fileinput
test_input = """\
3 5 4
abc
bca
dac
dbc
cba
(ab)(bc)(ca)
abc
(abc)(abc)(abc)
(zyx)bc
""".split('\n')
def parse(lines):
"""
>>> words, tests = parse(iter(test_input))
>>> words
['abc', 'bca'... |
77cd52ea67b4c26104805941c3e97f7b027d9e88 | davidfcc7/django | /funciones.py | 354 | 3.96875 | 4 | def conversacion (mensaje):
print('hola')
print('como estas?')
print(mensaje)
print('adios')
opcion = int(input('elige una opcion (1, 2, 3): '))
if opcion == 1:
print('esta es la opcion 1')
elif opcion == 2:
print('esta es la opcion 2')
elif opcion == 3:
print('esta es la opcion 3')
el... |
b57eb35249052c0c997a58a052fc1a1f495ffc78 | CristianaJeler/Rabin_Cryptosystem | /Rabin.py | 8,400 | 3.78125 | 4 | import string
from math import sqrt, floor
from random import randint
from MillerRabin import miller_rabin
redundancy_size = 4
class KeyValidationError(Exception):
pass
class TextValidationError(Exception):
pass
'''
function to compute the Jacobi symbol of a modulo n
'''
def jacobi_symbol(a, n):
... |
626e30ceba84d1466c41943e16594d288be36341 | KarolinaLeonovich/TMScourse | /task_1_3.py | 577 | 4.09375 | 4 | def func_volume_and_face(edge, unit):
'''Returns volume and face of cube'''
volume = edge ** 3
face = edge ** 2
if edge == 1:
response_line = f"Volume is {volume} cubic {unit}.\nFace is {face} square {unit}."
elif edge <= 0:
response_line = "Please check your data!"
else:... |
0fa032f42089df4f8c5d6a11689a520041992815 | MayBeLaterOrNot/CodeEditor | /test.py | 273 | 3.71875 | 4 | def factorize(n):
factors = []
k = int( n**0.5) + 1
for i in range(1, k):
if n%i == 0:
factors.append(n//i)
if n//i != i:
factors.append(i)
factors.sort()
return factors
num = input()
print factorize(num) |
7f60969008de702bb20d0535f09cd86a6d142584 | kiew-ay/Adventure | /Setting.py | 5,786 | 3.703125 | 4 | '''
----------------------------------------------------------------------------------------------------------------------------
IMPORTS
----------------------------------------------------------------------------------------------------------------------------
'''
import pygame
from pygame.locals import *
... |
653a21863e7d597ce1e7a84b776fb5cb0b6f6bb1 | hongki-jung/algorithm | /알고리즘입문/quicksort/main.py | 549 | 3.734375 | 4 | # 퀵정렬
def qsort(lt, rt):
if lt<rt:
pos=lt # 분할된 영역의 시작 지점
pivot = arr[rt]
for i in range(lt, rt):
if arr[i]<=pivot:
arr[i], arr[pos] = arr[pos], arr[i]
pos+=1
arr[rt], arr[pos] = arr[pos], arr[rt]
# return
# pos가 축이 있는 지점
Qsort(lt, pos-1)
Qsort(pos... |
55834e0f10ae40fe13a48c0a3a7fe1de851eeb32 | hongki-jung/algorithm | /프로그래머스/구현/오픈채팅방/main.py | 683 | 3.640625 | 4 | from collections import deque
def solution(record):
answer = []
dq=[]
user ={}
for i in range(len(record)):
record[i]=record[i].split()
for content in record:
if content[0] == 'Enter':
user[content[1]]=content[2]
elif content[0] == "Change":
... |
bfb2dbddc8c50f7da047398ec83cc5bcbb1b96b8 | EbrahimSadri/prefix_infix_postfix | /main.py | 931 | 3.609375 | 4 | import sys
from input_handler import input_handler_function
from menu_handler import show_menu, act_on_input
print("\n")
# --------------------------------- Main ---------------------------------
while True:
# input expression
expression, expression_format = input_handler_function()
# gi... |
75111fa3ad1ea837e510fdbbde44233e0f47487e | moose1200/HashTable | /HashTable.py | 4,450 | 3.65625 | 4 | import random
import time
class Node:
#data is designed to be a (string,int)
def __init__(self,data):
self.payload = data
self.rightChild = None
self.leftChild = None
self.root = None
#Sets Right child
def setRight(self,node):
self.rightChild = node
... |
5ec281f9780ca072b4e7cd963ac21ffece5ad3a7 | h4k/PythonHomeworks | /loops.py | 1,247 | 3.9375 | 4 | numbers = [6,5,3,8,4,2,5,4,11]
sum1 = 0
for val in numbers:
sum1 = sum1 + val
print("Sum is ", sum1)
# ======================================
print(range(10))
print(list(range(10)))
# ======================================
genre = ['pop', 'rock', 'jazz']
for i in range(len(genre)):
print("I like ", gen... |
62240a367672c500046f2f2119ae28e3a55670d2 | 31337root/Python_crash_course | /Exercises/Chapter5/6.Ordinal_numbers.py | 281 | 4.03125 | 4 | numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
if numbers:
for number in numbers:
if number is 1:
print("1st")
elif number is 2:
print("2nd")
elif number is 3:
print("3rd")
else:
print(str(number) + "th")
|
63d1906f2c48c3498ca6f1905aed9df9d2038062 | 31337root/Python_crash_course | /Exercises/Chapter10/test_cities.py | 570 | 3.6875 | 4 | import unittest
from city_country import city_formated
class CityCountryTest(unittest.TestCase):
"""Test for 11.city_country.py"""
def test_city_country(self):
"Do Santiago, Chile"
formatted_name = city_formated("Santiago", "Chile")
self.assertEqual(formatted_name, "Santiago, Chile")
... |
a6049ffd3561278863dc7452ecf9cc0c15d8ed3b | 31337root/Python_crash_course | /Exercises/Chapter7/5.Deli.py | 473 | 3.984375 | 4 | sandwich_orders = ["Chesse", "Salami", "Sausage", "pastrami", "pastrami", "pastrami"]
finished_sandwiches = []
print("We're out of pastrami, sorry.")
while "pastrami" in sandwich_orders:
sandwich_orders.remove("pastrami")
while sandwich_orders:
sandwich = sandwich_orders.pop()
print("We'll prepare a " + ... |
20059f23388b82201b8a8210f90fe3cc04a16e5a | 31337root/Python_crash_course | /Exercises/Chapter5/0.Conditionial_tests.py | 500 | 4.15625 | 4 | best_car = "Mercedes"
cars = ["Mercedes", "Nissan", "McLaren"]
print("Is " + cars[0] + " the best car?\nMy prediction is yes!")
print(cars[0] == best_car)
print("Is " + cars[1] + " the best car?\nMy prediction is nop :/")
print(cars[1] == best_car)
print("Is " + cars[2] + " the best car?\nMy prediction is nop :/")
pr... |
2fd583bc3fd65e0755b86287cd76b6db42547d9e | 31337root/Python_crash_course | /Exercises/Chapter3/9.Every_function.py | 204 | 3.796875 | 4 | ways = ["Lola", "Lol", "HLola", "Lolita"]
ways.reverse()
print(ways)
print(sorted(ways))
ways.sort(reverse=True)
print(ways)
ways.sort()
print(ways)
print("The lenght of tthe list is " + str(len(ways)))
|
e0dd073eb1e42062d620d409338f0b2fe4463bc8 | 31337root/Python_crash_course | /Exercises/Chapter6/5.People.py | 406 | 3.859375 | 4 | lola = {"first name": "Lola", "last name": "Moreno", "age": 15,
"city": "Madrid"}
omar = {"first name": "Omar", "last name": "Martinez", "age": 21,
"city": "Bogotá"}
juliette = {"first name": "Juliette", "last name": "Martínez", "age": 23,
"city": "Bogotá"}
people = [lola, omar, juliette]
for person in pe... |
f8478f5397d7dce0e19b85cbbc5ee68f8f20e870 | 31337root/Python_crash_course | /Exercises/data_visualization/die_matplot.py | 468 | 3.5625 | 4 | import matplotlib.pyplot as plt
from die import Die
# Create a D6
die = Die()
# Make some rolls, and store results in a list.
results = []
for roll_num in range(1000):
result = die.roll()
results.append(result)
# Analyze the results.
frequencies = []
for value in range(1, die.num_sides+1):
frequency = r... |
836bc9c742c5f02265830404754329d3ac5b02cb | phzang/Codecademy-Projects | /customer_service_bot.py | 14,419 | 4.125 | 4 |
# # Off-Platform Project 1: Customer Service Bot
#
# Hi there! In this off-platform project, you will be working as a software engineer for the **Definitely Not Sinister Cable Company**! They have hired you to build for them a bot that can handle basic customer service requests on their website.
#
# First, you will... |
c6cf9ec493b780adc5ee52954572260a13caa295 | phzang/Codecademy-Projects | /stringmethods.py | 1,290 | 3.5 | 4 | highlighted_poems = "Afterimages:Audre Lorde:1997, The Shadow:William Carlos Williams:1915, Ecstasy:Gabriela Mistral:1925, Georgia Dusk:Jean Toomer:1923, Parting Before Daybreak:An Qi:2014, The Untold Want:Walt Whitman:1871, Mr. Grumpledump's Song:Shel Silverstein:2004, Angel Sound Mexico City:Carmen Boullosa:2013... |
c6ac2ead400609b6a372f36b1f75894121edf82e | sandesh-singh/Student_Managment_System | /college.py | 3,752 | 4.15625 | 4 | import sqlite3
import tkinter as tk
from tkinter import messagebox, ttk
mainwindow = tk.Tk()
mainwindow.title("Registration form")
connection = sqlite3.connect('student2.db')
print("Database opened successfully")
TABLE_NAME = "student_table"
STUDENT_ID = "student_id"
STUDENT_NAME = "student_name"
STUDENT_... |
0ec7426ecd9095dd510340b34871bf74adedfe43 | dongxijia/Eigenfaces | /eigenfaces.py | 12,657 | 3.515625 | 4 | #!/usr/bin/env python
__author__ = 'Aleksandar Gyorev'
__email__ = 'a.gyorev@jacobs-university.de'
import os
import cv2
import sys
import shutil
import random
import numpy as np
"""
A Python class that implements the Eigenfaces algorithm
for face recognition, using eigenvalue decomposition and
principle component a... |
3c2cbe361ad0a9bc120c45c8e499eae169ba452b | dilettanted/learning | /python/learning/state1/接受输入并保存.py | 433 | 3.90625 | 4 | def file_write():
file_name=input('请输入文件名称:')
file=open(file_name,'a')
print('请输入文件内容:【单独输入 \':w\'保存并退出】')
while True:
file_content=input()
file=open(file_name,'a')
if file_content==':w':
file.close()
break
else:
file.write(... |
396843200c934d4da8e490a0bba5e1e38db39e3e | chuckwondo/dsp | /python/q5_datetime.py | 637 | 3.53125 | 4 | #!/usr/bin/env python
# Hint: use Google to find python function
from datetime import datetime
# a)
date_start = '01-02-2013'
date_stop = '07-28-2015'
date_format = '%m-%d-%Y'
print(datetime.strptime(date_stop, date_format) - datetime.strptime(
date_start, date_format))
# b)
date_start = '12312013'
date_stop =... |
b7f6abdcd6e7a7415f203d67cba59b990ee036cb | axaa42/Machine-Learning | /knnclassification/KNN_CLASSIFICATION.py | 4,699 | 3.734375 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
from sklearn import metrics
from sklearn.grid_search import GridSearchCV
from sklearn.model_selection i... |
5daba68736bd9386ebf21f829e64a63e703a8126 | swarna123sh/text-analysis-tokenization | /main.py | 715 | 3.96875 | 4 | import nltk
import matplotlib.pyplot as plt
# Sentence Tokenization
from nltk.tokenize import sent_tokenize
nltk.download('punkt')
text="""Hello student. Welcome to the session on Python today. Having learnt pygames, tkinter, turtle graphics and OOPS, it is time for you to get introduced to plotting graphs and natural... |
76e88443c9c78c7b043e5c90fd260cac80491293 | priyareena/helo | /m.py | 63 | 3.5 | 4 | l=[1,2,3,4]
a=l[0]
for i in l:
if(a==i):
i=a
print (i)
|
87ac464be423af80612db8289a998629c4b603c9 | priyareena/helo | /displayodd.py | 114 | 3.875 | 4 | l=int(input("Enter the l:"))
u=int(input("Enter the u:"))
for i in range(l,u+1):
if(i%2!=0):
print(i)
|
fd42767e98cb39cd7d407354593bfd8292d533c9 | priyareena/helo | /factorial.py | 118 | 4.125 | 4 | num=int(input("Enter a number"))
n=1
while (num>0):
n=n*num
num=num-1
print ("Factorial of the given number is ",n)
|
0322efe06991654cf95bbee44bb2a4289224805e | priyareena/helo | /swb.py | 95 | 3.859375 | 4 | a=int(input('enter the number'))
b=int(input('enter the number'))
a=b^a
b=b^a
a=b^a
print(a,b)
|
33fc22722975ce9270806b318e1b57feaff8ef6a | priyareena/helo | /mm.py | 58 | 3.5625 | 4 | l=[2,3,4]
a=l[0]
for i in l:
if(a==i):
i=a
print(i)
|
a21017cc16b98233500849c0975f569a5233c83f | priyareena/helo | /arrayintegr.py | 268 | 3.9375 | 4 | def findMax(arr, low, high):
max = arr[low]
i = low
for i in range(high+1):
if arr[i] > max:
max = arr[i]
return max
arr = [1, 30, 40, 50, 60, 70, 23, 20]
n = len(arr)
print ("The max element is %d"%
findMax(arr, 0, n-1))
|
c7663e6804cc478e517727f7996c6f5df936d364 | jerrywardlow/Euler | /6sumsquare.py | 592 | 4.1875 | 4 | def sum_square(x):
'''1 squared plus 2 squared plus 3 squared...'''
total = 0
for i in range(1, x+1):
total += i**2
return total
def square_sum(x):
'''(1+2+3+4+5...) squared'''
return sum(range(1, x+1))**2
def print_result(num):
print "The range is 1 through %s" % num
print "... |
12f3aa99faaf55e7095fbfa04231f4605f634dff | MikhailChernetsov/python_basics_task_1 | /Hometask4/ex5/main.py | 644 | 4 | 4 | '''
5. Реализовать формирование списка, используя функцию range()
и возможности генератора. В список должны войти четные числа
от 100 до 1000 (включая границы).
Необходимо получить результат вычисления произведения всех элементов списка.
Подсказка: использовать функцию reduce().
'''
from functools import reduce
even... |
8428faf468f3c47d0e789bc73037d4da2380b206 | MikhailChernetsov/python_basics_task_1 | /Hometask3/ex1/main.py | 1,562 | 4.34375 | 4 | '''
1. Реализовать функцию, принимающую два числа (позиционные аргументы)
и выполняющую их деление. Числа запрашивать у пользователя,
предусмотреть обработку ситуации деления на ноль.
'''
# Вариант 1 - через исключения
def division(dividend, divisor):
try:
result = dividend / divisor
except ZeroDivis... |
f1daf4070d96abbf38d819e0ad7928f6b90d6e92 | Doulfa/itp-u4-c2-hangman-game | /hangman/game.py | 2,760 | 3.578125 | 4 | from .exceptions import *
from random import randint
# Complete with your own, just for fun :)
LIST_OF_WORDS = []
def _get_random_word(list_of_words):
word =''
if len(list_of_words) == 1:
return list_of_words[0]
if len(list_of_words) > 1:
size_l=len(list_of_words)-1
... |
edc017e1bab3245565ddd5db422109e34dd2785c | HAS-Tools-Fall2020/homework-Bensketball | /assignment_4/week4_questions_BM.py | 5,426 | 3.96875 | 4 | # Starter code for Homework 4
# %%
# Import the modules we will use
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# %%
# ** MODIFY **
# Set the file name and path to where you have stored the data
filename = 'streamflow_week4.txt'
filepath = os.path.join('data', filename)
print(os.g... |
854ff9de7d74fe8d4dbf75399cbcdc5e4cae0026 | pranatsharma1/Datastructures | /Recursion/Print1ToN.py | 300 | 3.78125 | 4 | def print1ToN(n):
if n==0:
return
smalloutput=print1ToN(n-1)
print(n)
return
n=10
print1ToN(n) #this print 1 to 10
# but we can print n to 1
def printNto1(n):
if n==0:
return
print(n)
smalloutput=printNto1(n-1)
return
printNto1(n) |
a49cabcf1288d85f652349fbbf9071a1a30ef43e | Satyajit-Codys/efficientSolutions | /PrimeNumber.py | 393 | 4.03125 | 4 | n = int(input())
def primeNumber(n):
if n == 1: return False
#We can save many cases by putting extra checks like if 'N%2==0' and 'N%3==0'
if n==2 or n==3: return True
if(n%2==0 or n%3==0): return False
for i in range(3,int(n**0.5)): #0 to square root of N
if n%i==0 or n%(i+2)==0:
... |
7e24356df39a4916084ab6e33ec4734db45ab7b3 | aditya2kahol/Transformers-Summarization | /run.py | 1,649 | 3.5625 | 4 | from summarizer import Summarizer
text = """
Machine learning (ML) is the study of computer algorithms that improve automatically through experience.
It is seen as a subset of artificial intelligence. Machine learning algorithms build a mathematical model
based on sample data, known as "trainin... |
de7890db84895c8c8b9e5131bbf7528dc9e3a74f | Annarien/Lectures | /L6.2_25_04_2018.py | 356 | 4.3125 | 4 | import numpy
#make a dictionary containing cube from 1-10
numbers= numpy.arange(0,11,1)
cubes = {}
for x in numbers:
y = x**3
cubes[x]=y
print ("The cube of "+ str(x) +" is "+ str(y))
# making a z dictionary
# print (cubes)
print (cubes)
#for x in cubes.keys(): #want to list ... |
e537c9e0e4dae76a740382e49219cd2d83f08772 | cagrawal11/Python-scripting-hands-on | /helpshift.py | 200 | 3.859375 | 4 | try:
start = int(raw_input("Enter number whose multiples are required: "))
stop = int(raw_input("Enter : "))
except:
print "Non integer value entered!"
else:
print range(start, stop, start)[::-1]
|
f4606b5aa50e6c472afc4e357f1432513b755bc0 | juhyun0/python_exam3 | /ifelif.py | 325 | 3.6875 | 4 | print('과목 1 : ')
n1=int(input())
print('과목 2 : ')
n2=int(input())
if (0<n1 and n1<=100)and(0<n2 and n2<=100):
n3=(n1+n2)/2
print("평균 : ")
print(n3)
if (n3>=90):
print('A')
elif (n3>=80):
print('B')
elif (n3>=70):
print('C')
else:
print('F')
else:
print('계산할 수 없는 숫자 입니다.')
|
a89ea4ce058601df6527f18c953a6b28fabfa61b | pwiecha/python_snippets | /algos/search/old_code/linear_binary_search.py | 3,457 | 4.15625 | 4 | import algos_search_common
''' Linear and binary (normal and recursive) search implementations
Both looks for the element in the sorted array '''
#@algos_search_common.time_this
def linear_search(target, sequence):
'''
Linear search algorithm
For list of len n:
Best case O(1)
Worst case O(n)
... |
4cd3fcb85a6de5c5171b16ffdd81168ac740f1e4 | pwiecha/python_snippets | /OOP/ntu_edu_sg_tutorial/pub_prot_priv.py | 1,311 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Python convention of public/protected/private variables
@author: pwiecha
"""
class PPPClass:
c_pub = 555
_c_prot = 666
__c_priv = 777
def __init__(self):
self.i_pub = 5
self._i_prot = 10
self.__i_priv = 15
self.__i_... |
c502c6a6e440af0f124694f7ed86e7b496401ef8 | joemarshall/g54mrt-useful-code | /sensors1/plotsensor.py | 1,026 | 3.515625 | 4 | # matplotlib code to run on a PC to plot a CSV file
from matplotlib.pyplot import *
from matplotlib.ticker import FuncFormatter
import time,calendar
import csv
xValues=[]
yValues=[]
# in this bit, we read the CSV file into python
with open("sensordata-1443654000000-1443826800000.csv") as file:
reader=csv.DictReader... |
9cdfbe9534951cb8dff04dd10d23989b7e2e3f41 | joemarshall/g54mrt-useful-code | /sensors2/median-filter.py | 871 | 4.0625 | 4 | # example code used in the lecture to make the graph of how a median filter removes
# noise
import random
import collections
# generate a rising line with some random noise added to test this with
testData=[]
for c in range(0,1000):
# normal / gauss random noise, variance 50 (so very noisy)
noiseValue=random.... |
a536b59b2fb3759f5e3bfa4fc29195b17536198e | buratina/Python-Data-Visualization-Solutions | /Section 04/sec04_rec08_fill.py | 198 | 3.578125 | 4 | import numpy as np
import matplotlib.pyplot as plt
from math import sqrt
t = range(1000)
y = [sqrt(i) for i in t]
plt.plot(t, y, color='red', lw=2)
plt.fill_between(t, y, color='silver')
plt.show()
|
f18d9b03a24538403c8cb93853fb0acca58cbdba | buratina/Python-Data-Visualization-Solutions | /Section 02/sec02-chunk-read.py | 1,073 | 3.640625 | 4 | import sys
filename = sys.argv[1]
with open(filename, 'rb') as hugefile:
chunksize = 1000
readable = ''
# if you want to stop after certain number of blocks
# put condition in the while
while hugefile:
# if you want to start not from 1st byte
# do a hugefile.seek(skipbytes) to skip... |
afbc6e1de89cf12c65ae783e9221ac3ee1bd4693 | mountainlandbot/diaspora-api | /diaspy/conversations.py | 2,386 | 3.59375 | 4 | #!/usr/bin/env python3
class Conversation():
"""This class represents a conversation.
.. note::
Remember that you need to have access to the conversation.
"""
def __init__(self, conv_id, connection):
"""
:param conv_id: id of the post and not the guid!
:type conv_id: s... |
d50712514658b8684da51f1e1d6dae88a5d1fb9f | FangShinDeng/pythonlearning | /datatype.py | 1,612 | 4.3125 | 4 | """
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
"""
x = 'John'
print(type(x))
# Numeric Types
x = 5
print(type(x))
x = 5.4
print(type(x))
x = 5j #虛數
print(type(x))
# S... |
abd714b1abd2e1fe46797782b26790e56cb4587e | NazSood/Sum-square-difference | /Sum-square-difference.py | 348 | 3.6875 | 4 |
number = 1
result = 0
result2 = 0
for i in range (1, 101):
result += number * number
result2 += number
number += 1
#print("Result: {:d} & number: {:d}" .format(result, number))
print("Result: {:d}" .format(result))
print("Square of sum {:d}" .format((result2 * result2)))
print("difference: {:d}" .format((re... |
0d879555e601867d9b6939b7939871650618f206 | yuyan1991/Python-Study-Draft | /python_decorator3.py | 1,354 | 3.625 | 4 | # -*- coding: utf-8 -*-
import functools
# def log(text = ''):
# def decorate(func):
# @functools.wraps(func)
# def execute(*args, **kw):
# print('===Before===')
# print('Execute %s(%s): %d'%(func.__name__, text, func(*args, **kw)))
# print('===After===')
# ... |
6affc66d9e99e9f4c6e6e11725a3dd8af9b3bd4c | yuyan1991/Python-Study-Draft | /python_mapreduce5.py | 709 | 3.625 | 4 | # -*- coding: utf-8 -*-
from functools import reduce
def str2float(s):
digits = {}
for i in range(10):
digits[str(i)] = i
def power(base, n=2):
res = 1
for i in range(n):
res *= base
return res
def convert(c):
return digits[c]
def add(x, y):
... |
4dce49eb3c633b1def6e0118827dfeaf7d03aff2 | york0ut/Criptografia-2016.1 | /completo.py | 137 | 3.953125 | 4 | x = input("Enter a number: ")
def completo (n):
i = 2
while n>1 and n>i:
while n%i != 0:
i = i+1
n = n/i
print i
completo(x)
|
e1336bc4c6810f7cd908f333502a3b6c83ca394c | bossenti/python-advanced-course | /sets.py | 1,137 | 4.21875 | 4 | # Set: collection data-type, unordered, mutable, no duplicates
# creation
my_set = {1, 2, 3}
my_set_2 = set([1, 2, 3])
my_set_3 = set("Hello") # good trick to count number of different characters in one word
# empty set
empty_set = set # {} creates a dictionary
# add elements
my_set.add(4)
# remove elements
my_se... |
613ec4ab95407e21b45bb222db9bdcbbf4819066 | rgrammer/Randomized-Quicksort | /RandomizedQuicksort/sortStates.py | 2,788 | 3.515625 | 4 | from random import randint
#Formula for Randomized-Partition
def ranodmizedPartition(A,start,end):
pivot=randint(start,end)
temp=A[end]
A[end]=A[pivot]
A[pivot]=temp
newPivotIndex=start-1
for index in range(start,end):
if A[index]<A[end]:#check if current val is less than pivo... |
1fe211da9f204d6cb05d6d04705ae5fb6bd043ec | KevinP5963/Parcial-1 | /ejercicio9.py | 319 | 4.0625 | 4 | print("ingrese su nombre de usuario")
username = input ()
print("hola "+ username)
A=float(input("ingrese un monto a invertir: "))
B=float(input("ingrese su interes anual: "))
C=float(input("por cuantos años hara esta inversion: "))
capital=A*(1+C*B)
print("el capital obtenido de la inversion es de: ",capital) |
ea3f2f7770eaa193bc9762bec5bbc2c8691713cb | henglinyang/Pace | /Pace.py | 3,874 | 3.578125 | 4 | from Const import Const
import sys
class Pace(object):
_marathon = Const(42195)
_mile = Const(1609.34)
class TimeFormatError(Exception):
pass
def __init__(self, distance, time):
self._seconds = self.time_to_seconds(time)
self._meters = self.distance_to_meter(str(distance))
... |
be6764bf63b633b2f0ef0441c015495e88fccc13 | AndreiVataselu/flapPY | /Bird.py | 797 | 3.9375 | 4 | import pygame
class Bird:
def __init__(self, screen):
# Initialize the bird
self.x = 70
self.y = 280
self.width = 35
self.screen = screen
self.color = (0, 0, 0)
self.falling_speed = 6
# Create the rect of the bird
self.rect = pygame.Rect(s... |
c70fbb28c9d3f74dd13d9c4a32cfa3f455bae36e | nvnsaharan/placement_practice | /Graph/BFS.py | 387 | 3.703125 | 4 | # s = node where to start
def BFS(s, graph):
visited = [False, ..., False]
# boolean array for visited size = no. of nodes
queue = []
queue.append(s)
visited[s] = True
while queue:
s = queue.pop(0)
print(s, end=" ")
for i in graph[s]:
if visited[i] == False:... |
c5a4306e3a7de337a0567e8da0b66808881ca089 | nvnsaharan/placement_practice | /Sorting/SelectionSort.py | 225 | 3.859375 | 4 | def sort(A):
for i in range(len(A) - 1):
min = i
for j in range(i + 1, len(A)):
if A[min] > A[j]:
min = j
A[i], A[min] = A[min], A[i]
print(A)
sort([2, 1, 5, 3])
|
0473436545a37999dd4788a5438e8db3116d506e | chengaojie0011/offer-comein | /py-project/tree/tree_build 2.py | 1,308 | 4.28125 | 4 | # -*- coding:utf-8 -*-
class Node(object):
"""节点类"""
def __init__(self, value=None, left=None, right=None):
self.value = value
self.left = left
self.right = right
class Tree(object):
"""二叉树类"""
def __init__(self):
"""初始化树类的根节点和遍历队列"""
self.root = Node()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.