blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
ba5a8a85c8abce6f29ecbc4036d4643928c517cd | tanaywasekar/Health-program | /ex1.py | 1,678 | 3.578125 | 4 | import datetime
import time
from pygame import mixer
def Time():
return datetime.datetime.now()
def Play_music(file, stopper):
mixer.init()
mixer.music.load(file)
mixer.music.play()
while True:
a = input()
if a == stopper:
mixer.music.stop()
... |
6505e85b5d6e5cf2578af641bfa6d261b74fbf40 | LsHanaha/Algoritms | /rec_binary_search.py | 278 | 3.859375 | 4 | def rec_binary_search(arr, num):
mid = int(len(arr)/2)
if arr[mid] == num:
return arr[mid]
return rec_binary_search(arr[:mid-1], num) if arr[mid] > num else rec_binary_search(arr[mid +1:], num)
arr = [1, 2, 3, 4, 5, 6, 7, 8]
print(rec_binary_search(arr, 7)) |
2bfc368d78b96988ec6829941849fd0a5aff557b | RoKu1/cracking-the-coding-interview | /Linked_Lists/4Partition.py | 3,011 | 4.0625 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LList:
def __init__(self):
self.head = None
def givehead(self):
return self.head
def printlist(self):
temp = self.head
while temp is not None:
if temp.next is not... |
682b13c02233a61c80cc555bd327374030d1abe9 | ljia2/leetcode.py | /solutions/linkedlist/138.Copy.List.with.Random.Pointer.py | 2,373 | 4.0625 | 4 | # Definition for singly-linked list with a random pointer.
class Node(object):
def __init__(self, x):
self.label = x
self.next = None
self.random = None
class Solution(object):
def copyRandomList(self, head):
"""
A linked list is given such that each node contains an ad... |
0bb04f919a0efe83acc82197096856925ff772cf | ksrntheja/08-Python-Core | /venv/oops/83CarHASAEngineAccessStaticDirectly.py | 321 | 3.65625 | 4 | class Engine:
a = 10
def __init__(self):
self.b = 20
def m(self):
print('Engine Specific Functionality')
class Car:
def m(self):
print('Car using Engine Class STATIC Functionality')
print(Engine.a)
c = Car()
c.m()
# Car using Engine Class STATIC Functionality
# 10... |
a6ea6d40b8b45a65136015cc12509fe9b108753b | bubble501/turtle-kids-teaching | /level_1_turtle/lesson_10/peppapig_house.py | 2,011 | 3.890625 | 4 | def window(a, b):
'''绘制长为a,宽为b的窗户,起笔为左上角向右'''
color("white", "#b0d5e8")
# 先画外框 并填色
pensize(4)
begin_fill()
for n in range(2):
forward(a)
right(90)
forward(b)
right(90)
end_fill()
# 画窗户格子
pensize(3)
# 竖立格子
pen_move(a/2)
right... |
a766833c69d3ea18809e3a0d60f8be11b1de83a9 | Eunsubkim/2020_Feb_python_learning | /.vscode/class_0219.py | 1,835 | 4.03125 | 4 | '''변수'''
'''quiz'''
# python=100
# age=27
# print('파이썬', python)
# print('나는', age)
# python=int(input("파이썬 점수:\n"))
# c=int(input("C언어 점수:\n"))
# java=int(input("Java 점수:\n"))
# sum=python + c + java
# ave=python + c + java/3
# print("3과목의 합계 : %d \n3과목의 평균 : %.2f" % (sum,ave))
'''예제'''
# flt= 123.567
# print("rou... |
4c7ba62d3a1f8c42ce9a048af5e03a0ce0e6c75a | mryingster/ProjectEuler | /problem_107.py | 2,481 | 3.640625 | 4 | #!/usr/bin/env python
print("Project Euler - Problem 107")
print("Using problem_107.txt, a 6K text file containing a network with forty vertices, find the maximum saving which can be achieved by removing redundant edges whilst ensuring that the network remains connected.\n")
debug = False
array = []
# Read file in, ... |
0dab9692795b1bacc03afc757a1487f2a140f504 | AyushAryal/mazesolving | /problem.py | 1,387 | 3.546875 | 4 | from graph import Graph
def find_adjacent(board, vert_pos):
adj = []
x, y = vert_pos
len_x, len_y = len(board[y]), len(board)
if x < len_x-1 and board[y][x+1] in "+SE":
adj.append((x+1, y))
if y < len_y-1 and board[y+1][x] in "+SE":
adj.append((x, y+1))
if x != 0 and board[y]... |
541a3b19385380e4e31794bc9d84675918b0b232 | mvkumar14/Data-Structures | /binary_search_tree/binary_search_test.py | 255 | 3.796875 | 4 | from binary_search_tree import BinarySearchTree
test = BinarySearchTree(3)
arr = [1,2,4,5,6,7,8]
for i in arr:
test.insert(i)
print(test.left.value,test.value,test.right.value)
print(test.contains(4))
print(test.get_max())
test.in_order_print()
|
e770436820fed5bb0acf900e8d0a7a1c5e22c674 | FionaTuite/CodeSignal-Arcade | /intro/Smooth Sailing/sortbyheight/code.py | 219 | 3.953125 | 4 | def sortByHeight(a):
l = sorted([i for i in a if i != -1])
for c ,i in enumerate(a):
if i == -1:
l.insert(c,i) # c is the position where the element i is going to be inserted.
return(l)
|
291f4617154c22e0c85c6321b2bd0692de26f9ab | keremh/codewars | /Python/7KYU/cantors_diagonals.py | 800 | 3.71875 | 4 | def cantor(nested_list):
i = 0
new_list = []
size = len(nested_list[0])
for i in range(i, size):
if nested_list[i][i] == 0:
new_list.append(1)
else:
new_list.append(0)
return new_list
"""Test
example1 = [[0,0],
[1,1]]
T... |
e116e417254213a6688d8281d4791bb7a86315b2 | Rafsun83/Python-Basic-Practice-Code- | /OOPexaple.py | 248 | 3.671875 | 4 | class triangle:
def __init__(self, height, width):
self.height = height
self.width = width
def calculation(self):
area = .5 * self.width * self.height
print(area)
t = triangle(5,7)
t.calculation() |
9f1ddf45df6a506e78da5855348f9c60e09503c0 | kubragulmez/VSCode-Education | /03_donguler/0310_mantiksal_operatorlar.py | 903 | 3.953125 | 4 | #region and
"""
print(5==5 and 15>5)
print(5==5 and 15<5)
print(5==25 and 15>5)
print(5==35 and 15<5)
"""
#endregion
#region or
"""
print(5==5 or 15>5)
print(5==5 or 15<5)
print(5==25 or 15>5)
print(5==35 or 15<5)
"""
#endregion
#region not
"""
print(not 5==5 )
print(5!=5 )
"""
#endregion
"""
sayi=int(input("Lütfen s... |
f4d198b2f1c1458072faf97e317a1acb031ffa40 | joneyyx/LeetCodes | /elementaryAlgorithms/Array/283MoveZeros.py | 2,480 | 3.890625 | 4 | # Given an array nums, write a function to move all 0's to the end of it while
# maintaining the relative order of the non-zero elements.
#
# Example:
#
# Input: [0,1,0,3,12]
# Output: [1,3,12,0,0]
# Note:
#
# You must do this in-place without making a copy of the array.
# Minimize the total number of operations.
from ... |
2e814d6f9433fa062b3d92c01d6f486645439f46 | haedal-programming/teachYourKidsToCode | /function/pingPongCalculator.py | 949 | 3.546875 | 4 | # 단위 변환 함수 선언
def convert_in2cm(inches):
return inches * 2.54
def convert_lb2kg(pounds):
return pounds / 2.2
# 단위 입력
height_in = int(input("키를 인치 단위로 입력하세요: "))
weight_lb = int(input("몸무게를 파운드 단위로 입력하세요: "))
# 단위 변환
height_cm = convert_in2cm(height_in)
weight_kg = convert_lb2kg(weight_lb)
# 탁구공과 내 키, 몸무게 비교하기
p... |
7b28e5a0031b0aae357ed04e92dafeed745c4500 | anaxronik/Eulers-tasks-python | /9.py | 792 | 4.09375 | 4 | # Тройка Пифагора - три натуральных числа a < b < c, для которых выполняется равенство
#
# a^2 + b^2 = c^2
# Например, 32 + 42 = 9 + 16 = 25 = 52.
#
# Существует только одна тройка Пифагора, для которой a + b + c = 1000.
# Найдите произведение abc.
max_number = 1000
sum_numbers = 1000
def find_triple_pifagor(sum_num... |
7d9cb61baedf04b97bfdba4053eea0f23a99e82a | superduperjolly/twitter-mood-monitor | /tw_mood_monitor/viz_tools.py | 1,164 | 3.75 | 4 | """Some functions to help the web app to make the viz.
We will do all the data manipulation here to compartmentalize
it from the app creation.
"""
from functools import reduce
import pandas as pd
from config import TWEETS_CSV
def get_hashtags(filepath=TWEETS_CSV):
"""Will procure a list of unique hashtags base... |
f1596707ac9cda9da12f4d863ce8cc6f0c286c87 | esddse/leetcode | /medium/78_subsets.py | 437 | 3.546875 | 4 |
import copy
class Solution:
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def addone(sets, num):
origin = copy.deepcopy(sets)
for lst in sets:
lst.append(num)
return or... |
ca776810d4643aca1334fd586ba755fb2e234741 | lurroque/collections | /main.py | 1,400 | 3.53125 | 4 | from exemplo_conta import (
Conta,
ContaCorrente,
ContaPoupanca,
ContaInvestimento,
ContaSalario
)
# Um objeto só é instanciado se o seu construtor for chamado
# Se há necessidade de usar uma estrutura em que as posições
# são mais importantes, é nessário trabalhar com outro tipo de dado.
# Tupla
... |
f672eea3c524f5a8f84b10d2c6681f355dd4c6d9 | alicavdar91/My-Work | /koşullu ifadeler ödev.py | 1,984 | 3.765625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # 1. şık cevabı
# In[11]:
A= float(input("SICAKLIK DEĞERİNİ GİRİNİZ:"))
B= str(input("SICAKLIK BİRİMİNİ YAZINIZ(C YADA F):"))
D= float(A)
C= float((5/9) * (D - 32))
F= float((D*9/5))+32
if B == ("C"):
print("GİRMİŞ OLDUĞUNUZ {}C= {}'DİR.".format(D,F))
elif B==("F"):
... |
69a18cce94af10c5a2daeb7d97899a1b948616f4 | ajchico7991/pdsnd_github | /final_bikeshare.py | 8,001 | 4.5 | 4 | #final bikesharae
#test for bikeshare
import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.... |
345196901e92fdeddaf6739ec0c145c4769f804b | rodrigoacaldas/PeO-IFCE-2020 | /acertePreco/acertePrecoPesquisaBinaria.py | 1,137 | 3.875 | 4 | from random import randint
print("*********************************")
print("Bem vindo ao jogo de Adivinhação!")
print("*********************************")
numero_menor = 0
numero_maior = 100
numero_secreto = randint(numero_menor, numero_maior)
total_de_tentativas = 0
acertou = False
def pesquisa_binaria(esquerda , ... |
9ca82c2fe20ceed8cc55d70ca401c6e4f2968a55 | ShubhAgarwal566/Maze-Solver | /dfs1.py | 1,922 | 3.9375 | 4 | def start(myTurtle, walls, finish, cellWidth):
myTurtle.shape('circle') # set the shaoe of myTurtle as circle
myTurtle.pensize(2) # set the pen width as 2
myTurtle.showturtle() # make the turtle visible
visited = [] # list of nodes that have been visited
def dfs_path(x, y, visited):
'''
func: recursive... |
cdb33fe7f921cb903019cabd92be367aeea3b5e8 | hardenmvp13/Python_code | /python知识体系/10,数据库/sql 总结.py | 4,192 | 3.625 | 4 | '''
基本查询:SELECT * FROM <表名>
条件查询:SELECT * FROM students WHERE score >= 80; “分数在80分或以上的学生”
SELECT * FROM students WHERE score >= 80 AND gender = 'M'; “分数在80分或以上”,并且还符合条件“男生”,
SELECT * FROM students WHERE score >= 80 OR gender = 'M'; “分数在80分或以上”或者“男生”,满足任意之一的条件”
SELECT * FROM studen... |
3e0d992b1f82361fb9a107d996572e8ec26b3bf5 | sandraa18/Mimir | /sequence.py | 1,002 | 4.0625 | 4 | #Byrjum á að biðja um lengd á rununni
#runan er: síðustu þrír tölustafir plúsaðir saman gefa næstu tölu
#Ef lengdin er 1 þá prentum við út fyrsta staf í runu
#Ef lengdin er 2 þá prentum við út fyrstu tvo stafi í runu
#Upphafsstillum fyrstu þrjá töllustafi
# Ef lengdin er meira en tveir förum við í while lykkju
# Byrjum... |
d15b4a2b51ed0cfda2d5b7234442c8c5ce11a14c | digvijaybagul/tryout | /tut1.py | 420 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 06 12:14:00 2015
@author: vhd
"""
print 'Hello'
import os
print os.getcwd()
x=3
if x>2:
print "x greater than 2"
print "xx xx"
elif x<4:
print "x more than 2 but less than 4"
else:
print x
y=[1,3,'cat',4.0,True,83.67]
for x in y:
p... |
31a4f89537f7345a6edb2767cf9e9ea9bf3784bc | sescobb27/CursosPython | /palindrome.py | 641 | 4.28125 | 4 | #!/usr/bin/env python3.3
def is_palindrome(str):
return reverse(str) == str
def reverse(str):
rev = ''
for char in str:
rev = char + rev
return rev
def is_palindrome_v2(str):
n = len(str)
return str[:n//2] == reverse(str[n - n // 2:])
n = input("type the word:\n")
while len(n) > 0:
print("is_palindrome",... |
cba54a9419178f3997948e416a2ec2d066fba5e7 | EdwardRamos2/EstruturaSequencial | /04_bimonthly_average.py | 531 | 4 | 4 | #Faca um Programa que peca as 4 notas bimestrais e mostre a media.
nota1 = int(input("Insert primeira nota bimestral"))
nota2 = int(input("Insert segunda nota bimestral"))
nota3 = int(input("Insert terceira nota bimestral"))
nota4 = int(input("Insert quarta nota bimestral"))
soma = (nota1 + nota2 + nota3 + nota4)
val... |
76255f033680c59c1adec6234651ad7428474531 | supersonicphil/python | /99bottles.py | 545 | 3.890625 | 4 |
n = 100
while n > -1:
if n == 1:
print('There is ' + str(n) + ' bottle of beer on the wall...pass the last one round')
n = n -1
print('There are ' + str(n) + ' more beers left')
elif n == 0:
print('There are no more beers so go to the shop and buy some mo... |
5a956426765d5204b94ab96f4efa3ac064658ab9 | hoh1/python4data | /tuple.demo.py | 709 | 4.28125 | 4 | #tuple is immutable; can't be changed, thus safe
# tuple uses ( ), instead of [ ]
classmates = ('Michael','Bob','Tracy')
print(type(classmates))
print(classmates)
# classmates.append('Mark')
t=(1,2)
print(type(t))
print(t)
# if there is only one element inside the list. it translates as the type of that element, n... |
22b070afbc0cfa46e556e1e26115c301ce25bf19 | tzhou2018/LeetCode | /arrayAndMatrix/697findShortestSubArray.py | 1,318 | 3.625 | 4 | '''
@Time : 2020/3/9 19:46
@FileName: 697findShortestSubArray.py
@Author : Solarzhou
@Email : t-zhou@foxmail.com
'''
"""
思路:
注意到,最短连续子数组的长度为多次出现的某个元素的最后索引减去第一次出现的索引,在加上1
定义三个dictionary,第一个用来统计每个元素出现的次数,
第二个用来统计元素第一次出现的索引,
第三个用来统计元素最后一次出现的索引
"""
class Solution(object):
def findShortestSubArray(self, nums):
... |
7148083a9f950e5e72b3ddf9aa8a48251bf9c1bc | NurbaTron/psycopg2.randomData | /month1/day.12.py | 1,720 | 4 | 4 | """args - позиционные жлементы, **kwargs - именованные элементы"""
# def mysum(a, b, *c):
# print(a)
# print(b)
# print(*c)
# print(c)
# print(type(c))
# mysum(54, 99, 54, True, "code", 54, 88, 77, 89, 57)
# def test(a, **kwargs):
# print(a)
# print(type(kwargs))
# print(kwargs)
# f... |
0c1b80527a6cf2f48608bf56f662a7469f435f0d | koshalsingh/python-algorithms | /GaussSeidedMethod1.py | 1,135 | 3.65625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 13 22:44:24 2019
@author: curaj
"""
import numpy as np
#lower matrix
def lower(a):
n=np.shape(a)[0]
m=np.shape(a)[1]
l=np.zeros([2,2], dtype='int')
for i in range(n):
for j in range(m):
if(i>=j):
... |
ceecb5a92b9355a7026d3276d9ca8ce66c59882c | Caleno83/LeetCode-Solution-Python | /LeetCode/Arrays/Two_Sum.py | 1,517 | 3.84375 | 4 | """
1. Two Sum
Easy
20605
723
Add to List
Share
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any ord... |
18d066526553fc9beaccd553794d060655b8aaa4 | RiikkaKokko/JAMK_ohjelmoinnin_perusteet | /exercise07/Tehtävä_L07T04.py | 290 | 3.6875 | 4 | kysymys1=input("Enter a number: ")
kysymys2= input("Enter another number: ")
summa= int(kysymys1) + int(kysymys2)
print(summa)
erotus= int(kysymys1) - int(kysymys2)
print(erotus)
tulo = int(kysymys1) * int(kysymys2)
print(tulo)
jakolasku = int(kysymys1) / int(kysymys2)
print(jakolasku) |
e88c0fe5b30212c1f828c113caeb3c502a15fed0 | sotoedu/python_exam | /class002/Chapter.7/Practice/1.py | 348 | 3.859375 | 4 | '''
다음 중 정규식 "a[.]{3,}b"과
매치되는 문자열은 무엇일 까?
A. acccb
B. a....b
C. aaab
D. a.cccb
'''
import re
p = re.compile("a[.]{3,}b")
print(p.match('acccb')) # None
print(p.match('a....b')) # <_sre.SRE_Match object; span=(0, 6), match='a....b'>
print(p.match('aaab')) # None
print(p.match('a.cccb')) # None
# 답 : B
|
83322958710a9bc061e2c1e2f35fba54a4cc7bdb | I-Al-Istannen/SpotifyDownloader | /spotifydownloader/spotifyapi/PlaylistIO.py | 1,815 | 3.59375 | 4 | import os
from typing import Callable
import PathHelper
from spotifyapi import SpotifyApi
def write_playlist_by_url(playlist_url: str, output_folder: str) -> str:
"""Writes the playlist with the given url to a file.
:return: The path to the written file
"""
parts = split_playlist_url_in_parts(playli... |
9e32cbe9fbd4f761bd3c725d77f10b710557e2d1 | projjal1/Algorithms-Implementation | /longest_pallindromic_substring_dp.py | 1,292 | 3.625 | 4 | #Find out the longest palindromic substring
class Solution:
def longestPalindrome(self, s: str) -> str:
l=len(s)
if l==1 or l==0:
return s
max_word=""
#Let's create a dp array
dp=[]
#Assign 0 value initially to th... |
f7592d35688e5a2673abd2030596c36985a8dd5d | liukai545/Algorithms-in-Python | /algorithm/InsertSort.py | 294 | 3.5625 | 4 | # _*_ encoding:utf-8 _*_
import algorithm
list = [1, 4, 9, 13, 34, 26, 10, 7, 4]
for i in range(0, len(list)):
for j in range(0, i + 1)[::-1]:
if (j - 1 >= 0):
while (list[j] < list[j - 1]):
algorithm.swap(list, j, j - 1)
print list
print(list)
|
f7b28c1a0bed9581ae5b925335ab59ee88716c69 | supremepoison/python | /Day14/Code/homework/student/student_info.py | 2,589 | 3.734375 | 4 |
list = []
def max_min_score():
L = sorted(list, key = lambda d:d['score'], reverse = True)
print_student(L)
return L
def min_max_score():
L = sorted(list, key = lambda d:d['score'])
print_student(L)
return L
def max_min_age():
L = sorted(list, key = lambda d:d['age'], reverse = True)... |
fba3e85cc4d410dd28c245f64fda2d06d8be407f | tj---/ba1 | /w9/9_8.py | 1,915 | 3.515625 | 4 | import sys
import node
from collections import deque
def main():
lines = [line.strip() for line in open(sys.argv[1])]
Text = lines[0]
SuffixArray = [int(numeric_string) for numeric_string in lines[1].split(", ")]
LCP = [int(numeric_string) for numeric_string in lines[2].split(", ")]
length = len(SuffixArray)
f... |
4cc0bb489d80a9dc5aa8b02070e2c085a9e8b33e | mark-walbran/advent-of-code-2019 | /Dec4/dec4.py | 1,475 | 3.6875 | 4 | def part1(lowerLimit, upperLimit):
validNumbers = set()
for i in range(lowerLimit, upperLimit + 1):
iString = str(i)
prevC = 0
flag1 = False
flag2 = True
for c in iString:
if c == prevC:
flag1 = True
if int(c) < int(prevC):
... |
2348e6e8c25ce7ba5c146d0e8e754faa07b9fdc4 | causeyo/udemy_modern_bootcamp | /excercise_challenge/01_excercise.py | 1,323 | 4.03125 | 4 | def reverse_string(text):
return text[::-1]
'''
reverse_string('awesome') # 'emosewa'
reverse_string('Colt') # 'tloC'
reverse_string('Elie') # 'eilE'
'''
def list_check(elements):
return all([isinstance(element, list) for element in elements])
'''
list_check([[],[1],[2,3], (1,2)]) # False
list_check([1, T... |
87d2bd22b8a2f196f66c7a2bac570caae674a2ff | naswfd/data_structures_-_algorithms | /recursive_sum | 141 | 3.78125 | 4 | #!/usr/bin/env python3.6
def rec_sum(n):
# base case
if n == 0:
return 0
else:
return n + rec_sum(n-1)
print(rec_sum(5))
|
c24d35c85da9cc1026d6ce7a5fd6e4817b1f35e9 | arthurDz/algorithm-studies | /leetcode/maximum_frequency_stack.py | 2,731 | 3.9375 | 4 | # Implement FreqStack, a class which simulates the operation of a stack-like data structure.
# FreqStack has two functions:
# push(int x), which pushes an integer x onto the stack.
# pop(), which removes and returns the most frequent element in the stack.
# If there is a tie for most frequent element, the element clo... |
6033031b036171fb3ba1c552b2b6bedc4f5976e6 | shouliang/Development | /Python/LeetCode/7days/150_evalute_reverse_polish_nation.py | 2,469 | 3.921875 | 4 | '''
计算逆波兰式
150. Evaluate Reverse Polish Notation:https://leetcode.com/problems/evaluate-reverse-polish-notation/
思路 : 双指针,存在环:则快慢指针肯定相遇,不存在环:快指针能到达表尾
基本思路
什么是逆波兰表达式?其实就是后缀表达式!!!你又问了,什么是后缀表达式呢?你数据结构一定都忘光了!!!
后缀表达式就是把操作数放前面,把操作符后置的一种写法,我们通过观察可以发现,第一个出现的运算符,
其前面必有两个数字,当这个运算符和之前两个数字完成运算后从原数组中删去,把得到一个新的数字插入到原来的位置,
继续做相同运算,... |
1a0a069261d4c562b27f98fda63b8327e687b834 | Este1le/Auto-tuning | /gbssl/graph.py | 7,478 | 3.546875 | 4 | """
Build graph for the use of Graph-based Semi-Supervised Learning.
"""
# Authors: Xuan Zhang <xuanzhang@jhu.edu>
# Lisence: MIT
import numpy as np
import regression
import classification
import logging
class Graph():
def __init__(self, model, x, y, distance, sparsity, logger, domain_name_lst,
... |
66dd587d413c3b753978d0fd9ee34b910e8e5e68 | danjamthelamb/Python-Challenge | /PyBank/Main.py | 1,432 | 3.625 | 4 | import os
import csv
month_count = 0
profit_losses = 0
last_month = 0
this_month = 0
change = 0
greatest_inc = 0
greatest_dec = 0
average_change = 0
change_tally = 0
budget_data_path = os.path.join('Resources', 'budget_data.csv')
with open (budget_data_path, newline='') as budget_data:
read_budget_data = csv.rea... |
72ef7d2594ff4c634a4edb1e82b3c5e048aadd33 | prathamesh-collab/python_tutorials-pratham- | /mymodule/moduletest2.py | 594 | 3.71875 | 4 | #!/usr/bin/env python3
numberone=1
ageofqueen=78
def printhello():
print("hello world")
def timesfour(input):
print(input*4)
class piano:
def __init__(self):
self.type=input("what type of piano \n")
self.height=input("what height \n")
self.price=input("how much did it cost \n")
... |
4603380ecb2f9bbd476085e60d6e0a3e52e116ce | subezio-whitehat/CourseMcaPython | /c1python/reverse.py | 144 | 3.953125 | 4 | num=int(input("Enter the number:"))
rev=0
while(num>0):
rem=num%10
rev=(rev*10)+rem
num=num//10
print("\nReversed nuumber is:",rev)
|
9f5ed215cac50e5666e22f70b29e85a185103feb | fyllmax/Programming101 | /week4/Zoo/gen_zoo_db.py | 698 | 3.8125 | 4 | import sqlite3
db = sqlite3.connect('animals.db')
# Get a cursor object
cursor = db.cursor()
cursor.execute('''
CREATE TABLE zoo_animals(id INTEGER PRIMARY KEY, spieces TEXT,
age INTEGER, name TEXT, gender TEXT, weight INTEGER)
''')
print("The table is created.")
db.commit()
base2 = [("lio... |
1fbf5f0913b6fddfbedb3da82f5316b2bbde4fb1 | KshitijMShah/Sudoku_Graph_Coloring | /main.py | 3,893 | 3.875 | 4 | from sudoku import SudokuConnections
class SudokuBoard :
def __init__(self) :
self.board = self.getBoard()
self.sudokuGraph = SudokuConnections()
self.mappedGrid = self.__getMappedMatrix() # Maps all the ids to the position in the matrix
def __getMappedMatrix(self) :
matrix ... |
a8cecfe47eda7d8f1649621ef80edfd26b696d50 | moreirafelipe/univesp-alg-progamacao | /S1/V2 - Arquivos/probPratico1.py | 161 | 3.765625 | 4 | fahrenheit = eval(input('Digite a temperatura em escala Fahrenheit: '))
celsius = 5/9 * (fahrenheit - 32)
print('A temperatura em graus Celsius é: ', celsius) |
b5198df588003606b73a854f61fe7733849d772b | Josverl/micropython-stubber | /snippets/common/validate_machine.py | 3,818 | 3.53125 | 4 | # board : ESP32
# ref : https://docs.micropython.org/en/latest/esp32/quickref.html
import utime as time
import machine
machine.freq() # get the current frequency of the CPU
machine.freq(240000000) # set the CPU frequency to 240 MHz
# Pins and GPIO
# Use the machine.Pin class:
from machine import Pin
p0 = Pin(0,... |
c99e949a8f46f4d93501eeb3906565a42e970f52 | Kasonsx/awesome-python-webapp | /example/advanced.py | 778 | 3.75 | 4 | #-*- coding: utf-8 -*-
from functools import reduce
#map函数
def f(x):
return 2*x+1
l=[1,2,3,4,5,6,7,8,9]
print(list(map(f,l)))
#reduce
def add(x,y):
return x+y
print(reduce(add,[1,3,5,7,9]))
def str2int(s):
def fn(x,y):
return x*10+y
def char2num(s):
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': ... |
1d79200335c104d3006e3ae696ce1d1d969e1536 | elllot/Algorithms | /StackQueueHeap/SmallestRangeKList.py | 1,330 | 3.765625 | 4 | """
Given k sorted lists of integers of size n each, find the smallest range
that includes at least element from each of the k lists. If more than one
smallest ranges are found, print any one of them.
"""
import heapq
def smallestRange(lists):
if len(lists) < 2: return 0 # can throw an error depending ... |
88b87d3445bc0e98b9cd1d495bb2c3a818b33335 | adriaferrer/lab-refactoring | /bet_placing.py | 966 | 3.96875 | 4 | import re
import sys
def place_bet(pot):
"""
The player places the bet at the beginning of each round
:param pot: total amount of money remaining for the player (int)
:return: bet (int)
"""
bet = 0
while (bet < 5) or (bet > 200):
bet = input(
"How much money do you want... |
699dc764786abe9362babb9f4435a99641213a5f | miskyX/misky_paython | /文件python/chonggou.py | 864 | 3.875 | 4 | ## 重构 ,把代码划分为具体的函数
import json
# 如果以前有存储,我们就加载数据
#如果没有,就提示用户输入,并存储
def love_numbers(): #创建一个函数,把后面的代码封装起来
'''注释:表明这个函数是干啥的。问候老用户并指出他喜欢的数字'''
file_name = 'love_numer1.json'
try:
with open('love_number1.json') as file_object:
my_love_number = json.load(file_object)
except FileNotFo... |
05c58a6d21dfbee6cc0b48cd7d9fc90e0f36018d | InSeong-So/Algorithm | /python/lib/recursion/StringLength.py | 132 | 3.640625 | 4 | def length(str:str):
if str == "":
return 0
else:
return 1 + length(str[1:])
# 검증
print(length("test")) |
1f4154ed07b1b28afd638b7f962a645521143440 | AnatolyDomrachev/karantin | /is28/cherkasov28/task1/task1-12.py | 295 | 4.03125 | 4 | def printFibonacchi(k):
prev = 1; prev2 = 0; current = 0
for i in range(0,k):
print(i+1," - ",current)
current = prev+prev2
prev2 = prev
prev = current
n = int(input("Введите номер числа фибоначи: "))
printFibonacchi(n) |
7acb1973876edd810b80c6e85bf28c65d3b7e7eb | BerilBBJ/scraperwiki-scraper-vault | /Users/G/geoglrb/bicycle_stores_1.py | 5,676 | 3.53125 | 4 | import scraperwiki
# Blank Python
# Access website
#html = scraperwiki.scrape("http://www.yelp.com/search?find_desc=bike&find_loc=Seattle%2C+WA&ns=1#cflt=bikes&find_desc=&rpp=40")
html = scraperwiki.scrape("http://www.yelp.com/search?find_desc=bike&find_loc=Seattle%2C+WA&ns=1#cflt=bikes")
# print html
# previous we... |
9bfa6452bf517b7f2fc75a4651662d5690424fd7 | ceradon/game | /script.py | 557 | 3.5 | 4 | #!/usr/bin/env python
class Letter_Game(object):
def __init__(self):
self._intro = [
""
]
self._questions = [
("What does AMS stand for?", "Administrative Management Society"),
("In a block style letter, how many times do you press enter after th... |
99963ef074675fa7a5d839bd101747952e3e0ae2 | oltionzefi/daily-coding-problem | /problem_1/problem_1.py | 1,657 | 3.953125 | 4 | # Recursion!!!
# 1. First we will create a simple solution with simple recursion which will see that it is not efficient
# since does calculation of the values in recursive function a lot of time, so we have repeated calculation
# which makes us worried about performance.
# 2. Second we will try to add a memo for memoi... |
a6c8c8bc89c793d9184b785f668a69dada6ef906 | kramer-1/kramer-1.github.io | /story.py | 4,767 | 4.0625 | 4 | import time
import sys
def delay_print(s):
for c in s:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(.02)
def die():
delay_print(' You died. ')
def live():
delay_print(' You survived! ')
def greeting():
delay_print("Do you want to go on an adventur... |
b8f9dfa1818ac22083701f075db8d3981342780e | sathiya-narayanan/guvi-coding | /product of digits of a number.py | 154 | 3.984375 | 4 | print("enter a number")
n=int(input())
p=1
while(n>1):
l=n%10
p=p*int(l)
n=n/10
print("the product of the digits of the number is",p)
|
8fc24fc587c00607ea0bc793bfbc5a0c86e91780 | AlbertoAlfredo/exercicios-cursos | /Curso-em-video/Python/aulas-python/Desafios/desafio050.py | 156 | 4 | 4 | n = 0
for c in range (0, 6):
n2 = int(input("Digite um valor: "))
if n2 % 2 == 0:
n += n2
print("A soma dos número pares é: {}".format(n)) |
2a4aedbf8cf19e2c22912d4e134c98ca7a6fa5a0 | emanonGarcia/express-yourself | /textminer/extractor.py | 174 | 3.515625 | 4 | import re
def phone_numbers(text):
return re.findall(r'[(][0-9)]{3}[)] [0-9]{3}-[0-9]{4}', text)
def emails(input):
return re.findall(r"[a-z\.]*\@[a-z\.]*", input)
|
b064bc4d21dc3e4bd42c248d09b142b7eb030160 | Willianan/Interview_Book | /剑指offer/36_两个链表的第一个公共节点.py | 670 | 3.6875 | 4 | # -*- coding:utf-8 -*-
"""
@Author:Charles Van
@E-mail: williananjhon@hotmail.com
@Time:2019-08-26 11:16
@Project:InterView_Book
@Filename:36_两个链表的第一个公共节点.py
@description:
题目描述
输入两个链表,找出它们的第一个公共结点。
"""
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def FindFirstCommonNod... |
9708aecf1e5ac611586c33921af87abbd502cc0d | JohnByrneJames/SpartaGlobalRepo | /Python-Files/Exercise-Files/Reading-Images/image_read_write.py | 789 | 3.828125 | 4 | from PIL import Image # I installed the PIL 'pip install Pillow' through the terminal
class ReadImage:
my_image = None
def __init__(self, image):
self.my_image = Image.open(image)
def read_my_image(self):
print(self.my_image.format, self.my_image.size, self.my_image.size)
self.my... |
61a312cbea5fed1a36580d63b2c8eca7bfa3fa1c | olivelawn/cs231-python | /12/great-int.py | 662 | 3.640625 | 4 | #!/usr/local/bin/python3
import sys
import re
# lets not mess with original argv.
args_list = sys.argv
# delete program itself from the list
del args_list[0]
if args_list:
filename=args_list[0]
else:
filename='/users/abrick/resources/urantia.txt'
# pattern to match
pattern = r'\d+'
# list to store all the intege... |
29a680e15f3793b15f7b7240ba0a85af045a0bfb | tockata/HackBulgaria | /week3/2-Resolve-with-Functions/divisors.py | 256 | 3.921875 | 4 | def divisors(n):
count = 1
result = []
while count <= n - 1:
if n % count == 0:
result += [count]
count += 1
return result
n = input("Enter n: ")
n = int(n)
print("Divisors of {} are {}".format(n, divisors(n))) |
010fc66bdada9b54e1a356fac810bbb9a2e0e6cd | calwoo/python-algos-and-ds | /array-based/stack.py | 482 | 4.125 | 4 | """
Implementation of a stack in Python. This is trivial because the built-in list already has all
the stack features in it.
"""
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def push(self, item):
self.items.append(item)
def ... |
85a465359f2662c06cf28d0cb67190eb3e88670b | JingGH/Hello-Python3 | /ex30.py | 699 | 4 | 4 | people = 30
cars = 40
trucks = 15
if cars > people:
print("We should take the cars.")
elif cars < people:
print("We should not take the cars.")
else:
print("We can't decide.")
if trucks > cars:
print("That's too many trucks.")
elif trucks < cars:
print("Maybe we could take the trucks.")
else:
... |
bb4b922cdc1616e0031a9ad2932094aaee661864 | evgeniysafonov/pdsnd_github | /bikeshare.py | 8,875 | 4.46875 | 4 |
import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'new york': 'new_york_city.csv',
'washington': 'washington.csv' }
MONTH_CONVERTION = { 'january': 1,
'february': 2,
... |
2af8769efee763f63269dcc9ba7bc95888067aa5 | KannaVairavan/python-newsfeed | /app/utils/filters.py | 716 | 3.875 | 4 | from datetime import datetime
def format_date(date):
#The format_date() function expects to receive a datetime object and then use
#the strftime() method to convert it to a string.
#The %m/%d/%y format code will result in something like "01/01/20"
return date.strftime("%m/%d/%y")
print(format_date(d... |
2da445adb61c706d89f4d37cdc2c8b7a2770c69f | cihatyalman/eCommerce_site_with_user_tracking | /Entities/store.py | 626 | 3.53125 | 4 | class Store:
def __init__(self,name="",price="",link=""):
self.name = name
self.price = price
self.link = link
def toMap(self):
map={}
map["name"] = self.name
map["price"] = self.price
map["link"] = self.link
return map
class StoreDe... |
05ea7050ccc7cd273089befc953684192016cb05 | thedarkknight513v2/daohoangnam-codes | /Daily studies/29_May_18/factorial.py | 124 | 4.09375 | 4 | n = int(input("Please input n"))
factorial = 1
for i in range(1, n+1):
factorial = factorial * i
print(factorial)
|
a7611a15245b642a5d668c73f623edba171e19ae | kaiserkonok/python-data-structures-for-beginner | /selection_sort.py | 389 | 3.9375 | 4 | def selection_sort(arr):
for i in range(len(arr) - 1):
min_index = i
for j in range(i + 1, len(arr)):
if arr[min_index] > arr[j]:
min_index = j
if min_index != i:
temp = arr[i]
arr[i] = arr[min_index]
arr[min_index] = temp
da... |
072c9a27d918d4537b3af3720994083f45de6c51 | DStheG/ctci | /04_Trees_and_Graphs/10_Check_Subtree.py | 1,935 | 3.84375 | 4 | #!/usr/bin/python
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
04.10.Check Subtree
T1 and T2 are two very large binary trees, with T1 much bigger than T2.
Create an algorithm to determine if T2 is a subtree of T1.
A tree T2 is a subtree of T1 if there exists a node n in T1 such th... |
27269b3307c73247dc46275dddec9e82b09dc984 | afrigon/fastapi-template | /app/routes/route.py | 317 | 3.578125 | 4 | import abc
class Route:
@abc.abstractmethod
def get_name(self):
return ''
@abc.abstractmethod
def register(self):
pass
def __eq__(self, other):
if isinstance(other, Route):
return self.get_name() == other.get_name()
return self.get_name() == other
|
0626d7683d2bd0b9fcf54500d13fd95b3f9b6df3 | daniel-reich/turbo-robot | /2TF3FbDiwcN6juq9W_7.py | 619 | 4.34375 | 4 | """
Given a `date`, return how many days `date` is away from 2021 (end date not
included). `date` will be in **mm/dd/yyyy** format.
### Examples
days_until_2021("12/28/2020") ➞ "3 days"
days_until_2021("1/1/2020") ➞ "366 days"
days_until_2021("2/28/2020") ➞ "308 days"
### Notes
All given da... |
0d48167ea9ff216d6237435c1a500b950d746279 | ProfessorBurke/PythonObjectsGames | /Chapter2TextbookCode/Listing 2_18.py | 1,449 | 4.15625 | 4 | """A program that searches for a word in text."""
def analyze_text(text: str, word: str) -> None:
"""Find occurrences of word in text."""
# Annotate variables
num_occurrences: int
index1: int
index2: int
output: str = ""
if word in text:
# Word is in text, count occu... |
84b6bab7d9b113c55c29c4bf200bd1b03410e28f | CarlosRubio9827/valhallaseries | /ejemplo.py | 424 | 3.75 | 4 | def jumpingOnClouds(c):
i = 0
x = 0
for i in range(i, len(c)-2):
print(i)
if c[i+1] == 1:
x+=1
i+=2
print("a")
elif c[i+2] == 0:
i+=3
x+=1
print("b")
else:
x+=1
print("c")
... |
c41744c2a09267d38111f3d642c61d5ce5539758 | kefo7771/Algorithms | /Assignment 1/hw1_3c.py | 1,020 | 3.703125 | 4 | A = [1,2,3,4,30]
B = [10,20,30,40,50]
def checkIfElementInCommon(A, B):
#Assume A, B are already sorted
for i in range(len(A)):
for j in range(len(B)):
if (A[i] == B[j]):
print("True")
return True
print("False")
return F... |
5f02f9b53814ddf4d754a73c016658b6ab2f4c81 | grantholly/code-guild | /code-guild/python/collections/tuples.py | 348 | 3.65625 | 4 | __author__ = 'grant'
t = 1, 2, 3
print(t)
t = (1, 2, 3,)
print(t)
e = (3, 4)
print(t + e)
print(t * 2)
"""
Tuples are heterogeneous and we can nest them
"""
t = (1, (2,), 'three')
print(t)
print(t[0])
print(t[:-1])
print(t[:2])
print(t.index('three'))
print((t + e + (3,)).count(3))
print(t.count(1))
pr... |
9420b198c302fb797cffccaeb3a450913bb385fb | BaymaxBei/data-structure | /str/trie.py | 1,000 | 4.0625 | 4 |
class Trie(object):
'''
trie树
'''
def __init__(self) -> None:
self.trie = {}
def insert(self, word):
tmp = self.trie
for w in word:
if w not in tmp:
tmp[w] = {}
tmp = tmp[w]
tmp['is_word'] = True
def search(self, word):... |
e65370124b2c6b9239c1421db86944ebb09a3643 | juanjotr/especialidad | /EJERCICIO1.py | 142 | 4.0625 | 4 | ''' Programa 1 '''
NUM = input("Introduce un numero y los multiplicare por 3: ")
NUM = int(NUM)
NUM = NUM * 3
print("El resultado es: ", NUM)
|
fe5abfe2152951938cb84af8069e5c54ca91650e | zhlei99/more_and_more_learning | /data_structure/SearchMethod.py | 997 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 14 21:17:13 2019
@author: zhaolei
"""
'''
查找
'''
class SearchMethod():
def __init__(self, a):
self.list = a
'''
二分查找
a = [1,3,5,7,9,10]
时间复杂度O(lgn)
空间复杂度O(1)
二分查找:查找操作快,插入慢,由此引入BST(二叉查找树)
'''
de... |
f7bb1963455c2bee3a93b66eb825611ce8f3fbf7 | damodardikonda/Python-Basics | /core2web/Week7/Day37/harshed.py | 222 | 3.6875 | 4 | lb=int(input("Enter tthe Number"));
ub=int(input("ENter the upper bound"));
for i in range(lb,ub+1):
num=i;
s=0;
while n!=0:
s+=num%10
num=int(num/10)
if(i%s==0):
print(i,end='')
|
153703299612f41bb0201d451f9c6936cb52e553 | valleyceo/code_journal | /1. Problems/l. Design/b. Class - LFU Cache.py | 3,810 | 3.8125 | 4 | # LC 460. LFU Cache
'''
Design and implement a data structure for a Least Frequently Used (LFU) cache.
Implement the LFUCache class:
LFUCache(int capacity) Initializes the object with the capacity of the data structure.
int get(int key) Gets the value of the key if the key exists in the cache. Otherwise, returns -1.... |
cdf8ee3071a208c6d605898cf333dd33e0db5dba | fbokovikov/leetcode | /solutions/reverse_linked_list.py | 3,293 | 3.984375 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __str__(self) -> str:
res = ""
while self.next is not None:
res += str(self.val) + "->"
self = self.next
res += str(self.val)
return res
class Solution:
def rev... |
f289fff58fb3d016e810734cab972450055bc18b | KodaSong/ML_Fall_2019 | /class_helper.py | 11,696 | 3.546875 | 4 | import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
from sklearn import datasets, neighbors, linear_model
from sklearn.model_selection import train_test_split
import functools
import itertools
from ipywidgets import interact, fixed
import pdb
class Classification_Helper():
def __init__(... |
6ccabea432df84afdc9d8127742a04afb961be3d | qiguangyang/demos_lxf | /do_filter.py | 1,350 | 4 | 4 | # -*- coding: utf-8 -*-
# 素数算法:埃氏筛法
# 首先,列出从2开始的所有自然数,构造一个序列:
# 取序列的第一个数2,它一定是素数,然后用2把序列的2的倍数筛掉:
# 取新序列的第一个数3,它一定是素数,然后用3把序列的3的倍数筛掉:
# 取新序列的第一个数5,然后用5把序列的5的倍数筛掉:
# 不断筛下去,就可以得到所有的素数。
def _odd_iter():
n = 1
while True:
n = n + 2
yield n
def _not_divisible(n):
return lambda x: x % n > 0
def p... |
9283f5902daf6f604be795eabd9b0188e7b9b3b2 | takapdayon/atcoder | /abc/AtCoderBeginnerContest124/C.py | 311 | 3.71875 | 4 | def coloring_colorfully(s):
ans = 0
color = {"0":"1", "1":"0"}
for i in range(1, len(s)):
if s[i-1] == s[i]:
ans += 1
s[i] = color[s[i]]
return ans
def main():
s = list(str(input()))
print(coloring_colorfully(s))
if __name__ == '__main__':
main() |
99ea0cdecc55305baaaade3053be55b2bab02f93 | YasirHabib/logistic-regression-in-python | /Section2/logistic_regression_1.py | 484 | 3.734375 | 4 | # demonstrates how to calculate the output of a logistic unit using numpy.
# the data X and weight matrix w are randomly generated from a standard normal distribution.
import numpy as np
N = 100
D = 2
X = np.random.randn(N, D)
# add bias term
X = np.column_stack([X, np.ones(N)]) # We can alternatively also us... |
587071afd716df5fae2e40602a5a861fa4c7c2b5 | wzulfikar/lab | /python/lambda.py | 333 | 4.15625 | 4 | # While normal functions are defined using the def keyword,
# in Python, anonymous functions are defined using the `lambda` keyword.
print('- lambda to add two numbers', (lambda x, y: x + y)(4, 2))
def multiplier(base: int) -> int:
return lambda x: base * x
m = multiplier(5)
print("m of 5 =", m(5))
print("m of... |
f0791110c2793ddf31a0adb84a922d30afc4ad92 | Deepti3006/InterviewPractise | /Amazon Interview/countDuplicateCharacters.py | 364 | 4.09375 | 4 | def countDuplicateCharacters():
string1 = input("Enter the string")
string2 =""
string1 = string1.lower()
string1 = string1.replace(" ","")
print(string1)
for i in string1:
index = string1.count(i)
if index >1 and i not in string2:
string2 = string2+i+str(index)
... |
7456f316c14f6d4e51b46c238560cbf3bc60a0a1 | Karocyt/PythonBootcamp | /D00/ex04/operations.py | 1,221 | 3.90625 | 4 | #! /usr/bin/env python3
import sys
class InputError(Exception):
pass
USAGE = (f"usage: {sys.argv[0]} <number1> <number2>\n"
f"Example:\n\tpython operations.py 10 3")
def prog(*args):
if len(args) is 1:
raise InputError("not enough arguments")
elif len(args) > 2:
raise InputEr... |
2fa854625dc48c92d8c4d7ecd6d99f1ef6c06e0f | mburakergenc/Essential-Algorithms-Python | /Queues/LinkedListQueues.py | 654 | 3.90625 | 4 | class Node(object):
"""
Singly Linked List Algorithms
"""
def __init__(self, data=None, next=None, prev = None):
self.data = data
self.prev = prev
self.next = next
def __str__(self):
return str(self.data)
# Create Nodes
node1 = Node("1")
node2 = Node("2")
node3 = N... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.