blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
82c44eccaa08aade29c1ff0ec0b3dc14a2585ceb | aquaeye-ai/calacademy-fish-id | /lib/scripts/image_scraping/google_images_js_scraper.py | 6,706 | 3.703125 | 4 | """
Script to scrape google images.
Adapted from: https://www.pyimagesearch.com/2017/12/04/how-to-create-a-deep-learning-dataset-using-google-images/
One must first manually google search for images, open the js console in the browser and then paste the following code
snippets to download a 'urls.txt' file containing ... |
40eea727becdee3502158876119ceae056fd937e | virtyaluk/leetcode | /problems/21/solution.py | 678 | 3.875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
node = ListNode(0)
tracker = node
while l1 and l2:
val ... |
afb35fa7549da03f9202a95638bcaf63c90edc83 | virtyaluk/leetcode | /problems/987/solution.py | 1,081 | 3.765625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def verticalTraversal(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
... |
6c6cdbcf4408127d4fe0170a9007dba54c29c38e | HarshitRaj112233/Tic-Tac-Toe | /game.py | 3,941 | 4.15625 | 4 | # import random
board=["-","-","-","-","-","-","-","-","-"]
game_still_on=True
array=[]
piece=["X","O"]
opted=[]
winner=None
player1=input("Write Player1 name: ")
player2=input("Write Player2 name: ")
turn=player1
choose=None
dict={}
opted2=None
def display_board():
for row in range(9):
if(row==0):
... |
afbb2dd0cd85f5505fdb88bbef4b1d56620654b0 | daesy13/try_except_python | /exception4.py | 432 | 3.9375 | 4 | # Creating your own exception
try:
f = open("currupt_file.txt")
if f.name == "currupt_file.txt":
raise Exception #here we create our own exception using "Exception"
#which is used around line 9
except FileNotFoundError as e:
print(e)
except Exception as e:
print("Error!") #Here we change... |
991c3c4d595558a40ab202ac2b6bb8cd986c7041 | www111111/A1804_02 | /10/练习.py | 539 | 3.65625 | 4 |
class Car(object):
def __init__(self,carType):
self.carType=carType
def move(self):
print('%s car moving。。。。。'%self.carType)
def stop(self):
print('%s car stop。。。。。'%self.carType)
def Fun(self):
self.move()
self.stop()
class Car_Store(object):
def order(self,... |
ba94f73ff2b05f0e8315a99cc09581f8e76516a0 | www111111/A1804_02 | /13/tuidaoshi.py | 319 | 3.734375 | 4 | #推导式
a = [i for i in range(1,100,2) ]
print(a)
a = [i for i in range(1,100) if i%2!=0]
print(a)
b = [i for i in range(1,5) for j in range(1,3)]
print(b)
b = [j for i in range(1,5) for j in range(1,3)]
print(b)
#range(5) 0-4
b = [(i,j,k) for i in range(1,5) for j in range(1,3) for k in range(1,3)]
print(b)
|
940402206346aafb1d3dfab2829ff0acde6f1dfd | kennyxcao/tic-tac-toe-python | /TicTacToe.py | 4,003 | 4.09375 | 4 | # Create a Tic Tac Toe game
from __future__ import print_function
from IPython.display import clear_output
import random
def display_board(board):
"""Print out a board"""
clear_output()
for i, item in enumerate(board):
if i in [2,5,8]:
print(item)
else:
print(item, ... |
acee040fe5699aa41d5677761681159f1306442f | fajarmf10/CodeChallenges | /hackerrank-contests/project-euler/euler006.py | 312 | 3.53125 | 4 | #!/bin/python3
import sys
def sumsquare(n):
return(n*(n+1)*(2*n+1)//6)
def squaresum(n):
return(sum(i for i in range(1, n+1))**2)
def domath(n):
ans = abs(squaresum(n)-sumsquare(n))
return ans
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
print(domath(n)) |
8a1d965262e4318df8bda81627818406341280c9 | fajarmf10/CodeChallenges | /hackerrank-contests/project-euler/euler002.py | 351 | 3.890625 | 4 | #!/bin/python3
import sys
def fiboSumEven(n):
answer=0
curr=1
next=2
while(curr<=n):
if(curr%2==0):
answer+=curr
curr, next = next, curr+next
return(answer)
if __name__ == '__main__':
t = int(input().strip())
for a0 in range(t):
n = int(input().strip()... |
bc03283a33fc5fa22f8d6fa465b3d0f441142286 | mariuslungu97/stock-prediction-framework | /src/classify_data.py | 5,101 | 3.703125 | 4 | """
============IMPORTS============
"""
import pandas as pd
class DataClassifier:
"""
Classifies financial data by labeling each point as a buy(2), hold(0), or sell(1), based on the following params:
1. target_col
2. t_in_future
The classification is performed using dynamic thresholds defi... |
5028c0801873fc5df02c3f7c40d477382ca5d1eb | HUHANK/Web | /project/wb/background_server_c/MTime.py | 4,820 | 3.625 | 4 | # -*- coding:utf-8 -*-
import datetime, calendar, time, pytz
def getNowTimestamp():
return time.time()
#YYYY-MM-DD
def getYearWeek(strdate):
date = datetime.datetime.strptime(strdate, '%Y-%m-%d')
YearWeek = date.isocalendar()
return YearWeek
#获取当前年份,第几周,一周的第几天
def getNowYearWeek():
date = dateti... |
ccb80096e314f8494efa8dd70a041d7ae021c774 | merlin2181/TicTacToe_with_AI | /Tic-Tac-Toe with AI/task/tictactoe/tictactoe.py | 13,546 | 4.21875 | 4 | """
A more involved game of Tic Tac Toe that offers the ability to play against the computer using
two different difficulties: easy and hard
To play: type "start" followed by either user, easy, medium or hard.
Example: 'start easy user' ==> start the game, player1 is easy computer, player2 is the user
Example: 'start... |
c288767133b7d6162e42066e91ba110191e87772 | mitchboulton/practice_projects | /getWeather_simple.py | 994 | 3.59375 | 4 | import requests
from bs4 import BeautifulSoup
# Pulls Charlotte weather website
res = requests.get('https://forecast.weather.gov/MapClick.php?textField1=35.1975&textField2=-80.8345#.XBwoGFxKhPY')
# Tests for errors
try:
res.raise_for_status()
except Exception as exc:
print('There was a problem: %s' ... |
6e7b9dd4581e5131939d4be08757daf47431bd22 | nidhi117/project | /HS08TEST.py | 158 | 3.6875 | 4 | xx = input().split()
x = float(xx[0])
y = float(xx[1])
if x + 0.50 > y or y == 0 or x%5 != 0:
print("%.2f" % y)
else:
print("%.2f" % (y - x - 0.50))
|
44e0bf77ae99c63b2862e1335ec07fc353c3a1dc | typisk/Inf3331 | /Oblig 9/src/math_quiz.py | 2,580 | 3.8125 | 4 | import sys
from random import randint
limits = [10,25,100]; gameOn=True
def result(q, n1, n2): #q is question type
if (q == 1):
return {'type':'plus', 'res':n1+n2}
elif (q == 2):
return {'type':'minus', 'res':n1-n2}
elif (q == 3):
return {'type':'times', 'res':n1*n2}
else:
... |
bfe7718ec9c445f00a1f7f1cffcab9dd335bcfab | artemon87/Py | /work.py | 746 | 3.671875 | 4 | from datetime import datetime
from collections import namedtuple
def main():
options = ['a', 'b']
displayOptions = ['Add RD file(s)', 'Print list of RD files']
for index in range (0, 2):
print(str(options[index])+') '+displayOptions[index])
done1 = True
while done1:
try:
... |
4102d3f11ac57a8a7b14cce548dff931abba532a | yunhyon/finance_project | /Linear_Algebra.py | 145 | 3.59375 | 4 | def transpose(A):
B=[]
for j in range(len(A[0])):
C = []
for i in range(len(A)):
C.append(A[i][j])
B.append(C)
return B
|
2bc59f5913b27bd871d16b4d9bc41a4e06e9b178 | Thrshan/amazon-price-scrapper | /sql_handler.py | 853 | 3.9375 | 4 | import sqlite3
def insert_data_db(db_file, table_name, data):
try:
con = sqlite3.connect(db_file)
cur = con.cursor()
# # Create table
cur.execute('''CREATE TABLE IF NOT EXISTS {}
(date text, timestamp real, price real)'''.format(table_name))
# Insert a ... |
1d336f9f1f24eaa865ee42cd9e92482c909b802d | acoderly/misc | /algorithm/is_bst.py | 4,319 | 3.78125 | 4 | # 判断一棵树是否是搜索二叉树。
class DoubleLinkedList:
class Node:
def __init__(self, data):
self._data = data
self._next = None
self._pre = None
def __init__(self):
self.__head = DoubleLinkedList.Node("__head")
self.__tail = DoubleLinkedList.Node("__tail")
... |
c141b1a408f3a61ed4f7696136500067a327d39a | dxg4268/PyDictionary | /Dictionary.py | 528 | 4.34375 | 4 | # Program to build a dictionary
# Given dictionary
dictionary = {"mutable":"can change", "immutable":"can not change",
"abandon":"give up", "splendid":"magnificent",
"admire":"praise", }
dictionary['set'] = 'collection of well-defined objects'
# Taking input from the $USER
print("Hello!")
... |
026faaacd755ac1fcadf20504138e8815e7cd14e | axeloh/algdat | /Oving8/ratatosk.py | 1,631 | 3.5 | 4 | from sys import stdin
class Node:
def __init__(self):
self.children = []
self.ratatosk = False
# Dybde-først-søk
def dfs(root):
stack = [root]
depth = 0
while len(stack) > 0:
node = stack[-1]
if node.ratatosk:
return depth
if node.ch... |
e9861f3fe7e5f1782442647011ac814503ec7cd5 | sakayaparp/CodeChef | /ALGORITHMS/Tree/Binary_Search_Tree/Binary_search_tree.py | 1,689 | 4.25 | 4 |
#a program used to demonstrate simple operations in a binary search tree
class Node:
def __init__(self,node):
self.left=None
self.right=None
self.node=node
def insert(self,objnode):
if self.node:
if objnode<self.node:
if self.left is None:
... |
a79ee45fad8ff52da661e99e696aec3736a4f30b | sakayaparp/CodeChef | /ALGORITHMS/Matrix/Matrix Multiplication/matrixMultiplication.py | 508 | 3.921875 | 4 |
def multiply(m1, m2, mat1,
n1, n2, mat2):
res = [[0 for x in range(n2)]
for y in range (m1)]
for i in range(m1):
for j in range(n2):
res[i][j] = 0
for x in range(m2):
res[i][j] += (mat1[ i][x] *
mat2[ x][j])
for i in range(m1):
for j in range(n2):
print (res[i][j],
end = ... |
50d636c57dae412c1ff64927325289500c826325 | sakayaparp/CodeChef | /Easy/Count Substrings/countSubstrings.py | 208 | 3.609375 | 4 |
n = int(input("Number of tests: "))
for c in range(0, n, 1):
q = int(input("Number of characters: "))
l = input("Characters: ")
c = int(l.count('1')*(l.count('1')+1)/2)
print("Result: ", c)
|
7b07c718095e87941671696daccbb4a4c74a2a02 | confuzzed03/Python-UDP-File-Transfer | /ftpc.py | 7,197 | 3.625 | 4 | '''
Client Program
Assuming program is ran on beta.cse.ohio-state.edu (or any machine separate from server),
client will send all bytes of desired local file to server. Client will use following protocol:
The payload of each UDP segment will contain the remote IP (4 bytes), remote port (2 bytes),
a fla... |
ec7fb47d7a79bc6f4be75d1e1f8faeb1fdd17ef7 | ShubhamMahitkar/bmi-calculator | /BMI_Calculator.py | 1,162 | 3.515625 | 4 | import json
from collections import defaultdict
data_file = [{"Gender": "Male", "HeightCm": 171, "WeightKg": 96 }, { "Gender": "Male", "HeightCm": 161, "WeightKg":85 }, { "Gender": "Male", "HeightCm": 180, "WeightKg": 77 }, { "Gender": "Female", "HeightCm": 166,"WeightKg": 62}, {"Gender": "Female", "HeightCm": 150, "W... |
0ee6c3d1b3f74cfc2b932f7f4ad0ca9a253b9285 | varunmuriyanat/programming_machinelearning | /code/06_real/print_samples_of_specific_digit.py | 526 | 3.53125 | 4 | # Print a few examples of a specific MNIST digit.
import mnist
import numpy as np
import matplotlib.pyplot as plt
DIGIT = 5
X = mnist.load_images("../data/mnist/train-images-idx3-ubyte.gz")
Y = mnist.load_labels("../data/mnist/train-labels-idx1-ubyte.gz").flatten()
digits = X[Y == DIGIT]
np.random.shuffle(digits)
r... |
e9bbaa3b503a78297064d3aa27f46a54b5cbab70 | varunmuriyanat/programming_machinelearning | /code/02_first/solution/linear_regression.py | 933 | 3.734375 | 4 | # This file contains the functions used by linear regression, but not the code
# that runs them. Import these functions with 'import linear_regression', and
# use them with 'linear_regression.function_name()'.
import numpy as np
def predict(X, w, b):
return X * w + b
def loss(X, Y, w, b):
return np.average... |
a6030b542266755a7ef3625dcfddfd11631b9731 | varunmuriyanat/programming_machinelearning | /code/15_development/plot_gd.py | 1,696 | 3.5 | 4 | # Plot the path of GD on a function of one input, to show how a bigger learning
# rate makes the system learn faster, but a learning rate that's too large
# makes the GD algorithm diverge.
import numpy as np
import matplotlib.pyplot as plt
# ------------------------------------
# Change this value to visualize GD
# w... |
ba77b8e85ffb1884e294aaaff941893cd95f77fb | varunmuriyanat/programming_machinelearning | /code/03_gradient/gradient_descent_final.py | 800 | 3.703125 | 4 | import numpy as np
def predict(X, w, b):
return X * w + b
def loss(X, Y, w, b):
return np.average((predict(X, w, b) - Y) ** 2)
def gradient(X, Y, w, b):
w_gradient = 2 * np.average(X * (predict(X, w, b) - Y))
b_gradient = 2 * np.average(predict(X, w, b) - Y)
return (w_gradient, b_gradient)
d... |
307eb362ae1a0c0c3982721d9a38bf5df5366cd4 | varunmuriyanat/programming_machinelearning | /code/11_training/plot_sigmoid.py | 626 | 4.03125 | 4 | # Plot the sigmoid function.
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
def sigmoid(z):
return 1 / (1 + np.exp(-z))
MARGIN_LEFT = -10
MARGIN_RIGHT = 10
# Configure axes
plt.axis([MARGIN_LEFT, MARGIN_RIGHT, -0.5, 1.5])
plt.xticks(fontsize=15)
plt.yticks(fontsize=15)
# P... |
4c1ac683329f8911b0ff96cdc0b80d8ffd385dfc | EvanJamesMG/Classical-algorithms | /InsertionSort.py | 1,675 | 3.78125 | 4 | # coding=utf-8
import collections
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
'''
三、插入排序 InsertionSort
时间复杂度: 最好O(n) 最坏O(n^2) 平均O(n^2)
辅... |
89f1dbedfae4e6c5514c05546a580f29e88501b0 | Ahmedm2006/ncss-challenge-2017 | /unmasked/unmasked.py | 1,767 | 3.953125 | 4 | from math import sqrt as square_root
from string import punctuation
word_length_frequencies = {}
def increment_value_at_index(index, list_):
try:
list_[index] += 1
except IndexError:
list_ += [0 for _ in range(len(list_), index)] + [1]
def word_frequencies(file_name):
word_frequencies ... |
a76a13710d6d3910b0dffe2c27eecad5f7673c67 | Ahmedm2006/ncss-challenge-2017 | /interleavings.py | 802 | 3.828125 | 4 | def get_remaining_interleavings(so_far, option_one, option_two):
if not option_one:
return [so_far + option_two]
if not option_two:
return [so_far + option_one]
remaining_from_option_one = get_remaining_interleavings(
so_far + option_one[0],
option_one[1:],
option_tw... |
cac2be2db1be2e8aaabb9651c1440fa85fe5756c | Ahmedm2006/ncss-challenge-2017 | /alien_numbers.py | 1,734 | 3.953125 | 4 | BASE = 5
CHARACTER_VALUES = {
'a': 0,
'e': 1,
'i': 2,
'o': 3,
'u': 4
}
VALID_CHARACTERS = list(CHARACTER_VALUES.keys()) + [character.upper() for \
character in CHARACTER_VALUES.keys()]
def alien2float(string):
index_in_string = 0
integer_components = []
fractional_components = [... |
4fe0e85f96597ce2ecfaa34fef190dc692bda7d4 | kim-byoungkwan/Coding_Test_1 | /문제풀이강의_1_해시(지문이해)_prog.py | 5,450 | 3.53125 | 4 | ###.1 해시(지문이해)
# 문제의 크기는 무엇에 지배되는지를 생각한다.
# 어떠한 제약조건이 문제에 존재하는지를 생각한다.
##.1 처음 완성 답안
# def solution(participant, completion):
#
# answer = ''
#
# for i in participant:
#
# num_p = participant.count(i)
#
# num_c = completion.count(i)
#
# if num_p > 1:
#
# i... |
6f2a281b75668a154589d44ccbf9e7deb576e284 | kim-byoungkwan/Coding_Test_1 | /학원5_queue.py | 258 | 3.75 | 4 | from collections import deque
queue = deque()
queue.append(1)
queue.append(2)
queue.append(3)
queue.popleft()
queue.append(4)
queue.append(5)
queue.popleft()
print(queue)
queue.reverse()
print(queue)
print(list(queue)) |
8fa855c09233b2a45221e01db3beb9c890964b9a | kim-byoungkwan/Coding_Test_1 | /학원4_card0905.py | 3,585 | 3.859375 | 4 | import random
def func_random_card():
cards = ["A","2","3","4","5","6","7","8","9","10","J","Q","K"]
card = random.choice(cards)
return card
def func_to_num(card):
if card == "A":
card = 1
elif card =="J":
card = 11
elif card =="Q":
card =... |
0afb988ba4a4aec1b2072a1c96f49114f2aec5c9 | skenny/adventofcode2020 | /day5.py | 1,169 | 3.578125 | 4 | def find_seat(input):
row = binary_search(input[:7], 0, 128)
col = binary_search(input[7:], 0, 8)
return (row, col, row * 8 + col)
def binary_search(path, min, max):
for c in path:
mid = int((max - min) / 2)
if c in ['F', 'L']:
max -= mid
else:
min += mid... |
866bbd2d6ecf44e9c759a18e95ba24acc933ccea | skenny/adventofcode2020 | /day12.py | 2,454 | 3.78125 | 4 | INPUT_FILE = "day12-input"
TEST_INPUT_FILE = "day12-input-test"
def read_input(file):
with open(file, "r") as fin:
return [l.strip() for l in fin.readlines()]
def navigate(steps):
# E is 0, S is 90, W is 180, N is 270
direction = 0
x = 0
y = 0
for step in steps:
action = step[... |
975588a004dd5d5d21cf6e2ca71fb02c18797ed7 | Pasavento/DiscursoOdio | /Programas2.7/Odio2/supervisado/Datos.py | 4,524 | 3.5 | 4 | # -*- coding: utf-8 -*-
# Python 3.5 y 2.7
# Juan Carlos Pereira y Ana Peraita
import numpy as np
class Datos(object):
supervisado=True
TiposDeAtributos=('Continuo','Nominal')
tipoAtributos=[]
nombreAtributos=[]
nominalAtributos=[]
datos=np.array(())
# Lista de diccionarios. Uno por cada ... |
df46f44002926afb5e461f187dbadbf775d8ffa9 | cs-fullstack-2019-fall/python-review2-cw-jessica-bruno | /jessbrun.py | 1,052 | 4.59375 | 5 | #
# python-review2-cw
# Create a task list. A user is presented with the text below. Let them select an option to list all of their tasks, add a task to their list, delete a task, or quit the program. Make each option a different function in your program. Do NOT use Google. Do NOT use other students. Try to do this on ... |
564475e292ef16a84a80f78a34bfd8299a4cd82a | SeitaBV/smartcharginggame | /scripts/arrivalProcess.py | 3,147 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 9 15:16:03 2018
@author: Daphne
"""
import itertools
import random
import numpy as np
import simpy
#s = np.random.poisson(5, 10)
RANDOM_SEED = 42
GAS_STATION_SIZE = 200 # liters
THRESHOLD = 10 # Threshold for calling the tank truck (in %)
FUEL_TANK_SIZ... |
bfc5520853cf0cfa781d49077197eeb6d111959a | RumanBhuiyan/Most-Common-DSA-Topics | /Stack/StackImplementation.py | 478 | 3.828125 | 4 | class stack:
keepStack=[]
def isEmpty(self):
return True if len(self.keepStack)==0 else False
def size(self): #self is binding this method with the class.
return len(self.keepStack) #its mendatory for every function inside class
def push(self,data):
self.k... |
82001140ed3ae1e8124f9828d8fcfb0fa07db6bc | vendulabezakova/dice | /dice.py | 208 | 3.6875 | 4 | import random
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
print("You threw " + str(dice1) + " and " + str(dice2) + ".")
total = int(dice1) + int(dice2)
print("The result is " + str(total) + ".") |
4eb0e6482499715477dff4fc0e012c1e565645dd | Leksite03/Dsc-futa-numpy | /Numpypractice.py | 994 | 3.984375 | 4 | import numpy as np
#numpy array
my_array=np.array([1,2,3,4,5,6,7,8,9])
print(my_array)
print(" ")
#2d array
_2d_array=np.array([[1,2,3], [4,5,6], [7,8,9]])
print(_2d_array)
print(" ")
#using the arange() function
arr=np.arange(0,13,2)
print(arr)
print(" ")
#getting the shape of an array
shaped=my_array.shape
print(s... |
253d42e436a94bebfa9d24d49710fe33d015648e | zerotsukaima/Zh_P | /поискОдЧис_строка.py | 304 | 4 | 4 | while True:
a = input("Введите трехзначное число: ")
if a[0] == a[1] or a[1] == a[2] or a[2] == a[0]: #проверить если a[0]==a[1]==a[2]
print("Есть одинаковые числа ")
else:
print("Нет одинаковых чисел ") |
9abe9b9e4fba6f62ca776e291d19dc2f1ab6014d | DoomyDwyer/cipher-utils | /logger.py | 1,755 | 3.53125 | 4 | # logger.py
# Author: Steve Dwyer
# Changes:
# 1 May 2017:
# Support environments where the python logging module isn't available, such as trinket:
# Custom implementation created to avoid dependency on other python modules
# This version will print to the console exclusively
import time
# Levels
ALL = 0
DEBU... |
367720fbac6a42efdf96c7e004786df3a5404d58 | gaip/CPSATSeleniumPython | /PythonPrograms/forloopRange.py | 99 | 3.640625 | 4 | #decrementing order
#for i in range(100,0,-1):
# print(i)
for j in range(0,11,2):
print(j) |
8296356540a6e3e4f4e104ec8f33c8ef643662e5 | gaip/CPSATSeleniumPython | /PythonPrograms/whileWithBreak.py | 103 | 3.96875 | 4 |
while(True):
a=int(input("enter the number: "))
if(a<0):
break
print(a)
|
da7de07bcaf2686251ba93f7e1aa0fcf66c17a39 | Exodus111/Projects | /Other_Scripts/Tkinter_Browser/test.py | 920 | 3.5 | 4 | """
This is an improved version of the tutorial I gave
on Aug 14th, 2015
I had made the same mistake with packing to nonetype objects
making all the frames useless. This fixes that.
"""
from tkinter import *
def ok_func():
print("ok")
# first we declare our root widget.
root = Tk()
# Then we make our Widgets... |
43099d81256865ad85bd016e49d1375a2b463422 | woo-nny/Study | /삼성 SW/3.IF/if1.py | 129 | 3.640625 | 4 | num = int(input())
for i in range(1,num+1):
if (num%i ==0):
print("{}(은)는 {}의 약수입니다.".format(i,num)) |
5cd8848d43ae8fabc610122b87b8209dd0d98958 | woo-nny/Study | /삼성 SW/2.연산자/연산자1.py | 65 | 3.6875 | 4 | a=float(input())
print("{:.2f} inch => {} cm".format(a,a*2.54)) |
d6642b892e2c73cc291439b3daca6b01bb051858 | tanyafish/rainbow-hat | /examples/learning-cards/card03-temperature-reading.py | 370 | 3.9375 | 4 | # code from Learning Card 02 - Rainbow HAT
# import the rainbowhat module
import rainbowhat
# create a variable to store the temperature reading in
temperature = rainbowhat.weather.temperature()
# sends the data from the reading to the display
rainbowhat.display.print_float(temperature)
# displays the da... |
02bc3d09a2260950c7986fef47c901063636596d | ShadeShiner/RayTracerChallenge-Python | /src/Canvas.py | 2,534 | 3.65625 | 4 | from src.Color import Color
class Canvas(object):
def __init__(self, width, height):
self.width = width
self.height = height
self.pixels = []
# Set each pixel to be black by default
for row in range(self.height):
pixel_rows = []
for column in range... |
87fa6e57daabc7405814e837039aac5677a35c4d | logeshmohan/python | /palin.py | 80 | 3.578125 | 4 | n=input()
a=n[::-1]
if n==a:
print("yes")
else:
print("no")
|
e8884024e6cc01fe87c7589e6b2909dd76758e0b | srikanthpragada/PYTHON_03_AUG_2020 | /demo/oop/person.py | 347 | 3.71875 | 4 | class Person:
def __init__(self, name, email):
self.name = name
self.__email = email # Private attribute
def print_details(self):
print("Name :", self.name)
print("Email :", self.__email)
p = Person("Tom", 'tom@gmail.com')
#print(p.__email)
#p._Person__email = 'tommy@gmail.c... |
fbf15af7fd6327bbe6af9bd818c952de53b9e6c0 | srikanthpragada/PYTHON_03_AUG_2020 | /demo/basics/leap_year.py | 198 | 4.34375 | 4 | # Take year and display whether it is leap year
year = input("Enter year :")
year = int(year) # Convert string to int
if year % 4 == 0:
print("Leap Year")
else:
print("Not a leap year")
|
5f358b9ec572dfafca0caf9ac54368a541b05179 | srikanthpragada/PYTHON_03_AUG_2020 | /demo/database/add_employee.py | 407 | 3.859375 | 4 | import sqlite3
con = sqlite3.connect(r"c:\classroom\aug3\hr.db")
cur = con.cursor()
name = input("Enter name :")
job = input("Enter job :")
salary = int(input("Enter salary :"))
try:
cur.execute("insert into employees(name,job,salary) values(?,?,?)", (name, job, salary))
con.commit()
print("Added Success... |
95a5f624f948b1c983be3b66c60208d71f7c1913 | srikanthpragada/PYTHON_03_AUG_2020 | /demo/oop/employees.py | 756 | 3.65625 | 4 | class InvalidSalaryError (Exception):
def __str__(self):
return "Invalid Salary!"
class Employee:
def __init__(self, name, salary):
self.name = name
if salary < 0:
raise InvalidSalaryError()
self.salary = salary
def print_details(self):
print("Name : ... |
6066e0194937c2b28d94320e1314c1b848c26141 | MJSchut/ImageScraperBing | /main.py | 809 | 3.53125 | 4 | """ImageScraper: Search for an image and download to folder."""
__author__ = "MJ Schut"
from dirmaker import DirMaker
from imagescraper import ImageScraper
# variables
verbose = True
searchTerm = "GOB"
imageAmount = 100
# Step 1. Make reference image folder
if verbose:
print "Generating image folders..."
dirMak... |
309a8fe5db3f176e29c07387350c66d7db7eb48e | oykali/Python | /蛋糕.py | 2,006 | 4.21875 | 4 | """
print('hello world hello python')
"""
from turtle import *
import math
# 设置画布宽高/背景色和设置画笔粗细/速度/颜色
screensize(600, 500, '#99CCFF')
pensize(5),speed(10),color('red')
# 定义椭圆函数: 绘制蜡烛火焰和被圆柱函数调用
def ellipse(x,y,a,b,angle,steps):
penup(),goto(x,y),forward(a),pendown()
theta = 2*math.pi*angle/360/steps
for i in ... |
316adbc0f6a07719c808155ade013a9c2b296d80 | msha096/Leetcoding | /July-challenge/Construct Binary Tree from Inorder and Postorder Traversal.py | 1,055 | 3.734375 | 4 | class Solution(object):
def buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
:rtype: TreeNode
"""
# this question needs to use index
# postorder: left, right ,root
# inorder: left, root, right
# the l... |
97f645b1fbf21cec78c53727d83fe949a98c639d | msha096/Leetcoding | /Aug - Challenge/Find Right Interval.py | 1,077 | 3.578125 | 4 | class Solution(object):
def findRightInterval(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[int]
"""
n = len(intervals)
for i in range(n):
intervals[i].append(i)
intervals.sort(key = lambda x:x[0])
#print intervals
... |
2864d1db3af2a7f13ddbfcfa3af8a05c5c1fcf10 | msha096/Leetcoding | /July-challenge/Word Search.py | 1,092 | 3.65625 | 4 | class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
# backtracking, dp
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == word[0]:
... |
e753b3ec35383812990a477d159ac79d6d31bb34 | msha096/Leetcoding | /Aug - Challenge/Valid Palindrome.py | 303 | 3.609375 | 4 | class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s = s.lower()
tmp = []
for i in range(len(s)):
if s[i].isalpha() or s[i].isdigit():
tmp.append(s[i])
return tmp==tmp[::-1] |
6735286d17a4518ad7456303d5ca286433c622f1 | EvgenyFisenko/python_basics | /lesson01/lesson01hw06.py | 1,218 | 4.125 | 4 | # Спортсмен занимается ежедневными пробежками.
# В первый день его результат составил a километров.
# Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего.
# Требуется определить номер дня, на который общий результат спортсмена составить не менее b километров.
# Программа должна принимать значени... |
1fb547531bdd6c23dfd6956ae2319aa64a3495d4 | EvgenyFisenko/python_basics | /lesson01/lesson01hw05.py | 1,481 | 4.34375 | 4 | # Запросите у пользователя значения выручки и издержек фирмы.
# Определите, с каким финансовым результатом работает фирма
# (прибыль — выручка больше издержек, или убыток — издержки больше выручки).
# Выведите соответствующее сообщение. Если фирма отработала с прибылью,
# вычислите рентабельность выручки (соотношение п... |
889fb56a391e3fab90526547f970a30df4252624 | EvgenyFisenko/python_basics | /lesson05/lesson05hw05.py | 778 | 3.8125 | 4 | # Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных пробелами.
# Программа должна подсчитывать сумму чисел в файле и выводить ее на экран.
import random as rnd
def cr_file():
with open("hw_05.txt", "w", encoding="u8") as w_file:
lst = [rnd.randrange(100, 1001, 2) for... |
69895311fc4284373d58fcefc3d07ea9aff71813 | EvgenyFisenko/python_basics | /lesson04/lesson04hw02.py | 787 | 4.1875 | 4 | # Представлен список чисел. Необходимо вывести элементы исходного списка, значения которых больше предыдущего элемента.
# Подсказка: элементы, удовлетворяющие условию, оформить в виде списка. Для формирования списка использовать генератор.
from random import randint
def gen_list():
return [randint(11, 22) for el... |
87d46d35934849eb638eff7b7bddd1a590714e45 | EvgenyFisenko/python_basics | /lesson02/lesson02hw05.py | 988 | 3.96875 | 4 | # Реализовать структуру «Рейтинг», представляющую собой не возрастающий набор натуральных чисел.
# У пользователя необходимо запрашивать новый элемент рейтинга.
# Если в рейтинге существуют элементы с одинаковыми значениями,
# то новый элемент с тем же значением должен разместиться после них.
while True:
if input(... |
fecff9516420978f00adeb205c9e33ba12111324 | Abeelie/Python-Data-Structures-Exercise | /fs_4_reverse_vowels/reverse_vowels.py | 887 | 4.28125 | 4 | def reverse_vowels(s):
"""Reverse vowels in a string.
Characters which re not vowels do not change position in string, but all
vowels (y is not a vowel), should reverse their order.
>>> reverse_vowels("Hello!")
'Holle!'
>>> reverse_vowels("Tomatoes")
'Temotaos'
>>> reverse_vowels("Re... |
9d82da78b02017a3b10bfabd3dba039a5d7262b4 | raghav1674/ds-python-self | /Linkedlist/list.py | 4,041 | 3.984375 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class List:
__size = 0
def __init__(self):
self.head = None
def push_front(self, data):
List.__size += 1
new_node = Node(data)
new_node.next = self.head
... |
ccd501ffe108f8d22e955a41d376dc55330dee51 | MegIvanova/Python | /Lab2/EightDaysCalendar.py | 1,034 | 4.25 | 4 | import calendar
'''
Created on Sep 12, 2015
@author: meglena
'''
print ('### Program Name: EightDaysCalendar ###')
print('\nDescription: Program that outputs 5 calendars, each with 8 days per week, asking the user for the values of n and d each time.')
def main():
count = 0
while count < 5:
if c... |
f9104bae93143cf4b2001de7da62a7a3def93ecd | manmaysukhadeve/class-109 | /class-109/height-weight.py | 3,077 | 3.546875 | 4 | import pandas as pd
import statistics
import csv
df = pd.read_csv('class 109.csv')
height_list = df["Height(Inches)"].to_list()
weight_list = df["Weight(Pounds)"].to_list()
height_mean = statistics.mean(height_list)
weight_mean = statistics.mean(weight_list)
height_mode = statistics.mode(height_list)
weight_mo... |
e8dc28fa4d49bedb21a65c1254ae098bea676828 | greatGarv99/Snake-Water-Gun | /main.py | 2,015 | 4.125 | 4 | # Importing required modules
from emojis import encode as emoji
from random import choice as choose
from time import sleep as wait
# Printing instructions
print(f"Welcome to Snake({emoji(':snake:')}), Water({emoji(':ocean:')}), Gun({emoji(':gun:')})!")
print("The respective codes are--> ")
print(f"{emoji(':snake:')} :... |
ec3e9c868961a0dcc4a7a5a477b520b86a5a2a12 | LandonBeach/securityScripting | /parrot_server.py | 1,415 | 3.515625 | 4 | # This is a server that sends back the data that it receives.
# Author: Landon Beach
# Date: 4/5/17
import socket, argparse
# Parse the arguments and assign it to the variable "options".
parser = argparse.OptionParser()
parser.add_argument("-s", "--server", default="127.0.0.1", dest="svr_addr", help="Bind to IP addre... |
c4903914584366b7ee83441117ff270718de1d82 | AhmadBasha/python-beginner | /guess-the-number/main.py | 2,054 | 3.96875 | 4 | #Number Guessing Game Objectives:
import art
import random
from replit import clear
# print the number of user attempts
def playerAttempts(num):
print(f"You have {num} attempts to guess the correct number")
# to check the difficulty of the game
def theLevel(level) :
if level == "easy" :
playerLevel = 10
... |
49036f31e200e24ad7bc2e0b37c0749313a9b179 | milan-sas/PrimenjenaTeorijaIgara | /V1/bandits.py | 1,902 | 3.515625 | 4 | # %% Define enviroment
import numpy as np
from numpy.random import rand, randint
import matplotlib.pyplot as plt
np.random.random()
#bandits = [(1, 1), (5, 10), (-3, 15), (15, 2), (-24, 3)]
def enviroment(a, bandits):
assert 0 <= a < len(bandits)
mean, dev = bandits[a]
return mean + (ran... |
415927a03237d86ccf88782def9ab98392f2f8e2 | shahmeerathar/Project-Euler | /2_EvenFibonacciNumbers.py | 573 | 4.03125 | 4 | # Each new term in the Fibonacci sequence is generated by adding the previous two terms.
# By starting with 1 and 2, the first 10 terms will be:
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
# By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
... |
f415a4e97a600d763b75a8995e0875b342594a62 | sanskar001/Python-Programming-Exercises | /vowels_and_consonent.py | 551 | 4.34375 | 4 | # This is python program to find are vowels more than consonent inside given string.
def vowel_and_consonent(string):
count = 0
for s in string:
if s in ['a','e','i','o','u','A','E','I','O','U']: # vowel list
count = count + 1
if count < len(string) - count:
... |
9b9eef8decc80926b08b71061fc8ebb5521af61c | sanskar001/Python-Programming-Exercises | /pair_inside_sequence.py | 398 | 3.984375 | 4 | # This is python program to find out the pair inside given sequence which have sum equal to given number.
def number_arrange(seq,number):
first = []
second = []
for n in seq:
if n <= number:
first.append(n)
else:
second.append(n)
return first + se... |
c46a374b5d8fc2b04fa8cd7bce69672451c8c033 | sanskar001/Python-Programming-Exercises | /project_2.py | 554 | 4.25 | 4 | # this python program to finding out email address from long string
# example654@gmail.com
import re
import test
email_regex=re.compile(r'(\w+)(@)(gmail|yahoo)(.com)')
match_object=email_regex.findall('''these are email address of all students came here for summer taining program
snaskarm001@gmail.com,
abhish... |
dbd910058bfd4924d5aacebfb6b0b62e7f5ced30 | htang6/ML-From-scratch | /NN/Model.py | 1,474 | 3.859375 | 4 | import abc
import numpy as np
from NN.CoreUtility import *
class Model(abc.ABC):
@abc.abstractmethod
def add_layer(self):
pass
@abc.abstractmethod
def train(self, x, y, lr):
pass
# back-propagation is a way of dynamic programming?
class LinearModel(Model):
def __init__(self):
... |
fd50267f6f4ea834a82b3a252c17ac64d43cfb06 | mohelghar/python_examples | /python_examples/ex02_plot/ex02_plot.py | 325 | 3.5 | 4 | from math import radians
import numpy as np
import matplotlib.pyplot as plt
#from __future__ import division, print_function
def main():
x = np.arange(0, radians(1800), radians(12))
y = np.arange(0, radians(1500), radians(10))
plt.plot(x, np.cos(x), 'r')
plt.plot(x, np.sin(y), 'b')
plt.show()
mai... |
b98c5c1fc0aeb2a9c82686f6f3ddcae526d5aba5 | LeoNull/testurllib2 | /imooc/test/instance.py | 284 | 4 | 4 | class Person(object):
def __init__(self, name, sex, birth, job):
self.name = name
self.sex = sex
self.birth = birth
self.job = job
xiaoming = Person('xiaoming', 'Male', '1990-1-1', job="Student")
print xiaoming.name
print xiaoming.job
|
a53fcad18be71abcbe57f68e05a8728490030c61 | JyothiRBangera/InternshipTasks | /Internshipexe1.py | 572 | 3.875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
days="thirty days"
print(days[0])
# In[2]:
challenge= "I will win"
print(challenge[7:10])
# In[3]:
challenge= "I will"
print(len(challenge))
# In[4]:
challenge= "I will win"
print(challenge.lower())
# In[5]:
a="30 Days"
b="30 hours"
c=a+b
print(c)
# In... |
9a4404a13acd02c0e36a28e1c8600cf13dd88f19 | JyothiRBangera/InternshipTasks | /_Internship task8.py | 2,504 | 4.21875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[26]:
#types of errors
#SyntaxError:
#indexerror:error caused when trying to access an item at invalid index
#ModuleNotFoundError:caused when module is not defined
#KeyError:caused when key is not found
#ImportError:caused when operation or function is applied to object of ... |
8140fc73beea281b6bdb8497fce3059a48ce660a | VSyrkin/Python_prof | /dz_2/hard.py | 5,583 | 4.15625 | 4 | # Задание-1: уравнение прямой вида y = kx + b задано в виде строки.
# Определить координату y точки с заданной координатой x.
# equation = 'y = -12x + 11111140.2121'
# x = 2.5
# вычислите и выведите y
print('\nЗадача №1\n')
# equation = input('Введите уровнение вида y = kx + b: ')
# x = float(input('Введите x:'))
eq... |
4e3656e82e16dfe0cdbc369ced1fc335bdd718a7 | VSyrkin/Python_prof | /dz_2/easy.py | 2,199 | 3.875 | 4 | import random
# Задача-1:
# Дан список фруктов.
# Напишите программу, выводящую фрукты в виде нумерованного списка,
# выровненного по правой стороне.
# Пример:
# Дано: ["яблоко", "банан", "киви", "арбуз"]
# Вывод:
# 1. яблоко
# 2. банан
# 3. киви
# 4. арбуз
# Подсказка: воспользоваться методом .format()
print('\... |
516add79eecdc269ba502e23458daf327da6b117 | dxd1/exercism-python | /run-length-encoding/run_length.py | 760 | 3.703125 | 4 | def encode(decoded):
encoded = ''
last = decoded[0]
counter = 0
for letter in decoded:
if last == letter:
counter += 1
else:
encoded += encode_letter(counter, last)
last = letter
counter = 1
encoded += encode_letter(counter, last)
r... |
9f3b996184822af9798925bf5b6e50173b0e2b69 | dxd1/exercism-python | /simple-cipher/cipher.py | 1,661 | 3.640625 | 4 | import re
from random import randint
class Caesar:
@staticmethod
def encode(text):
return Caesar.shift(3, text.lower())
@staticmethod
def decode(text):
return Caesar.shift(-3, text.lower())
@staticmethod
def shift(num, text):
pattern = re.compile('[^a-z]+')
te... |
3afd9bd31a04e854b3063d60f7c9467ee8841002 | dxd1/exercism-python | /roman-numerals/roman.py | 1,515 | 3.703125 | 4 | from math import floor
from collections import defaultdict
numerals = defaultdict(str, {
1: 'I',
5: 'V',
10: 'X',
50: 'L',
100: 'C',
500: 'D',
1000: 'M'
})
def numeral(arabic):
if arabic >= 4000 or arabic <= 0:
raise ValueError('Number must be greater than 0 and less than 4000'... |
9be49f39903837f44eade6d91da11cf3456af8c5 | dxd1/exercism-python | /series/series.py | 296 | 3.59375 | 4 | def slices(number, digits):
if digits>len(number) or digits<1:
raise ValueError('The number of digits has to be between 1 and '+str(len(number)))
slices = []
for i in range(0, len(number)-digits+1):
slices.append(map(int, list(number[i:i+digits])))
return slices
|
530aa0199a37339f9a00fe67e5df23327de544c3 | keerthitejakonuri/K-Nearest-Neighbours-Python | /knn.py | 1,025 | 3.703125 | 4 | # K-Nearest Neighbors (K-NN)
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('zip_codes_states_1.csv')
X = dataset.iloc[:, [1, 2]].values
X1 = dataset.iloc[:,[0,1,2,3,4,5]].values
# Taking care of missing data
from... |
16e79b9f5dfd0535ded6089229543f6b9f9e3433 | PatzHum/Functions | /bedmas.py | 3,182 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Patrick'
import re
def bedmas(Equation):
def parse_brackets(equation):
bracket_locs = [[]]
layer_num = 0
deepest_layer = 0
for i, j in enumerate(equation):
if j == '(': # If the object is an open bracke... |
5d23ef0cfedb6d431af70baceb9d2eb6f9e10c89 | SamuelMarsaro/Listas-Python-CESAR | /Lista 7/sam/q3_sam.py | 256 | 4.21875 | 4 | word = input()
while word != "SAIR" or word != "FIM":
word = word.replace("4", "A")
word = word.replace("5", "S")
word = word.replace("1", "I")
word = word.replace("3", "E")
word = word.upper()
print(word)
word = input() |
717d00a8b5770e360e2d5a1fca787518cb0e927c | SamuelMarsaro/Listas-Python-CESAR | /Lista 6/q3_sam.py | 4,611 | 3.75 | 4 | users_answer = "S"
fatal_accidents_country = 0
total_accidents_country = 0
no_victims_accidents = 0
total_vehicles_country = 0
total_accidents_city = 0
more_accidents = 0
less_accidents = 9999999
total_city = 0
non_fatal_accidents_country = 0
no_victims_accidents_country = 0
biggest_ivt = 0
smallest_ivt = 1... |
748b2e5e4cd08ceeaf9ca56a9fdb55e382e0b75f | kkhushi/dgplug-2008 | /khushbu/python/roman.py | 1,639 | 3.984375 | 4 | #!/usr/bin/env python
def printit(k,ch): #function to print characters repeatedly
r = ''
for i in range(0, k):
r+=ch
return r
def roman(x): #function to print roman equivalent
r = []
k = x/1000
r.append(printit(k,'m')) #m = 1000
x = x%1000
if x >= 900: ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.