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 |
|---|---|---|---|---|---|---|
49dadd18e4e305d2eda16336c2bc495ffecb91ce | destinyson7/terminal-based-chess-emulator | /board.py | 1,594 | 3.703125 | 4 | from piece import Piece
class Board:
def __init__(self):
self.board = []
for i in range(8):
temp = []
for j in range(8):
temp.append(Piece('a1', 'abc'))
self.board.append(list(temp))
def disp(self):
check = 1
strf = ' '
... |
f6457593cc9db9d9db149102a50275f26f1dc34f | steinwurf/waf | /src/wurf/url_download.py | 2,292 | 3.625 | 4 | #! /usr/bin/env python
# encoding: utf-8
import cgi
import os
from .compat import IS_PY2
if IS_PY2:
# Python 2
from urllib2 import urlopen
from urlparse import urlparse
else:
# Python 3
from urllib.request import urlopen
from urllib.parse import urlparse
class UrlDownload(object):
def... |
049cc9ac58ea78c50dbb4d17d268c56ea867098d | jbester/python-util | /fnutil.py | 1,962 | 3.59375 | 4 | from typing import Any, Callable
from .symbols import symbol
def compose(outer_fun: Callable, inner_fun: Callable):
"""Compose two functinos
:param outer_fun: function takes result of innerfunction as parameter
and provides return value of the composed function
:param inner_fun: function takes paramt... |
dcbb15a887f7d028d2475a53f3ef9c35ecd61c2a | grihabor/start-python | /rus/elementary/05_list.py | 6,297 | 4.03125 | 4 | """
Краткое содержание
list(), [] - создание списка
len() - длина списка
list[] - обращение к элементам списка
list.append() - добавление элемента в конец
list.extend() - расширить первый список элементами второго
str.split() - разбить строку на список подстрок
"""
### list(), []
# Для хранения большого количества д... |
dcbc317b038e0ad0cb9614c21b7cb89b118e3778 | mine1984/Advent-of-code | /2015/day21/day21ab.py | 5,016 | 3.546875 | 4 | # In this game, the player (you) and the enemy (the boss) take turns attacking. The player always goes first. Each attack reduces the opponent's hit points by at least 1. The first character at or below 0 hit points loses.
# Damage dealt by an attacker each turn is equal to the attacker's damage score minus the defende... |
0b4d27af46b970681bc3cfa835cac2382f27baa4 | mine1984/Advent-of-code | /2015/day14/day14b.py | 1,960 | 3.875 | 4 | # Reindeer can fly at high speeds, but must rest occasionally to recover their energy. Santa would like to know which of his reindeer is fastest, and so he has them race.
# Reindeer can only either be flying (always at their top speed) or resting (not moving at all), and always spend whole seconds in either state.
#
# ... |
27e7222fb66d90849f97f8c1077833420eb2e3d3 | mine1984/Advent-of-code | /2015/day19/day19a.py | 2,323 | 3.96875 | 4 | # The North Pole is equipped with a Red-Nosed Reindeer nuclear fusion/fission plant, capable of constructing any Red-Nosed Reindeer molecule you need. It works by starting with some input molecule and then doing a series of replacements, one per step, until it has the right molecule.
# However, the machine has to be ca... |
12425d6d2936eb685205b19f46249a342c7af38f | mine1984/Advent-of-code | /2015/day09/day09ab.py | 2,371 | 3.90625 | 4 | # This year, however, he has some new locations to visit; his elves have provided him the distances between every pair of locations. He can start and end at any two (different) locations he wants, but he must visit each location exactly once.
#
# What is the shortest distance he can travel to achieve this?
#
# What is ... |
478bd044e73046c891620bfc871e426948116c38 | danielj32/holbertonschool-interview | /0x00-lockboxes/0-lockboxes.py | 514 | 3.75 | 4 | #!/usr/bin/python3
"""unlock boxes """
def canUnlockAll(boxes):
"""
method that determines if all the boxes can be opened
* boxes is a list of lists
* A key with the same number as a box opens that box
"""
for key in range(1, len(boxes) - 1):
validation = False
for idx in range... |
fbd6a1670fd7fb547a88eaf03699e34503658b56 | omlean/mini-project-london | /trip-planner.py | 2,545 | 3.625 | 4 | """
A little console program to plan bus and tube trips
in London
"""
import requests as re
import tfl_env as env
app_id = env.PRIMARY_KEY
app_key = env.SECONDARY_KEY
def main():
response = None
while True:
if response is None:
start = input("Enter the start location: ")
en... |
c62b48836ffbe4c20404677fc3f842b1eff75c5d | XintoMax/HelloWorld | /GuessTheNumber.py | 2,212 | 3.90625 | 4 | import random
a = (random.randrange(1, 50))
b = (random.randrange(1, 50))
attempts_left = 3
attempts = 1
print(a, b)
print("")
while True:
print("I am thinking of 2 numbers between 1 and 50...")
a2, b2 = int(input("a: ")), int(input("b: "))
if a2 == a and b2 == b:
print("Good Job!")
... |
de82d212208cf49b21a6ed758586e0d95d33ebf3 | XintoMax/HelloWorld | /LoginSystem.py | 1,620 | 4.0625 | 4 | while True:
login = input("Login or Register? ").lower()
login_data = []
if login == 'register' or login == 'r':
first_name = input("First Name: ").capitalize()
last_name = input("Last Name: ").capitalize()
print("-----------------")
username = input("Please provide Us... |
db51bb8a52d961d5451e04362c694998d1b8d452 | XintoMax/HelloWorld | /8Ball.py | 809 | 3.796875 | 4 | from tkinter import *
import random
answer_choices = ["Yes", "Probably not", "Maybe", "Absolutely", "Nope", "Ask me tomorrow"]
root = Tk()
root.title("Magic 8Ball -TF")
root.geometry("300x150")
def eight_ball_reply():
ran_ans = random.choice(answer_choices)
x = question.get()
if "?" in x:
... |
27669425b0e2759e8ddb9bd4575dfc1ad8fe90c7 | TaureanRoberts/AIForGames | /drawing_util.py | 4,360 | 3.78125 | 4 | import math
import pygame
from vector2_class import Vector2
class Shape(object):
'''Base class for drawing all shapes'''
def __init__(self, pos, col, surface):
self.position = pos
self.color = col
self.draw_surface = surface
self.pygame_object = None
def change_color(self, ... |
e07dda4d5e46355a672a563cff0aeeb4db33ec7b | colindmurray/Cointracker | /cointracker/connect.py | 3,730 | 3.5 | 4 | import psycopg2
from psycopg2.extras import execute_batch
from config.config import config
def insert_row(table_name, data):
"""
connect to the database server and inserts data as row in table for db
Args:
table_name(str): the table having the row of data inserted into
data (dictionary): a ... |
dd3cc3546705ccd3726de5d9573c081719c0ded4 | Holmaren/CryptoPartA | /part1_crypto.py | 2,183 | 4.03125 | 4 | # COMP90043 Cryptography and Security
# Cryptography Skeleton Function for Project
#
# Candidates will have to implement the following skeleton functions.
# Candidates may create additional skeleton functions by importing the skeleton functions from a seperate file.
# Do not alter the function declarations in this ... |
4ef3d8f3e5002a6ec37472b4d6812c355b0c495b | SaketZode/Python-basic-learning | /OOP_Concepts/exception_handling.py | 229 | 3.6875 | 4 | a = 10
b = 'asd'
try:
res = a/b
except ZeroDivisionError:
print("divide by zero error")
except TypeError:
print("invalid data types")
except BaseException:
print("something went wrong")
finally:
print("bye")
|
1761deff9e04bab9e770abfc863772c08a170f34 | SaketZode/Python-basic-learning | /General/variable_length_args.py | 436 | 3.734375 | 4 | def sum(*nums):
sum = 0
for i in nums:
sum += i
return sum
print(sum(1, 2, 3, 4, 5))
print(sum(45, 67, 23))
def person(name, age, city):
print("Name : ", name)
print("Age : ", age)
print("City : ", city)
person(name='saket', city='Bangalore', age=23)
def human(name, **data):
... |
3d11597d4aeb54f624b3b6571a39e28ef52584e0 | Dlmss/NN | /math_util.py | 1,139 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 19 19:50:07 2017
@author: Ewan
"""
import numpy as np
def relu(Z):
"""
Implement the ReLU function
@param Z -- matrix of the output of the linear part
@return A -- the result of the ReLU function applied on Z
""... |
6f868f9f5c23474d617e25ad64e4983c3db25392 | ApoorvaCh/Performance-based-incentive-policy-using-Python | /incentive.py | 11,730 | 3.703125 | 4 | # importing libraries
import pandas as pd
import numpy as np
amount_s=input('How much amount should be paid to the faculty for 1 mark of score: ')
#reading file
sample=input("Enter Academic result file location:")
data=pd.read_excel(sample)
#handling missing values
data.fillna('xxx', inplace=True)
temp=''
for i in r... |
11de0e4d856d39d723f424f6e87aa1f1161cf444 | jlblancopastor/misc_python | /bin/COMPUTE/split_fasta_to_two_GBS.py | 1,354 | 3.515625 | 4 | #!/usr/bin/env python
"""
Name: split_fasta_to_two.py
Author: Michael G. Harvey
Date: 14 October 2013
Description: split fasta files into two to separate trans- and cis-Andean individuals for separate
analyses in COMPUTE
"""
import os
import sys
import argparse
from Bio import AlignIO
def get_args():
parser =... |
6c4890211950152c5aec3572ebe3d578e47a55c6 | jsilber17/Predicting-Car-Prices-Using-Scrapy-Selenium | /scraper_project/carfax/carfax/spiders/craigslist_crawl.py | 4,517 | 3.5 | 4 | import requests
import csv
import pandas as pd
import scrapy
from scrapy.http import Request
from scrapy import Selector
class AutoListSpider(scrapy.Spider):
name = 'craigslist'
cities = ['newyork' ,'chicago', 'losangeles', 'denver', 'rochester', 'seattle',
'madison', 'portland', 'at... |
753ecfdef342ed94ae28474a9dcaa4f74940bc56 | suzusu/intro-info | /td4.py | 967 | 3.609375 | 4 | # Exercice 1 : Afficher les nombres paires entre 0 et 30.
X = 0
for compteur in range(16):
print(X)
X = X + 2
# Exercice 2 : Afficher en ordre décroissant les nombres de 10 à 1.
x = 10
while x != 0:
print(x)
x = x - 1
# Exercice 3 : Calculer 1 x 2 x 3 x 4 x 5 x 6 avec une boucle.
y = 1
for x in ran... |
76a065b1a4d65edce9b4b59843b37379ccd7ef16 | jeanilieski/Jupyter-Notebook | /1. Loops/read write a file.py | 645 | 3.640625 | 4 | #read write a file
import csv
from csv import DictReader
value=('the answer', 42)
print value
s=str(value)
print s
#f.write(s)
for sth in s:
print sth
f=open('csv1.csv')
r=csv.DictReader(f)#r = csv.DictReader(f) or r=csv.reader(f)
for sth in r:
print sth
print '********************'
d... |
1c39974603ee76e31ce0b21a08ffe3e91a6f6a8d | wsmorgan/LatticeVisualizationTools | /src/surface_structs.py | 13,086 | 3.578125 | 4 | import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.cm as cm
import math as mt
from itertools import product
"""
This program is meant to be able to take a set of lattice vectors
for the most commonlattices, sc, fcc, hcp, bcc, and retur a picture
with the desired surface, eg (100), (110), (111),... |
0d02725116a334c8cb5f2d75f2722386391bf174 | KhoraLee/univProjects | /1st Year (2020)/Python/Assign2-06.py | 388 | 3.59375 | 4 | def findMax(a):
keyset = set(a)
freqdict = dict()
for i in a:
freqdict[i] = a.count(i)
sort = sorted(freqdict.items(),key=lambda i: i[1],reverse=True)
cur = sort[0][1]
max_value = sort[0][0]
for k, v in sort:
if v !=cur:
break
if max_value < k:
max_value = k
return max_value
a1=[1,2,3,4,3,5,2,5,3... |
4730289115061d042431fcf056f3b47901c6e7b0 | niteya-shah/Web-Mining | /crawler/json_work_library.py | 340 | 3.59375 | 4 | """
Libraries used to store and retrieve data
Uses the json format for simplicity
"""
def store_list(filename,file):
import json
with open(filename, 'w') as filehandle:
json.dump(file, filehandle)
def retreive_list(filename):
import json
with open(filename, 'r') as filehandle:
return js... |
0991d680c4b08cfdc6df6969cd01bf17438fc200 | DylanMeeus/PythonPlayground | /AdventOfCode/5.py | 614 | 3.84375 | 4 | # Problem 5 of advent of code
# find out how many steps it take to escape a list
# "0 3 0 1 -3"
def getInput():
f = open("input5.txt",'r')
inp = f.read()
strNumbers = inp.split("\n")
return list(map(lambda k: int(k), strNumbers[:-1]))
def solve():
print("solving problem")
input = getInput()... |
65054690805e1e06608ad47b230bb979588d6c5a | bgilroy26/AditWorkbook | /lecture_122/enumerator.py | 131 | 3.640625 | 4 | a = [1, 2, 3]
if __name__ == "__main__":
[print("Item " + str(y) + " has index " + str(x)) for x, y in enumerate(a)]
|
e3e5c2bbfe5c902f69d1e641b419d618d2f74789 | bgilroy26/AditWorkbook | /lecture_164/password3.py | 890 | 3.921875 | 4 | import string
import sys
def validate_has_number(user_password):
if any(i.isdigit() for i in user_password):
return True
return False
def validate_has_upper(user_password):
if any(i.isupper() for i in user_password):
return True
return False
def validate_length(user_password):
... |
ef8a2a6135ddd5d1a0594194c671ca6085a72f49 | bgilroy26/AditWorkbook | /lecture_88/vector_add.py | 543 | 3.640625 | 4 | import itertools
import pprint
import sys
def vector_add(*vectors):
#throw error if vector length mismatch
if len(set(map(len, vectors))) != 1:
raise ValueError('vectors are not of equal length')
resultant_vector = map(sum, [(vectors[0][0], vectors[1][0]), (vectors[0][1], vectors[1][1]), (vect... |
745f5841e5604a0b9b8ce712e683cd8922d922f1 | mcgettin/ditOldProgramming | /yr2/sem2/basicPhysics/linearMotion/oldVer.py | 2,584 | 4.03125 | 4 |
import turtle
import math
class Ball(object):
def __init__(self,turt,dX=0,dY=0,vX=0,vY=0,radius=1,sticky=1,forw=True,colour='red'):
self.dX=dX
self.dY=dY
self.vX=vX
self.vY=vY
self.radius=radius
self.colour=colour
self.forward=forw
... |
e6b66f0546dbc49e7c16401c358e33fa34d19724 | mcgettin/ditOldProgramming | /yr2/sem1/py_tests/RomaNum.py | 1,580 | 3.921875 | 4 | #Roman numeral converter
print("Program: Roman Numeral Converter")
print("--------------------------------------------------------\n"\
"M.= 1,000,000 D.= 500,000 C.= 100,000 L.= 50,000\n"\
"X.= 10,000 V.= 5,000\n\n"\
"M = 1,000 D = 500 C = 100 L = 50\n"\
"X = 1... |
d87dd3a0e51d7f889c07f8b1f39307ec3d27846a | mcgettin/ditOldProgramming | /yr2/sem2/solarSys/sphereObj.py | 308 | 3.78125 | 4 | class Sphere(object):
def __init__(self,radius=1,mass=1):
self.radius=radius
self.mass=mass
def __str__(self):
return "This is a generic Sphere:\n radius = {}\n mass = {}\n".format(self.radius,self.mass)
def __repr__(self):
return self.__str__()
|
fdc29dfc4a3a43ddd89df86af1fabe4aa61ef629 | mcgettin/ditOldProgramming | /yr2/sem1/euler/eu4.py | 373 | 3.5625 | 4 | def bigPalin(small,big):
num1=big
num2=big
max=0
while num1 >= small:
while num2 >= small:
if(str(num1*num2)==str(num1*num2)[::-1]):
if(max< num1*num2):
max=num1*num2
num2-=1
num1-=1
num2=big
return max... |
07ae1231801ddaf8f5d1c6771fb1732a89d7d308 | mcgettin/ditOldProgramming | /yr2/sem2/Labs/1_vector/vectorObj.py | 660 | 3.875 | 4 | import math
class Vector(object):
def __init__(self,p1=0,p2=0):
self.x=p1
self.y=p2
def __str__(self):
return "vector: (0,0) , ({},{})".format(self.x,self.y)
def __repr__(self):
return self.__str__()
def __add__(self,vect): #vector+vector
... |
116a118de339f846066ebed7b1ef56033572a3db | JoeCP17/-algorithm-list-string-list-minority | /01_char_array.py | 1,184 | 3.640625 | 4 | # Q.
# 1. 입력으로 소문자의 알파벳 순으로 정렬된 문자열이 입력됩니다.
# 2. 각 알파벳은 중복이 가능합니다.
# 3. 중간에 없는 알파벳이 있을 수도 있습니다.
#
# 입,출력 예시와 같이 입력 문자열에 나타나는
# 각 알파벳의 종류,갯수를 요약하여 나타내시오.
# 문자의 개수를 셀 count 필요
# 들어있는 문자 파악 (sort 정렬 이용)
#
def summarize_string(input_str):
count = 0
same_array = ' '
index = len(input_str)
f... |
669c96051159e28260689b5bee2f33c71e4ef8b6 | SEugene/gb_algo | /hw_07_01.py | 1,128 | 4.1875 | 4 | """
Отсортируйте по убыванию методом "пузырька" одномерный целочисленный массив, заданный случайными числами
на промежутке [-100; 100). Выведите на экран исходный и отсортированный массивы. Сортировка должна быть реализована
в виде функции. По возможности доработайте алгоритм (сделайте его умнее).
"""
from random impor... |
e9aedc4da6ae5bc6f95788ec50247ecd44dc5c62 | johanrosenson/advent-of-code-2016 | /day3/part2.py | 718 | 3.578125 | 4 | # https://adventofcode.com/2016/day/3
import re
lines = open('input').read().splitlines()
valid = 0
def triangles(lines):
triangles = []
stack = [];
for line in lines:
[v1, v2, v3] = [int(v) for v in filter(None, re.split(r'\s+', line))]
stack.append([v1, v2, v3])
if len(stack) ... |
fbf4ebee75de3e235dad631e9184311b26205ca5 | jahirulislammolla/CodeFights | /InterviewPractice/Arrays/isCryptSolution.py | 278 | 3.53125 | 4 | def isCryptSolution(crypt, solution):
a,b={},[]
for x,y in solution:
a[x]=y
for i in crypt:
c=''
for j in i:
c+=a[j]
if c[0]=="0" and len(c)>1:
return 0
b+=[c]
return int(b[0])+int(b[1])==int(b[2])
|
ec9d5610d6c64e2625c30801a948f45a48187ea0 | jahirulislammolla/CodeFights | /Fights/neighboringCells.py | 372 | 3.59375 | 4 | def neighboringCells(matrix):
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if i > 0:
matrix[i][j] += 1
if j > 0:
matrix[i][j] += 1
if j < len(matrix[i])-1:
matrix[i][j] += 1
if i < len(matrix)-1:
... |
c99ded2bf392ffbd2da54e46c9f4230bcfb4f2c4 | jahirulislammolla/CodeFights | /Fights/isDivisibleBy3.py | 182 | 3.90625 | 4 |
def isDivisibleBy3(inputString):
x=inputString.split("*")
y=[]
for i in range(10):
m=str(i).join(x)
if int(m)%3==0:
y.append(m)
return y
|
e8f3cce6afe383ca20da4f18d77e61d3e394ea7e | jahirulislammolla/CodeFights | /Fights/sumUpDigits.py | 103 | 3.5625 | 4 | def sumUpDigits(d):
s=0
for i in d:
if "0"<=i<="9":
s+=int(i)
return s
|
13960705466eb9ceb28358e117d64d0df5d474cd | jahirulislammolla/CodeFights | /Fights/leapYear.py | 131 | 3.71875 | 4 | def leapYear(year):
if year%400==0:
return True
if year%4==0 and year%100!=0:
return True
return False
|
a90bff198cf0a8550d38237142faa134462d911e | jahirulislammolla/CodeFights | /Fights/cyclicSequence1.py | 383 | 3.734375 | 4 | def cyclicSequence(sequence):
found = False
st = -1
for i in range(1, len(sequence)):
if sequence[i - 1] == sequence[i]:
return False
if sequence[i - 1] > sequence[i]:
if found:
return False
found = True
st = i
return st !... |
97cf4d56b78a082d425b02092659b870a0b90e89 | jahirulislammolla/CodeFights | /InterviewPractice/Bits/bitsToFloat.py | 147 | 3.625 | 4 | def bitsToFloat(bits):
intp = int(bits >> 16)
frap = float(bits & 0xFFFF)
while frap >= 1.:
frap /= 10.
return intp + frap
|
e707dad98cb45bed9c62a81f1bba38fba4bcad23 | jahirulislammolla/CodeFights | /Fights/eulersTotientFunction.py | 164 | 3.5 | 4 | from fractions import gcd
def eulersTotientFunction(n):
result=1
for i in range(2,n):
if (gcd(i, n) == 1):
result+=1
return result
|
9ddbb3dee74685b1b3f9997922bad88ee8248a3c | sdpython/mlinsights | /mlinsights/helpers/parameters.py | 1,280 | 3.59375 | 4 | """
@file
@brief Functions about parameters.
"""
import textwrap
def format_value(v):
"""
Formats a value to be included in a string.
@param v a string
@return a string
"""
return ("%r" % v.replace("'", "\\'")
if isinstance(v, str) else f"{v!r}")
d... |
f6847bd11641b37842434616f5ccac863218d239 | wenxy1989/python37-test | /payable.py | 1,454 | 3.796875 | 4 | class Payable:
def __init__(self,count=0,name='Payable'):
self._count = count
self._name = name
def subtract(self,count):
if self._count >= count:
self._count -= count
return True
return False
def plus(self,count):
self._count += count
def add(self,to):
self.plus(to._coun... |
261b240c9b77b022ba58c1a4bcddc42e5506c7b0 | ajyang818/ProjEuler | /euler003.py | 1,038 | 3.609375 | 4 | # Euler Problem 3: largest prime factor of 600,851,475,143
from math import sqrt
toBreak = 600851475143001
primes = [2, 3]
def countNCheck(toBreak):
n = 5
highestPrime = 1
orig = toBreak
if toBreak % 2 == 0:
toBreak = toBreak / 2
highestPrime = 2
if toBreak % 3 == 0:
to... |
26ab13287b1ea07319831266fe190de1762bb084 | pombredanne/Revision-Scoring | /revscores/languages/language.py | 591 | 4.125 | 4 | class Language:
"""
Constructs a Language instance that wraps two functions, "is_badword" and
"is_misspelled" -- which will check if a word is "bad" or does not appear
in the dictionary.
"""
def __init__(self, is_badword, is_misspelled):
self.is_badword = is_badword
self.is_missp... |
3f072babd4c741e05a1224f4f14557bb6eea03e7 | JCamyre/DataStructuresAlgorithms | /linkedlisttesting.py | 1,024 | 3.953125 | 4 | class LinkedListNode:
def __init__(self, val, next=None):
self.val = val
self.next = next
def __str__(self):
return str(self.val)
def create_linked_list(vals):
if len(vals) <= 0:
return 0
head = LinkedListNode(vals[0])
cur = head
for i in vals[1:]:
... |
2ba161fc1db34f099b29ed03b0bf2307bcb9dcdf | jamnicki/gui_web_app | /server/utils.py | 1,034 | 3.578125 | 4 | import re
def close_file_objects(file_objects):
"""Close all file objects from given list.
Args:
file_objects (list): contains file objects to close
"""
for file in file_objects:
file.close()
def shorten_exception_message(exception_message_raw):
"""Shortens an exception message ... |
5ad6738a1af2940468d6a2f2597d6e189d779f94 | whaleloops/cifar_cnn | /image_utils.py | 1,761 | 3.640625 | 4 | import urllib2, os, tempfile
import numpy as np
from scipy.misc import imread
"""
Utility functions used for viewing and processing images.
"""
def preprocess_image(img, mean_img, mean='image'):
"""
Convert to float, transepose, and subtract mean pixel
Input:
- img: (H, W, 3)
Returns:
- (1, 3, H... |
4b3aa2b7f61be71e34a5b75e0faf129704cf70bb | KedarJani/dsa-analysis | /sgp2/temp.py | 955 | 3.921875 | 4 | calendar = []
for i in range( 0,12 ):
month = []
for j in range( 0,4 ):
month.append( [] )
calendar.append( month )
def get_index( name ):
months = ['january','february','march','april','may','june','july','august','september','october','november','december','january','february','march','april... |
044c97316565d3e02113e108c09b258f33aba582 | katelyj/Project1_NYCDOE_Blocked_Website | /dbMaker.py | 749 | 3.640625 | 4 | import sqlite3
f="database.db"
db = sqlite3.connect(f) #open if f exists, otherwise create
c = db.cursor() #facilitate db ops
q = "CREATE TABLE users (user TEXT, pass TEXT)"
c.execute(q)
q = "CREATE TABLE SavedSongs (url TEXT, user TEXT, title TEXT, artist TEXT)"
c.execute(q)
#q = "INSERT INTO SavedSongs VALUE... |
b33ac32fa7e7b73aa0d785c611856e370dce617d | ianyxtan/SDV602-exercises-week2 | /fizzBuzz/q3.py | 614 | 3.828125 | 4 | def fizz_buzz(fizz_on_multiple_of, buzz_on_multiple_of, up_to):
i = 0
listoftuples = []
while i < up_to+1:
tuples = []
if(i % fizz_on_multiple_of == 0 and i % buzz_on_multiple_of == 0):
tuples = (i,'fizzbuzz')
elif(i % fizz_on_multiple_of == 0):
tuples = (i,... |
0f885db6afb8c2301f9f56832338c7dc44336e55 | maturivinay/python_lee | /Lab_Assignment_1/Source/Classes_attending_list.py | 507 | 3.9375 | 4 | x = input("enter the students list for python.Enter none to halt entering")
i = 0
l1 = []
while(x!="none"):
l1.append(x)
i = i+1
x = input("enter next student details in python class")
print(l1)
y = input("enter the students list for web development .Enter none to halt entering")
j = 0
l2 = []
while(y!="non... |
91d391c5b407484acb59bb2af7504003ce83a9e5 | jjy1132/Python-Sample | /for_list01.py | 282 | 3.75 | 4 | array = []
for i in range(0,20,2):
array.append(i*i)
print(array)
print()
array1 = [i*i for i in range(0,20,2)]
print(array1)
print()
array2 = ["사과","자두","초콜릿","바나나","체리"]
output = [fruit for fruit in array2 if fruit != "초콜릿"]
print(output)
|
26035d0fd919a5e5e258292c6247574bc1902ac0 | jjy1132/Python-Sample | /upper.py | 221 | 4.0625 | 4 | a= input("> 1번째 숫자 : ")
b= input("> 2번째 숫자 : ")
print()
print("{} + {} = {}".format(a,b,int(a)+int(b)))
string = "hello"
string.upper()
print("A지점 : ", string)
print("B지점 : ", string.upper())
|
68c9223443c9e48fbdc1c3c22d22f04b40b818b3 | jjy1132/Python-Sample | /tuple_use.py | 569 | 3.84375 | 4 | [a,b] = [10,20]
(c,d) = (10,20)
print("a:",a)
print("b:",b)
print("c:",c)
print("d:",d)
print()
tuple_test = 10,20,30,40
print("#괄호가 없는 튜플의 값과 자료형 출력")
print("tuple_test:",tuple_test)
print("type(tuple_test):", type(tuple_test))
print()
a1, b1, c1 = 10,20,30
print("#괄호가 없는 튜플을 활용한 할당")
print("a1:",a1)
print("b1:"... |
a6c8968d0f3c7cc8cd5c523b6b29d73ba7b69283 | joudkh/Programming-Languages | /Lecture 2/Lecture 2 (syntax).py | 1,320 | 4.03125 | 4 | """
many line comments syntax
"""
print(5)
print(6+2)
print(7.0/2)
print(5==2)
print(5>2)
print(5&2)
print ('hello'+' world')
print ("hello world")
print ("--------------------------------------------------")
x = 5
print (x)
x=x+1
print (x)
print ("-----------------------------------------------... |
10fed729debcd5ba51cfa9da23c2a6e548f6a0ac | kunalrustagi08/Python-Projects | /Programming Classroom/exercise7.py | 920 | 4.21875 | 4 | '''
We return to the StringHelper class, here we add another static method called
Concat, this method receives a single parameter called Args, which is a
"Pack of parameters", which means that we can pass as many parameters as we
want, then, within this function there will be A variable called Curr that
will be ini... |
580438f74309cbffd7841166b374f8814c04eea3 | kunalrustagi08/Python-Projects | /Programming Classroom/exercise3.py | 1,441 | 4.46875 | 4 | '''
Create a class called Calculator. This class will have four static methods:
Add()
Subtract()
Multiply()
Divide()
Each method will receive two parameters: "num1" and "num2" and will return the
result of the corresponding arithmetic operation.
Example: The static addition method will return the sum of num1 and num2... |
130d9e5dd29b1f817b661e9425ffe278ccc44e8d | rebht78/course-python | /exercises/solution_01_04.py | 347 | 4.125 | 4 | # create first_number variable and assign 5
first_number = 5
# create second_number variable and assign 5
second_number = 5
# create result variable to store addition of first_number and second_number
result = first_number + second_number
# print the output, note that when you add first_number and second_number you ... |
238197e2ff2f3af08f4c4dc3e638a1f4e3814bda | echubi/Python-Challenge | /Learning-Plan/main.py | 277 | 3.890625 | 4 | i = 0
words = []
while i <= 9:
word = input("Input the words: ")
words.append(word)
i = i + 1
def listtostring(s):
str1 = ""
for ele in s:
str1 += ele
return str1
b = (listtostring(words))
reverse = ' '.join(reversed(b))
print(reverse)
|
6c2497718d44bf127b0a2c86b9526ac874cce48c | Yasemnerdogan/Kodluyoruz-71.AnkaraFullStack-Python-Angular | /ödevler/3)Python-hafta2-bireysel/döngüler/d.1)En uzun Collatz zinciri.py | 667 | 3.640625 | 4 |
has2={}
def collatz(x):
liste=[]
liste.append(x)
sayi=x
while(sayi>1):
if sayi%2==0:
sayi=int(sayi/2)
if sayi in has2:
liste+=has2[sayi]
break
else:
liste.append(sayi)
else:
sayi=3*sayi+1
... |
148de8c950021454a31140244e8cb84698a93513 | Yasemnerdogan/Kodluyoruz-71.AnkaraFullStack-Python-Angular | /ödevler/3)Python-hafta2-bireysel/fonksiyonlar/f.6)Machin formülü ile Pi'yi bulmak.py | 400 | 3.5 | 4 | def hesap(x, hata =10**(-8)):
n = 1
sonterim = x # serideki ilk terimimiz
işaret=-1
while sonterim < hata:
hesab = işaret*((x**n)/n)# yeni terim bir öncekini x ile çarpıp terim sıra numarasına bölerek bulunuyor.
toplam=sonterim+hesab
sonterim=toplam
n += 2
iş... |
4614ca246bdf2f2291fb8cc8be42b38b54483bd2 | cherieuu/Algorithm | /[Do_it]_Python/chap06/sorted_sort.py | 639 | 3.671875 | 4 | # [Do it! 실습 6C-4] sorted() 함수를 사용하여 정렬하기
print('sorted() 함수를 사용하여 정렬합니다.')
num = int(input('원소 수를 입력하세요.: '))
x = [None] * num # 원소 수가 num인 배열을 생성
for i in range(num):
x[i] = int(input(f'x[{i}]: '))
# 배열 x를 오름차순으로 정렬
x = sorted(x)
print('오름차순으로 정렬했습니다.')
for i in range(num):
print(f'x[{i}] =... |
5beeeca4f4d67d9523a20994fc70fe1567d18650 | cherieuu/Algorithm | /[Do_it]_Python/chap01/max3.py | 411 | 3.796875 | 4 | # [Do it! 실습 1-1] 세 정수를 입력받아 최댓값 구하기
print('세 정수의 최댓값을 구합니다.')
a = int(input('정수 a의 값을 입력하세요.: '))
b = int(input('정수 b의 값을 입력하세요.: '))
c = int(input('정수 c의 값을 입력하세요.: '))
maximum = a
if b > maximum: maximum = b
if c > maximum: maximum = c
print(f'최댓값은 {maximum}입니다.') |
20177b4df3ed2a7342b88fa3fb70aa83b332a8fe | aroraayush/python-concepts | /decorators/basics.py | 468 | 3.5 | 4 | def mylogger(func):
def wrapper(*args, **kwargs):
print(f'=== Running "{func.__name__}()" from Decorator ===')
return func(*args, **kwargs)
return wrapper
@mylogger
def add(a,b):
"""Doc string of function add
Args:
a (int): Number 1
b (int): Number 2
"""
return ... |
d4e968523b9279da8cd73403fe409e9a2732fefe | saahil1292/fsdse-python-assignment-1 | /square_of_numbers.py | 220 | 3.75 | 4 | #def squareOfNumbers(n):
# print {i:i*i for i in range(n+1)}
#
#squareOfNumbers(100)
def squareOfNumbers(n):
dict1 = {}
for i in range(n+1):
dict1.update({i:i*i})
return dict1
squareOfNumbers(5)
|
699df761c72329d625426ce163b6ac12598c277b | Ravi-0809/Python-hackerrank | /Intro/sol6.py | 283 | 4.0625 | 4 | def leap(year):
if year%100 == 0 and year % 400==0:
return True
if year % 100 ==0 and year % 400 != 0:
return False
if year % 4 == 0 and year % 100 != 0 and year % 400 != 0:
return True
if __name__ == "__main__":
year = int(raw_input("Enter a year: "))
print leap(year)
|
b4c8c504d6d29b31032e70ad3034982d97011715 | Ravi-0809/Python-hackerrank | /Intro/sol5.py | 122 | 3.703125 | 4 | import math
if __name__ == "__main__":
n = int(raw_input())
if n>=1 and n <=20:
for i in range(n):
print pow(i,2)
|
d323c1939f8d76b989b1a2e8c4e6ce7a271db9cc | yueranwu/practical | /prac_08/texi_test.py | 581 | 3.546875 | 4 | """
CP1404 Practical
This is a test program for testing Taxi class
"""
from taxi import Taxi
def main():
"""
print taxi information
"""
prius_taxi = Taxi("Prius 1", 100)
prius_taxi.drive(40) # Drive the taxi 40m
print(prius_taxi) # print the taxi's current details and the current fare
... |
783af591f08b0c7040a5bf252f5afbe67fe1bb59 | chetan-techqware/new_codes | /collect_module.py | 294 | 3.515625 | 4 | import collections
from collections import Counter
# c = Counter("chetan saini")
# print(c)
# print(list(c.elements()))
# c = Counter(["a","a","b","c","c","c"])
# c = Counter(cats = 4 , dogs = 5)
# c = Counter(a=4, b=2, c=0, d=2)
# d = ['a','b','b','c']
# c.update(d)
# c.subtract(d)
# print(c)
|
9a2f4b4caba519118cb3bffd57930ea88b9985f7 | werdze/WikiFilmActorScraper | /Analysis.py | 7,203 | 4.03125 | 4 | import matplotlib.pyplot as plt
from Graph import Graph
"""
Finds the youngest and oldest actors in an efficient/shorter way
"""
# Credit to Patrick Hurtado for oldest_and_youngest
def oldest_and_youngest(graph):
o = sorted(graph.actors, key=lambda actor: actor.age)[-1].age
youngest = sorted(list(filter(lamb... |
c5e23d3f211ac1dfa1325bdeb29e7b576667f6f3 | Mahalia-ym/Camino-optimo | /Pract1 Mahalia/code (1)/run.py | 2,317 | 3.515625 | 4 | # Search methods
import search
print("Prueba 1 de A a B")
ab = search.GPSProblem('A', 'B'
, search.romania)
print("Breadth_First", search.breadth_first_graph_search(ab).path())
print("Depth_First", search.depth_first_graph_search(ab).path())
print("Recorrido y profundidad: ", search.busqueda_e... |
5f644d63efe61a89a91fe0bd87870ea78d3240eb | siyuke21/DeSUHU | /utils/file.py | 895 | 3.71875 | 4 | import os
class File:
def __init__(self, path='/', mode='w'):
self.path = path
self.mode = mode
def set_path(self, path):
self.path = path
def set_mode(self, mode):
self.mode = mode
def _is_exist(self):
directory = self.path
directory = directory.... |
28865d66282fe64b02746058daff5e1c464c0d75 | chefmohima/ProblemSet-Arrays | /01_replace_even_numbers.py | 224 | 3.515625 | 4 | #IC - Traverse array in reverse
#Given an array of numbers, replace each even number with two of the same number.
#e.g, [1,2,5,6,8] -> [1,2,2,5,6,6,8,8]. Assume that the array has enough space to accommodate the result.
|
39e669b95b5b08afdab3d3b16cb84d673aecbf8e | ctsweeney/adventcode | /day2/main.py | 2,106 | 4.375 | 4 | #!/usr/bin/env python3
def read_password_file(filename: str):
"""Used to open the password file and pass back the contents
Args:
filename (str): filepath/filename of password file
Returns:
list: returns list of passwords to process
"""
try:
with open(filename, "r") as f:
... |
459e3276198c11c5ab623a3d4ad7bfef12db8cb8 | SerhiiKarasov/python | /training/home3.py | 8,471 | 3.53125 | 4 | #! /usr/bin/python3
# -*- coding: utf-8 -*-
# Write function with one attribute which returns a class depends on name attribute.
def functionWithOneAttribute(oneattribute):
if(oneattribute == "ororo"): return type("ORORORO",(),{})
elif(oneattribute == "ururu"): return type("URURURU",(),{})
print(functionWithOn... |
5c353ec65594725732c0f1257367b8d666fa72e9 | SerhiiKarasov/python | /db2txt/tools.py | 1,757 | 3.671875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
""" a set of function to dump content
"""
import sys
import sqlite3
import os
from logger import LOGGER
from configuration import SQL_COMMAND
def write_to_txt(data, txt_filename):
"""[summary]
Arguments:
data {[type]} -- [description]
txt_filename {... |
8334e2ffe81ca40f28c7385c27bbeb3977040f88 | TTitcombe/PrivacyPanda | /privacypanda/email.py | 1,390 | 4.03125 | 4 | """
Code for identifying emails
"""
import re
from typing import List
import pandas as pd
from numpy import dtype as np_dtype
__all__ = ["check_emails"]
OBJECT_DTYPE = np_dtype("O")
# Whitelisted email suffix.
# TODO extend this
WHITELIST_EMAIL_SUFFIXES = [".co.uk", ".com", ".org", ".edu"]
EMAIL_SUFFIX_REGEX = "(" ... |
20a511876739ad1d16612fa6586bcab504503d2e | bhargav-s/pythonpractice.github.io | /20dictonary.py | 129 | 3.578125 | 4 | classmates = {'bhargav' : 'noisy' , 'ajay' : 'decent','nandan' : 'not a good'}
for k,v in classmates.items():
print( k + v ) |
c08dff076a8390f83a6deecc9b533c976104d04c | bhargav-s/pythonpractice.github.io | /39zipping.py | 159 | 3.8125 | 4 | firstname = ['bhargav','ajay','nandan','karthik']
lastname = ['s','v','cb','b']
names = zip(firstname,lastname)
print(names)
for a,b in names:
print(a,b) |
5cb50cc07e8cb2a28b8ed06a403dd8d69db1a33d | isailg/python_notes | /condition.py | 293 | 4.1875 | 4 | # age = int(input("Type your age: "))
# if age > 18:
# print("You are of age")
# else:
# print("You are a minor")
number = int(input("Type a number: "))
if number > 5:
print("Greater of 5")
elif number == 5:
print("Equal to 5")
elif number < 5:
print("Less than 5")
|
d7949dd2796e11198b1367e893027dd9e434bd93 | XleonardoX/UNICAMP-TT002 | /game.py | 1,427 | 3.5625 | 4 | import random
import copy
def checavizinhos(x, y, board):
neighbors = 0
execao = [-1, 0, 1]
#for para lidar com celulas das bordas (com menos de 8 vizinhos)
for i in execao:
for j in execao:
if (i == 0) and (j == 0):
pass
elif ((y + j) < 0) or ((y + j) > (25 - 1)):
pass
elif ((x + i... |
3a2dd17db00a0588e4d98cf11ee7eff43a1be7d1 | bosmobosmo/advent-of-code | /2015/day 5/problem2.py | 905 | 3.90625 | 4 | def is_really_nice(string: str) -> bool:
return has_double_repeats(string) and has_repeat_with_wall(string)
def has_double_repeats(string: str) -> bool:
for substring in get_substrings(string):
if string.count(substring) >= 2:
return True
return False
def get_substrings(st... |
deb22b1d23b9d2ee09b8e18d272cc65430954eaa | bosmobosmo/advent-of-code | /2022/day 2/solution.py | 1,316 | 3.546875 | 4 | import enum
def main() -> None:
with open('input', 'r') as f:
input = f.read().splitlines()
part_one(input)
part_two(input)
def part_one(input: list[str]) -> None:
score_gain = {
'X': 1,
'Y': 2,
'Z': 3,
}
point_gain = {
'0': ['A Z', 'B X', 'C Y'],
... |
bbd74ab22ca545f4f62774326f4b9ba2d38307e3 | bosmobosmo/advent-of-code | /2019/Day 1/solution.py | 355 | 3.78125 | 4 | f = open('input.txt', 'r')
#part 1
# total = 0
# for line in f:
# total = total + int(int(line) / 3) - 2
# print (total)
#part 2
def count_fuel(mass):
fuel = int(mass/3) - 2
if fuel < 6:
return fuel
else:
return (fuel + count_fuel(fuel))
total = 0
for line in f:
total = total + c... |
197d7e14872fdb6d9a172f9e281b8ae85beff531 | ringsaturn/cnholiday | /cnholiday/__init__.py | 1,651 | 3.5625 | 4 | """If the day is China holiday?
"""
import json
import os
from datetime import datetime, timedelta
from typing import Dict
DATA_PATH = "data.json"
def load_data(json_path: str) -> Dict:
with open(json_path) as f:
return json.loads(f.read())
class CNHoliday:
data = load_data(os.path.join(os.path.di... |
b870e516f1c45a0525208b944804a0424a361db4 | dky/cb | /legacy/fundamentals/stacks-queues/stack.py | 862 | 3.90625 | 4 | class Node:
def __init__(self, val):
self.val = val
self.next = None
class Stack:
# creates an empty stack
def __init__(self):
self.first_name = None
self._size = 0
# prints out stack in order
def __str__(self):
pass
# adds an item to teh stack
def... |
7e2673225932da4fdd467b972578c90f8026b76d | dky/cb | /legacy/arrays/containerMostWater.py | 509 | 3.65625 | 4 | # arr [1, 8, 6, 2, 5, 4, 8, 3, 7]
# O(n)runtime
# O(1)space complexity
def containerMostWater(arr):
if len(arr) < 2:
return -1
start = 0
end = len(arr) - 1
max_prod = float('-inf')
while (start < end):
prod = min(arr[start], arr[end]) * (end - start)
max_prod = max(max_prod... |
1f4e9d17d6a821f80129beec0f9888c77b657eae | dky/cb | /legacy/coaching-calls/04-25-k-digits.py | 1,446 | 3.625 | 4 | # Edge 1
# s = '11'
# returns 11?
# k = 1
# # Edge 2
# s = '324'
# k = 2
# # returns 0008?
# Edge 2
#s = '100089'
s = '12498'
k = 2
# returns 0008?
# Good way to get rid of leading zeros?
#12498
#498
#124 * Potentially smallest
#249
#298
#198
def rmkd(s, k):
# print(len(s))
# if k >= len(s) return "0"
... |
017a3268e5de015c8f0c25045f44ae7a4ffe7a50 | dky/cb | /legacy/fundamentals/linked-lists/03-08-20/LinkedList.py | 1,893 | 4.1875 | 4 | class Node:
def __init__(self, item, next=None):
self.item = item
self.next = next
class LinkedList:
def __init__(self):
# We always have a dummy node so the list is never empty.
self.head = Node("dummy")
self.size = 0
def __str__(self):
out = ""
cu... |
105e9536a5a82cde5cf7c204e0d3316ceab5867d | dky/cb | /legacy/educative/lpfs/functions-as-arguments.py | 470 | 4.28125 | 4 | """
def add(n1, n2):
return n1 + n2
def subtract(n1, n2):
return n1 - n2
def multiply(n1, n2):
return n1 * n2
def divide(n1, n2):
return n1 / n2
"""
def calculator(operation, n1, n2):
return operation(n1, n2) # Using the 'operation' argument as a function
#... |
6032304ddc5282dc69d7416a4bb1315933ab2023 | abhijnashree/Python-Projects | /progr9.py | 196 | 4.03125 | 4 | diction1={1:'speckbit',2:'world',3:'quiet'}
a=input("word to be searched")
if
print(''' )
for key,values in dict1.items():
... print(key,values, sep='--')
...
1--speckbit
2--world
3--quiet |
e8a31744973bb64d08f4f68e9a5aa1657803c599 | abhijnashree/Python-Projects | /program8.py | 165 | 4.3125 | 4 | dictionary1={}
for i in range(3):
key=input("enter usn: ")
val=input("enter name: ")
if key not in dictionary1.keys():
dictionary1[key]=val
print(dictionary1)
|
9390e6095c6140ba0117bfd18fb63844189d7a68 | abhijnashree/Python-Projects | /prac1.py | 218 | 4.28125 | 4 | #Read Input String
i = input("Please insert characters: ")
#Index through the entire string
for index in range(len(i)):
#Check if odd
if(index % 2 == 0):
#print odd characters
print(i[index])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.