blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
1a47ce4b14527145732b7c9701526f910c6b26ed | Pasinozavr/5th-year-le-man | /GP/projet/francais.py | 1,174 | 3.578125 | 4 | class Question:
def __init__(self, difficulty, question, answer, propositions):
self.difficulty=difficulty
self.question = question
self.answer = answer
self.propositions = propositions
def difficulty():
return self.difficulty
def question():
retu... |
8b5102d8cad871ef0c7eef261ff17f65eb531fbe | floorberkhout/commit4life | /code/algorithms/randomize.py | 917 | 3.765625 | 4 | ###############################################################
# randomize.py
# Runs random algorithm
###############################################################
import random
import time
def randomize(board):
""" Makes random algorithm to solve Rush Hour """
solution = []
counter = 0
# Pl... |
fb7963f02bd9327a4e04c01258e0c465ad02b413 | aweret1/OOP | /Практика new upgr/a1/012.py | 522 | 3.875 | 4 | w = input('Наш or Не наш:')
if w == 'Не наш':
weight = float(input('Вага:'))
height = float(input('Ріст:'))
print('IMT:',703*weight/height**2)
elif w == 'Наш':
weight = float(input('Вага:'))
height = float(input('Ріст:'))
print('IMT:',weight/height**2)
import datetime
def printTi... |
4710e1e5abef2aaa2a5d6ed267d247e56b681713 | riteshsharthi/botx | /FAQ/nlp_engine/extractors/Company_next.py | 690 | 3.640625 | 4 | import re
class CompanyNameExtractor:
def __init__(self):
pass
def company_code_extract(self,txt):
match = re.findall(r'[\w\.-]+-[\w\.-]+', txt)
if len(match)==0:
number = re.findall(r'[\w\.-]+\d[\w\.-]+', txt)
else:
#number = re.findall(r'[\w\.-]+... |
b3f9583dc914397397e6541830cb750321d1a955 | SiddharthaHaldar/leetcodeProblems | /297-serialize-and-deserialize-binary-tree/297-serialize-and-deserialize-binary-tree.py | 1,828 | 3.671875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
... |
5797688d1b231c3d44167465e85ce9dfe0a5012e | mAzurkovic/Interview-Prep | /ds-algos/binary-search.py | 402 | 4.0625 | 4 | def binarySearch(arr, left, right, val):
if (left <= right):
mid = (left + right) // 2
if (arr[mid] == val):
return mid
elif (val < arr[mid]):
return binarySearch(arr, left, mid - 1, val)
else:
return binarySearch(arr, mid + 1, right, val)
... |
890ab0093276295ce41455d4f528b3bfa551512c | manikshahkataria/codes | /eee.py | 614 | 4.09375 | 4 | def nth_prime_number(n):
if n==1:
return 2
count = 1
num = 3
while(count <= n):
if is_prime(num):
count +=1
if count == n:
return num
num +=2 #optimization
def is_prime(num):
factor = 2
while (factor < num):
if num%factor ==... |
5390283e707dde13a8802ab9bbc27a0ff7c5b36a | Engi20/Python-Programming-for-Beginners | /14. OOPS/101.3.DefiningCreatingClasses.py | 463 | 3.828125 | 4 | class Student:
def __init__(self,name,roll,marks):
self.name = name
self.roll = roll
self.marks = marks
def display(self):
print('Student Name: ',self.name)
print('Student Roll No: ', self.roll)
print('Student Marks: ', self.marks)
print()
St... |
30f39a52e1ce8ec5419c3b43630dfa5d58b17c3f | ttyskg/ProgrammingCompetition | /AtCoder/ABC/035/d.py | 1,350 | 3.53125 | 4 | import sys
from heapq import heappush, heappop, heapify
def dijkstra(s, links):
"""Dijkstra algorism
s: int, start node.
t: int, target node.
links: iterable, link infomation.
links[i] contains edges from node i: (cost, target_node).
return int, minimal cost from s node to t node.
... |
5907c8b14724e678abd619240a378d3553c1f7b8 | alexanderlao/CptS-355_Programming_Language_Design | /HW1/HW1.py | 4,362 | 3.859375 | 4 | # Alexander Lao
# Intended for Windows
# returns a dictionary defined by mapping a char
# in s1 to the corresponding char in s2
# PRECONDITION: s1 and s2 must be the same length
def makettable (s1, s2):
dictionary = dict (zip (s1, s2))
return dictionary
# loops through each char in s and replaces th... |
66f4415bf11d9d5f20d9187493a97d1e4b1b2232 | netor27/codefights-solutions | /arcade/python/arcade-theCore/12_ListBackwoods/100_ReverseOnDiagonals.py | 1,029 | 4.40625 | 4 | '''
The longest diagonals of a square matrix are defined as follows:
the first longest diagonal goes from the top left corner to the bottom right one;
the second longest diagonal goes from the top right corner to the bottom left one.
Given a square matrix, your task is to reverse the order of elements on both of its l... |
324034e1cf6d41061184d38c03efbb8ab43ba977 | mathieu-clement/cs560-restaurants | /scores.py | 6,981 | 3.65625 | 4 | #!/usr/bin/env python3
import csv
import datetime
class Restaurant:
def __init__(self, rest_id, name, street, zip_code, lat, lon):
self.id = rest_id
self.name = name
self.street = street
self.zip_code = zip_code
self.lat = lat
self.lon = lon
self._inspection... |
a56995f43c9c365cea356797185cef17635d0dbc | jaydee220/PCSII_Sapienza | /Ex42.py | 143 | 3.796875 | 4 | import math
if __name__ == '__main__':
b = int(input())
a = int(input())
print (str(round((math.degrees(math.atan2(b,a)))))+"°")
|
9d8f44435e2a55054d50a659d656ba6d6192305b | adikadu/DSA | /longestWordInSentence.py | 272 | 3.890625 | 4 | import re
def LongestWord(sen):
a = re.findall(r"[a-zA-Z]+", sen)
l = len(a[0])
ind = 0
for i in range(1, len(a)):
if len(a[i]) > l:
l=len(a[i])
ind = i
# code goes here
return a[ind]
# keep this function call here
print(LongestWord(input())) |
fd0e5bc2875e7108a9c015f5ac7efc3be4acf793 | ganhan999/ForLeetcode | /506、相对名次.py | 1,523 | 4.0625 | 4 | """
给出N 名运动员的成绩,找出他们的相对名次并授予前三名对应的奖牌。
前三名运动员将会被分别授予 “金牌”,“银牌” 和“ 铜牌”("Gold Medal", "Silver Medal", "Bronze Medal")。
(注:分数越高的选手,排名越靠前。)
示例 1:
输入: [5, 4, 3, 2, 1]
输出: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"]
解释: 前三名运动员的成绩为前三高的,因此将会分别被授予 “金牌”,“银牌”和“铜牌” ("Gold Medal", "Silver Medal" and "Bronze Medal").
余... |
aeffa44e5b5e12448c08811d9b103468ff1cb7e3 | junwha0511/ALGOPY | /2018/euclidean.py | 273 | 3.75 | 4 |
def getGCD(a, b):
if a%b == 0:
return b
elif a%b >0:
return getGCD(b,a%b)
a = int(input('두 정수를 입력하세요\n'))
b = int(input())
if a<b:
l=b
s=a
else:
l=a
s=b
print('최대공약수는 '+str(getGCD(l,s))+'입니다')
|
01137bccda7a0998798a4eab0dfb6ca360161a2e | gmal1/algoholics-anon | /python/cracking-coding/stacks_queues/animal_shelter.py | 2,174 | 3.78125 | 4 | from enum import Enum
class AnimalSpecies(Enum):
dog = 1,
cat = 2
class Animal:
def __init__(self, species: AnimalSpecies, name: str):
self.species = species
self.name = name
class Node:
def __init__(self, animal: Animal):
self.animal = animal
self.next = None
class A... |
e930a6b73fa86e80ebd85b197f71480f3b9da528 | c-boe/Reinforcement-learning | /4 Dynamic programming/Gambler's Problem/value_iteration.py | 5,591 | 3.5625 | 4 | """
Implementation of Exercise 4.9 in Chapter 4 of Sutton and Barto's "Reinforcement
Learning"
"""
import matplotlib.pyplot as plt
import numpy as np
from gamblersproblem import GamblersProblem
def value_iteration(env, theta):
'''
Value iteration
Parameters
----------
env :
Gambler's pr... |
8d0c24bafc991e1bd3b4e81af4222a54f643476d | gabriellaec/desoft-analise-exercicios | /backup/user_054/ch26_2020_10_07_14_57_45_448762.py | 279 | 3.921875 | 4 | casa = float(input('valor da casa? '))
salário = float (input('salário? ' ))
meses = float (input('durante quantos meses quer pagar? ' ))
prestação = casa/meses
if prestação< 0.3*salário:
print ('Empréstimo aprovado')
else:
print ('Empréstimo não aprovado')
|
3b78a6d3a19b261f34a70755b70284c7c730ca41 | halucinka/projectEuler | /p45.py | 412 | 3.6875 | 4 | #!/usr/bin/env python3
import math
triangle = set()
pentagonal = set()
hexagonal = set()
big_number = 10000000000
i = 1
while (i*(i+1)/2 < big_number):
triangle.add(i*(i+1)/2)
if (i*(3*i-1)/2 < big_number):
pentagonal.add(i*(3*i-1)/2)
if (i*(2*i-1) < big_number):
hexagonal.add(i*(2*i-1))
... |
f904a94d92b3ee5ca3e0bb90a7cdb45e4869b61b | NitzanRoi/Histogram-Quantization | /sol1.py | 7,257 | 3.59375 | 4 | from skimage import color
from skimage import io
import numpy as np
from numpy.linalg import inv
import matplotlib.pyplot as plt
GREYSCALE_CODE = 1
RGB_CODE = 2
MAXIMUM_PIXEL_INTENSE = 255
TRANSFORMATION_MATRIX = np.array([
[0.299, 0.587, 0.114],
[0.596, -0.275, -0.321],
[0.212, -0.523, 0.311]
])
THREE_DIM... |
c5eafe7e423a587215bf02993150f3b6800a6d4f | jessie-JNing/Algorithms_Python | /Recursion_DP/Magic_index.py | 1,332 | 4.1875 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
A magic index makes A[i]=i.
Given a sorted array of distinct integers, try to find a magic index,
if one exists, in array A.
@author: Jessie
@email: jessie.JNing@gmail.com
"""
def find_magic_index(nums):
if len(nums)<1:
return None
else:
mid = len(... |
293fd59027e7984239965970dffe697e951f7a2a | rlerichev/IntCurvSurf | /tests/functions.py | 3,096 | 3.984375 | 4 | #!/usr/bin/env python3
#
# Ejemplo de Funciones
#
# Mutables!!!
def putNext(n, s, things):
n += 1
s = s*2
things.append(n)
things.append(s)
print( things )
# Riemman's Z
def riemannZ(z, n=3):
res = 0
i = 1
while i <= n:
res += i**z
i += 1
return res
# Evaluar expresión
def feval(expr, x=1.0):
return... |
7d9385f4fc367d13c1a51afac0142d22266a7d7c | RedMarbleAI/RedVimana.Bunnings.ComputerVision | /Size2.py | 334 | 3.5 | 4 | class Size2(object):
def __init__(this, width, height):
this.mWidth = width
this.mHeight = height
@property
def Width(this):
return this.mWidth
@property
def Height(this):
return this.mHeight
@property
def Area(this):
return this.mWidth ... |
5d56613f7e067437821070e45452e0a2c45df9b6 | akashmaji946/Python_May_2021_Inspire | /03_02_main.py | 314 | 3.84375 | 4 |
## Variables
x = 20
print(x)
# int -> integer
# str -> string (a seq of characters)
# dynamically typed lang
name = "Ankush"
print(name)
surname = 'Agarwal'
print(surname)
# OOP => object oriented prog.
print(type(x))
print(type(name))
# inbuilt func
# type() => datatype
print("he said 'hello'")
|
166e61865830944af3e1a6e3b9545f58c05d5a4e | laszlomerhan/Hangman | /Hangman/task/hangman/hangman.py | 1,426 | 3.84375 | 4 | import random
while True:
print('H A N G M A N\n')
choose = input('Type "play" to play the game, "exit" to quit: ')
if choose == 'play':
random_word = random.choice(['python', 'java', 'kotlin', 'javascript'])
guessed_word = "-" * len(random_word)
lst = []
count = 0
... |
2bb65b0a50d9a26f4e4b76761f145fcffe93c247 | frank-say/mit-python-psets | /ps1/ps1b.py | 962 | 4.21875 | 4 | annual_salary = input('Enter your annual salary: ')
annual_salary = float(annual_salary) # 获取输入的年薪
portion_saved = input(
'Enter the percent of your salary to save, as a decimal: ')
portion_saved = float(portion_saved) # 获取输入的存钱比例
total_cost = input('Enter the cost of your dream home: ')
total_cost = float(total_... |
64fb10c953c8cf61541cd7b5a2e62d828e6a538f | sevilzeynali/prepocessing-arabic-texts | /preprocessing_arabic_texts.py | 815 | 4.09375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import nltk
from nltk.stem.isri import ISRIStemmer
import re
# loading stemmer for arabic
st = ISRIStemmer()
# asking an arabic text from user
try:
while True:
print("Enter an arabic text: ")
# getting the text entered by user
text=input()
... |
ad48e5f3ce6899049e7cb19d5176290e0ed7d889 | Velignis/Demo-or-Repu | /tictactoe AI group project.py | 6,593 | 4.0625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[3]:
#Reference: http://www.sarathlakshman.com/2011/04/29/writing-a-tic-tac
import copy
import time
class Game(object):
"""A tic-tac-toe game."""
def __init__(self, grid):
"""Instances differ by their grid marks."""
self.grid = copy.deepcopy(grid) ... |
e346a05db813fd69aa2e5171f13612dcc57f9a6a | ttinning/sport_scoring_app | /tests/team_test.py | 812 | 3.578125 | 4 | import unittest
from models.team import Team
class TestTeam(unittest.TestCase):
def setUp(self):
self.team1 = Team("Eagles", "Philadelphia")
self.team2 = Team("Cowboys", "Dallas")
def test_team1_has_team_name(self):
expected = "Eagles"
actual = self.team1.name
self.ass... |
f6c8c2620e3e7b7d7a4d7005157b0886fa2f6aca | stgasser/AdventOfCode2020 | /Day18/18_2.py | 1,843 | 3.71875 | 4 | def parse_input(filename):
with open(filename) as f:
return [line.replace(' ', '') for line in f.read().splitlines()]
def part1(equations):
def evaluate(eq):
stack = list()
last = ''
op = next(eq, None)
while op is not None:
if op in {'+', '*'}:
... |
ea541abd209983876edec0c06842a11f1460aadd | maxzhuhl/code | /AM3.4.py | 2,579 | 3.640625 | 4 | #浏览器操作
import time
from selenium import webdriver
#浏览器操作练习
#创建一个驱动
driver = webdriver.Chrome()
#1.打开百度
driver.get('https://www.baidu.com')
# driver.find_element_by_name("tj_trhao123").click()
# 2.窗口最大化
# driver.maximize_window()
# 3.刷新,点击hao123等待5s刷新
# time.sleep(5)
# driver.refresh()
# 4.后退
# time.sleep(2)
# driver.b... |
406010dbd2b4904ab9878b5931d98980b650e6b4 | DevelopGadget/Basico-Python | /Recursos Profe/sets.py | 1,200 | 4.375 | 4 | #Los conjuntos son una coleccion de datos desorganizados y no indexados
#creacion de un conjunto
thisset = {"apple", "banana", "cherry"}
print(thisset)
#Acceder a los elementos del conjunto
for x in thisset:
print(x)
#Verificar si un elemento esta presente en el conjunto
print("banana" in thisset)
#Insertar(al fin... |
ad7aacc18a687568b540faafebb15bf1bc15d910 | ShriRachana/Python-practice | /General Practice/while_else.py | 96 | 3.96875 | 4 | x = 3
y = x
while y > 0:
print y
y = y - 1
else:
print "ye ye shall here ye"
|
83a1c32966ab2118923182797af8d71d147407e3 | yhancsx/algorithm-weekly | /cracking_the_coding_interview/8.3.py | 321 | 3.546875 | 4 | def findMagixNumber(nums):
l = 0
r = len(nums)-1
while l <= r:
m = (l+r)//2
if nums[m] == m:
return m
if nums[m] < m:
l = m + 1
else:
r = m - 1
return None
nums = [-40, -20, -1, 1, 2, 3, 7, 8, 9, 12, 13]
print(findMagixNumber(nums))... |
582172066cd45a66264ddceeb4793442e2a17941 | Roshan1115/PythonNTEL | /Week3/SelectionSort.py | 203 | 3.671875 | 4 |
#My Version of Selection sort
def selectionsort(l):
for i in range(len(l)):
for j in range(i, len(l)):
if(l[i] > l[j]):
(l[i], l[j]) = (l[j], l[i])
return(l) |
b4b80340e4445eea1522d730281a70a29739b9cc | AllieChen02/LeetcodeExercise | /BfsAndDfs/P743NetworkDelayTime/NetworkDelayTime.py | 903 | 3.546875 | 4 | import unittest
from typing import List
import collections
import heapq
class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
graph = collections.defaultdict(dict)
for start, dest, cost in times:
graph[start][dest] = cost
h = [(0, k)]
... |
55dcdd2fc3039b366617b68e1cf1014e09a2e6a8 | StevenDunn/CodeEval | /FollowingInteger/py2/fi.py | 507 | 3.515625 | 4 | #following integer soln in py for code eval by steven a dunn
import sys
from itertools import permutations
def parse_digits(line):
digits = "".join(sorted(line.rstrip()))
remaining = 6 - len(digits)
padding = "0" * remaining
return padding + digits
f = open(sys.argv[1], 'r')
for line in f:
origin... |
9d521c9ec1b7df0683f483029e93fc99245890df | karata1975/laboratory | /Таблица сумм с -числом.py | 116 | 3.65625 | 4 | print()
for row in range(0, 10, ):
for col in range(0, -10, -1):
print(row + col, end='\t')
print()
|
6a2674ce73d12e5004d944a453cde86a96aae48c | shankarpentyala07/python | /print_example.py | 141 | 4.03125 | 4 | print("print is used to print output to std out")
print("20 days are " + str(20*24*60) + " minutes")
print(f"20 days are {20*24*60} minutes") |
15013f815cbdd9e123f34009f9912c134c675d71 | alexliyang/cardiac-segmentation-cc | /test1.py | 234 | 3.734375 | 4 | class Num123(object):
def __init__(self, i):
self.i = i
input = [1,2,3,4]
nums = map(lambda x: Num123(x), input)
print(list(nums))
def f(x):
return x*x
f_map = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print (list(f_map)) |
66aaa1dd919ad435383d5c48b193405741e03545 | john-fitz/pairs_trading | /portfolio_management.py | 5,869 | 3.96875 | 4 | import pandas as pd
import numpy as np
from typing import Optional, Union
import pickle
DEFAULT_PURCHASE_AMT = 100
def trade_amount(coin1: str, coin2: str, hedge_ratio: float, long1: bool, fictional: bool) -> Union[float, float]:
""" checks positions for coin1 and coin2 to see the dollar amount of each coin that ... |
d7557c39b32e9dccabfd81f1d470b3924c40aa66 | j16949/Programming-in-Python-princeton | /3.2/interval.py | 643 | 3.71875 | 4 |
class Interval:
def __init__(self,left,right):
self._l = left
self._r = right
def contains(self,other):
if self._r >= other._r >= other._l >= self._l:
return True
return False
def intersects(self,other):
if other._r > self._r >= other._l:
... |
502c14b880c3978f1da66afc5b4d9f184250a54f | rafaelperazzo/programacao-web | /moodledata/vpl_data/59/usersdata/170/40645/submittedfiles/testes.py | 34 | 3.59375 | 4 | x=1
while x<=3:
x=x+1
print(x) |
5898f8c9ca9b7cc1b481dc617493bc365e93e80d | ses1142000/python-30-days-internship | /day 2 py internship.py | 433 | 3.578125 | 4 | Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> (a,b,c)=(3,4,5)
>>> print(a/10)
0.3
>>> print(b*50)
200
>>> print(c+60)
65
>>> str="sharon,sam,saji,sindhu,philip"
>>> print(str.replace("... |
14148008a2a0286ca20034dc12688a8ee4d406a4 | Eduardo95/creative_informatics_exam | /exam_problem/2015/problem3.py | 356 | 3.53125 | 4 | with open("program.txt") as f:
sentence = f.readlines()
sentence = [i.replace("\n", "") for i in sentence]
ans = []
line_a = ""
line_b = sentence[0]
for index in range(0,len(sentence)-1):
line_a = line_b
line_b = sentence[index+1]
if line_a == line_b and (line_a not in ans):
ans.append(line_a... |
9a5ec71a0426288e88565a48c0350994dcf05c1f | kseob/bioinfo-lecture-2021-07 | /21.07.05/005.py | 272 | 3.671875 | 4 | import sys
if len(sys.argv) != 2:
print(f"#usage: python {sys.argv[0]} [num]")
sys.exit()
num = int(sys.argv[1])
if num%3 ==0 and num%7 == 0 :
print ('3','7')
elif num%3 == 0 :
print ('3')
elif num%7 == 0 :
print ('7')
else :
print('not')
|
29093f93cd61a3fa947795e96224501d8df165db | unnunnjyann/kmeans | /readData.py | 383 | 3.578125 | 4 | import csv
def readData(fileName):
"""
:param fileName:
:return: a 2-dimensional array
"""
data = []
with open(fileName) as csvFile:
reader = csv.reader(csvFile)
for item in reader:
temp = []
for attribute in item:
temp.append(float... |
a4ec294248eb476059132d1d0d1e327f10d28e4c | alexandraback/datacollection | /solutions_2449486_0/Python/ulrikdem/codejam.py | 1,259 | 3.765625 | 4 | # Hezekiah's Code Jam Solution
# Usage: python3 codejam.py < file.in > file.out
def more(line):
return int(line.split()[0])
def solve(lines):
split = lines[0].split()
height = int(split[0])
width = int(split[1])
lawn = []
lengths = []
for row in range(0, height):
lawn.append([])
line = lines[row + 1].split... |
a082307f366bf727534b0e58e8f6ff72284b3820 | theTrio11/python-docs | /second.py | 219 | 3.640625 | 4 | #second progam
print("Enter the name of the students")
a=str(input())
b=str(input())
c=str(input())
print("Enter the marks of the three students")
x=int(input())
y=int(input())
z=int(input())
print("The sum is=",x+y+z)
|
1c7045e929f5adc6501084b3e5609470fca62da1 | airpark69/pythonStudy | /py1/test2.py | 393 | 3.890625 | 4 | a=True
print(type(a))
a=70
if a >= 80:
print("pass")
else:
print("not")
if a >= 90:
print("A")
elif a >= 80:
print("B")
elif a >= 70:
print("C")
elif a >= 60:
print("D")
else:
print("점수아님")
a=11
if 13 <= a <= 18:
print("1300")
j="901223-4234567"
if j[j.index("-") + 1] == "1" or j[... |
e91837cc3a948c57117f1d73830864ddfb8c440c | Slimmerd/COMP1811-Python-CW | /administrator_features/api/database_management.py | 5,015 | 3.546875 | 4 | import csv
import os
import sqlite3
import tkinter as tk
class DatabaseAPI:
def __init__(self):
self.path = os.path.dirname(os.path.dirname(__file__))
self.database_path = self.path + '/database/all_about_toys.db'
self.connection = sqlite3.connect(self.database_path)
self.cursor =... |
96af4e636f01e6a8b6ff60ebf345d335ef7aec4f | nazarov-yuriy/contests | /yrrgpbqr/p0381/__init__.py | 1,737 | 3.625 | 4 | import unittest
from typing import List
import random
import collections
class RandomizedCollection:
def __init__(self):
self.hashmap = {}
self.list = []
def insert(self, val: int) -> bool:
res = val not in self.hashmap
self.hashmap.setdefault(val, set()).add(len(self.list))
... |
021e522044931d8657f12c5c32569c6e19790ec2 | ShadieKamata/alx-higher_level_programming | /0x01-python-if_else_loops_functions/8-uppercase.py | 191 | 4.28125 | 4 | #!/usr/bin/python3
def uppercase(str):
for c in str:
islower = ord(c) >= 97 and ord(c) <= 122
print("{:c}".format(ord(c) - 32 if islower else ord(c)), end="")
print()
|
dd25dcf789a3baac49842673e53f36ff5daa427c | mnauman319/Snake | /app.py | 11,618 | 3.8125 | 4 | '''
------------------------Snake Rules------------------------
1. Each item eaten makes the snake longer
2. The player loses when the snake runs into the
end of the game board
3. The player loses when the snake runs into itself
'''
import tkinter
import random
from typing import List
from snake im... |
cf0a6095d63a84ad5913f07260a57e485a903263 | LoisBN/python | /env/code/tme8.py | 3,611 | 3.890625 | 4 | #Tme 8
#exercice 8.2
#question 1
def moyenne(listOfNumber):
"""list[number]->float
retourne la valeur moyenne de l 'ensemble des valeurs contenues dans la liste"""
#result:float
result = 0.0
#number:number
for number in listOfNumber:
result = result + number
return result/len(li... |
43117b6e7f248510e5350ba1f3a4c5fdef2b3ec1 | qpcode/smc | /smc/agent.py | 399 | 3.859375 | 4 | """ Class for Agent """
class Agent:
def __init__(self, init_x, init_y):
""" Constructor for Agent class """
self.x = init_x
self.y = init_y
class AgentTrajectories:
def __init__(self):
self.xs = []
self.ys = []
def add_point(self, x, y):
""" adds a new p... |
1fa91a0b68f1bbed75ec3e43527ed3ae94838813 | SergeiLSL/Programming-course | /Глава 3 - Обработка ошибок Функции/task_3.3 - Создать функцию нахождения суммы или разности чисел.py | 465 | 3.9375 | 4 | """
Написать функцию, которая принимает на вход два аргумента.
Если аргументы больше нуля, возвращаем их сумму.
Если оба меньше - разность. Если знаки разные - возвращаем 0
"""
def result(x, y):
if a > 0 and b > 0:
return a + b
else:
return a - b
a, b = int(input()), int(input())
print(resu... |
bb5fa80c90ba0d6eb1eaf9f0e1426720fc1946d3 | Rahul-Kumar-Tiwari/PyOS | /programs/example.py | 686 | 3.765625 | 4 | # PyOS
# Made for Python 2.7
# programs/example.py
# Import the internal.extra script and give it the shortcut of 'e'.
import internal.extra as e
def app():
# This is the function that will run when the 'example' command is typed in.
# Clear the console screen
e.cls()
"""
This line of code below... |
c7bcb6a14802296993bce5620131761bbda188c2 | BielWeb/Estudando-Python | /geradorCurriculo.py | 2,382 | 3.75 | 4 | print('---------GERADOR DE CURRÍCULOS---------')
#declaracao de variaveis - INICIO
nome = str(input('Nome completo: '))
ano = int(input('Ano de Nascimento: '))
prof = str(input('Sua profissão: '))
end = str(input('Seu endereço: '))
fone = str(input('Seu telefone: '))
email = str(input('Seu email: '))
curso1 = str(input... |
b817cd12ee0dfc2c629bb96e7ae3f4cfc32ca886 | JBaba/PyLearn | /Scripts/classExp.py | 1,389 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 16 10:56:09 2015
@author: nviradia
"""
class Robot:
""" This is robot class """
population = 0
def __init__(self,name):
""" Init the robot class """
self.name = name
print("class",self.name,"is initialized")
Robot.pop... |
97e0d6e56de983f5e223e39cf58700df77016b63 | StanislawAniola/Recruitment_task_backend_internship032021 | /currency_project/DatabaseClient.py | 6,533 | 3.8125 | 4 | import sqlite3
from sqlite3 import Error
from datetime import datetime
class DatabaseClient():
"""
establish connection to database
:return: connection object
"""
def __init__(self, start_date, end_date, currency_name="btc-bitcoin"):
self.start_date = start_date
self.end_date = end... |
1dcf46d72d77e69d34b2bea1157f17ca3b714f1e | fzjawed/Snake-Game | /PetPy.py | 3,960 | 3.84375 | 4 | import turtle
import time
import random
delay = 0.1
score = 0
high_score = 0
#Setting the window for the game
wnd = turtle.Screen()
wnd.title("Snake Game by Zo")
wnd.bgcolor("light blue")
wnd.setup(width=600, height=600)
wnd.tracer(0)
#Setting the text for the game
pen = turtle.Turtle()
pen.speed(0)... |
b576d5bc9865fdaa4a352b2630fb318e17fcc110 | BoraxTheClean/advent-of-code-2020 | /day2/day_2.py | 653 | 3.625 | 4 | def password_validator(constraint,char,password):
start,end = parse_range(constraint)
return bool(password[start-1] == char) != bool(password[end-1] == char)
def parse_range(constraint):
constraint = constraint.split('-')
return int(constraint[0]),int(constraint[1])
def get_input():
f = open('in... |
9e58c0d9f59a650d5a1d037fecb0dbad996fbdbb | AshFromNowOn/Hansard_sentiment | /Python/search_mockup.py | 2,402 | 3.671875 | 4 | # COMPLETELY FAKE SEARCH MOCKUP THAT DOES NOTHING
print("What would you like to do?")
print("1: Search via Member of Parliament Name \n"
"2: Search via Topic\n"
"3: Input Sentence for sentiment extraction\n"
"4: Retrain Sentiment Analysis Model(!)\n"
"Q: Quit Program")
input("Choice:")
print("--... |
c8aa33cedd74a6de08899ed01c0f710aa88ef83f | BenAAndrew/AStar | /tools/vector.py | 790 | 4.1875 | 4 | class Vector:
"""
Class to represent a position on the maze.
Stores x & y and enables some useful tools.
"""
def __init__(self, tuple):
self.x = tuple[0]
self.y = tuple[1]
def __str__(self):
return f"x: {self.x}, y: {self.y}"
def get_values(self):
return se... |
3ae0e868f8e29967e9739d7a4466961f60aa48c3 | Aasthaengg/IBMdataset | /Python_codes/p02403/s318962068.py | 95 | 3.578125 | 4 | while 1:
h,w=map(int,raw_input().split())
if (h,w)==(0,0):
break
print ("#"*w+"\n")*h |
12514f423d6f7e4d95b1781cda7da73b6bdac9aa | nnayk/PythonStuff | /61a/2021/Lab1/Q6.py | 417 | 4.15625 | 4 | def falling(n, k):
"""Compute the falling factorial of n to depth k.
>>> falling(6, 3) # 6 * 5 * 4
120
>>> falling(4, 0)
1
>>> falling(4, 3) # 4 * 3 * 2
24
>>> falling(4, 1) # 4
4
"""
"*** YOUR CODE HERE ***"
if k==0:
return 1
else:
product=k
... |
4f953276889a63df2ef8eeed0802aaa340e9909b | Qiong/ycyc | /pchallengecom/equality.py | 1,026 | 3.640625 | 4 | #http://www.pythonchallenge.com/pc/def/equality.html
#http://www.pythonchallenge.com/pc/def/linkedlist.php
#http://wiki.pythonchallenge.com/index.php?title=Main_Page
#http://wiki.pythonchallenge.com/index.php?title=Level3:Main_Page
import string
import re
def main():
"""
This is testing for comments
for multiple ... |
170d7a6323e5df6fc018ed0063ac3155cd6622b9 | TestowanieAutomatyczneUG/laboratorium-9-cati97 | /tests/test_car.py | 1,052 | 3.5625 | 4 | import unittest
from unittest.mock import *
from src.Car import *
class TestCar(unittest.TestCase):
def setUp(self):
self.temp = Car()
def test_needsFuel_return_true(self):
self.temp.needsFuel = Mock(name='needsFuel')
self.temp.needsFuel.return_value = True
self.assertEqual(se... |
e806b00d811753b564fd057d6288a2dd34de3428 | cardinalion/leetcode-medium | /998_Maximum_Binary_Tree_II.py | 672 | 3.6875 | 4 | class Solution:
def insertIntoMaxTree(self, root: 'TreeNode', val: 'int') -> 'TreeNode':
add = TreeNode(val)
if root == None:
return add
if root.val < val:
add.left = root
return add
tmp = root
while tmp ... |
2061b686f9aed9382e7c160d43fada6f70c54c89 | Divyansh-03/PythoN_WorK | /leap_year.py | 402 | 4.3125 | 4 | ''' Any year is input through the keyboard. Write a program to
determine whether the year is a leap year or not.
(Hint: Use the % (modulus) operator) '''
year = int(input( " Enter an year "))
if year %4 ==0 :
if year%100==0:
if year%400==0 :
print(" It is a Leap Year ")
else :
print(" It is not a Leap yea... |
11d9ee67f5aa71bb15048d434720d90173dc886a | akula0611/positive-number | /positive numbers.py | 193 | 3.859375 | 4 | pos=[]
InputList=list(map(int,input("Enter input list with spaces in between each number").split()))
for i in InputList:
if i>0:
pos.append(i)
print("The positive number are ",pos)
|
aa0da4713e3b2c888ff94ace67ff870d6ba92dad | JoyKrishan/Personal_Projects | /2 Web Access using Python/Regex.py | 310 | 3.609375 | 4 | import re
fname=input('Enter the file name\n')
lst=list()
try:
fhandle=open(fname)
except:
print('File could not be found',fname)
quit()
for line in fhandle:
if re.search('[0-9]+',line):
num=re.findall('[0-9]+',line)
for i in num:
lst.append(int(i))
print(sum(lst))
|
1229676ec32b6f8bb15cef4da29a06616437e672 | cliffpham/algos_data_structures | /algos/loops/unsorted_subarray.py | 746 | 3.671875 | 4 | import unittest
class Test(unittest.TestCase):
def test1(self):
self.assertEqual(
solve([2, 6, 4, 8, 10, 9, 15]),
5
),
def test2(self):
self.assertEqual(
solve([1,2,3,3,3,3]),
0
)
def solve(nums):
nums_sorted = nums[:]
num... |
14919685cb619ff2b687d908003bef0dab47adb3 | Sudo-Milin/Coursera_Crash_Course_on_Python | /Module_3/Graded_Assesment_Q02.py | 399 | 4.4375 | 4 | ### The show_letters function should print out each letter of a word on a separate line.
# Fill in the blanks to make that happen.
def show_letters(word):
# For loop interates each letter in the 'word' parameter that is passed during the function call.
for letter in word:
# For each letter encountered is print... |
2a3bd8fec4825cd9b41279431bdb6bfe1a710eef | pydupont/Massey_teaching | /LinuxAndPythonIntroductionForStaff/python2/exercise1_recursive.py | 287 | 4.125 | 4 | # answer to the exercice 1 wiht a different method
# this is called a recursive method (i.e. the function calls itself)
def fibonnaci(n):
if (n==0):
return 0
elif (n==1):
return 1
else:
return fibonnaci(n-1) + fibonnaci(n-2)
print fibonnaci(7)
|
336904cfc91ca04da3bce3ec282b20380b2641cb | bsarazin/sideways-shooter | /asteroid.py | 1,171 | 3.796875 | 4 | import pygame
from pygame.sprite import Sprite
class Asteroid(Sprite):
"""space rock!"""
def __init__(self, ai_settings, screen):
super(Asteroid, self).__init__()
self.ai_settings = ai_settings
self.screen = screen
self.speed_factor = self.ai_settings.asteroid_speed_factor
... |
6d330e122a705d3cc7de29a7101a37950c574f00 | thiago-allue/portfolio | /02_ai/1_ml/3_data_preparation/code/chapter_26/01_define_dataset.py | 629 | 3.578125 | 4 | # example of creating a test dataset and splitting it into train and test sets
from sklearn.datasets import make_blobs
from sklearn.model_selection import train_test_split
# prepare dataset
X, y = make_blobs(n_samples=100, centers=2, n_features=2, random_state=1)
# split data into train and test sets
X_train, X_test, y... |
507dd557d8018c48f3b1a643d1871d6a2c1a5fdb | Jason-Yuan/Interview-Code | /LeetCode/Binary_Search_Tree_Iterator.py | 827 | 3.921875 | 4 | # Definition for a binary tree node
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class BSTIterator(object):
def __init__(self, root):
self.q=[]
while root:
self.q.append(root)
ro... |
79240a2a5774e149b9b7ad897c68154f62f322bf | wangyendt/LeetCode | /Contests/301-400/week 302/2341. Maximum Number of Pairs in Array/Maximum Number of Pairs in Array.py | 685 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 _*-
"""
@author: wangye(Wayne)
@license: Apache Licence
@file: Maximum Number of Pairs in Array.py
@time: 2022/07/17
@contact: wang121ye@hotmail.com
@site:
@software: PyCharm
# code is far away from bugs.
"""
import collections
from typing import *
class Solution:
... |
8900814ba83e94345c3c1b8261653dbad0ab55d8 | justRadek/pythonStudy | /recusrcion, iteration.py | 2,291 | 4.3125 | 4 | #fibonaci by using generators
"""def fib(num):
a, b = 0, 1
for i in range(0, num):
yield "{}: {}".format(i+1, a)
a, b = b, a+b
for item in fib(12):
print(item)"""
#generators for listing dictionarz items
"""myDict = {"throne": "iron", "ass": "huge", "number": "infinite"}
for ke... |
bdb39e85ed5a155510175404197c7ca66240dd8b | iaora/ClappyBird | /quest.py | 1,199 | 3.9375 | 4 | import pygame
class QuestGame(object):
""" This class is a basic game.
This class will load data, create a pyscroll group, a hero object.
It also reads input and moves the Hero around the map.
Finally, it uses a pyscroll group to render the map and Hero.
"""
def __init__(self):
""" In... |
cfd60d34e598c28342c70f79724b5f2fea351a76 | basimsahaf-zz/Coding-Challenges | /nthtolast.py | 1,566 | 3.921875 | 4 | """Write a function that takes a head node and an integer value n and
then returns the nth to last node in the linked list."""
class Node(object):
def __init__(self,k):
self.value = k
self.nextnode = None
#Testing Client
class TestNthToLast(object):
def TestClient(self,sol):
a = Node... |
d8a5dcf066fc8e69f35fb6647a48c1d7ab53fa56 | imnotbeno/Algorithms-and-Data-Structures | /dynamic_programming.py | 688 | 4.4375 | 4 | # !python3
# Memoization of nth fibonacci number, using a lookup table
'''
def fib(n, lookup):
# bas case
if n == 0 or n == 1:
lookup[n] = n
# if the value is not in the lookup array, calculate it and store it
if lookup[n] is None:
lookup[n] = fib(n-1, lookup) + fib(n-2, lookup)
... |
a41108c300fa310c836d5c2f225929bb02c279a2 | YMyajima/CodilityLessonPython | /lesson4-1/solution.py | 1,045 | 3.640625 | 4 | class TestValue:
def __init__(self, A, expect):
self.A = A
self.expect = expect
class Solution:
def __init__(self):
self.test_values = [
TestValue([4, 1, 3, 2], 1),
TestValue([4, 1, 3], 0),
TestValue([3, 1], 0),
TestValue([3, 3, 2], 0),
... |
c61c8f95784a8ac91a1a85f0e6b12b8552d2cc03 | alosoft/bank_app | /bank_class.py | 2,453 | 4.3125 | 4 | """Contains all Class methods and functions and their implementation"""
import random
def account_number():
"""generates account number"""
num = '300126'
for _ in range(7):
num += str(random.randint(0, 9))
return int(num)
def make_dict(string, integer):
"""makes a dictionary of Account N... |
46d6976a5cd7a7b7b1ce657ac7aee54f98fc3de9 | Wambonaut/Machine-Learning-Homework | /ExerciseSheet2/Exercise1.py | 834 | 3.65625 | 4 | import numpy as np
import matplotlib.pyplot as plt
##Exercise 1: Mean-shift and K-Means
##1a) Implement the Epanechikov-Kernel
def k(x,mu=0,w=1):
return np.where(np.abs((x-mu)/w)<1, 3/(4*w)*(1-((x-mu)/w)**2), 0)
x=np.linspace(-3,3,100)
plt.plot(x, k(x))
plt.show()
##1b) Mean-shift on a 1d data set
def mean_shi... |
a5d5780a39642ab67414f3b0563dffb4be8f95de | cealicea171/todo-manager | /manager.py | 5,688 | 4.0625 | 4 | import time
import datetime
import item
class Manager(object):
print('Hi, Welcome to your Reminder App')
def startUp():
print('1 : Would you like to see your tasks?')
print('2: Would you like to create a task?')
print('3: Would you like to mark a task complete?')
decision = ... |
159a822e425c79b78c16a264d76b4de610ed59a4 | YanivHollander/HashcodeDelivery | /OrderInventory.py | 3,273 | 3.84375 | 4 | from Definitions import Product
import unittest
from typing import Dict
class Order(object):
def __init__(self):
self._products: Dict[Product, int] = {} # Dictionary for frequency of each product
def __repr__(self):
return repr((self._products))
def __str__(self):
ret = "Order: "... |
443803f431de9b818d4733718eb43cfd2d665d8a | lqzcf10/helloworld | /Pyhton/nine.py | 525 | 3.875 | 4 | class PrintTable(object):
'''ӡžų˷'''
def __init__(self):
print('ʼӡ9*9˷')
self.print99()
def print99(self):
#for(int i=1; i<10; i++){
# for(int j=1; j<=i; j++){
# print('%d*'+i+'%d='+j+(i*j)+' ');
# }
# println();
#}
for i i... |
8ea56d030bb00fc9facec5712b2c79278872b31b | Rediet8abere/leetcode | /container.py | 512 | 3.515625 | 4 | def maxArea(height):
"""
:type height: List[int]
:rtype: int
"""
maxarea = -2147483648 #minValue
area = 0
i = 0
j = len(height)-1
while i<j:
if height[i] < height[j]:
area = height[i]*(j-i)
i+=1
... |
a2009148ed8bdf2b701e981d900fe5eb57f57464 | ShravanSk123/Data_Structures | /ProbSolvingAlgo/ValidateIP.py | 584 | 3.765625 | 4 | # validates ipv4 and ipv6 addresses
import re
def isIPV4(s):
try:
return str(int(s)) == s and 0 <= int(s) <= 255
except:
return False
def isIPV6(s):
if len(s)>4 or re.match("\W",s): # "\W" is used for special characters
return False
try:
int(s,16)
return Tru... |
e1ed3fe70cd61eeb94137759526a0818467b548c | davidbusch1/pythonExercises | /ex2.py | 688 | 3.984375 | 4 | #Faça um programa para calcular e exibir a porcentagem
#de comissão de vendas de um vendedor, conforme o volume
#mensal de vendas do mesmo digitado pelo usuário
vendas = float(input("Digite o valor de vendas: "))
if vendas <= 5000:
comissao = vendas * 0.02
print(f'O valor da sua comisão é de {comissao}.'... |
bb8a86b2c13d3ee77eca2a27be11894648211497 | ai2-education-fiep-turma-2/05-python | /solucoes/Sergio/ex2.py | 436 | 4.03125 | 4 | idade = int(input("Digite a sua idade: "))
if(idade >= 16 and idade <= 69):
peso = int(input("Digite o seu peso (em kg): "))
if(peso >= 50):
horas_sono = int(input("digite quantas horas dormiu na última noite: "))
if(horas_sono >= 6):
print("Tudo certo para sua doação de sangue, obrigado!")
else:
print(... |
5c7b28864969b1053fe60fd9410cc11f7b41f38d | masrur-ahmed/Udacity-AI-for-Trading-Nanodegree | /quiz/m5_financial_statements/readability_solutions.py | 1,739 | 3.53125 | 4 | # solutions for readability exercises
# tokenize and clean the text
import nltk
import numpy as np
from nltk.stem import WordNetLemmatizer, SnowballStemmer
from collections import Counter
from nltk.corpus import stopwords
from nltk import word_tokenize
from syllable_count import syllable_count
nltk.download('wordnet... |
5e96b4a4032e67a3af1abbdbdb75dc0bfa3989e2 | SalmaHassan3/8Puzzle | /8Puzzle.py | 8,470 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 15 15:23:44 2018
@author: salma
"""
import heapq
import math
import timeit
#A class for nodes in search tree
class Node:
#constructor
def __init__( self, board, parent, operator, depth):
self.board= board
self.parent = parent
self.operator = o... |
6ea073999482bceaf7bbd23336bbd8bf6379f288 | DanLesman/euler | /p4.py | 323 | 3.8125 | 4 | def is_palindrome(n):
for k in range (1,len(str(n))/2+1):
if str(n)[k-1] is not str(n)[len(str(n))-k]:
return False
return True
largest_palindrome = 0
for i in range (100,1000):
for j in range (100,1000):
if is_palindrome(i*j) and i*j > largest_palindrome:
largest_palindrome = i*j
print (largest_palindro... |
6ed262c90acd762b453335f6b558d55a7fa39566 | alectar/Study_Python | /WORKDIR/Calc_1.py | 475 | 3.765625 | 4 | #! Python3
import sys
A = int(sys.argv[1])
B = int(sys.argv[3])
Opr = sys.argv[2]
print(str(A) + ' and '+ str(B))
if Opr == '+':
print (str(A) + ' ' + Opr + ' ' + str(B) + ' = ' + str(A+B))
elif Opr == '-':
print(str(A) + ' ' + Opr + ' ' + str(B) + ' = ' + str(A-B))
elif (Opr == 'x') or (Opr == '*'):
print... |
10f40c4a02e45a8e36f03458a4d27882aaaa16e3 | NoSuchThingAsRandom/Arcade-Games | /Snake/Snake.py | 6,400 | 3.734375 | 4 | import random
import time
import pygame
def play(increase_speed):
# Colours
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# Dimensions
rows = 25
columns = 25
cell_width = 20
cell_height = 20
offset_height = 0.1
o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.