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 |
|---|---|---|---|---|---|---|
d1c9e62287730ad99a0282891c8227292b025964 | writerlab/pbo_rpl3 | /tugas_ranger_1/23_dimas.py | 474 | 3.875 | 4 | print ("===LATIHAN===")
Nama = input ("Nama:")
Kelas = input ("Kelas:")
nilai=int(input("Nilai Latihan= "))
#ini adalah proses
if nilai>75:
hasil ="A"
elif nilai<= 75 and nilai> 70:
hasil ="B"
elif nilai<= 69 and nilai> 61 :
hasil ="C"
else:
hasil ="D"
print ("===HASILNYA===")
... |
b1e00a27f67b81e6d6dec4c19b960d5ee06df1dd | writerlab/pbo_rpl3 | /latihan/calc.py | 1,351 | 3.8125 | 4 | import os
def perkalian(x, y):
hasil = x * y
print("Hasil =",hasil)
def pembagian(x, y):
hasil = x / y
print("Hasil =",hasil)
def penjumlahan(x, y):
hasil = x + y
print("Hasil =",hasil)
def pengurangan(x, y):
hasil = x - y
print("Hasil =",hasil)
while True:
print('=== KALKULATOR ===')
print('[1... |
d879e20ac7aa4984649e608ec39e0ab8c480cebe | nixiaoxi/REST | /REST.py | 6,440 | 3.65625 | 4 | # Ni Xiaoxi Python Coding Exercise
import pandas_datareader.data as web
import pymysql.cursors
import pandas as pd
import numpy as np
import seaborn as sns; sns.set()
import pylab
import datetime
import holidays
ONE_DAY = datetime.timedelta(days=1)
# assume US holidays for illustration only
HOLIDAYS_US = holidays.US()... |
e2a4d88c5f532a900ec2121d564394acdb4cc9ed | Sumyak-Jain/Python-for-beginners | /while_0.py | 96 | 3.671875 | 4 | a=int(input("enter a number"))
i=1;
while i<11:
print("%d X %d = %d" % (a,i,a*i))
i=i+1
|
6504666739a835fe93c7f8da6090e51e5e107725 | mayanksh/Pythonagain | /venv/leetcode/number_of_items.py | 670 | 3.65625 | 4 | class solution():
def countmatches( items, rulekey, rulevalue):
d = {'type': 0, 'color': 1, 'name': 2}
c = 0
# items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]]
#ruleKey = "color"
#ruleValue = "silver"
index= d[rulekey]
... |
bf772445c70ed744a38609bb35aa045d5d5e29ec | sujanay/python-interview-questions | /tree.py | 2,011 | 4.125 | 4 | from __future__ import print_function
# Binary Tree Node
class TreeNode:
def __init__(self, v, l=None, r=None):
self.value = v
self.left = l
self.right = r
# insert data to the tree
def tree_insert(root, x):
attr = 'left' if x < root.value else 'right'
side = getattr(ro... |
092c5aa4f9d16b1fdf0f48906b23875c871e504a | sujanay/python-interview-questions | /integer_in_list.py | 730 | 3.96875 | 4 | # Write a function which takes as input a sorted list of integers (from the smallest to the largest) and
# an integer, it returns True if the integer is in the list, False if not.
import time
mylist = [i+1 for i in range(250000000)]
def isInTheList(mylist, num):
if mylist[-1] < num: return False
hi = mylis... |
2e615d7d4fc73f1a5540ec12938b87b2f769b5b9 | sujanay/python-interview-questions | /python/Algorithms/IsAnagram.py | 515 | 4.4375 | 4 | """check if the two string are anagrams of each other"""
"""
Method-1:
This method utilizes the fact that the anagram strings, when
sorted, will be equal when testing using string equality operator
"""
def Is_Anagram(str1, str2):
if len(str1) != len(str2):
return False
str1_sorte... |
4856c2750fcfa6690ad5c6fe259b42864031f9b8 | KokoShterev/python | /201106/14Constantine_2.py | 347 | 3.96875 | 4 | # задача 2
# Напишете програма, която при зададен string преброява гласните(бонус ако е за кирилица):
# "effect" -> 2
# "course" -> 3
# ** y не е гласна
a = input()
count = 0
for i in a:
if i.lower() in 'aeiouаъоуеиюя':
count += 1
print(count)
|
c3e8ce61c2acb08a0a5c03f93ebe3eef91191970 | KokoShterev/python | /test210122/calculate.py | 850 | 3.5 | 4 | # Напишете програма, която калкулира приходите за консултантска компания. Компанията приема основно заплащане по 200лв/ден, като има и схема за бонус след отработени определни дни. Схемата за бонусите е следната:
# 0 до 14 дни 0
# 14 до 30 дни 50лв + основното заплащане
# 30 до 60 дни 80лв + основното заплащане
# над ... |
f86962e8561a49d1c410b3f4ed660c7c91da7bd2 | dan255/vision-transform-codes | /vision_transform_codes/training/sparse_coding.py | 37,827 | 3.59375 | 4 | """
This implements sparse coding dictionary learning
"""
import time
import torch
from utils import plotting as plot_utils
def train_dictionary(training_image_dataset, validation_image_dataset,
init_dictionary, all_params):
"""
Train a sparse coding dictionary
The inputs should vary in th... |
7f4759e36aa88863687e526ff8dcdc966cb87109 | krutarthpurohit/pythonPrograms | /Experiment 6, Assignment 1.py | 446 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 1 12:13:24 2021
@author: Krutarth Purohit
Experiment 6
Assignment 1: Applying node voltage analysis, find the value of node voltages v1 and v2 for the circuit shown
in Fig. 6.3.
"""
from numpy import array,mat, transpose, zeros,identity,eye,divide
from num... |
e31f712465d64b868893af5b533befaebdb7c001 | bnb1212/hello-git | /pythonProject/practice_Multi_05.py | 592 | 3.609375 | 4 | import threading
n = 1000000
balance = 0
def add(n, lock):
global balance
for i in range(n):
lock.acquire()
balance += 1
lock.release()
def sub(n, lock):
global balance
for i in range(n):
lock.acquire()
balance -= 1
lock.release()
if __name__ == '__mai... |
6fbca8223d7758c2079fcd691d1e04438ca42257 | cxgoal-97/optimization | /linearSearch/monotoneSearch.py | 12,330 | 3.671875 | 4 | from linearSearch.linearSearch import LinearSearch
import numpy as np
class AccurateLinearSearch(LinearSearch):
"""
This class is used to find a suitable search area.
"""
def __init__(self, method="GoldenRate", find_area_method="GoAndBack", max_iter=100, **opt):
"""
:Note
This... |
9933a98eb401d17d1dd46202fdbd58cc108cc9ed | danielabrasilva/disaster_response_pipeline | /data/etl_pipeline.py | 2,191 | 3.53125 | 4 | # import libraries
import pandas as pd
import re
from sqlalchemy import create_engine
# load messages dataset
messages = pd.read_csv('disaster_messages.csv')
messages.head()
# load categories dataset
categories = pd.read_csv('disaster_categories.csv')
categories.head()
# merge datasets
df = pd.merge(messages, categ... |
8ba114592dbf2cb24b7d441d2bf84cac1b5a3228 | chendaye/py100 | /基础/练习/栗子-07.py | 509 | 4.25 | 4 | """
计算点的距离
"""
from math import sqrt
class distance:
def __init__(self, x, y):
self.x = x
self.y = y
def move_to(self, x, y):
self.x = x
self.y = y
def move_by(self, x, y):
self.x += x
self.y += y
def dis(self, x, y):
return sqrt((self.x - x)... |
88154d1f0dfcaaea8134620ca9951feea02b7f00 | chendaye/py100 | /基础/练习/栗子-01.py | 237 | 3.734375 | 4 | """
完美数(自身以外的因子)
6=1+2+3
28=1+2+4+7+14
"""
for num in range(1, 10000):
sum = 0
tmp = num
for m in range(1, tmp - 1):
if tmp % m == 0:
sum += m
if sum == num:
print(num)
|
2aba59ed3490ac62a196d51bbcabe89ee1366fca | AnFrBo/coupon_optimization | /module_baseline_heuristic_model.py | 4,023 | 3.578125 | 4 | """
Created on Wed Mar 10 00:54:21 2021
The purpose of this module is to:
* apply a heuristic/rule-based logic for coupon assignment
* get top 5 coupons for every shopper
The Heuristic "Model"
Assumptions:
(1) A customer will continue buying products with a coupon, if she has done so previously.
(2) Products whic... |
22e9086e309e5b27a4d390bbc6174cf28ad5ed3b | Gurpreet2/data-analysis | /data-analysis-backend/src/model/datasets.py | 2,341 | 3.546875 | 4 | from utils.dateutils import get_date_format
from datetime import datetime as dt
import json
class DataCollection(object):
"""
This object contains an arbitrary collection of data in this format
{
'fields': ['first field', 'second field', 'and so on'],
'data': [
{
... |
2354a04f15d7e15a48c942db55f7657f214dd221 | dishasahu/dishaPythonAssignments | /exercise_ii_a/math_eq_a.py | 199 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 12 16:05:05 2019
@author: abc
"""
x=int(input("enter the value of x"))
y=int(input("enter the value of y"))
z=((x+3)*(x**2))/((y-4)*(y+5))
print(z) |
cda2462295df1b2fb9b601cdfbb26f9eb39dd38a | AngelGus79/EjerciciosPython | /1.7.KeepingDictionariesinOrder.py | 460 | 4.03125 | 4 | """
OrderedDict es una funcion que mantiene el orden de los elementos a como se van ingresando
se importa del modulo collections.
Un OrderedDict mantiene una lista doble ligada para mantener el orden, por lo que un OrderedDict
tendra un tamaño de mas del doble que un diccionario convencional
"""
from collections impor... |
9583781186a895e705d03b8104a04107acde5363 | AngelGus79/EjerciciosPython | /2.2.MatchingTextattheStartorEndofaString.py | 1,626 | 4.0625 | 4 | """
Una manera de checar extensiones o principios de una cadena como para validar si es una
url son los metodos str.startswith() o str.endswith() que devuelven valor booleano
"""
url = "http://holamundo.com"
print(url.startswith('http://')) #True
#en caso de ser muchos parametros se debe poner solamente en TUPLA
pri... |
bbae9af404fd23f1247180e9e5ee4d2b6bdc7645 | AngelGus79/EjerciciosPython | /2.3.MatchingStringsUsingShellWildcardPatterns.py | 965 | 3.578125 | 4 | """
En este ejemplo se muestra como buscar coincidencias usando el patron del shell de unix
o windows con las funciones fnmatch() y fnmatchcase()
"""
from fnmatch import fnmatch, fnmatchcase
print(fnmatch('archivo.txt','*.txt')) #True por que archivo.txt se ajusta
#Un uso interesate es el siguiente
import os
lis... |
0c6915946501c633f351a946f7bd0cf6edadca42 | baykier/code-place | /python/solid_python/ch1/for.py | 418 | 4.0625 | 4 | # -*- coding:utf-8 -*-
# for
for n in range(2,10):
for x in range(2,n):
if n % x == 0:
print(n, 'equals', x, '*', n // x)
break
else:
print(n, 'is a prime number')
# even number
for num in range(2, 10):
if num % 2 == 0:
print(num, 'is a even... |
0ba446c9fea0df18255ac4d845cdcee1fad6369f | baykier/code-place | /python/cook_book/ch7/7.1.py | 615 | 3.71875 | 4 | # coding: utf-8
#接受任意数量的参数
# *参数后面只接受关键字参数即 m=v 形式,否则报错
def get_arg(*arg, m):
print(arg, m)
get_arg(1, 23, 4, 55, 34434, 't', m='hhh')
# 一个函数只能有一个*参数 下面会报错
# def get_arg2(*arg, *arg2):
# print(arg, arg2)
# get_arg2(3,2,2,2,7)
# 任意参数在位置参数之后,在最后一个位置参数后面
def get_arg3(m,n, *arg2):
print(m, n,arg2)
get_ar... |
ac19586e753e63f115790c71a7a1660b94428044 | kchung90/Python-Labs-Assignments | /Labs/Lab11/parse_args.py | 3,545 | 4.0625 | 4 | """
@author Kevin Chung
This module accepts command line arguments from a user through the
terminal to create a Request object.
"""
import argparse
class Request:
"""
Represents an object that stores data queried from a user using
command line arguments
"""
def __init__(self, mode: str, input_da... |
293495eb045745c624a661b6a61dccda37f77bfa | Carlos-DR/PrimeroPasosPython | /Tres en raya.py | 4,407 | 4.46875 | 4 | # Implementación del juego Tic-Tac-Toe para dos jugadores en Python.
'''' Haremos el tablero usando diccionario.
en qué teclas estará la ubicación (es decir, arriba a la izquierda, a la mitad a la derecha, etc.)
e inicialmente sus valores serán un espacio vacío y luego, después de cada movimiento
cambia... |
daac72e28c9f12cf9265c4048aa4e667c94fb7e1 | AndyPeee/TheLifeOfAndyP | /AFLgorythym.py | 3,338 | 4.09375 | 4 | class Stack:
def __init__(self):
self.list = []
def pop(self):
return self.list.pop()
def push(self, x):
self.list.append(x)
def length(self):
return len(self.list)
def peek(self):
return self.list[-1]
class Queue:
def __init__(self):
self.list =... |
38da15fd5fb128cdbbea6a7c848769367c4ab25f | thecattest/cs_converter | /converter.py | 1,303 | 3.6875 | 4 | from string import ascii_uppercase as letters
def to_tenth(n, base):
exponent = 0
res = 0
for point in str(n)[::-1]:
if not point.isdigit():
try:
point = letters[:base - 10].index(point.upper()) + 10
except ValueError:
raise ValueError('СИ не... |
a8ce7b50c17b1c2a577da458201f9a8fbd4c483f | ArnaudClarat/Float | /floatToHexa.py | 1,071 | 3.78125 | 4 | def deTOhex(nbr):
ent, dec = nbr.split(".")
bin1 = bin(int(ent))[2::]
print(bin1)
if bin1 == "0":
long = 10
test = False
else:
long = 10 - len(bin1)
test = True
temp = float("0." + dec)
bin2 = ""
for i in range(long):
print(temp)
temp = tem... |
727107f83ec94b59a60b7a160eb15cf2804e04cd | sulinghe/new | /text1.py | 1,298 | 3.625 | 4 | """
1. 小明家必须要过一座桥。小明过桥最快要1秒,小明的弟弟最快要3秒,小明的爸爸最快要6秒,小明的妈妈最快要8秒,小明的爷爷最快要12秒。每次此桥最多可过两人,而过桥的速度依过桥最慢者而定。过桥时候是黑夜,所以必须有手电筒,小明家只有一个手电筒,而且手电筒的电池只剩30秒就将耗尽。小明一家该如何过桥,请写出详细过程。
编程题(20分)
1. 一个长度为n-1的递增排序数组中的所有数字都是唯一的,并且每个数字都在范围0~n-1之内。在范围0~n-1内的n个数字中有且只有一个数字不在该数组中,请找出这个数字。
1 <= 数组长度 <= 10000
示例:
输入: [0,1,2,3,4,5,6,7,9]
输出: 8
"""
... |
23870181e6c38eb55ef5419974c9b92af2d72c50 | maaldic/GlobalAIHubPythonCourse | /Final_Project.py | 954 | 3.75 | 4 | class Employees():
def __init__(self, Name, Age):
self.name = Name
self.age = Age
self.language = set({})
def addLanguage(self,languageList):
self.language.add(languageList)
def showInfo(self):
for i in self.language:
print(i)
class Manager... |
ff3609ef6ac4a6b9042a2d3980e64e9f33363bb9 | surbhimadan1995/deep_learning_final | /model/batch.py | 8,175 | 4.03125 | 4 | '''
Steps to read in file with one review per line (i.e one document per line)
- Remove HTML markup
- Break list of docs into list of sentences and each sentence into list of words
- Map any numeric token in text to 'NUMBER'
- Map any symbol token that is not .!? to 'SYMBOL'
- Map any < 5 frequency word token to 'UNKN... |
23e3a1fe6d1df0f4679ff7a5e90d78770a4f4828 | hazemy/cuboid_detection | /annot_utils.py | 1,054 | 3.578125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
from PIL import Image
def convert2jpg(images_dir):
'''
Converts images from png to jpg. Transparent png images are converted to jpg with white background
'''
for filename in os.listdir(images_dir):
if filename.endswith(".png"... |
3cbb76e7840cf244a5549c32ea94c2d71f60901a | skraymond/adventofcode2016 | /day03/src/Triangle.py | 1,097 | 3.8125 | 4 | class Triangle:
def __init__(self, sides):
self.sd1 = int(sides.split()[0].strip())
self.sd2 = int(sides.split()[1].strip())
self.sd3 = int(sides.split()[2].strip())
def isValid(self):
valid = True
if not self.sd1 + self.sd2 > self.sd3:
print "%d + %d < %d" ... |
ddfa85de6554833e9f3be71d283c089a9010c648 | timothy-salazar/geospatial_data | /src/census_crawl.py | 9,231 | 3.734375 | 4 | import urllib
from contextlib import closing
import re
import os
import shutil
import time
from ftplib import FTP
class censusFtp():
"""This class is my first time working with python's ftplib - or ftp
connections programatically at all. It's rough, and it's not pretty, but it
does what it's supposed to d... |
29038099db0f513b7c978ab5bf4edc4e1487f5f7 | liulizhi1996/Artificial-Intelligence | /Experiment 1/agent.py | 7,444 | 3.765625 | 4 | from graphics import *
import random
# width of each grid
GRID_WIDTH = 25
# color list, provided for agent
COLOR = ["blue", "red", "green", "orange"]
class Agent:
"""
An agent locates at position (agent_x, agent_y), drawn on the map using a colored circle.
"""
def __init__(self, pos_x, pos_y):
... |
58f8b2e2f4daf6a8dc371628f85e639b903996d5 | stephaniepham/programming | /les3/3_2.py | 174 | 3.765625 | 4 | leeftijd=eval(input('Enter your age: '))
paspoort=(input('Do you have a passport: '))
if leeftijd >= 18 and paspoort == 'ja':
print('Gefeliciteerd, ' 'je mag stemmen!')
|
afcd9e113bfcae19191606d081fe6dddcc027fec | choikangseok/BackAl | /2884.py | 273 | 3.609375 | 4 | from sys import stdin
user_input = stdin.readline().split()
hour = int(user_input[0])
min = int(user_input[1])
if min < 45 :
hour = hour - 1
min = 60 + min - 45
if hour < 0:
hour =23
else:
min = min - 45
print(str(hour) + " " + str(min))
|
823b31e20c34f688297ea0e17a1120af5d5d0da9 | choikangseok/BackAl | /2920.py | 424 | 3.5 | 4 | from sys import stdin
listN = list(map(int, stdin.readline().split()))
checkpoint= 0
for i in range(8):
if (listN[i+1] == (listN[i]-1)):
checkpoint = 1
elif (listN[i+1] == (listN[i]+1)):
checkpoint = 2
else:
checkpoint = 3
break
if i == 6:
break
if checkpo... |
f94f9b36c9dfffc8b4f49406e04cf96e77840f46 | miguelbernal/ejercicios | /01_minimo_maximo.py | 1,780 | 3.90625 | 4 | # VERSION 3
# Usando substring
while True:
numero = input("Introduzca un número (Vacio=Salir): ")
if numero == "":
break
decena = numero[-2:]
digito_1 = decena[0:1]
rango_1 = digito_1+"0"
rango_2 = digito_1+"9"
print("El mínimo es %s y el máximo %s" % (rango_1,rango_2))
rango_3... |
f15ac0458086a615ecc5467b1a6404ef51f2bac0 | annabelle1999Belcina/sdElective1 | /Annabelle_Belcina_EMDAS.py | 3,218 | 4.28125 | 4 | while True: #infinite
Input = input("Enter equation: ")
equation = [] # Storage for the whole equation.
digit = '' #Storage for the digits as one number.
for i in Input: #Scanning every element inputed.
if i >= '0' and i <=... |
e144fb85701cc202cce531c1721cfe3d9c04e17a | sepi4/algoritmit2 | /hanoiTower.py | 340 | 3.734375 | 4 | siirtoja = 0
def print_move(fr, to):
global siirtoja
siirtoja += 1
# print('move from ' + str(fr) + ' to ' + str(to))
def towers(n, fr, to, spare):
if n == 1:
print_move(fr, to)
else:
towers(n-1, fr, spare, to)
towers(1, fr, to, spare)
towers(n-1, spare, to, fr)
towers(4, "alku", "loppu", "a... |
50f9235779fc7791a2d5ec51dbf216489fa6e156 | knaticat/rosalind_problems | /recurrence.py | 265 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 14 11:05:12 2020
@author: biotik
"""
def fib(n,k):
fibo = [0]
for i in range(1,n+1,1):
if i <= 2: f = 1
else: f = fibo[i-1] + k*fibo[i-2]
fibo.append(f)
return fibo[n]
|
1e35dfd9d79d8d9773583be09f090cb15de514da | Stegallo/adventofcode | /y_2019/common.py | 1,154 | 3.90625 | 4 | import argparse
import importlib
from abc import ABC, abstractmethod
class AoCDay(ABC):
"""
Abstract class Day
"""
@abstractmethod
def __init__(self, day):
self._input_data = load_input(day)
self._preprocess_input()
@abstractmethod
def _preprocess_input(self):
"""... |
aa80754395720ba7f981b61842783d9590d44e3f | Mrmalik01/PythonCode | /quickSort.py | 675 | 3.78125 | 4 | # Author : Khizar Malik
# Date : 22 Oct 2018
def quickSort(A):
quickSortRec(A,0,len(A))
def quickSortRec(A,lo,hi):
if hi-lo <=1:
return
iPivot = partition(A,lo,hi)
quickSortRec(A,lo,iPivot)
quickSortRec(A,iPivot+1,hi)
def partition(A,lo,hi):
pivot = A[lo]
B = [0 for i in r... |
b3554ace99a9f2df79f386fafd19464937d7d4e6 | tapczan666/sql | /homework_03.py | 504 | 4.21875 | 4 | # homework assignment No2 - continued
import sqlite3
with sqlite3.connect("cars.db") as connection:
c = connection.cursor()
# find all car models in the inventory
c.execute("SELECT * FROM inventory")
inventory = c.fetchall()
for car in inventory:
print(car[0], car[1])
print(car[2])
# find all order date... |
8b76b924d8973303ec92b3cb9525eb2cc883a1eb | Lab-Work/bikeshare | /codes/preprocessing_scripts/remove_duplicate_trips.py | 2,662 | 3.5625 | 4 | """
Removes the duplicate trips from the master_trip_list.csv.
From whence did they come? We do not know.
Author: Chase Duncan
Contact: cddunca2@illinois.edu
"""
import csv
from tools import *
"""
CONSTANTS
"""
DATA_DIR = "/Users/chaseduncan/Desktop/capital/data/capital_trip_data/master_trip_list.csv"
"""
DATA STRUC... |
093b447de52dceb9cca161203d7227f26dac4c6f | Lab-Work/bikeshare | /codes/preprocessing_scripts/tools.py | 3,455 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
A few utility methods used by various other files.
Created on Sat May 3 12:33:42 2014
@author: brian
"""
from datetime import datetime
import math
program_start = datetime.now()
#A convenient print statement for long runs - also includes a timestamp at the beginning of the message
#Argum... |
cceb80bd25edc7b1fd11cc55254d42c6214f35bf | santoshketa/Matrix-factorization-from-scratch | /question1.py | 5,560 | 4.15625 | 4 | #
### Utility functions
def zeros_matrix(rows, cols):
"""
Creates a matrix filled with zeros.
rows: the number of rows the matrix
cols: the number of columns the matrix
returns list of lists which is a matrix
"""
M = []
while len(M) < rows:
... |
3468722bd044822a7f85464074bc0a6cdae623bb | prydej/WordCount | /Tracker.py | 712 | 4.1875 | 4 | """
Author: Julian Pryde
Name: Essay Tracker
Purpose: To count the number of words over two letters in a string
Dat: 22MAR16
Input: A String
Output: An integer containing the number of words over 2 letters in input
"""
import sys
# Read String from file
essay_handle = open(sys.argv[1])
essay = essay_handle.read()
essa... |
c5d088c46afe6c9090d9afe34338191178dc69fc | raj-andy1/my-python-doodle | /my-python-practice/russian.py | 604 | 3.640625 | 4 | # russian peasants algorithm
import time
def russian_algo(num1, num2):
table = {}
total = 0
while num1 != 0:
table[num1] = num2
num1 = num1 // 2
num2 = num2 * 2
for key in list(table):
if (key % 2) == 0:
del table[key]
return sum(table.values())
def te... |
b1f6b0de924ca2b7509c8cd23662e43a3b56c0d6 | Terrance88/Skogestad-Python | /Example_3.9.py | 1,186 | 3.96875 | 4 | import numpy as np
"""Blending process: mix sugar (u1) and water (u2) to
control amount (y1 = F) and sugar fraction(y2 = x) in a soft drink"""
#y = G*u
#After linearization the equations become:
"""y1 = u1+u2
y2 = (1-x*)/(F*)u1 - (x*/F*)u2
given that at steady-state
x* = 0.2
F* = 2 kg/s"""
#therefo... |
9a5b0be919f0966157df2da90a041a0a2756858c | jongwony/hackerrank | /algorithms/implementation/bon_appétit.py | 331 | 3.640625 | 4 | """
https://www.hackerrank.com/challenges/bon-appetit/problem?h_r=next-challenge&h_v=zen
Anna Brian sharing meal, split the bill equally
Anna allergic -> won't pay
:return: refund pay
"""
def bonAppetit(bill, k, b):
bill.pop(k)
if sum(bill) / 2 == b:
print('Bon Appetit')
else:
print(b - s... |
9392c695883572c666e556b16d4d8046a3e3380b | qiminghui/python | /python/fuduji.py | 126 | 3.671875 | 4 | a = input("the add number:")
b = int(input("how much"))
res = 0
for i in range(b):
res += int(a)
a += a[0]
print(res) |
86e237575d601d1a4ed1d93ce0bccf4a6bfe90f2 | jeffsharris/scramblesquares | /hummingbird_solver.py | 4,289 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
maxPosition = 0
totalPositions = 0
birdNames = {1: "Green head", 2: "Red head", 3: "Blue head", 4: "Spotted head", 5: "Spotted tail", 6: "Blue tail", 7: "Red tail", 8: "Green tail"}
class Tile:
def __init__(self, side1, side2, side3, side4):
self.sides = []
... |
6f7ab28ffcd006024d1e9aee3e8be38a8a5ec886 | Harrolee/misc-work-n-tools | /Quantiphi/stars.py | 390 | 3.859375 | 4 | #takes a max and a min
def print_waveform(max, min):
star = '*'
#print max to 1 stars descending
for i in range(max,min - 1,-1):
print(star * i)
#print 1-max stars ascending
for i in range(min + 1, max + 1):
print(star * i)
if __name__ == "__main__" :
max = input("type ma... |
7320d3096bbd109d65831a9a9d70f82a2135be8f | miha-pavel/hillel_python_base | /Lecture-10_OOP/OOP.py | 12,359 | 4 | 4 | # # Создаем класс Car
# class CarMercedez:
# # создаем атрибуты класса
# name = "c200" # Все экземпляры этого класса будут иметь атрибут arg, равный "Python" Но впоследствии мы его можем изменить
# make = "mercedez"
# model = 2008
# # создаем методы класса
# def start(self): # self - ... |
2527038fa431876a737ed6a238622f6f082aa468 | miha-pavel/hillel_python_base | /Lecture-7/set_code.py | 9,568 | 3.890625 | 4 | # set_ = {1,2,3,4,5}
# print('set_: ', set_)
# print('type(set_): ', type(set_))
# dict_ = {}
# set_1 = set()
# print('set_1: ', set_1)
# print('type(set_1): ', type(set_1))
# Удаление дупликации
# fruits = ["apple", "banana", "cherry", "apple", "cherry", "apple"]
# print(fruits)
# set_fr = set(fruits)
# new_list = ... |
450bbf2388c493179d495997080c3bc358a107cf | deisler134/euler_code | /prime.py | 395 | 3.984375 | 4 | def check_prime(n:int)->bool:
if n < 1:
return False
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i*i <= n:
if n % i == 0 or n % (i+2) == 0:
return False
i += 6
return True
if __name__ == "__main__":
n = 104743
if check_prime(n): print('{... |
90e7f2fa195903339c17739eb2b79645fc094aa0 | hz7/queue-simulation | /QueueSim.py | 8,057 | 3.734375 | 4 | #!/usr/bin/env python
"""
usage: QueueSim input_file output_file
input_file is path for json formated file specifying these simulation parameters:
nservers - number of servers
capacity - line capacity, customer leaves if line size exceed capacity, can be infinite
arrival_rate - inter-arrivals times are exponential wi... |
685b403c2206bacaf1fefa828a311751ad19e05b | liufubin-git/python | /public_method/indicator_calculation_method/kurtosis.py | 1,985 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
@Time : 2020/11/14 16:59
@Author : liufubin
@FileName: kurtosis.py
@description: 峰度计算
"""
import numpy
import pandas
from public_method.indicator_calculation_method.standard_deviation import StandardDeviation
class Kurtosis(object):
@staticmethod
def kurtosis(month_fund_yield)... |
ed8ee248a18b06e7aa80ff5c79a0d28739771634 | 009shanshukla/multithreading_multiprocessing | /multithreading.py | 789 | 3.765625 | 4 | import time
import threading
def square(num):
print("cal sq num")
for i in num:
time.sleep(0.2) #C.P.U will be no more in idle state
print("sq =",i*i)
def cube(num):
print("cal cube num")
for i in num:
time.sleep(0.2) #C.P.U will be no more in idle state
print("cu =",i*i*i)
arr=[1,2,... |
afcb41d5a8161d204bb6668f12553a374eb61b7b | readytoashare/APSSDC-Django-Batch-1 | /Day-3/cons.py | 460 | 3.703125 | 4 | class Student:
def __init__(f2,a,b):
print("i am From Construtor method")
f2.a=a
f2.b=b
def add(f1):
c=30
d=40
print("Addition of {} and {} is {}".format(f1.a,f1.b,f1.a+f1.b))... |
ebdacd39cadd67b8f37987f555e3de39e232d59a | mmadymarov/python-ci-cd | /mock_objects.py | 3,249 | 3.765625 | 4 | """
Writing test double classes can become tedious pretty quickly, because
you often require one class per method called in the test, and all of
these classes must be set up to correctly chain their responses. If you
write multiple test scenarios, you either have to make the test doubles
generic enough to cover several... |
88729212ca32c3b818a0dfa98ce356d8e4b6a1a6 | markwingerd/spool | /merc.py | 5,804 | 3.515625 | 4 | from gmech import Gmech
class Merc:
""""""
def __init__(self, gmech):
"""Initialize Merc variables."""
self.gmech = gmech
self.points = 0
self.this_weeks_pool = 0
self.pool = 0
self.history = []
# Variables to store and display stats
self.weekly_o... |
d140e80177d2ef30ac754342fead193f42fb4507 | AkashKedari/py-projects | /Object-Oriented-Programming/my_functions.py | 7,401 | 4.25 | 4 | # Akash Kedari
# Object Oriented Programming - section 01 - Project
def horizontal_line (width , string):
return(width * string)
def vertical_line(shift,height,string):
vert_line = str()
for a in range(height):
vert_line += " " * shift + string + '\n'
return vert_line
def t... |
57b89b59e46d03e357c9dc16aa9561111710c1ff | lshinkuro/praxis-academy | /novice/minggu_1/hari-2/latihan/tugas_hitung_total_bayar.py | 698 | 3.890625 | 4 | ''' buatlah program untuk:
1.menampilkan total pembayaran
2.untuk menampilkan kembalian
'''
n = int(input("masukan berapa jumlah item yang dibeli :"))
nilai =[]
jumlah_total=0
for i in range(0,int(n)):
tmp=int(input("masukan harga barang ke %d:"%(i+1)))
nilai.append(int(tmp)) #ngubah file yang... |
fa70e49dde2839dd087979d0bdcf3d099a101a0d | kvembar/Advent_Of_Code_2020 | /Day15.py | 969 | 3.8125 | 4 | #Rambunctious Recitation (AOC Day 15)
#Keshav V.
order = [0,5,4,1,10,14,7] #My input, for the first time NOT IN A SEPARATE FILE!
index = 6 #Current number to analyze
first_occurences = {} #The latest occurence of a number and where it is.
for ind, i in enumerate(order):
first_occurences[i] = ind #Takes in occure... |
8c3088094f9ec90c337a4d9131d25155494ec288 | kvembar/Advent_Of_Code_2020 | /Day16.py | 5,027 | 3.6875 | 4 | # Ticket Translation (AOC Day 16)
# Keshav V.
# Note: This one was pretty fun! It took me a while to solve it, but this was actually interesting!
import re #RETURN OF THE REGEX
#Part 1
with open("Day_16_input.txt","r") as f: #This with function is the first one in a while to have the parsing be done in it.
valid ... |
edcca49ecfa055c024bac44ac695f9bcdaa47490 | newfacade/machine-learning-notes | /_build/jupyter_execute/02_linear_regression.py | 13,706 | 3.890625 | 4 | # Linear Regression
## Model
given a dataset $\left \{ (x^{(1)},y^{(1)}),...,(x^{(n)},y^{(n)}) \right \} $, where $x^{(i)} \in \mathbb{R}^{d},\ y^{(i)} \in \mathbb{R}$.
linear regression is trying to model $y^{(i)}$ from $x^{(i)}$ by a linear model:
$$h_{\theta}(x^{(i)}) = \theta_{0} + \theta_{1}x_{1}^{(i)} + \thet... |
d4049bd772c828c35e05c5fc6744a96f7ddb8362 | lookinfuu/homework6 | /6.1-3_XOR_WITH_AS.py | 2,130 | 3.53125 | 4 | import random
import string
def key(text):
key = input("Введите ключ (Enter - ключ будет создан автоматически):")
if not key:
key = "".join(random.choice(string.digits + string.ascii_letters) for i in range(random.randint(1, len(text))))
print(f"Ключ был создан автоматически:{key}")
key = b... |
41b36ecd4074063d9619c0beb07484323f4d81c1 | Eric-J-G/Eric-J-G | /Mav101 Daily Work 6.5.py | 614 | 3.8125 | 4 | droid_num = int(input("How many droids did you buy? "))
x = input("Week: ")
droids = list(range(1, droid_num + 1))
a = 0
n = 0
m = 1
j = 1
for x in range(droid_num):
droids[n] = float(input(f"Price of Droid {j}: "))
n += 1
j += 1
total = sum(droids)
avr = total/droid_num
with open("Droid_... |
9296eb6aadf1fac64fcbfd92b052079898432245 | Eric-J-G/Eric-J-G | /Number Guessing Game.py | 749 | 3.953125 | 4 | import random
low = random.randint(1, 500)
high = random.randint(501,1000)
print(f"Pick a number between {low} and {high}. Press Enter to continue")
input()
yn = 0
while yn != "yes":
guess = random.randrange(low, high, 1)
while True:
print(f'Is your number {guess}? ')
yn = input()
... |
774b91883f0ef764b09328fea23a937c93eb0f3f | Eric-J-G/Eric-J-G | /Mav101 Daily Work 3.2.py | 172 | 4.09375 | 4 | def sum_of(n):
return sum(range(0, int(n) + 1))
print("The sum of all positive integers up to that point is: " + str(sum_of(int(input("Please input a number: "))))) |
94e5b134cc8f72d02fba0f7d0bb8787314782816 | TomCC7/learning | /ComputerNetworking/2/httpServer.py | 2,044 | 3.921875 | 4 | """
Description: 我来写个小http服务器2333
Author: C.C
Date: May 5 2020
"""
from socket import *
class Server():
def __init__(self, port=12001):
self.port = port
self.socket = socket(AF_INET, SOCK_STREAM)
try:
self.socket.bind(('0.0.0.0', self.port))
except OSError:
... |
44473c6405aaa3b116b39c9887e9dd7c53413b1f | Luciano-Grilli/ejercicios-python-del-curso-seguido | /excepciones.py | 915 | 4.125 | 4 | import math
try: #acortar decimales
num1 = int(input("Ingrese un numero: "))
num2 = int(input("Ingrese otro numero: "))
print("resultado de la division es:","{0:.2f}".format(num1/num2))
except ZeroDivisionError:#al lado se puede poner el tipo de error o no y que respond... |
ee918e978a2599fce1beccd95786c218e6b49d59 | Luciano-Grilli/ejercicios-python-del-curso-seguido | /Condicionales II.py | 269 | 3.875 | 4 | print("Verificar edad")
#lower(),upper() minusculas o mayusculas
edad=int(input("Ingrese su edad:"))
if edad > 100 or edad <= 0:
print("edad incorrecta")
elif edad < 18:
print("No puede pasar")
else:
print("puedes pasar")
print("finalizado")
|
6199c577d8e6bef67694d770bded9339a9293ac4 | AzwadRafique/Azwad | /Whacky sentences.py | 602 | 4.3125 | 4 | import random
adj = input("Insert an adjective ")
noun = input("Insert a noun ")
verb = input("Insert a verb ending with 'ing' ")
if verb.count('ing') == 0:
verb = False
while verb == False:
verb = input("Please insert a verb ending with 'ing' ")
sentences = [f"Our house has {adj} furniture and th... |
d2b105a85201dc8c909dc6c53854c9dfbe04252e | AzwadRafique/Azwad | /Emailsv.py | 1,536 | 4.21875 | 4 |
while 1 == 1:
number_emails = {
'manha@gmail.com': '12345',
'jack@gmail.com': '124567'
}
login_or_sign_in = input('login or sign in: ')
if login_or_sign_in.upper() == 'LOGIN':
email = input('what is your email: ')
if email in number_emails:
password... |
f7a38ebdb08959d53822840c6e2cd596912b3b8e | joaovicmendes/ioca-trabalho | /Trabalho 2/src/solver.py | 5,668 | 3.5625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Universidade Federal de São Carlos – UFSCar
# Departamento de Computação
# Introdução a Otimização Combinatória Aplicada – Trabalho 2
# Prof. Dr. Mário César San Felice
# Aluno: João Victor Mendes Freire
# RA: 758943
# Baseado em https://gurobi.github.io/modeling-examples/f... |
d52abe68346ca38568c98102ac8460451f0cd3c8 | Code360In/IBM | /Day01/trans_lists.py | 4,137 | 3.53125 | 4 | Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> # Lists
>>> L = ['red', 'green', 'blue']
>>> type(L)
<class 'list'>
>>> L1 = ['cyan', 'magenta', 'black']
>>> # Operators
>>> L + L1
['red', ... |
9e8f5898b35641656ceb08158ef24ba0dd1f8130 | tarunmishra007/send-a-message | /shape.py | 457 | 3.828125 | 4 | import turtle
def draw_square(obj):
for i in range(4):
obj.forward(100)
obj.right(90)
def draw_shapes():
turtle.bgcolor("red")
brad=turtle.Turtle()
brad.shape("turtle")
brad.color("yellow")
brad.speed(2)
for i in range(36):
draw_square(brad)
brad.right(10)
... |
62c4537088528385610307fd483d9df1be90aa2f | camilleb03/card-games | /games/card_game/card_game.py | 941 | 3.859375 | 4 | class CardGame:
"""
Represents a card game
"""
MAX_PLAYERS = None
GAME_NAME = None
deck = None
def __init__(self):
self.player_names = []
self.hands = []
if self.MAX_PLAYERS == None:
raise NotImplementedError('Subclasses of CarGame must define MAX_PL... |
f71bbcf1d8f46d704d2d6362285ce4b311f50d1a | DanielMarquesz/AD1_FP | /teste_q1.py | 557 | 3.515625 | 4 |
lista = ['gol','47P','a','futebol','laranja','8 x9','13 XL','ou','Juca 2','ué','Aaaaá']
tamanho = []
for i in range(len(lista)): # Número de Dígitos
string = lista[i]
total = 0
for ch in lista[i]: # transformar essa parte em uma função
if ch.isdigit():
total += 1
stringAt ... |
2544749d85f8f5e358d0be6cd4ffbaf5dbea78c9 | rhogan29/SQL | /notes.py | 3,664 | 3.96875 | 4 | # import sqlite3
import sqlite3
#import Notes and Author class from other files
from note import Note
from author import Author
##connect to a database. If one doesnt exist,
#this creates a new one. If it already does,
#this will just connect to it.
conn = sqlite3.connect('notes.db')
#instead of setting a file nam... |
136c41ab474e89fe5d0e6b848bd32169b09b00ff | David-Matos-Correia/Code-for-Discord-bot | /bot_discord.py | 660 | 3.65625 | 4 | import discord
#required to the library asyncio
import asyncio
#Your bot's token
#create a .txt file with your bot's token, and place it together where the .py file is
#the token is purchased from the Discord developer portal
def read_token():
with open("token.txt", "r") as f:
lines = f.readlines(... |
235280cd1e6221e270a8bd16633780b91342fa0c | basdawimp/RPG-Gmae-Maker | /main.py | 2,968 | 3.609375 | 4 | from room import Room
from item import Item
from character import Enemy
from rpginfo import RPGInfo
#Create Game
spooky_castle = RPGInfo("The Spooky Castle")
RPGInfo.author = "Me"
#Creat the rooms
kitchen = Room("Kitchen")
ballroom = Room("Ballroom")
dining_hall = Room("Dining Hall")
#Create items
ball = Item("ball"... |
f80e43489e02ba0c2ad7853c76cb903c51883f99 | FutureRiotEmployee/Text-RPG-Project | /town.py | 3,904 | 3.984375 | 4 | char = {'name':'Hero',
'class':'Unassigned',
'lvl': 1,
'xp': 0,
'lvlNext': 25,
'turn':True,
'gold':100,
'potions':{'health': 2,
'strength': 3},
'events':{'casinoTutorial':False,
'fillerTutorial':False},
... |
d7809acfafad848ed6a689bf1afe2d96b2bccbe6 | Python-lab-cycle/Najmalfawaz | /area of circle.py | 111 | 4.125 | 4 | #area of a circle
import math
r=float(input("Enter the radius"))
area=math.pi*r**2
print("area =",area)
|
88560fae6e205390be6ef0e5f66132efe9d9b713 | Gummi354/Tile_Traveler | /tile_traveller.py | 4,101 | 4.1875 | 4 | # Constants
NORTH = 'n'
EAST = 'e'
SOUTH = 's'
WEST = 'w'
import random
def move(direction, col, row, move_counter):
''' Returns updated col, row given the direction '''
move_counter += 1
if direction == NORTH:
row += 1
elif direction == SOUTH:
row -= 1
elif direction == EAST:
... |
f9c65b83f7e205de2bce0641ef59c4304a4d4c09 | johnjdailey/lambdata-johnjdailey | /test/rectangles_test.py | 715 | 3.859375 | 4 | # test/rectangles_test.py
import unittest
# assume this function exists in buyholdsell/rectangles.py
def calc_area(l, w):
"""
Params: l and w are both real positive numbers representing the length and width of a rect
"""
if l <= 0 or w <= 0:
raise ValueError
return l * w
class TestRectan... |
4faa53f12c19156542233750630a64aa75d4e79c | johnjdailey/lambdata-johnjdailey | /test/assignment_test.py | 891 | 3.671875 | 4 | # test/assignment_test.py
import unittest
from pandas import DataFrame
from buyholdsell.assignment import add_state_names
# OBJECTIVE: test the add_state_names() function from the buyholdsell/assignment.py file
class TestAssignment(unittest.TestCase):
def test_add_state_names(self):
# expect that ... |
f8d7e8a10d9c24e6cbe8c1a5335063b795449fa1 | ECastro10/CLI_Quest | /game.py | 8,889 | 3.890625 | 4 | from Character import Character
from Move import move_list
import random as r
def gen_stats(person):
'''
INPUT: takes person objects stat attributes which equal 0
USAGE: to randomly generate stats within limits
OUTPUT: none
'''
person.maxhp = r.randint(14, 18)
person.hp = per... |
bb6185e70e4112a8faffc2462c16e9da176065aa | futurewei/cs61a | /projects/hog/hog.py | 14,165 | 4.125 | 4 | """The Game of Hog."""
from dice import four_sided, six_sided, make_test_dice
from ucb import main, trace, log_current_line, interact
GOAL_SCORE = 100 # The goal of Hog is to score 100 points.
######################
# Phase 1: Simulator #
######################
def roll_dice(num_rolls, dice=six_sided):
"""Si... |
1604ef637cfb038fb81c5f2cec09793d74511879 | dimamik/AGH_Algorithms_and_data_structures | /PRACTISE/CWICZENIA/04_29_Shortest_Path/Online/Zad_8.py | 1,011 | 3.71875 | 4 | """
Implementacja na listach incydencji, wykorzystuje krotki postaci:
(DISTANCE,INDEX,WAGA)
"""
def LS_Krotki_graph_init(V,E):
"""
Inicjalizacja grafu z krotkami
Zwraca graph
"""
graph=[[] for _ in range(V)]
for i in range(E):
x,y,w=map(int,input().strip().split())
... |
e861813a5b4548f6978affa50a69f9d7017a718e | dimamik/AGH_Algorithms_and_data_structures | /PRACTISE/LATO_FOR_EXAM/Hackerrank/Others/Time_Convertion.py | 357 | 3.84375 | 4 | def timeConversion(s):
#
# Write your code here.
#
if (s[:2]=="12" ):
if ( s[8:10]=="AM"):
return "00" + s[2:8]
else: return s[:8]
if s[8:10]==("PM"):
time = int(s[:2])
time+=12
s = str(time) + s[2:8]
return s
else:
return s[:8]... |
b2d4628c07f82cbcc304291e2e3838ddf70a52bf | dimamik/AGH_Algorithms_and_data_structures | /Bit_Algo/03_23 Dynamiczne/Zad_3.py | 777 | 3.734375 | 4 | """ Dostajemy listę wartości. Gramy z drugim graczem. Wybieramy zawsze jedną wartość z jednego z
końców tablicy i dodajemy do swojej sumy, a następnie to samo robi nasz przeciwnik. Zakładając, że
przeciwnik gra optymalnie, jaką maksymalną sumę możemy uzbierać?
“Uogólniony problem paczki mentosów” """
def mentos(a... |
5e01ca5bf89fe158c4990b5b4268d470ac8db2d2 | dimamik/AGH_Algorithms_and_data_structures | /Sorting arrays/Geekforgeeks_problems/Zad_11_Number_Of_Pairs_that.py | 3,054 | 4.125 | 4 | """
Given two arrays X[] and Y[] of positive integers, find number of pairs such that x^y > y^x where x is an element from X[] and y is an element from Y[].
"""
"""
NOT MINE!!!
The problem can be solved in O(nLogn + mLogn) time. The trick here is, if y > x then x^y > y^x with some exceptions.
Following are simpl... |
6c9206bfa76a68e10d1699dfeba09c071a5d9560 | dimamik/AGH_Algorithms_and_data_structures | /Graphs_new/DFS/Mosts.py | 9,159 | 4.15625 | 4 | class graph:
def __init__(self, repr,is_Matrix,is_weighted=False ):
"""
A graph class to represent graph using known structures\n
is_Matrix==True:
We have A Matrix n*n with a M[i][j] - weight of edge from i to j,
or 0 in case of no vertex
For Example... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.