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 |
|---|---|---|---|---|---|---|
9971c2273e83ae2010a55f76d3f3c8871098bb53 | technolawgeek/HW | /Lesson1/Task5.py | 2,048 | 4.1875 | 4 | """
Запросите у пользователя значения выручки и издержек фирмы.
Определите, с каким финансовым результатом работает фирма (прибыль — выручка больше издержек,
или убыток — издержки больше выручки). Выведите соответствующее сообщение. Если фирма отработала с прибылью,
вычислите рентабельность выручки (соотношение прибыли... |
18045288b76888c749899172b5f23e64e94c43f7 | SebastianFrizzo/CP1404_Practicals | /PASS_9/pet.py | 2,089 | 3.703125 | 4 | class Pet:
def __init__(self, name='', age=0.0, diet='', micro_chipped=False, colour=''):
self.name = name
self.age = age
self.diet = diet
self.micro_chipped = micro_chipped
self.colour = colour
def __str__(self):
return "The {}, {} is {} years old and has a {} diet".format(self.__class__, self.name, sel... |
56926a8bc9f0c903ed1fae7f6369d3851b467852 | 653737623/eco-cmdb | /multiplication.py | 134 | 3.90625 | 4 | for i in range(1,10):
for j in range(1,i+1):
print("%d*%d=%d" %(j,i,i*j),end=" ")
print("\n")
print("multiplication")
|
26184cc08dc6edd8a350e91eda6c145c5238f1fc | alberesdejesus/Simple-Python-Projects | /Higher-lower/main.py | 1,694 | 4.03125 | 4 | from art import logo, vs
from game_data import data
import random
def randomperson():
"""Get data from random account"""
return random.choice(data)
def format_data(person):
"""Format account into printable format: name, description and country"""
name = person['name']
description = person['descr... |
7cbea7f0bd0645048484806489ed71c2c6e580b7 | wonpyo/Python | /Basic/VariableScope.py | 1,207 | 4.3125 | 4 | # Variables can only reach the area in which they are defined, which is called scope. Think of it as the area of code where variables can be used.
# Python supports global variables (usable in the entire program) and local variables.
# By default, all variables declared in a function are local variables. To access a g... |
25209b004ddb4eae65d34e63235622fa9fa44a3d | wonpyo/Python | /Basic/MethodOverloading.py | 1,019 | 4.4375 | 4 | # Several ways to call a method (method overloading)
# In Python you can define a method in such a way that there are multiple ways to call it.
# Given a single method or function, we can specify the number of parameters ourself.
# Depending on the function definition, it can be called with zero, one, two or more para... |
a2cfdf0723538af644a2eee5372069785bdc048e | wonpyo/Python | /Basic/Threading.py | 1,526 | 4.53125 | 5 | """
A thread is an operating system process with different features than a normal process:
1. Threads exist as a subset of a process
2. Threads share memory and resources
3. Processes have a different address space in memory
When would you use threading?
Usually when you want a function to occur at the same time as yo... |
50a126e7540a343ff18cbe16262324bf091cc0a4 | cameron-teed/ICS3U-3-08-PY | /leap-year.py | 548 | 4.34375 | 4 | #!/usr/bin/env python3
# Created by: Cameron Teed
# Created on: Oct 2019
# This is program finds out if it's a leap year
def main():
# calculates if it is a leap year
# variables
leap_year = " is not"
# input
year = int(input("What is the year: "))
# process
# output
if year % 4 ==... |
90a8f7b5589fc7e90ec01da55cfc58578ce493af | nywogud/python | /most_frequent.py | 219 | 3.765625 | 4 | def most_frequent(list):
maximum = []
for i in range(len(list)):
maximum.append(list.count(list[i]))
return list[maximum.index(max(maximum))]
print(most_frequent(["e", "c", "b","b", "aaa", "aaa"])) |
90c36b2b5e006ce7f92ae975bd4efc805e29d97d | Sambhaji-Jagtap/Py_Functions | /functions.py | 96 | 3.515625 | 4 | def fun():
return "Sambhaji", "Jagtap", 1234
a=fun()
print(a)
for item in a:
print(item) |
788bb01234e13321ef2c909e82da51b8605810dd | sadfool1/Hacker-Rank | /Hard/Computer Game/Bad Running Time.py | 3,140 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 14 15:17:12 2020
@author: jameselijah
Sophia is playing a game on the computer. There are two random arrays A & B, each having the same number of elements.
The game begins with Sophia removing a pair (Ai, Bj) from the array if they are not co-prim... |
567b25f4d4360963cdbc7d82b1ff6ff70348566d | Dikshap/Academic-Projects | /FinalProject/ArraySum/sum.py | 1,123 | 3.609375 | 4 | #Author: Diksha Pande
#Assingment : Sum of array element in python
import time
import multiprocessing.dummy as mp # uses threads instead of full processes
def something(duration=0.000001):
"""
Function that needs some serious benchmarking.
"""
time.sleep(duration)
# You may return anything you want,... |
8443e51b356bcb587b14da114e4b29bb8c461ede | abraveboy/show_me_the_code | /0011.py | 542 | 3.625 | 4 | #第 0011 题: 敏感词文本文件 filtered_words.txt,里面的内容为以下内容,当用户输入敏感词语时,则打印出 Freedom,否则打印出 Human Rights。
import glob
filter = glob.glob('f*.txt')[0]
filter_words =[]
with open(filter) as wb:
for line in wb:
filter_words.append(line.strip())
def judge(word):
return word in filter_words
if __name__ =... |
50cdfe6dd5d6826a19477bbd440f7b1af507619e | ElleDennis/build-a-blog | /crypto/helpers.py | 1,276 | 4.4375 | 4 | def alphabet_position(letter):
"""alphabet_position receives single letter string & returns 0-based
numerical position in alphabet of that letter."""
alphabetL = "abcdefghijklmnopqrstuvwxyz"
alphabetU = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
letter = letter.lower()
if letter in alphabetL:
retu... |
72ebe7780969118e2fe28fe615c542d4cebe7434 | buggoing/pythonTools | /time-datetime-string.py | 1,308 | 3.671875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import datetime
import time
# 日期时间字符串
st = "2017-11-23 16:10:10"
# 当前日期时间
dt = datetime.datetime.now()
# 当前时间戳
sp = time.time()
# 1.把datetime转成字符串
def datetime_toString(dt):
print("1.把datetime转成字符串: ", dt.strftime("%Y-%m-%d %H:%M:%S"))
# 2.把字符串转成datetime
def string... |
3e2ca4d070a65cd8849f89c1709a6829781bc9ba | DiyadotSaha/minesweeper_boardSetup | /minesweeper_boardSetup.py | 4,867 | 3.765625 | 4 | bomb_cordinates = []
def main():
message = input('Enter the coordinates of the game board (ex. 2 4): ')
r_c = message.split(' ')
row, col = int(r_c[0]), int(r_c[1])
num_bombs = input("Enter the number of bombs (ex. 3): ")
global bomb_cordinates
bomb_cordinates = bomb_coords(num_bombs)... |
c003771d01a4dcc7caa02a99aee7729fd6fcb181 | zaturnvalley/python_intro | /basicsPartThree.py | 1,991 | 3.625 | 4 | # Python Notes
# # making modules
# import exampleModule
# exampleModule.exampleFunc('test')
#pre built in modules are in python lib
#third part modules are in packages
#needs to be in local dir of proj yr working on in lib
#error handling with try and accept
# try:
# print('Running the try...')
# import mars #t... |
08a09f80bc482ac15ccb96054272095915d06ce1 | kinkuraj/lovecalculator | /calculator.py | 838 | 3.734375 | 4 | firstname = input("Enter first person name:")
secondname = input("Enter second person name:")
name = firstname + secondname
name = name.replace(" ","")
#print(name)
list = []
for x in name:
count = name.count(x)
if count > 0:
list.append(count)
name = name.replace(x,"").strip()
#print(list)
d... |
45560f43c285361835e74370478d9f0f1157f306 | davidbrowning/python | /example15+/ex16.py | 550 | 3.609375 | 4 | from sys import argv
script, filename = argv
print "erasing %r" % filename
print "undo? CTRL-C (^C)."
print "continue? ENTER"
raw_input("?")
print ("Opening...")
target = open(filename, 'w')
print "Truncating the file. Goodbye!"
target.truncate()
print "I need three lines"
line1 = raw_input("line 1: ")
line2 = ... |
4ad19fd2cc5629774a834fbffcdfae0e56c40a05 | tanyuejiao/python_2.7_stuty | /lxf/interation2.py | 1,182 | 4.25 | 4 | #!/usr/bin/python
# coding:utf-8
# 当我们使用for循环时,只要作用于一个可迭代对象,for循环就可以正常运行,而我们不太关心该对象究竟是list还是其他数据类型。
# 那么,如何判断一个对象是可迭代对象呢?方法是通过collections模块的Iterable类型判断:
from collections import Iterable
# 可以使用isinstance()判断一个对象是否是Iterable对象:
# str是否可迭代
a = isinstance("abc", Iterable)
print ("a: %s" % a)
# list是否可迭代
a = isinstance([1,... |
ef79d66df178986222288328d66bb6daa3a4b3f1 | tanyuejiao/python_2.7_stuty | /lxf/class2.py | 1,908 | 4.125 | 4 | #!/usr/bin/python
# coding:utf-8
import types
'''获取对象信息
当我们拿到一个对象的引用时,如何知道这个对象是什么类型、有哪些方法呢?
使用type()
首先,我们来判断对象类型,使用type()函数:
基本类型都可以用type()判断:'''
print type(123)
# <class 'int'>
print type('str')
# <class 'str'>
print type(None)
# <type(None) 'NoneType'>
# 如果一个变量指向函数或者类,也可以用type()判断:
def abs():
pass
class Ani... |
3bc9d1205cb63ab27b8c9155df537d9d1fc10891 | tanyuejiao/python_2.7_stuty | /lxf/generator1.py | 1,012 | 4.03125 | 4 | #!/usr/bin/python
# coding:utf-8
# 要创建一个generator,有很多种方法。第一种方法很简单,只要把一个列表生成式的[]改成(),就创建了一个generator:
L = [x * x for x in range(10)]
print L
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
g = (x * x for x in range(10))
print g
# 创建L和g的区别仅在于最外层的[]和(),L是一个list,而g是一个generator。
# 我们可以直接打印出list的每一个元素,但我们怎么打印出generator的每一个元素呢?
# 如果要一... |
e1a296cfe2eb437daad088ff4070a689872bb03e | ishaik0714/MyPythonCode | /Strings_Prog.py | 1,232 | 4.375 | 4 | mult_str = """This is a multi line string,
this can have data in multiple lines
and can be printed in multiple lines !"""
print(mult_str) # The Multi-line string can be in either in three single quotes or three double quotes.
st1 = "Hello"
st2 = "World!"
print (st1+st2) # String Concatenation
str1 = "Hello Worl... |
ace99e84d5c4e658e75d0022ce127316ed590d52 | agreigra/feedly-challenge | /pipeline/graph/graph.py | 5,052 | 3.6875 | 4 | from random import choices
import sys
import os
sys.path.append(os.path.abspath('../utils'))
from utils import intersection
class Graph(object):
"""
A class used to represent a graph
Attributes
----------
nodes : dictionary
used to store the nodes of the graph
nodesNumber : int
... |
03cc46d1d22049cb1087186b5cd6c9f99ed7a7e2 | ishritam/python-Programming--The-hard-way-Exercises | /newinput.py | 371 | 3.578125 | 4 | from sys import argv
script,user_name=argv
print(f"Hi {user_name}, I am {script}")
print(f"Tell me your nick name {user_name}:")
name=input(">>")
print(f"your age: {name}?")
age=input(">>")
print(f"Do you like me {name}?")
like=input(">>")
print(f""" Hi {user_name}, I am {script}
your nickname is {name}
... |
c810b5c748c15512bbbec709dd8116ec6545fd47 | ishritam/python-Programming--The-hard-way-Exercises | /ex17.py | 918 | 3.765625 | 4 | from sys import argv #for argv
from os.path import exists #to define if its exists or not
script,from_f,to_f=argv #define with var argv
print(f"Does the file exist{exists(from_f)}") #used exists for the conformation of the file
new=open(from_f) #open the exist file
read=new.read() #read it and store it in ... |
0668c88a893abfb56771274730e5e3ef5af15c93 | ishritam/python-Programming--The-hard-way-Exercises | /fib.py | 208 | 3.875 | 4 | from functools import lru_cache
@lru_cache()
def fibonaci(n):
if n ==1 or n==2:
return 1
elif n > 2:
value= fibonaci(n-1) + fibonaci(n-2)
return value
for i in range (1,1000):
print(i ,fibonaci(i)) |
7d7345e069991fa81e85641c8a50449267e471b8 | ishritam/python-Programming--The-hard-way-Exercises | /ex12.py | 86 | 3.78125 | 4 | name=input("Name?")
age=input("age?")
print(f"So, Mr.{name}, You are {age} years old") |
4fa0e33790b98b542de820b91d1c248cd424060f | ishritam/python-Programming--The-hard-way-Exercises | /funt.py | 216 | 3.875 | 4 | def operation(a,b,op):
if op=="add":
return a+b
elif op=="sub":
return a-b
elif op=="mult":
return a*b
print(__name__)
if __name__=="__main__":
print(operation(2,5,"add"))
print(operation(5,2,"sub"))
|
e4b12d10e3c1fe546040b4524c39d6e6d5da81ad | ishritam/python-Programming--The-hard-way-Exercises | /e.py | 1,144 | 3.828125 | 4 | class Car(object):
run= False
def __init__(self,name,color,model,year):
self.name = name
self.color = color
self.model = model
self.year = year
def accelerator(self):
print("Car is speeding up...")
self.run=True
def brake(self):
if self.run==True:
print("Car is speeding down...")
self.run=... |
6dc9c19a034426fc30ef70fa133fad3f51951a07 | ishritam/python-Programming--The-hard-way-Exercises | /list manipulation.py | 198 | 3.796875 | 4 | example = ["Hello ", "my ", "name ", "is ", "Lyndon"]
print(*example) # if you put a * in front of the list it will leave out commas and quotes and brackets
x = [1, 2, 3, 4, 5]
print(x.index(1))
|
99fc18fb51c7acc90fdd76f5702f32bde54301e5 | ishritam/python-Programming--The-hard-way-Exercises | /ex5.py | 206 | 3.515625 | 4 | name= 'Shritam'
age = "19+"
height = 5.9 #inch
weight = 64
print(f"Hey! my name is {name}.")
print(f"I am not lieing . i am {age} years old")
print(f"My height is {height}")
print(f"my weight is {weight}") |
9bade3475caa1406b6f63613dd9e29fbb3e47711 | ishritam/python-Programming--The-hard-way-Exercises | /ex35.py | 1,918 | 3.71875 | 4 | def gold_room():
print("It's a room full with Gold.")
print("Chose how many coin do you want?")
choice= int(input(">>"))
if choice <50:
print("You are not a greedy person. Well done.")
print("You Won! Congratulation.")
elif choice > 50:
print("You are a greedy basted MF. Go to hell.")
tiger()
else:
prin... |
011e102f5aceadcf86738437b85cf66a0b6c0424 | oonisim/python-programs | /nlp/src/common/weights.py | 3,808 | 3.515625 | 4 | """Node weight initializations
"""
from typing import (
List,
Dict
)
import numpy as np
from common.constant import (
TYPE_FLOAT
)
def xavier(M: int, D: int) -> np.ndarray:
"""Xavier weight initialization for base-symmetric activations e.g. sigmoid/tanh
Gaussian distribution with the standard devi... |
e907335ba4b5342ff725bfcdebdf0661424d3a32 | oonisim/python-programs | /nlp/src/data/non_linear_plots.py | 11,323 | 4 | 4 | """Data for classifications"""
from typing import (
Tuple,
List
)
import numpy as np
from common.constant import (
TYPE_FLOAT,
TYPE_INT,
TYPE_LABEL
)
from mathematics import (
rotate,
shift,
is_point_inside_sector
)
def set_in_a_radius(radius: TYPE_FLOAT, d: int, n: int):
"""Genera... |
7d1246f165bd67122f256cf2c7e6e77420219166 | oonisim/python-programs | /graph/networkx/utility.py | 1,489 | 3.609375 | 4 | import os
import sys
import string
from itertools import (
product
)
from typing import (
List,
Tuple,
Any,
Optional,
)
import contextlib
CSV_FIELD_DELIMITER: str = ","
OS_EOL_CHARACTER = os.linesep
@contextlib.contextmanager
def smart_open(filename=None):
if filename and filename != '-':
... |
a926b0139fd958ab7d62c85e8f34dc141a38e7a4 | Jorden0205/CodeEval | /python3/easy/RollerCoaster.py | 411 | 3.65625 | 4 | import sys
with open(sys.argv[1], 'r') as test_cases:
for test in test_cases:
test = list(test)
case = True
for i, n in enumerate(test):
if not n.isalpha():
continue
if case == 1:
test[i] = n.upper()
else:
... |
85aafb01640fc5b3025d42db8fc9ffc6bb136bb6 | Keisha2810/KeishaCSC102 | /spyder_orangeassignment.py | 1,022 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 10 14:32:57 2021
@author: Keisha
"""
class Orange:
orangecounter = 157
def __init__(self,a):
self.a = a
@classmethod
def orangecalc(cls,a):
if (a > cls.orangecounter) :
print("The number requested is more than t... |
43aac5d74701d4aab69061bab454f8afeedc0ff5 | medrupaloscil/Python-Brainfuck-Interpreter | /bfi.py | 4,227 | 3.5 | 4 | import re
class Interpreter(object):
def __init__(self, text, debug = 0):
self.text = text
self.pos = 0
self.current_char = self.text[self.pos]
self.current_memory = 0
self.memory = [0]
self.current_loop = 0
self.loop_position = [0]
self.startInside =... |
44d74e7c37a86e4b50cd4c0ba48693397c379307 | KIMJOOYEON97/pythonStudy | /연습/H0521.py | 5,351 | 4.09375 | 4 | '''
a=int(input("한변의 값을 입력하세요 : "))
import turtle
turtle.forward(a)
turtle.right(120)
turtle.forward(a)
turtle.right(120)
turtle.forward(a)
turtle.right(120)
turtle.mainloop()
a=int(input("길이: "))
import turtle
turtle.speed(1)
turtle.bgcolor("red")
turtle.forward(a)
turtle.left(60)
turtle.forward(a)
turtle.left(60)
tu... |
c6159f39d6bf895a5886056e26f48fb519127b99 | KIMJOOYEON97/pythonStudy | /20.05 studyData/02day.py | 5,604 | 3.921875 | 4 | '''
# 주석처리 : 프로그램 코드로 동작하지 않고
# 단순한 설명이나 기술로 처리하는 부분
# 1)한줄 주석: "#"
print("1. Hello Python!!!")
#print("2. Hello Python!!!")
print("3. Hello Python!!!")
#print("4. Hello Python!!!")
'''
# 2) 여러줄 주석 : '''~''' or """~"""
''' <-주석의 시작
print("1. Hello Python!!!")
print("2. Hello Python!!!")
print("3. Hello Pytho... |
18333f2dedd3472b310aaca00cb9903efd88dc45 | KIMJOOYEON97/pythonStudy | /20.05 studyData/17day.py | 9,754 | 3.953125 | 4 | # 5. 예제 친구이름 관리를 함수로 기능을 나눠서 작성해주세요.
# (1.친구목록보기,
# 2.친구추가,
# 3.친구삭제,
# 4.친구수정,
# 0.종료)
#함수를 사용하는 이유: 재사용 =>코드사용을 최소화시킴&유지보수할때 <객체지향적>
'''
def fr_list(lst): #친구 목록 보기
print("========== 친구 목록 보기 ==========")
if lst != []:
for i in range(len(lst)):
print("{} : {}".format(... |
6357f6cbac14c8d961f21f64cf50cf16f499fbb1 | ysjk2003/Study_Python | /Built-in_functions.py | 5,264 | 3.53125 | 4 | #count
a = 'programing'
res = a.count('m')
print(res)
#count함수가 메소드로 지정된 변수의 문자열에서 count 함수 인자(문자)의 개수를 변환한다.
#만약 a에 숫자를 담고 count에 숫자 인자를 넣으면?
#불가능 문자열함수이기 때문
#그래도 숫자를 세고 싶다면?
#find함수가 메소드로 지정된 변수의 문자열에서 find함수 인자(문자)의 인덱스를 반환한다.
#만약 찾는 문자가 없다면? => -1출력
#ex) if(res==-1) 또는 res+1
a = 'programing'
res = a.find('m')
pri... |
5056c7df307dce795661dc9adc223384175131c9 | khanadetkh/INT491-BasicPythonProgramming | /mymoduel.py | 202 | 3.75 | 4 | def add (x,y):
return x+y
def sub (x,y):
return x-y
class MyClass:
def __init__(self,name):
self.name = name
def my_function(self):
print("hello "+self.name) |
9ad3e2eddfd9dd2867a6665746db5ccf7752e563 | theogobinet/SCtoSpotify | /interactions.py | 779 | 3.6875 | 4 | from math import inf
import os
def clear():
if os.name == "nt":
os.system("cls")
else:
os.system("clear")
def getInt(default=1, expected="choice", limit: int = inf):
print(f"Enter {expected} ({default} by default):")
while True:
i = input("> ")
if i == "":
... |
9887e1e54df3a48902cb496edeff28cab183fe28 | kervinck/pdfMax | /stats.py | 1,487 | 3.59375 | 4 |
from math import sqrt
class Stats:
def __init__(self):
self.z = 0.0 # location parameter
self.sum = 0.0
self.sumSq = 0.0
self.n = 0
self.min = float('inf')
self.max = float('-inf')
def add(self, x):
... |
57126a12762a41f241d99353b0b9006d009d7989 | vHelp-VIT/vHelp | /test.py | 2,478 | 3.90625 | 4 | class Node:
def __init__(self,data=None):
self.data=data
self.left=None
self.right=None
class BST:
def __init__(self):
self.root=None
def insert(self,ele):
def bst_insert(root,ele):
if(root==None):
return Node(ele)
elif(e... |
a48ae8f95690e8e5bc11588238f65258c770ff5a | metaganal/scripts | /Hello_world.py | 337 | 3.859375 | 4 | """
Print "Hello World" n times
"""
import argparse
import sys
parser = argparse.ArgumentParser("Print 'Hello World' n times")
parser.add_argument("integers", metavar="N", type=int, help="How many times 'Hello World' should be printed")
args = parser.parse_args()
for i in range(args.integers):
sys.stdout.writ... |
ebec89c297c99fcda8308e724233f465a67cbfaf | metaganal/scripts | /sort_descend.py | 447 | 3.71875 | 4 | """
Sort list by descending order
"""
import argparse
import sys
parser = argparse.ArgumentParser()
parser.add_argument("seq", help="Sequence to sort")
parser.add_argument("-dl", "--delimiter", dest="delim", default=",", help="Delimiter of sequence")
args = parser.parse_args()
line = args.seq
listseq = list(map(i... |
6e34f00009bb72af3165d86dd502c81f96e6d64a | metaganal/scripts | /dict.py | 182 | 4.1875 | 4 | """
Learning the basics of a python dictionary
"""
A = ["a", "d", "c", "b"]
B = ["3", "5", "8", "1"]
d = {}
for i in range(len(A)):
d[A[i]] = B[i]
print(A)
print(B)
print(d)
|
06e551a23e3076dda27d13be6984a22f416314ce | metaganal/scripts | /reverseiter.py | 149 | 3.890625 | 4 | """
Print 1 to 100 in reverse decrementing by 2
"""
for i in reversed(range(0, 101, 2)):
if i == 0:
print(1)
else:
print(i)
|
edb927e5bc493b144e8ea7c7acaa9a2f4edee5ef | ruszmate33/CS50x-C-and-Python-code | /readability/readability.py | 2,234 | 4.0625 | 4 | # import get_string from cs50 package
from cs50 import get_string
def main():
# prompt the user for a of text
text = get_string("Text: ")
# calculate cli value with helper functions
cli = calcCLI(countNumLetters(text), countNumWords(text), countSentences(text))
# from 1 to 16: output "Grade X" wh... |
86e32762e5293518091bc331d6e58a91cb47e61c | jds375/deep_learning | /back_propogation/back_prop.py | 1,453 | 3.96875 | 4 | class Variable:
def __init__(self, array):
"""
A variable in a computational graph. For our purposes this is restricted
to being an array (note that we can represent a scalar using arrays with a
1x1 array, so it's really scalars too).
Attributes
----------
array : numpy.array
... |
401f244a7769e25e99815772649023c905b18ba5 | viraatdas/ClassScheduleOptimizer | /Class_Maker.py | 1,012 | 3.515625 | 4 | #program assumes the number of required classes for a requirement will be less than 10,
#which is a fair assumption
#variables refer to the various track requirements
#first number in front of the inner list refer to how many of those classes need to be satisfied
ml = [373, 381, [1, 471,473],[1, 416, 512], [2, 348, 35... |
45410962e1a874db0f72e34f0c8e6210068bd866 | angellee0102/Operating-System | /scheduling/fcfs.py | 3,341 | 4 | 4 | # Python3 program for implementation of FCFS
# scheduling with different arrival time
# Function to find the waiting time
# for all processes
from operator import itemgetter
def findWaitingTime(processes, n, bt, wt, at):
service_time = [0] * n
service_time[0] = 0
wt[0] = 0
# calculating... |
9b7f1e3660a0ac3d0805dd11eb96b19210d45f6f | KarrXie/interview_code | /trees.py | 3,093 | 4 | 4 | # ӡݹ飩
def preOrderTraverse(node):
if node is None:
return None
print(node.val)
preOrderTraverse(node.left)
preOrderTraverse(node.right)
# ӡǵݹ飩
def preOrderTravese(node):
stack = [node]
while len(stack) > 0:
print(node.val)
if node.right:
sta... |
b9c3dd0a732d98011197407cdaad4a0b8fce71b3 | bagel/FunWithAlgorithms | /array/stock.py | 437 | 3.734375 | 4 | # stock
def stock(arr):
min_s = arr[0]
max_s = arr[0]
for i in range(1, len(arr) - 1):
#print(i, min_s, max_s)
if arr[i] < arr[i - 1]:
min_s = arr[i]
max_s = arr[i]
elif arr[i] > arr[i - 1]:
max_s = arr[i]
if arr[i + 1] < arr[i]:
... |
d9f554643b91a907df7f7c033581662e074cf9cb | jamestotle/python-cookbook-3rd | /chapter01/1.10. Removing Duplicates from a Sequence while.py | 546 | 3.71875 | 4 | def dedupe1(items):
seen = set()
for item in items:
if item not in seen:
yield item
seen.add(item)
def dedupe(items, key=None):
seen = set()
for item in items:
val = item if key is None else key(item)
if val not in seen:
yield item
... |
e1000a1ea7bcc94cef6019982a91882a26332771 | KushalGhimire17/Website-using-python-and-javascript | /name.py | 106 | 4.09375 | 4 | name = input("Enter name ")
print(f"Hello, {name}!")
x = (1,2,3)
for i in x:
print(i, end=" ")
|
cc839887c7cf99090033cf235542224e654e1b77 | zanpakt0/stepik_auto_tests | /2-1.py | 736 | 3.671875 | 4 | from selenium import webdriver
from selenium.webdriver.support.ui import Select
# select = Select(browser.find_element_by_tag_name("select"))
# select.select_by_value("1") # ищем элемент с текстом "Python"
def calc(x):
return str(math.log(abs(12*math.sin(int(x)))))
link = "http://suninjuly.github.io/selects2.html"
... |
5858448311a91f1a6cdbc375ec248866a69099b7 | lucas-broux/Projet-Map565 | /simulations/dependencies_analysis.py | 5,210 | 3.609375 | 4 | #!/usr/bin/env python
# # -*- coding: utf-8 -*-
"""
The purpose of this script is to analyse data with a time series approach.
Authors : LACOMBE Armand, BROUX Lucas.
Python version : 3.*
"""
# Imports.
from os.path import join
import numpy as np
import matplotlib.pyplot as plt
import pylab
import scipy.stats as stats... |
a5371068ad38abaab91f160c688599282d624a2d | verailina/python-demo | /tests/integration_tests/test_temperature_dataset.py | 1,717 | 3.765625 | 4 | """Test functionality of `TemperatureDataset` class on a small sample."""
import pandas as pd
from temperature_dataset import TemperatureDataset
cities = ["Andorrala Vella", "Vienna", "Minsk", "Brussels", "Sarajevo",
"Sofia", "Zagreb", "Prague", "Copenhagen", "Tallinn",
"Helsinki", "Paris", ... |
9186cf800f5810186962c8f0e11f1198721cd9d8 | Cathy-Kat/NannyOgg | /helloName.py | 242 | 3.984375 | 4 | # Uses a variable to greet
# Author: Cathy Walsh
name = "Cathy"
print ('hello' + name)
# this won't work
age = 34
#print('Your age is ' + age)
print ('your age is ' + str(age))
print ('Hello {} \tyour age is {}' .format(name, age))
|
8698aa545749d13a550704ba005888e0fbb0001f | syedsouban/PyEditor | /PyEditor.py | 1,690 | 4.15625 | 4 | import sys
print("Welcome to Python 2 Text Editor")
condition = True
while condition == True:
print("""What do you want to do:
1. Creating a new file
2. Writing to a saved file
3. Viewing a saved file
4. Exit """)
choice=eval(input("Enter your choice: "))
if choic... |
36c38bdde076f2acffc62e1074bfce8f68737f68 | Vern01/comp_v2 | /maths.py | 252 | 3.640625 | 4 | def solve(equation):
print("Needs to solve equation.")
class Math:
def __init__(self, memory):
self.memory = memory
def calc(self, string, ignore=""):
values = self.memory.set_values(string, ignore)
return string
|
9872d120af6e6098d4593b05bd82bdb8a5440d6e | maszpecha/AdventOfCode | /2017/day3/SpiralMemory.py | 783 | 3.515625 | 4 | from math import sqrt
from math import inf
class SpiralMemory:
def getCentres(self, n):
len = sqrt(n)
m1 = n - 1 / 2 * (len - 1)
m2 = n - 1 / 2 * (len - 1) * 3
m3 = n - 1 / 2 * (len - 1) * 5
m4 = n - 1 / 2 * (len - 1) * 7
return m1, m2, m3, m4
def calculate(sel... |
394abc1b9f9a6830bc4b1c5796f41d6827025c24 | philipjk/interview-cake-practice | /reverse_words.py | 671 | 3.625 | 4 | message = ['c', 'a', 'k', 'e', ' ',
'p', 'o', 'u', 'n', 'd', ' ',
'h', 'o', 'm', ' ',
's', 't', 'e', 'a', 'l']
def reverse_list(inl: list, start: int, end: int) -> list:
for i in range((end - start)//2):
inl[start + i], inl[end - i - 1] = inl[end - i - 1], inl[start + i]
... |
6eccc8a989af5c9b4edeb800321faaf9faa9bb6b | philipjk/interview-cake-practice | /graph_coloring.py | 1,643 | 3.796875 | 4 | from collections import deque
class GraphNode:
def __init__(self, label):
self.label = label
self.neighbors = set()
self.color = None
a = GraphNode('a')
b = GraphNode('b')
c = GraphNode('c')
a.neighbors.add(b)
b.neighbors.add(a)
b.neighbors.add(c)
c.neighbors.add(b)
graph = [a, b, c]
... |
932094a7dc1958795935c46ebc088fd7b6bd5266 | philipjk/interview-cake-practice | /permutation_palindrome.py | 1,040 | 4.03125 | 4 | def has_palindrome_permutation(the_string):
# Check if any permutation of the input is a palindrome
letterset = {char: 0 for char in the_string}
for char in the_string:
letterset[char] += 1
flag = 0
for char in letterset.keys():
if letterset[char] % 2:
flag += 1
... |
8831a7d94a367d0957da5591700505cd5edb6765 | philipjk/interview-cake-practice | /inplace_shuffle.py | 1,020 | 3.53125 | 4 | import timeit
import random
def get_random(floor, ceiling):
return random.randrange(floor, ceiling + 1)
def shuffle(the_list):
# Shuffle the input in place
if len(the_list) <= 1:
return
length = len(the_list)
for i in range(length):
r = get_random(0, length - i - 1)
th... |
11b05da01ab456b626f606eafd69b29cc2f4f949 | JianhangYin/LeetCode | /Python3/array/majority_element.py | 591 | 3.6875 | 4 | """
Given an array of size n, find the majority element.
The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
"""
class Solution:
def majorityElement(self, nums: list) -> int:
maj = nums[0]
... |
c8f84c458d047649c59c58c6a82bb9b56ee3593a | JianhangYin/LeetCode | /Python3/tree/path_sum.py | 1,408 | 4.0625 | 4 | """
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Note: A leaf is a node with no children.
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left ... |
78820d3df2290864d91394bdf42827db2ce75a11 | JianhangYin/LeetCode | /Python3/array/maximum_subarray.py | 1,575 | 3.625 | 4 | """
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
"""
class Solution:
def maxSubArray(self, nums: list) -> int:
if not nums:
return float("-inf")
middle_point = len(nums) // 2
max_left = ... |
47d9bc85f8ac13d04dc6bf878b990cd9fb21797a | JianhangYin/LeetCode | /Python3/hash_table/valid_sodoku.py | 2,077 | 4.0625 | 4 | """
Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
Each row must contain the digits 1-9 without repetition.
Each column must contain the digits 1-9 without repetition.
Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without rep... |
3c045548505ff492ad7d9142aed6dbaf3d937246 | JianhangYin/LeetCode | /Python3/string/implement_strStr().py | 599 | 3.96875 | 4 | """
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
"""
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if needle == '':
return 0
elif needle not in haystack:
return -1
... |
717af55d71462e6a6ff10b679e6d4c8f35b75fc1 | JianhangYin/LeetCode | /Python3/stack/valid_parentheses.py | 1,051 | 4.0625 | 4 | """
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
"""
... |
b2b0b24334fee60561c4008344dd36704f412d0c | JianhangYin/LeetCode | /Company/Amazon/VO/21. Merge Two Sorted Lists.py | 624 | 3.96875 | 4 | """
RECURSIVE METHOD!!!!
"""
# 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:
if not l1:
return l2
if not l2:
return... |
a7dcf750116a0bf7aac7a6ccaa311682eca282e6 | JianhangYin/LeetCode | /Python3/two_pointers/3_sum_closest.py | 1,236 | 3.65625 | 4 | """
Given an array nums of n integers and an integer target,
find three integers in nums such that the sum is closest to target.
Return the sum of the three integers. You may assume that each input would have exactly one solution.
"""
class Solution:
def threeSumClosest(self, nums: list, target: int) -> int:
... |
493552248f455479c16020af4d18e63f912cd974 | JianhangYin/LeetCode | /Python3/linked_list/middle_of_the_linked_list.py | 929 | 3.921875 | 4 | """
Given a non-empty, singly linked list with head node head, return a middle node of linked list.
If there are two middle nodes, return the second middle node.
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def... |
1d1901dba703ec8bcefddb46cdafced0b5c7e8f6 | JianhangYin/LeetCode | /Company/Amazon/VO/200. Number of Islands.py | 1,336 | 3.5 | 4 | """
This is a typical DFS problem, we increase the number of island every time we found a '1' in the grid. Then we applied
DFS to this grid and transform every '1' to '0'.
"""
class Solution:
def numIslands(self, grid: list) -> int:
num_island = 0
for row in range(len(grid)):
for col i... |
edfb83652324b42e821f1a3365a963afde560457 | somasan/projectone | /three/three4.py | 155 | 3.890625 | 4 | import turtle
turtle.shape('turtle')
i = 0
turtle.begin_fill()
while i < 360:
turtle.forward(1)
turtle.left(1)
i += 1
turtle.end_fill()
input() |
ab700fc4c0b47d32e2125835d775556dd7b80664 | timy600/PruebaDevo | /ejercicio1/ejercicio1.py | 1,019 | 4.03125 | 4 | """ Crear una función en python que dada una lista de números indique para cada número
si es un número perfecto, abundante o defectivo.
"""
def verificar_lista_numeros_perfectos(lista):
lista_respuesta = []
# Verificar que el parametro sea una lista
if type(lista) != list:
return "TypeError: Expec... |
a5208cfc047bfdd58e7812f00ecce58f752c1b38 | robertoterceros/Coursera---Algorithms-Specialization | /Week 4/BinarySearch.py | 346 | 3.78125 | 4 | def BinarySearch(A, low, high, key):
if high < low:
return (low - 1)
mid = (low + (high - low)/2) %Parte entera hacia abajo o the floor
if A[mid] == key:
return mid
else if key < A[mid]:
return BinarySearch(A, low, mid - 1, key)
else if key > A[mid]:
return BinarySear... |
de34c3d273fab4973ed52bfcaeacd93d3231734b | kgorshkoff/interview_preparations | /hw2/2.py | 629 | 3.984375 | 4 | # 2. Инкапсулировать оба параметра (название и цену) товара родительского класса.
# Убедиться, что при сохранении текущей логики работы программы будет сгенерирована ошибка выполнения.
class ItemDiscount:
def __init__(self, name, price):
self.name = name
self.price = price
class ItemDiscountRepo... |
257f1bfd2a75bea5ed865d19570878995cff1ebe | jiwon-0129/likelion_jw | /파이썬과제1_jiwon.py | 397 | 4.03125 | 4 | the_answer = {"현숙": "이화여대 멋사 대표님", "세은": "파이썬 세션 튜터", "두희": "멋사 창립자", "마루": "야옹"}
for i in the_answer:
print("다음은 누구에 대한 설명일까요?")
print(the_answer[i])
n=input()
if the_answer[i]==the_answer.get(n):
print("정답입니다.")
else:
print("오답입니다.")
continue
|
6919b594ebe9644dde975491f13fb47ab489a453 | swapnasrita/pandas | /02 Introduction to Pandas/DataFrames/s2_7_broadcasting.py | 694 | 3.578125 | 4 | import pandas as pd
# course_sales = {'course':['Python','Ruby','Excel','C++'],
# 'day':['Mon','Tue','Wed','Tue'],
# 'price':[5,10,15,20],
# 'sale':[2,3,5,7]
# }
# df_sales = pd.DataFrame(course_sales)
# print(df_sales)
course = ['Python','Ruby','Excel','C+... |
fbb3afb5abc39082d0cc9f80473069059f7c7ae4 | decentjik1128/python_code | /python_coding_stamp/2_gram.py | 320 | 3.984375 | 4 | text = 'hello'
for i in range(len(text)-1):
print(text[i], text[i+1], sep = '')
two_gram = zip(text, text[1:])
for i in two_gram:
print(i[0], i[1], sep = '')
text = 'this is python script'
words = text.split()
for i in range(len(words)-1):
print(words[i], words[i+1])
print(list(zip(words, words[1:])))
|
07305ad095da8a59f2f78b45f1a7d150dc483ea1 | decentjik1128/python_code | /python_coding_stamp/iterator_iter_next.py | 423 | 4.09375 | 4 | it = iter(range(3))
print(next(it))
print(next(it))
print(next(it))
import random
it = iter(lambda : random.randint(0,5), 2)
print(next(it))
print(next(it))
for i in iter(lambda : random.randint(0, 5), 2):
print(i, end = ' ')
while True:
i = random.randint(0,5)
if i ==2:
break;
print(i, end =... |
dfed4f7daaeeee0c29d70492807d2569a5d2e62b | conor-mcnally/WagesMonthly | /gui.py | 1,871 | 3.734375 | 4 | from tkinter import *
from tkinter import messagebox
import tkinter.simpledialog
import csv
def store():
adate = date.get()
aamount = amount.get()
if(adate == None):
print("Error with date")
messagebox.showerror("Error", "There was an issue inputting the date")
else:
result = m... |
d44ab2f4b12fbeb112faceddf889d477f0c796b2 | sunil830/PracticePerfect | /ListOverlap.py | 1,315 | 4.25 | 4 | """
Author: Sunil Krishnan
Date: 17-Apr-2016
Name: ListOverlap.py
Reference: http://www.practicepython.org/exercise/2014/03/05/05-list-overlap.html
Problem Statement:
Take two lists, say for example these two:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13... |
1bfdd00cd2b9e81f7cb1aa5a32a45127592a7f03 | jiekeman/untitled7 | /week1/05作业讲解.py | 1,687 | 3.921875 | 4 | # 1.老男孩好声音选秀大赛评委打分的时候,可以进行输入,
# 有10个评委,让10个评委依次打分,分数必须大于5分小于10分
# count = 1
# while count <= 10:
# fen = int(input('请第%s号评委评分:' % count))
# if fen < 5 or fen > 10:
# print("超出范围,请重新输入")
# continue
# else:
# print('第%s号评委打%s分' % (count, fen))
# count += 1
# 2.车牌区域划分
# cars = ['鲁A3... |
ff251d04253c952ca4faf297b0c5e4e6a5fb7e31 | Pooya-Jamshidi/page-rank-in-python | /PageRank.py | 2,070 | 3.609375 | 4 | #! python3
# PageRank.py - This program get a matrix with list in list and return a list contains page Rank of every element of it
# author : Pooya Jamshidi
# ....
# importing a method from that page and using is_float method
import functions as func
def page_rank(matrix, epsilon):
"""
This func... |
7bf65150951c855bed75af1ea7fc52bb3703fa2b | darkobodnaruk/crypto1 | /homework1.py | 5,352 | 3.5625 | 4 | #!/usr/bin/python
'''
The CoiciseeOqfor.Dictio.ary ....ag de..nes crypto a...he art..f. writing o g solvdn. code...
'''
def strxor(a, b): # xor two strings of different lengths
if len(a) > len(b):
return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)], b)])
else:
return "".join([chr(ord(x) ^ ord... |
0cfa1679aefc5ca6dd7fbe111e5004c2285bb9aa | crazyhottommy/primer3_scATAC_peaks | /prepare_primer3_input.py | 1,399 | 3.765625 | 4 | #! /usr/bin/env python3
import csv
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("input", help="Required. the FULL path to the 2 column input file, first column is the ID, second column is the DNA sequence")
parser.add_argument("primer3_template", help="primer3 Boulder-IO format template txt... |
c9b50807660cc7b13580964497807d0fcfa4980c | avee137/interview | /problems/rev_str_rec.py | 117 | 3.78125 | 4 | #!/usr/bin/env python
def rev(s):
if len(s)==1:
return s[0]
else:
return rev(s[1:])+s[0]
print rev("hello")
|
d80429008750e5ad5fd0c053f1ad92387e84b1e6 | barsauskasalius/first_program | /Codewars/8kyu/Quarter of the year.py | 300 | 3.625 | 4 | def quarter_of(month):
if month <= 3 and month > 0:
return 1
elif month > 3 and month <= 6:
return 2
elif month > 6 and month <= 9:
return 3
elif month > 9 and month <= 12:
return 4
## https://www.codewars.com/kata/5ce9c1000bab0b001134f5af/train/python |
4b8983410fc0771d188ccf184f82fff95203e556 | barsauskasalius/first_program | /Codewars/8kyu/Difference of Volumes of Cuboids.py | 216 | 3.546875 | 4 | def find_difference(a, b):
a = a[0] * a[1] * a[2]
b = b[0] * b[1] * b[2]
if a > b:
return a - b
else:
return b - a
# https://www.codewars.com/kata/58cb43f4256836ed95000f97/train/python |
d55f8b960006f64512cc2497603e852ac2d689e1 | barsauskasalius/first_program | /Codewars/8kyu/Invert values.py | 179 | 3.6875 | 4 | def invert(lst):
negativelist = [-x for x in lst]
return negativelist
print (invert([-1, 2, 3, 4, 5]))
#https://www.codewars.com/kata/5899dc03bc95b1bf1b0000ad/train/python |
d5727fa93ab9f912b068746209cabed0a0c38e74 | ratangupta/Python-Programming-Basics-and-Intermediate | /generator.py | 805 | 3.921875 | 4 | # Generate lock combo
CORRECT_COMBO = (3, 6, 1)
# Using traditional method
# found_combo = False
# for c1 in range(10):
# if found_combo:
# break
# for c2 in range(10):
# if found_combo:
# break
# for c3 in range(10):
# if (c1, c2, c3) == CORRECT_COMBO:
# ... |
447a4be3d6ce706a5bce989a1874910855360883 | bthodla/stock_tweets | /turtle_utils.py | 966 | 4.1875 | 4 | import turtle
import math
import time
def polyline(t: turtle, sides: int, length: int, angle: int):
"""Draws *sides* line segments with the given length and angle (in degrees) between them
:param t: turtle
:param sides:
:param length:
:param angle:
:return:
"""
for i in range(sides)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.