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 |
|---|---|---|---|---|---|---|
6dbe9d03f96deee92b78a62b254288772750bead | lance-lh/Data-Structures-and-Algorithms | /剑指offer/findX.py | 739 | 3.8125 | 4 | # -*- coding:utf-8 -*-
'''
现在有一个行和列都排好序的矩阵,请设计一个高效算法,
快速查找矩阵中是否含有值x。
给定一个int矩阵mat,同时给定矩阵大小nxm及待查找的数x,
请返回一个bool值,代表矩阵中是否存在x。
所有矩阵中数字及x均为int范围内整数。保证n和m均小于等于1000。
测试样例:
[[1,2,3],[4,5,6],[7,8,9]],3,3,10
返回:false
'''
class Finder:
def findX(self, mat, n, m, x):
# write code here
i,j = 0,m-1
wh... |
bde0349b060817650aa7cf652b61f87d4a26b930 | lance-lh/Data-Structures-and-Algorithms | /剑指offer/PrintNumber.py | 1,986 | 3.6875 | 4 | # -*- coding:utf-8 -*-
class Solution:
# 判断是否达到了最大的n位数
def Increment(self,number):
overFlow=carry=0
length=len(number)
# 逆序,从数组高index,即是数字低位开始
for i in range(length-1,-1,-1):
# ord()将字符串转换为十进制整数
# num表示每一位上的数,初始最低位进位为0,以后每一位都会加上carry
# num=ord(... |
55ebcd198f1cb23860040653950f2f46d818ae64 | lance-lh/Data-Structures-and-Algorithms | /剑指offer/FirstNotRepeatingChar.py | 968 | 3.6875 | 4 | #coding:utf-8
'''
find a first character in string
return its location
if not exist, return -1
capital case and little case differ
'''
# method 1
'''
def FirstNotRepeatingChar(s):
# check conditions
if len(s) <= 0 or len(s) >= 10000:
return -1
for i in s:
if s.count(i) == 1: # count() indi... |
f124c95489ab2db37a33397726b154b989a83ff2 | lance-lh/Data-Structures-and-Algorithms | /DSA/graph/findMinHeightTrees.py | 941 | 3.703125 | 4 | def findMinHeightTrees(n, edges):
'''
:param n: int
:param edges: List[List[int]]
:return: List[int]
'''
# create n empty set object
tree = [set() for _ in range(n)]
# u as vertex, v denotes neighbor vertices
# set add method ensure no repeat neighbor vertices
for u, v in edges... |
d15a1235a873a035ab705b166d372cf1b2ba0ec6 | lance-lh/Data-Structures-and-Algorithms | /剑指offer/ReverseList.py | 1,614 | 3.859375 | 4 | # -*- coding:utf-8 -*-
'''
输入一个链表,反转链表后,输出新链表的表头。
'''
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# stack-based solution
'''
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# if node is empty
if not pHead:
return
... |
d418910d4a1513f73f5424e010803b94303a3859 | viktaur/pyth_triple | /main.py | 615 | 4.09375 | 4 | def several():
n = input("Introduce the desired number of triples: ")
for i in range(1, eval(n) + 1):
a = i ** 2 - 1
b = 2 * i
c = i ** 2 + 1
print(a, b, c)
def one():
n = eval(input("Introduce the triple index: "))
a = n ** 2 - 1
b = 2 * n
c = n ** 2 + 1
p... |
d2a7aab6237bf70d488cbfa06073b4ea0aea53c8 | rvsp/cbse | /12_python.py | 1,317 | 3.90625 | 4 | ''' 12) Write a python script to store roll no, name and marks in 3 subjects of
students in a class in file marks.txt, append the file with 2 more records,
display the contents.
'''
def add3Record():
f = open('marks.txt', 'w+')
for i in range(3):
rollno = str(input('rollno: '))
name = str(inp... |
047db7802ba22bc7c0bf8ca712d33a28977ccc9c | rvsp/cbse | /14_python.py | 979 | 4.0625 | 4 | # 14) Write a python to read characters from the keyboard one by one all lower
# case characters get stored in the file lower.txt all upper case characters
# get stored in the file upper.txt and all other characters get stored in
# others.txt. display content of all files.
value = raw_input('enter value')
for s in val... |
f88ab43956f7e520c02516c133a3000e0e310a8a | goldbach/python-design-patterns | /observer/example.py | 1,473 | 3.53125 | 4 | from __future__ import annotations
from abc import ABC, abstractmethod
class Observable(ABC):
def __init__(self):
self._observers = []
def subscribe(self, o: Observer):
self._observers.append(o)
def unsubscribe(self, o: Observer):
self._observers.remove(o)
def notify_observ... |
c612a9f34a59aa72d361c71f1c5412bf83674bc7 | goldbach/python-design-patterns | /strategy/duck.py | 1,256 | 3.96875 | 4 | from abc import ABC, abstractmethod
class DuckStrategy(ABC):
@abstractmethod
def execute(self):
pass
class Duck:
def __init__(self, name: str, fly_behavior: DuckStrategy, quack_behavior: DuckStrategy):
self.name = name
self.fly_behavior = fly_behavior
self.quack_behavio... |
afd00da2567f3f27dbf4b22fa2e9803f839c8b7a | yeseullee/author_attribution | /clean/utils.py | 12,961 | 3.703125 | 4 | #Author: Yeseul Lee
#This file has a utility of functions I need for preparing and processing for each method.
from nltk.corpus import stopwords
from gensim import corpora, models, similarities
from collections import defaultdict
import numpy as np
import os.path
import ast, re, copy
import os
#This function is used ... |
899208941839a5d024ad7cd4bdc7c940f6fd96cf | renehuang/omnivest | /simulation/Simulator/Team.py | 1,268 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 26 13:48:14 2017
@author: reneh
"""
# Create class team for calculating the scores & average scores
import numpy as np
class Team:
def __init__(self, name, data):
self.name=name
self.data=data
#the lines that include team=name as th... |
114d909c19bfde24e1e4cbccf337b15d6479e418 | zerformza5566/CP3-Peerapun-Sinyu | /assignment/Exercise5_1_Peerapun_S.py | 436 | 4.25 | 4 | firstNumber = float(input("1st number : "))
secondNumber = float(input("2nd number : "))
plus = firstNumber + secondNumber
minus = firstNumber - secondNumber
multiply = firstNumber * secondNumber
divide = firstNumber / secondNumber
print(firstNumber, "+", secondNumber, "=", plus)
print(firstNumber, "-", secondNumber,... |
01aac35f76bb4a4c748a55e850593abf19f2c265 | toyetola/micropilot-entry-challenge | /toyetola/count_zeros.py | 730 | 3.96875 | 4 | def CountZeros(A):
if type(A).__name__ == 'list':
# initialize count which hold the value of the number of 0s found in array
count = 0
#loop through each value of the array and dtermine if zero is ecountered
for el in A:
if el == 0:
count += 1 #increament ... |
11e4cafe8e5fa73f4a49fc26f1465e6acec94d66 | Tp-Python-Org/Travail-G9 | /main.py | 1,390 | 3.515625 | 4 | #Fingbayle Josias-Perseverant 18A866FS
#Programmme principal
# seul la fonctionnalité client a été devéloppée
def menu():
print('\t\tMENU')
print('1 - Connectez vous en tant que Client')
print('2 - Connectez vous en tant que Gestionnaire')
print('3 - Connectez vous en tant que Guichetier'... |
d3dc409c940159401988fd9bf477284518543f8a | whitneybelba/cohort-data-functions | /cohort_data.py | 7,804 | 4.15625 | 4 | def unique_houses(filename):
"""TODO: Create a set of student houses.
Iterates over the cohort_data.txt file to look for all of the included house names
and creates a set called 'houses' that holds those names.
ex. houses = set([ "Hufflepuff",
"Slytherin",
"... |
9db558e8eb264d36e2e316ff5ac9d6729483f260 | anthonybaker/python-ml-exercises | /sklearn/plotting_learning_curves.py | 2,514 | 3.671875 | 4 | # In this exercise we'll examine a learner which has high variance, and tries to learn
# nonexistant patterns in the data.
# Use the learning curve function from sklearn.learning_curve to plot learning curves
# of both training and testing error.
from sklearn.tree import DecisionTreeRegressor
# import matplotlib as m... |
82f69f23f32940b0a95967c946843cfbaccd6d01 | kk31398/guvi-project | /3 in one large no.py | 214 | 4.09375 | 4 | a=int(input("Enter numbers:"))
b=int(input("Enter numbers:"))
c=int(input("Enter numbers:"))
if a>b:
big=a;
else:
big=b;
if c>big:
big=c;
print("the largest of the three a=",a,"b=",b,"c=",c,"is",big)
|
1b9f3d7efbce8a408868f4b3e0f1915321815e9b | kk31398/guvi-project | /Given a string S-check if it is a palindrome.Print yes or no.py | 68 | 3.828125 | 4 | value=str(input())
a=value[::-1]
print("yes" if a==value else "no")
|
4caab4c25f20dba8f5a137efca58eeaf09239046 | kk31398/guvi-project | /print_string_given_n_tiems.py | 94 | 3.765625 | 4 | string,n=input().split()
string=str(string)
n=int(n)
for i in range(1,n+1):
print(string)
|
e73d303b94809d03671e03b4a8bfa6e29e6f3402 | hunglnm/Analyze | /dhcp.py | 956 | 3.546875 | 4 | class DHCP:
Hostname = ""
Exclude = ""
def __init__(self):
self.Name = ""
self.VRF_Name = ""
self.NW=""
self.GW=""
self.DNS=""
def insert(self, cursor):
add_dhcp = ("INSERT INTO DHCP "
"(Name,Hostname,VRF_Name,NW,GW,DNS,Exclude) "
... |
ca1dae4e84b4d3220fa3ef82292e7243b5724c0f | shivamanhar/dynamic-programming | /19-nested-traverse.py | 472 | 3.828125 | 4 | names =[
"Adam",
[
"Bob",
[
"Chet",
"Cat"
],
"Barb",
"Bert"
],
"Alex",
[
"Bea",
"Bill"
],
"Ann"
]
def count_leaf_items(item_list):
count = 0
for item in item_list:
if isinstance(item, li... |
e47507bf63f5810cbcb6f37d7e128cd5ed26000f | shivamanhar/dynamic-programming | /10-bestSum-Dynamic.py | 813 | 3.703125 | 4 | def bestSum(targetSum, numbers, memo={}):
if targetSum in memo.keys():
return memo[targetSum]
if targetSum == 0:
return []
if targetSum < 0:
return None
shortestCombination = None
for num in numbers:
remainder = targetSum-num
remainderCombinat... |
240ab60f159e91c424b27bf412ac424fc15f6f09 | shivamanhar/dynamic-programming | /33-insert-between-two-nodes.py | 2,981 | 3.9375 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
def __repr__(self):
return self.data
class LinkedList:
def __init__(self, nodes=None):
self.head = None
if nodes is not None:
node = Node(data= nodes.pop(0))
sel... |
394fb63deada86fbb2221448a9961cb7195aec64 | shivamanhar/dynamic-programming | /tree/2-binary-tree.py | 575 | 3.640625 | 4 | class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def setData(self, data):
self.data = data
#get data
def getData(self):
return self.data
#get left child of a node
def getLeft(self):
return self.left
... |
01ffa93f4210003fa086e116d9de0de7ae80bb5e | shivamanhar/dynamic-programming | /24-recursive-present-delivery.py | 464 | 3.578125 | 4 | houses = ["Eric's house", "Kenny's house", "Kyle's house", "Stan's House"]
def deliver_presents_recursively(houses):
if len(houses) == 1:
house = houses[0]
print("Deliverying presents to", house)
else:
mid = len(houses) //2
first_half = houses[:mid]
second_half = houses[... |
920cf47fbd4c94587260fc0f3c7e8db80a2d2ee6 | 0h90/Mafioso | /Character.py | 674 | 3.53125 | 4 | from abc import ABC, abstractmethod
class Role(ABC):
def __init__(self):
self.player_id = 0
self.player_name = ""
self.role_name = ""
self.changed_role_name = ""
self.can_act = ""
self.act_time = ""
self.can_vote = True
self.alignment = "Villager"
... |
428c7cac16c659f521a1904f8fdb6dd8fed71522 | AndrewSnavely15/Monthly-Surprise | /Monthly_Surprise.py | 1,107 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 27 20:27:33 2020
@author: Andrew Snavely
"""
import random
import datetime
from datetime import datetime
from datetime import date
from datetime import timedelta
from tkinter import *
def last_day(any_day):
next_month = any_day.replace(day=28) + timed... |
5e0aa09e18545eb0db0f8e21b613e29007b6e25a | nicolesy/codecademy | /projects/codecademy_project_cho_han.py | 1,342 | 4.53125 | 5 | # codecademy_project_cho_han.py
# Create a function that simulates playing the game Cho-Han. The function should simulate rolling two dice and adding the results together. The player predicts whether the sum of those dice is odd or even and wins if their prediction is correct.
# The function should have a parameter t... |
e2f582531afef3bca4772cfdaeaa0ca0ae392146 | SkyBulk/bigb0ss-RD | /weChall/crypto_transposition-1.py | 776 | 3.90625 | 4 | ## wehChall Training: Crypto - Transposition I (Crypto, Training)
def transposition(ciphertext, key):
plaintext = ''
key = list(key)
numOfBlock = len(ciphertext) / len(key) # num of block -1
for block in range(numOfBlock): # block: 0 ~ num of block-1
for i in key:
... |
d18cd2c67c08728c29c27d1b8ece83f6064452c2 | keshavm02/cs591_c2_assignment_6 | /gaby/Problem3Tests.py | 2,844 | 3.765625 | 4 | import unittest
from Problem3 import *
class MyTestCase(unittest.TestCase):
def test_string_multiplication(self):
output = multiplyStrings("0","0")
expected = "0"
self.assertEqual(output, expected)
output = multiplyStrings("0","1")
expected = "0"
self.assertEqual(o... |
57642cb81b84ff07e6373ff93fc998fc42a7ff78 | sacry-/GKAD | /ad/queue.py | 594 | 3.859375 | 4 |
# FIFO - First in First Out
class Queue():
def __init__(self):
self.queue = []
def front(self):
try:
return self.queue.pop(0)
except IndexError:
print "Cannot take the front from an empty Queue!"
def enqueueAll(self, elems):
for elem in elems:
self.enqueue(elem)
def enqueue(self, elem):
sel... |
dbfb4ede5e2259e069f3b2c1dd14b7b06455fc96 | Rhange/hello_coding_algorithm | /07/diijkstras_algorithm_path.py | 1,998 | 3.6875 | 4 | """
1. Graph 모형 해시 테이블
"""
graph = {} # 메인 해시 테이블 생성
graph["start"] = {} # 또 다른 해시 테이블 생성
graph["start"]["a"] = 6
graph["start"]["b"] = 2
print(graph["start"].keys()) # 출발점의 모든 이웃값 확인
print(graph["start"]["a"]) # a node로 가는 edge의 weight
print(graph["start"]["b"]) # b node로 가는 edge의 weight
# 그래프에 있는 나머지 node들과 ... |
455a1e5e1501de2835e4d11e1c0df71be5ea993b | Szermekm/ibs-2020-10-coding-fundamentals-normal-exam | /average_temperature.py | 598 | 3.84375 | 4 | file = open('results.txt', 'r')
lowest = 30
lowest_year = 0
highest = 10
highest_year = 0
for line in file.read().splitlines():
if line[0].isdigit():
values = line.strip().split()
low = int(values[3])
high = int(values[1])
if low < lowest:
lowest = low
low... |
437f821cbc179a2122ad651fd33d7f6259b1dd0c | LeianChen/GUI_new2 | /agentframework.py | 3,518 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__version__ 1.0.0
Basic agent-based modelling. Builds agents into a 2D plane represented by a
raster environment. Scrapes some web data and use it to initialise the model.
Agents have methods of move, eat, and share.
"""
import random
class Agent():
def __i... |
c3e70988ab1beca50bbbdfd1a101f4a31c51856d | MiniOK/miniloveliness-001 | /mytestdemo/Selenium_demo.py | 2,062 | 3.546875 | 4 | from selenium import webdriver
"""
selenium作者地址:https://www.cnblogs.com/Snail-offort/p/8761652.html
HTTP请求报文和HTTP响应报文:https://blog.csdn.net/a_fool_program_ape/article/details/81748544
一、Selenium 爬虫入门
Selenium 的初衷是打造一款优秀的自动化测试工具,
但是慢慢的人们就发现,Selenium... |
18868e88cc99d47da4052c5231e1d78d4cba6332 | dmproia/java1301_myPythonPrograms | /lab8.py | 934 | 4.28125 | 4 | #============================
# PROGRAM SPECIFICATIONS
# NARRATIVE DESCRIPTION:Lab8
#
# @author (David Proia)
# @version(1/27/12)
#==============================
repeat = "Y"
print ("This program is designed to tell allow you to tell if you have a right triangle or not" )
print ()
while (repeat == "Y"):
X = fl... |
374237f38d1aa8bcca3106b0c3f4155250a6d7ec | dmproia/java1301_myPythonPrograms | /getpass.py | 326 | 3.609375 | 4 | pswd = open( "password.txt", "rt" )
for aLine in pswd:
value= aLine.split( " " )
print (value[0], value[1])
user = str()
while user != "1234":
user=input("Username: ")
if user == value[0]:
print ("System Acessed...")
else:
print ("Error: Incorrect username or password.")
pswd.cl... |
e98bb211016aadc1f3e17f1a917e2618690b2a1a | xiaowen1106/euler-project | /10.py | 249 | 3.859375 | 4 | primes = [2]
number = 2
def isPrime(number):
for i in primes:
if number%i == 0:
return False
return True
while True:
number += 1
if number >= 2000000:
break
if isPrime(number):
primes.append(number)
print primes
print sum(primes)
|
becea9ba9041a9164e3b972477a173ac869c031f | xiaowen1106/euler-project | /5.py | 234 | 3.734375 | 4 | answer = 1
factor = [1]
def divise(x):
global factor
for i in factor:
if x%i == 0:
x /= i
return x
for i in range(1,21):
if not answer%i == 0:
answer *= divise(i)
factor.append(divise(i))
print factor
print answer
|
d308910fab5c79722d2032ac9120c8e456588091 | SATHYAPRIYASUBRAMANIAN/python_programming | /beginner/armstrong.py | 186 | 3.921875 | 4 | n=int(input("Enter the number"))
if n!=0:
rem=n%10
result=rem**3
n=n/10
if result==n:
print("it is an armstrong number")
else:
print("It is not an armstrong number")
|
fcce11b791316096d5f0d27dd859354e63e13a50 | SATHYAPRIYASUBRAMANIAN/python_programming | /beginner/maximum.py | 118 | 3.90625 | 4 | a=[10]
for i in range(1,11):
b=int(input("enter the elemnts"))
a.append(b)
a.sort()
print("largest number is",a[n-1])
|
dca5b659482b372b0b077fdbcf02453665a7a0b9 | SATHYAPRIYASUBRAMANIAN/python_programming | /beginner/leap_year.py | 125 | 4.09375 | 4 |
year=int(input("Enter the year"))
if(year%4==0):
print("It is an leap year")
else:
print("It is not an leap year")
|
b1918063a6302eae2630cc0032ef08434884d032 | LanceJenkinZA/datesense | /src/datesense/dsrules/delimeter_rule.py | 3,303 | 3.984375 | 4 | from ..dstoken import DsToken
class DelimiterRule(object):
"""Delimiter rules mean that if some tokens are separated by a
delimiter, assumptions can be made for what those tokens represent.
DelimiterRule objects that are elements in the format_rules
attribute of DsOptions objects are evaluated during ... |
31600a896898d1cf4dd490c2c276bc3f4781d608 | honga/newcoder-tutorial | /Data Viz/graph.py | 2,078 | 3.515625 | 4 | """
Taking data we just parsed and visualize it with Math libraries
"""
from collections import Counter
import csv
import matplotlib.pyplot as plt
import numpy.numarray as na
from parse import parse
MY_FILE = "../data/sample_sfpd_incident_all.csv"
def visualize_days():
"""visualize data by day of week"""
# grab... |
553630a4edae9fc151eb0fd7fd2bd1d13f93d665 | dyilm/DYilm-IPSSI | /Python/script/ex3-2.py | 292 | 3.890625 | 4 | #! /usr/bin/python2
# -*- coding: utf-8 -*-
import math
print "\n== Calcul de la circonférence d'un cercle avec lecture au clavier ==\n"
print 'Entrer un rayon : '
rayon = input()
print "\nRayon : " + str(rayon) + "\n"
circ = math.pi * 2 * rayon
print "Resultat : " + str(circ) + "\n"
|
899a63cd411af83336fb2cada63342b2d122edae | dyilm/DYilm-IPSSI | /Python/script/ex5-2.py | 222 | 3.75 | 4 | #! /usr/bin/python2
# -*- coding: utf-8 -*-
print "\n== Calcul de puissance ==\n"
def power(**args):
return args['a']**args['b'];
r = power(a=2, b=4)
print '\nPuissance {a}**{b} : {res}\n'.format(a=2, b=4, res=r)
|
638ac949ef556b0e0ec4e29821f7f033067740b3 | dailonghao/wncg | /算法/敏感词替换.py | 210 | 3.859375 | 4 |
#敏感词汇库
a=['北京','程序员','公务员','领导','牛逼','你娘','你妈','love','sex']
words=input("please enter words:")
for x in a:
words=words.replace(x,'**')
print(words) |
8405b0a91db84f8697c28918ddd42788b112db57 | nktnlx/cs_path_codecademy | /5_plural_nouns/plural_nouns.py | 5,333 | 4 | 4 | # importing irregular nouns data from irregular_nouns_dict.py (should be in the same folder)
from irregular_nouns_dict import irregular_nouns, nouns_in_plurals
from tabulate import tabulate # https://pypi.org/project/tabulate/
import string
import sys
# making a list with punctuation signs to use it later
# when c... |
5e1f47498bf4e72b1ff23096a81c8fd65f32f9e9 | nktnlx/cs_path_codecademy | /3_words_stats/words_stats.py | 2,576 | 3.921875 | 4 | import argparse
import string
# parsing optional argument
parser = argparse.ArgumentParser(description='Words Stats')
parser.add_argument('--filename', help='name of a txt file to count symbols', type=str)
args = parser.parse_args()
# openning and reading file
with open(args.filename) as txt_file:
text = txt_fi... |
4e11d9a31d91efcaf0598bebaab4f70be8567a19 | a-udacity/udacityPython | /miniProject.py | 736 | 4 | 4 | import turtle
LENGTH = 200
def draw():
window = turtle.Screen()
window.bgcolor("white")
brad = turtle.Turtle()
brad.shape("turtle")
color = "yellow"
brad.color(color)
brad.speed(100)
n = 36
for counter in range(1, n + 1):
draw_triangle(brad)
brad.left(130)
... |
cf9889193ddaf780e80f3845cd93c1c9c164e2ed | ConorBoyle461/Analytics | /scripts/python/data_structures/linkedList.py | 676 | 3.890625 | 4 | class Node:
def __init__(self,data=None):
self.data = data
self.next = None
class linked_list:
def __init__(self):
self.head = Node()
def append(self,data):
new_node = Node(data)
current = self.head
while current.next != None:
current = current.next
current.next = new_node
... |
905d59735f3f453048b797a3dbccdc2a6d370a92 | adityaxpique/fest | /factorial.py | 179 | 4.25 | 4 | num=int(input("Enter the number whose factorial is to be calculated: "))
fac=1
while(num>0):
fac=fac*num
num=num-1
print("Factorial of the emtered number is",fac)
|
eb9dd4671c4a7660c63954dda9a704e093c25c47 | yangmyongho/3_Python2 | /chap09_Database_exams/exam04.py | 2,329 | 3.546875 | 4 | '''
문제4) emp.csv 파일을 읽어서 다음과 같이 db 테이블에 저장하시오.
<조건1> 테이블명 : emp_table
<조건2> 사원 이름으로 레코드 조회(sql문 작성)
<작업순서>
1. table 생성 : emp_table(sql 폴더)<no(int), name(varchar(20)), pay(int)>
2. python code : 레코드 추가
3. python code : 레코드 조회(사원이름)
'''
import pandas as pd
import pymysql
config = {
'host' : ... |
24e6edd40407a3c02dc2eaa6a4c8e8b0e5e251d6 | JesseDesjardins/SearchEngine | /inverted_index_builder.py | 3,604 | 3.671875 | 4 | import json
def build_courses_inverted_index(json_file):
""" Builds an inverted index using standard term frequency (# of occurences of term in doc) """
with open(json_file) as infile:
dictionary = json.load(infile)
print('Building inverted index...')
sorted_dictionary = sorted(dictionary['wor... |
df57d0979a5cf67a751efdff501ffe4d5559b4ba | gtmorganb/python_challenge | /PyBank/Resources/main.py | 2,192 | 3.734375 | 4 | #adding dependencies
import os
import csv
#assign path and join in the file
budget_data = os.path.join("budget_data.csv")
# #create empty output variables
months = 0
ProfitLoss = 0
num = 0
change = 0
dates = []
Profit = []
OverallProfit = []
#open and read csv
with open(budget_data) as csv_file:
pybank_rea... |
6f41a23b7aafb44f4a722637f8cd14fbeef74e2e | jianliangxu/xspider | /xspider/main.py | 265 | 3.78125 | 4 | import time
if __name__ == '__main__':
mylist = (x * x for x in range(3))
for i in mylist:
print(i)
print(time.strftime('%Y-%m-%d %H:%M:%S'))
time.sleep(2)
for i in mylist:
print(i)
print(time.strftime('%Y-%m-%d %H:%M:%S'))
|
1d100f4d11c1298d46d34559b7236404b4c49d73 | Okorin/mentor-bot | /ratelimits.py | 1,028 | 3.734375 | 4 | import time
class RateLimit:
def __init__(self, rate, per):
self.rate = int(rate)
self.per = float(per)
self._uses = self.per
self._window = 0.0
self._last = 0.0
def is_rate_limited(self):
# get current time
now = time.time()
# update last use
... |
0d2de2a0f752facc6d68e98d7cdb937706db6f9b | Durendal/adventofcode | /problem3-1.py | 1,072 | 3.640625 | 4 | from operator import mul
def calculate_move(coord, slope, width):
coord['x'] = (coord['x'] + slope['right']) % width
coord['y'] += slope['down']
return coord
def count_trees(map, slope, dim):
coord = {'x': 0, 'y': 0}
trees = 0
for i in range(dim['height']):
coord = calculate... |
e42315ad296b7b93a25a903964103ba04f0dd49d | shadowstep666/phamminhhoang-labs-c4e25 | /labs3/math2.py | 617 | 3.71875 | 4 | from random import randint, choice
from calc import eval
total = 0
while True:
x = randint(0, 9)
y = randint(1,9)
error = randint(-1,1)
pheptinh = choice(["+", "-", "*", "/"])
r = eval(x, y,pheptinh) + error
print(f"{x} {pheptinh} {y} = {r}")
user_answer = input("Y/N ").upper()
... |
058d1b670ba6d9ce3dbd8081a3779c2474f3518f | shadowstep666/phamminhhoang-labs-c4e25 | /labs3/homework/f-math-problem/calc.py | 214 | 4.0625 | 4 | def eval(x,y,op):
result =0
if op == "+":
result=x+y
elif op =="-":
result=x-y
elif op =="*":
result=x*y
elif op == "/":
result=x/y
return result |
967179697020fcf14089dbfea1cf61829a0f340b | wayne1116/Uva-Online-programming | /Python/12289-One-Two-Three.py | 275 | 3.71875 | 4 | a=int(input())
while a>0:
line=input()
if len(line)==3:
if line[0]=='o' and line[1]=='n' or line[1]=='n' and line[2]=='e' or line[0]=='o' and line[2]=='e':
print(1)
else:
print(2)
else:
print(3)
a-=1
|
61b6f797b4d136f5ae21782f153156afe6a318a9 | praveenkmr/HackerEarth | /Calculate the Power.py | 306 | 3.671875 | 4 | import math
def power(A, B):
if B == 0:
return 1
temp = power(A,B//2)%1000000007
if B%2 == 0:
return (temp * temp) % 1000000007
else:
return (A * temp * temp) % 1000000007
A, B = [int(x) for x in input().split()]
ans = int(power(A,B))
print(ans) |
a824915dfd1bcf53255911f3a821523ff3a9e5a7 | angeloasl/Python | /LICENSE.md/prova.py | 784 | 3.78125 | 4 | print("Bem Vindo!")
print("")
estoque = open("estoque.txt", "r+")
a = estoque.read(9);
print "Produto1:", a
b = estoque.read(3);
print "Valor1:", b
c = estoque.read(9);
print "Produto2:", c
d = estoque.read(3);
print "Valor2:", d
e = estoque.read(9);
print "Produto3:", e
f = estoque.read(3);
print "Valor3:", f
g = esto... |
215504ad95354baf30674044d4eb285dc87e8193 | Nayalash/ICS3U-Problem-Sets | /Problem-Set-Five/mohammad_race.py | 1,491 | 4.28125 | 4 | # Author: Nayalash Mohammad
# Date: October 19 2019
# File Name: race.py
# Description: A program that uses the Tortoise and Hare Algorithm to simulate a race.
# Import Required Libraries
import random
import time
# Helper Function To Display Name and Progress
def display(name, progress):
print(name + ": " + str(... |
94d53ee92c8275a4b71070097047f3085972db20 | Nayalash/ICS3U-Problem-Sets | /Problem-Set-Seven/mohammad_string_blank.py | 1,094 | 4.25 | 4 | # Author: Nayalash Mohammad
# Date: November 01 2019
# File Name: string_blank.py
# Description: A program that replaces multiple spaces with one
# Main Code
def main():
# Ask for string
string = input("Enter a string with multiple blank spaces...\n")
# Regex the string, and join it
newString = ' '.join(string.sp... |
ee4fcbdf674bc0e1eaa2f606eba75817beccc302 | Nayalash/ICS3U-Problem-Sets | /Problem-Set-Eight/mohammad_traffic.py | 2,021 | 3.75 | 4 | # Name: Nayalash Mohammad
# Date: November 07 2019
# File Name: traffic.py
# Description: A program that follows the traffic algorithm, provided by the problem set.
# Import Random Lib To use Randint Function
import random
# Main Code
def main():
# Init Data Array and index counter
data = []
index = 0
... |
d46054d6f12fb1140e5db12b87a461d140910079 | Nayalash/ICS3U-Problem-Sets | /Problem-Set-Three/mohammad_zodiac.py | 1,726 | 4.46875 | 4 | # Author: Nayalash Mohammad
# Date: October 01 2019
# File Name: zodiac.py
# Description: A program that displays your
# zodiac sign based on your birthday
# Ask user for their birthday
try:
day = int(input("Enter Birth Day: "))
month = int(input("Enter Month In Number Format (ex: September = 9) "))
except Val... |
2c3dd09d52eaa860167288b7192be1bcca2b176a | Nayalash/ICS3U-Problem-Sets | /Problem-Set-One/digit_breaker.py | 277 | 4.125 | 4 | # Author: Nayalash Mohammad
# Date: September 20 2019
# File Name: digit_breaker.py
# Description: A program that splits the digits in a number
# Ask a number from the user
number = input("Enter a Three Digit Number: ")
# Iterate over the provided string
for i in number:
print(i)
|
5ac0227ce91d1da024e91d7e6ea5e79862cb2d16 | travisdjohnson/Time | /Time.py | 1,007 | 3.5625 | 4 | import datetime
CA = datetime.date (2001, 6, 3) #The day I moved to California the first time
GA = datetime.date (2005, 9, 20) #The day I moved back to Georgia
NY = datetime.date(2013, 8, 25) #The day I moved to New York
CA2= datetime.date(2017, 7, 7) #The day I moved to California the second time
duration = (GA - CA)
... |
5fe00a185e847f3176e80c0c30e87cf52373f01f | smartmohanx/Tictactoe_game | /tic_part8.py | 4,975 | 3.875 | 4 | import pygame,sys,numpy as np
pygame.init()
board_row = 3
board_col = 3
LINE_COLOR = (23, 145, 135)
HEIGHT = 600
WIDTH = HEIGHT
square_size = HEIGHT/3
draw_lines_width = HEIGHT//100
circle_width = HEIGHT//25
x_line_width = HEIGHT//20
space = HEIGHT//10
screen = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.s... |
2494877cda4f8f5ebc6f88de5bd26cc0726d695e | Isaac3N/python-for-absolute-beginners-projects | /reading files.py | 1,110 | 4.53125 | 5 | # read it
# demonstrates reading from a text file
print("opening and a closing file.")
text_file= open("readit.txt", "r")
text_file.close()
print("\nReading characters from a file.")
text_file= open ("readit.txt", "r")
print(text_file.read(1))
print(text_file.read(5))
text_file.close()
print("\nReading the entire fi... |
f75b734c0b6c1848e23253466a2a637dd5220983 | Isaac3N/python-for-absolute-beginners-projects | /limited tries guess my number game.py | 608 | 4.21875 | 4 | # welcome to the guess my number game
# your to guess a number from 1-5
# your limited to 3 tries
import random
print (" welcome to the guess my number game \n your limited to a number tries before the game ends \n GOOD LUCK !")
the_number = random.randint(1,5)
guess = input (" take a guess: ")
tries = 1
while guess... |
28b88daf7d03b1b10b2a8df1e92a28f7f149e24e | deepk777/leetcode | /30-day-challenge-2020/May/week2/day13-remove-k-digits.py | 1,339 | 3.75 | 4 | # Remove K Digits
# Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible.
#
# Note:
# The length of num is less than 10002 and will be ≥ k.
# The given num does not contain any leading zero.
# Example 1:
# Input: num = "1432219", k = 3... |
cc68eb7b237f29daca53fa9ab7ddfa7e9b5006bf | deepk777/leetcode | /30-day-challenge-2020/April/week2/day12-last-stone-weight.py | 1,480 | 3.59375 | 4 | # Last Stone Weight
# We have a collection of stones, each stone has a positive integer weight.
# Each turn, we choose the two heaviest stones and smash them together. Suppose the stones have weights x and y with x <= y. The result of this smash is:
# If x == y, both stones are totally destroyed
# If x != y, the sto... |
551ad3905b45311d50b1cd95547356349286f946 | deepk777/leetcode | /30-day-challenge-2020/April/week1/day1-single-number.py | 563 | 3.90625 | 4 | # Given a non-empty array of integers, every element appears twice except for one. Find that single one.
# Note:
# Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
# Example 1:
# Input: [2, 2, 1]
# Output: 1
# Example 2:
# Input: [4, 1, 2, 1, 2]
# Output: 4
... |
57616a6dd5833d5e96721d0e5df73f5e4d65cda0 | deepk777/leetcode | /30-day-challenge-2020/May/week2/day12-single-element-in-a-sorted-array.py | 747 | 3.921875 | 4 | # Single Element in a Sorted Array
# You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Find this single element that appears only once.
# Follow up: Your solution should run in O(log n) time and O(1) space.
# Example... |
6e06d7903ea53fa0e3a02316395b8ae92d30048a | Divan009/Algorithms_DS | /Priority_Queue.py | 2,924 | 3.84375 | 4 | class PriorityQueueBase:
"""Abstract base class for a priority Queue"""
class _Item:
"""Lightweight composite to store priority queue items"""
__slots__ = '_key', '_value'
def __init__(self, k, v):
self._key = k
self._value = v
def __It__(self, other):
return self._key < other._key #compare items ... |
54936eb0f76a3addf085169aae50025a12f96533 | jhorwinski/python | /assn2.3.py | 148 | 3.734375 | 4 | # Enter Hours:35
# Enter Rate:2.75
# Pay: 96.25
h=raw_input('Enter Hours:')
r=raw_input('Enter Rate:')
h=float(h)
r=float(r)
p= h*r
print 'Pay:',p |
512644268a51e2df3f78a957a2db6f123864d46c | albina77/MIPT_Python | /w7/project/build/lib/my_mathematics/linear_algebra.py | 2,037 | 3.796875 | 4 | class Vector:
__x = None
__y = None
__z = None
def __init__(self, a, b, c = 0):
self.__x = a
self.__y = b
self.__z = c
def __str__(self):
return '('+str(self.__x)+', '+str(self.__y)+', '+str(self.__z)+')'
def __add__(self, other):
return Vector(self.__... |
507544ce7b50836fb525d5ecde05e0c2abd4f0fd | albina77/MIPT_Python | /w7/project/build/lib/my_mathematics/math.py | 1,284 | 3.796875 | 4 | import math
import cmath
class MyMath():
_complex = False # инкапсуляция!
pi = 3.14
def sin(self, x):
return math.sin(x)
def sqrt(self, x):
if (x < 0):
if self._complex == False:
raise ValueError("Нельзя! Мы работаем с действительными числами")
... |
555d7f835dd573bb0f58e12d64aade18cf83d793 | lionisakis/AI-Artificial-Intelligence | /project1/snake.py | 7,510 | 3.515625 | 4 | import tkinter
import random
RIGHT = "RIGHT"
LEFT = "LEFT"
DOWN = "DOWN"
UP = "UP"
NONE = "NONE"
DIRACTIONS=[RIGHT,LEFT,DOWN,UP,NONE]
class GameWord:
def __init__(self):
self.top = tkinter.Tk()
self.width=300
self.height=300
self.score=0
self.scoreText="Score: " + str(self.s... |
111c7e5018e2779b0cc2114a0c0883d6d40665b8 | Lslonik/python_algorithm | /HW_1/HW_1.6.py | 450 | 4.21875 | 4 | # Пользователь вводит номер буквы в алфавите. Определить, какая это буква
letter_number = int(input("Введите номер буквы английского алфавита: "))
if 97 <= ord(chr(96 + letter_number)) <= 122:
your_letter = chr(96 + letter_number)
print(f"Ваша буква: {your_letter}")
else:
print("Такой буквы нет в алфавите... |
70c6046607605e1e817655ea5d67df32d6491468 | Lslonik/python_algorithm | /HW_3/HW_3.2.py | 930 | 4.125 | 4 | # Во втором массиве сохранить индексы четных элементов первого массива. Например,
# если дан массив со значениями 8, 3, 15, 6, 4, 2, второй массив надо заполнить значениями 0, 3, 4, 5,
# (индексация начинается с нуля), т.к. именно в этих позициях первого массива стоят четные числа.
import random
SIZE = int(input('Введ... |
34ac7c7e8493b50d643a2003cdcbf63ee4b4d370 | Lslonik/python_algorithm | /HW_3/HW_3.1.py | 566 | 3.921875 | 4 | # В диапазоне натуральных чисел от 2 до 99 определить, сколько из них кратны каждому из чисел в диапазоне от 2 до 9.
START_DIGIT = 2
END_DIGIT = 10
START_NUMBER = 2
END_NUMBER = 100
for digit in range(START_DIGIT, END_DIGIT):
counter = 0
for number in range(START_NUMBER, END_NUMBER):
if number % digit... |
2eca57ab5232ee5c7fbaf90ed7689e4c992427d9 | lovegohome/remote-repo-example | /ch01/ex1_1.py | 741 | 3.609375 | 4 | # print("당신에 대해 알려주세요.")
# name = input("이름:")
# age = input("나이:")
# dream = input("꿈:")
#
# print("당신의 이름은 %s이며, \n"
# "나이는 %s살. 그리고 %s 라는 꿈을 갖고 있군요. 멋집니다."
# %(name, age, dream))
name = 'Serena'
age = 23
dream = '취업성공'
# print(name+'입니다.')
# print('저는', age+ '살이며 꿈은' +dream,end='')
# print('입니다.\n 반갑습니... |
988207876d95d5de27ef0fb9e14600343a9afe56 | macheenlurning/python-classwork | /Chap3Exam.py | 2,478 | 4.3125 | 4 | # Ryan Hutchinson
# Chapter 3 Exam
# Programming Projects 1 & 3
#1 - Car Loan
loan = int(input("Enter the amount of the loan: "))
if int(loan) >= 100000 or int(loan) < 0:
print("Total loan value {} might be incorrect...".format(loan))
response1 = input("Would you like to correct this? Type Yes or No:... |
82feb09dd068cc0927ba43a47dc506062da10a4c | aichet123456/https-github.com-new | /multi.py | 1,485 | 3.5 | 4 | import matplotlib.pyplot as plt
import numpy as np
def featureNormalization(x):
x_np=np.asarray(x)
mean=np.mean(x)
std=np.std(x)
return (x_np-mean)/std
def h_function(theta,x):
h=np.dot(x,theta)
return h
def grad(x,y,theta):
m = y.size
n = x[0, :].size
g_vector =... |
af56ad9ea9c86e8b5f52100ad676721b8671bfaa | KunstDerFuge/Project-Euler | /092.py | 881 | 3.921875 | 4 | # A number chain is created by continuously adding the square of the digits in a number to form a new number until it
# has been seen before.
#
# For example,
#
# 44 → 32 → 13 → 10 → 1 → 1
# 85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89
#
# Therefore any chain that arrives at 1 or 89 will become stuck in an endless l... |
a42ec0d9d166ce551f716bbffce0684123e7f82b | KunstDerFuge/Project-Euler | /026.py | 1,517 | 3.875 | 4 | # A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2
# to 10 are given:
#
# 1/2 = 0.5
# 1/3 = 0.(3)
# 1/4 = 0.25
# 1/5 = 0.2
# 1/6 = 0.1(6)
# 1/7 = 0.(142857)
# 1/8 = 0.125
# 1/9 = 0.(1)
# 1/10 = 0.1
#
# Where 0.... |
328843b514b2975592250ea92ebc12aad72de5f4 | KunstDerFuge/Project-Euler | /023.py | 1,771 | 4.0625 | 4 | # A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example,
# the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
#
# A number n is called deficient if the sum of its proper divisors is less than n and i... |
0b8bd6b5cf5c59e2a493402a28fd5e5adc442686 | KunstDerFuge/Project-Euler | /037.py | 1,650 | 3.640625 | 4 | # The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from
# left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left:
# 3797, 379, 37, and 3.
#
# Find the sum of the only eleven primes that are both truncatab... |
2e1d4f4c5e11e12db4e2b9d5d6ae16f48dcc60a4 | KunstDerFuge/Project-Euler | /069.py | 1,619 | 3.78125 | 4 | # Euler's Totient function, φ(n) [sometimes called the phi function], is used to determine the number of numbers less
# than n which are relatively prime to n. For example, as 1, 2, 4, 5, 7, and 8, are all less than nine and relatively
# prime to nine, φ(9)=6.
#
# n Relatively Prime φ(n) n/φ(n)
# 2 1 ... |
42b33b9680fbcb0e0bc1b73689808141e589c2b8 | KunstDerFuge/Project-Euler | /044.py | 1,037 | 3.8125 | 4 | # Pentagonal numbers are generated by the formula, P(n)=n(3n−1)/2. The first ten pentagonal numbers are:
#
# 1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
#
# It can be seen that P(4) + P(7) = 22 + 70 = 92 = P(8). However, their difference, 70 − 22 = 48, is not pentagonal.
#
# Find the pair of pentagonal numbers, P(j) an... |
e3bad7e864a3c6653d3a197833d391bb0956cded | KunstDerFuge/Project-Euler | /038.py | 1,453 | 4.09375 | 4 | # Take the number 192 and multiply it by each of 1, 2, and 3:
#
# 192 × 1 = 192
# 192 × 2 = 384
# 192 × 3 = 576
#
# By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated
# product of 192 and (1,2,3)
#
# The same can be achieved by starting with 9 and multiplying ... |
2cd5fa286539716c02db6e5c210add85f22232a2 | A01754461/02-decisiones-A01753493-tec | /assignments/02Licencia/src/exercise.py | 1,016 | 4 | 4 | """
Licencia de manejo;
Ingresa tu edad;
if (Edad mayor a 0)
{
if (Edad mayor o igual a 18)
{
if (¿Tienes identificación oficial?(s/n))
{
Imprimir Trámite de licencia concedido;
}
else
{
if (Respuesta es igual n?)
{
Imprimir No cumples con los requisitos
}
... |
f27e9be4205678a0b4cbd6e141efa621981c79a8 | zhrmrz/shortest_to_char | /shortest_to_char.py | 431 | 3.59375 | 4 | class Sol:
def shortest_to_char(self, s,c):
idx=[index for index, value in enumerate(s) if value == c]
l=[]
for i in range(len(s)):
min=len(s)-1
for j in idx:
ans=abs(i-j)
if ans<min:
min=ans
l.append(min... |
32d7d4547b6f51b1dfb8b438b40ec22f57fb6cec | irbraun/plant-phenotypes-nlp | /notebooks/_utils.py | 4,922 | 3.5 | 4 | import pandas as pd
import re
class Method:
def __init__(self, name, hyperparameters, group, number, function=None, kwargs=None, metric=None, tag=""):
"""Constructor for a Method class to define a single approach for distance measurements.
Args:
name (str): A string specifying just the general name of... |
7d36bdc1f94a63bf2028050548c9492c72fd5fc0 | arhao/FlightRecovery | /PassengerClass.py | 876 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
class Passenger(object):
'''旅客类'''
def __init__(self,id,flight,population):
self.id=id
self.flight=flight
self.population=population
self.status='waiting'
def __cmp__(self, other):
if self.__eq__(oth... |
d1987487263fb03b2dd1e6469fcbd71d89ec57c3 | MarkClerigo/fcpc_python_projects | /sample_clerigo.py | 539 | 4.0625 | 4 | # Declaring and Initialising variables in Python
#String
RoRO = "Loveteam"
Ralph = "Pogi"
Balbin = "Bobo"
Intro = "Hello World"
print(RoRO)
print(Ralph)
print(Balbin)
print(Intro)
#Arithmetic
addition = 1+1
subtraction = 1-1
multiplication = 1*1
division = 1/1
modulus = 1%1
print(addition)
print(subtraction)
print(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.