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 |
|---|---|---|---|---|---|---|
e4fe12b549beafec5188cac113b2fe5dc2c474d1 | Vivek15494/vehivle | /vehicle.py | 643 | 4.03125 | 4 | class vehicle():
no_of_wheels= 0
speed= 0
weight= 0
mileage= 0
color= ' '
def __init__(self,no_of_wheels,speed,weight,mileage,color):
self.no_of_wheels=no_of_wheels
self.speed=speed
self.mileage=mileage
self.color=color
de... |
6576d205ded2eb55bb61f325c12e4c57926e3961 | Chaudhari-Chirag/sippython | /exercise/ex2.py | 256 | 4.1875 | 4 | # -*- coding: utf-8 -*-
def max_of_three(num1, num2, num3):
if num1 > num2 > num3:
return num1
elif num1 < num2 < num3:
return num3
else: return num2
print (max_of_three(2, 3, 4))
print (max_of_three(4, 3, 2))
print (max_of_three(2, 4, 3)) |
4fd91d5b414a5268ea4baceed3e5a36a65e289a4 | Chaudhari-Chirag/sippython | /sip/sipA24_revloops.py | 458 | 4.21875 | 4 | # -*- coding: utf-8 -*-
#loops
#for loop
for i in range(1,5):
print(i, end=' ')
for i in range(1, 20):
if i%2==0:
print(i, 'is even number')
for i in range(1, 100):
if i%i==0 and i%2>0 and i%3>0 and i%5>0:
print(i, 'is prime number')
#while
while True:
s = input("Enter ... |
beaeb644f8fe8229b68743dd33a8c898fa70a701 | Nathiington/COMP322 | /Lab03/greatest.py | 279 | 4.1875 | 4 | num1 = int(input('Enter the first number: '))
num2 = int(input('Enter the second number: '))
if num1 > num2:
print('{0} is greater than {1}'.format(num1,num2))
if num2 > num1:
print('{0} is greater than {1}'.format(num2, num1))
else:
print('Both numbers are equal')
|
15c333a2098d819b9a27780609d683801c0e8643 | Btrenary/Module6 | /basic_function_assignment.py | 737 | 4.15625 | 4 | """
Author: Brady Trenary
Program: basic_function_assignment.py
Program takes an employee's name, hours worked, hourly wage and prints them.
"""
def hourly_employee_input():
try:
name = input('Enter employee name: ')
hours_worked = int(input('Enter hours worked: '))
hourly_pay_rate = floa... |
355d86803b6327930efb2ff6800a6120d07d5179 | surya-dev-singh/ceaser_cipher | /ceasear.py | 2,372 | 4.03125 | 4 | """program made by suryadevsingh"""
import time
print()
time.sleep(0.1)
print(" ########################")
time.sleep(0.1)
print(" CEASEAR CIPHER")
time.sleep(0.1)
print(" ########################")
time.sleep(0.1)
alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
alpha_to_numbe... |
8e18f3adfa72e6155048c8d91a6bd551641dce9e | GhayoorUlHaq/basic-python-codes | /gcd_with_euclidean_algo_using_while_loop.py | 338 | 3.8125 | 4 | def gcd(num1, num2):
dividend = max(num1, num2)
divisor = min(num1, num2)
remainder = dividend % divisor
while remainder >= 0:
if remainder == 0:
return divisor
else:
dividend = divisor
divisor = remainder
remainder = dividend % divisor
... |
b247074ec75f920382e80eeae0f68a123d8e15d0 | mathe-codecian/Collatz-Conjecture-check | /Collatz Conjecture.py | 743 | 4.3125 | 4 | """
The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined as follows: start with any positive integer n.
Then each term is obtained from the previous term as follows: if the previous term is even, the next term is one half the previous term.
If the previous term is odd, the next term i... |
1f77b65cded382e0c1c0b149edf94e02c67f5bb5 | farremireia/len-slice | /script.py | 375 | 4.15625 | 4 | toppings = ['pepperoni', 'pineapple', 'cheese', 'sausage', 'olives', 'anchovies', 'mushrooms']
prices = [2,6,1,3,2,7,2]
num_pizzas = len(toppings)
print('We sell ' + str(num_pizzas) + ' different kinds of pizzas!')
pizzas = list(zip(prices, toppings))
print(pizzas)
pizzas.sort()
print(pizzas)
cheapest_pizza = pizza... |
7737532e3bd26e6c3a7e9111df63ccd9d2b30632 | Akash127/Ticket-Viewer | /app/Connector.py | 1,931 | 3.59375 | 4 | import requests
from ConnectionConfig import Configuration
class ApiConnector:
'''Class defines API Connector Object to execute Query'''
def execute(self, query):
"""Execute the Query from Request Object using python
requests library.
Args:
query: A string which specifies the query ... |
9e91a77870db3c8b38edfe9b1f7a7fe53f3a7481 | Grigorii-Ilin/types-and-data-structures | /lift_v2/elevator.py | 7,173 | 3.578125 | 4 | from button import Button
from floor import Floor
from passenger import Passenger
class Elevator:
def __init__(self, index, floor):
self.id = index
self.max_weight = 500
self.cur_floor = floor
self.cur_passengers = []
self.is_elevator_up = False
self.is_elevator_dow... |
083b939bd350d016551eb51524fc80f7783c5c33 | jijerry/start_python | /program/str_maxnum.py | 405 | 3.640625 | 4 | """输出一个字符串中次数最多的字母和次数"""
s="aaaaaaaaaaaabbcccccddxxxxffff"
max_s_count = 0
max_s_count_letters = []
for i in s:
if s.count(i) > max_s_count:
max_s_count_letters = []
max_s_count = s.count(i)
if s.count(i) == max_s_count:
max_s_count_letters.append(i)
max_s_count = s.count(i)
pri... |
f6b536d65c9a58cc8b73b5349e29276c80f805d8 | Straw17/games | /Bagels.py | 1,500 | 4.09375 | 4 | import random
def getClue(secretNumber, guess):
clue = ''
for number in range(3):
if guess[number] in secretNumber and secretNumber[number] != guess[number]:
clue += 'Fermi '
elif secretNumber[number] == guess[number]:
clue += 'Pico '
if clue == '':
clue += '... |
c8342e18d1077d68cc9347caed09992dd79e566b | zym1990/python-learning | /pythonList.py | 452 | 4.0625 | 4 | magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)
#数字列表
for value in range(1,5):
print(value)
squares = []
for value in range(1,11):
square = value ** 2
squares.append(square)
print(squares)
for value in range(1,21,2):
print(value)
car = 'subaru'
print("is c... |
47e4b467aeb7ce8df8dd7077ce4ef88ecf3e3b70 | sgk98/travelling_salesman | /nn.py | 910 | 3.734375 | 4 | import pickle
import math
'''
Implementation of nearest neighbour algorithm for Travelling Salesman
'''
def nn():
fo=open("adj_mat","rb")
adj_mat=pickle.load(fo)
fo.close()
visited=[False for i in range(len(adj_mat))]
path=[0]
visited[0]=True
cost=0
while len(path)<len(adj_mat)+1:
... |
feb17193c8ad29ba2f6115627c95965105c83120 | lia-diez/Labs-Holovach | /lab5/lab5.py | 190 | 3.96875 | 4 | numb = int(input("Enter the number: "))
n = numb
while n > 9 :
sum = int(0)
while n > 0 :
sum += n % 10
n //= 10
n = sum
print ("The digital root of the number is:", n)
a = input ("") |
ff76720585886ea808fab74be605b6eda91e466e | geniusljr/Leetcode-Python | /Binary Tree Maximum Path Sum.py | 851 | 3.609375 | 4 | # Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return an integer
def maxPathSum(self, root):
maxSum = [-10000]
def m... |
4dd6b29ee3df71572d52c7efc23471e5ee4edbfb | yuyiwx/preparatorio-obi | /Aulas/6/subsets.py | 558 | 3.859375 | 4 | def subsets(nums, index):
# caso base
if index == len(nums): # lista vazia
return [[]]
# recursão
val = nums[index]
subsets_without = subsets(nums, index + 1) # todos os subconjuntos que não possuem val
subsets_with = [] # todos os subconjuntos que possuem val
for subset_without in s... |
543958853e30aac68b90aeec4a0709e78c53e507 | kalliroku/python_Algorithm_data_structure | /prime_number_gen.py | 1,061 | 3.703125 | 4 | # faster prime number generator
def prime1(n):
n += 1
checker = [True] * (n // 2)
for i in range(3, int(n ** 0.5) + 1, 2):
if checker[i // 2]:
k = i * i
ckecker[k // 2::i] = [False] * ((n - k - 1) // (2 * i) + 1)
return [2] + [2 * i + 1 for i in range(1, n // 2) if check... |
e9d41f89c9cd90972097f33ef97be1865f27a823 | stationarysalesman/betweenseq | /repeatsequences.py | 696 | 3.609375 | 4 | from bitmap import BitMap
class RepeatSequences:
"""Class to aggregate both repeat sequences and repeat
sequence bitmap into a single object."""
def __init__(self, size, frame_min, frame_max):
self.repeats = dict()
self.subseqs = dict()
self.bitmap = BitMap(size)
self.frame... |
b4483284ef1ac923c5def6cc3f7a1cfd5e5bb659 | davidquezada7/LaterT | /Alespi/alespi.py | 3,203 | 3.5625 | 4 | """
Google Vision API Tutorial with a Raspberry Pi and Raspberry Pi Camera. See more about it here: https://www.dexterindustries.com/howto/use-google-cloud-vision-on-the-raspberry-pi/
Use Google Cloud Vision on the Raspberry Pi to take a picture with the Raspberry Pi Camera and classify it with the Google Cloud Visi... |
62a247fa58ff4a293b335cf60fc45301ccb35091 | igorlousada/Curso-Basico-Alura | /seletor.py | 363 | 3.703125 | 4 | import adivinhacao
import forca
import random
print("Bem-vindo")
jogo = input("Qual jogo deseja jogar? (1) adivinhação (2)forca")
while True:
try:
jogo = int(jogo)
break
except:
print("Por favor, digite (1) para adivinhação e (2) para forca")
if jogo == 1:
adivinhacao.jogar(... |
1444f531d0e34ce3a857679d7689ebb74ab4e91e | gmaxwell1/pyECB_gmaxwell | /modules/arduinoPythonInterface.py | 6,743 | 3.515625 | 4 | """
Script for communication with Arduino Uno using standard serial protocol. A sketch needs
to be uploaded to the board for communication to be possible. Data is simply written to/
fetched from the serial port, so this script is mainly good for obtaining data from the
Arduino/whatever it is connected to.
Mainly for g... |
deefa01ac0ab3c0e80a00f0c963e61f8bd0281cf | huangyingw/Leetcode-Python | /47.py | 735 | 3.625 | 4 | '''
Time complexity: O(N*N!)
'''
from collections import defaultdict
class Solution:
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
ret = []
used = defaultdict(lambda: False)
self.dfs(nums, ret, [], u... |
5794cd2981f0da6f67d0b4c9202b1eefd7b2b349 | huangyingw/Leetcode-Python | /95.py | 979 | 3.859375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
if n == 0:
re... |
e989599eac34e9fe7087e7b3d8289182fbe66034 | huangyingw/Leetcode-Python | /211.py | 1,180 | 4.09375 | 4 | class TrieNode:
def __init__(self):
self.children = {}
self.isWord = False
class WordDictionary:
"""
@param: word: Adds a word into the data structure.
@return: nothing
"""
def __init__(self):
self.root = TrieNode()
def addWord(self, word):
node = self.roo... |
2cbe7a3154e4ff637ffe4cd317a3666c587dc875 | huangyingw/Leetcode-Python | /84.py | 513 | 3.5 | 4 | from typing import List
class Solution:
def largestRectangleArea(self, heights):
"""
:type heights: List[int]
:rtype: int
"""
stack = [-1]
heights.append(-1)
result, i = 0, 0
while i < len(heights):
if heights[i] >= heights[stack[-1]]:
... |
739265e873d8b1bd2504bb6958ce36488c6e2d8b | ZhangJifei/Study | /python/for.py | 66 | 3.734375 | 4 | a = ['A', 'B' , 'C']
for name in a:
print ("Hello %s" % name) |
87d31fe1d670b7c6dc43441b6eefc8f578cadc52 | truevines/GenericExercise | /isomorphic_strings.py | 1,115 | 4.1875 | 4 | '''
Given two strings s and t, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but ... |
d46999e4c6dd96a8edeac232fa3a989160530596 | alexzinoviev/itea_c | /advance/advance_04_3.py | 1,234 | 4.15625 | 4 | # class A:
# def __init__(self):
# self.x = 0 # public переменная
# self._x = 0 # private - не использовать!
# self.__x = 0 # hidden
#
#
# a = A()
# print(a.x)
# print(a._x)
# #print(a.__x)
#
# print(vars(a))
#
# print(a._A__x)
# class A:
# def __init__(self):
#... |
eb8d59a0d3ef46728c6c58f403a6b648e2d7fee3 | alexzinoviev/itea_c | /advance/advance_07.py | 1,929 | 3.890625 | 4 | class MyList:
def __init__(self, l):
#self._l = l.copy()
self._l = list(l) # защита от изменения внешнего состояния, и всегда будет списком
def __repr__(self):
return repr(self._l)
def add(self,a ):
self._l.append(a)
def __len__(self):
return len(self._l)
... |
07f099a03f47adb01089fa5ee59dc5788822a44e | alexzinoviev/itea_c | /advance/db/sql.py | 591 | 3.953125 | 4 | import sqlite3
db = sqlite3.connect('db.sqlite3')
cursor = db.cursor()
#c1 = cursor.execute("select * from students")
# print(c1)
# print(c1.fetchone())
# print(c1.fetchone())
# print(c1.fetchmany(2))
# print(c1.fetchall())
# for row in c1:
# print(row)
cursor.execute("insert into students (name, subj, mark) va... |
eaabc85901abae0664218830d9977eb2ea9a969f | alexzinoviev/itea_c | /base/test.py | 313 | 3.625 | 4 | # def checkio(number):
# # Your code here
# # It's main function. Don't remove this function
# # It's using for auto-testing and must return a result for check.
#
# # replace this for solution
# return str(number)
def fizzbuzz():
number = int(input("a=", a))
#print("my num", number) |
3257d03566e2167b4524ccce23976b545f1031a0 | alexzinoviev/itea_c | /advance/advance_17_3.py | 774 | 3.765625 | 4 | import tkinter as tk
from tkinter import messagebox
def calc():
try:
resv.set(xv.get() + yv.get())
except:
messagebox.showerror('Error', 'Invalid number')
def exit():
quit()
root = tk.Tk()
xv = tk.IntVar()
yv = tk.IntVar()
resv = tk.IntVar()
l1 = tk.Label(root, text='X:')
l1.grid(row... |
4599ae7839b9baa48c1bb64e39de3ee2dbb6cc26 | alexzinoviev/itea_c | /base/python_base3_2.py | 1,509 | 3.734375 | 4 | # автомат для ввода денег, номиналы 1 грн 50 25 5 1 коп - выдать деньги оптимальным количеством монет
# перевести число в копейки
coin_100 = 100
coin_50 = 50
coin_25 = 25
coin_5 = 5
coin_1 = 1
try:
amount = float(input('amount='))
if amount<0:
raise ValueError("Amount can't be less then 0")
amount... |
1298ee30fc05673e328c16d89b266a1c043b57db | alexzinoviev/itea_c | /advance/advance_10_2.py | 412 | 3.734375 | 4 | """
многопоточность
modules:
threading
multiprocessing
"""
import threading
import time
print(time.ctime())
l = threading.Lock()
a = 0
def f():
global a
for i in range(10000):
l.acquire()
a += 1
l.release()
ts = []
for i in range(100):
t = threading.Thread(target=f)
t.start... |
676cb92df66f7e93c7d367afc2c7793683637334 | alexzinoviev/itea_c | /base/python_base5.py | 145 | 4.09375 | 4 | def max_(x,y):
"""add x and y
>>> max_(2,3)
3
>>> max_(3,2)
3
"""
if x>y:
return x
else:
return y |
0a9904a2b00b620c6f7782091febf87ed5a41162 | generation-DELON02/Sandra-Mini-Project | /archive projects/order.py | 551 | 3.640625 | 4 | #create a json file with dict info
#open json file
#pass dictionary through to json
#write to json file
import json
order_list=[]
dicts={ "customer_name": "John", "customer_address": "Unit 2, 12 Main Street, LONDON, WH1 2ER", "customer_phone": "0789887334", "courier": 2, "status": "preparing" }
order_list.append(... |
c36aed981c24c916208fdfb226b2a53b8248ab0b | hadesfranklyn/TabelaHashPython | /TabelaDeHash/lista_encadeada.py | 1,120 | 3.53125 | 4 | class Celula:
item = None
proximo = None
def __init__(self,item):
self.item = item
class Lista_Encadeada:
inicio = None
tamanho = 0
def __init__(self):
self.inicio = Celula(None)
#verificar se tá vazia
def estaVazia(self):
return self.tamanho == 0
#inserir
def inserir(self,item,pos):
if pos <= se... |
8bfdbde94ed88f87b3abf8b59f8b2a0d9f280756 | v-shchenyatskiy/GB_Python | /1. Lesson_1/les01_2.py | 1,084 | 4.0625 | 4 | # Пользователь вводит время в секундах.
# Переведите время в часы, минуты и секунды
# Выведите в формате чч:мм:сс. Используйте форматирование строк.
# 1 s * 60 = 1 m * 60 = 1h = 3600 s
# 1h * 24 = 1d = 86400 s
user_sec = int(input('Введите время в секундах: '))
# 1 - считаем часы
days = 0
hours = user_sec... |
adc93ae32b9b422d66a8b2468040d8163f6e1560 | v-shchenyatskiy/GB_Python | /2. Lesson_2/les02_4.py | 684 | 3.96875 | 4 | # Пользователь вводит строку из нескольких слов, разделённых пробелами.
# Вывести каждое слово с новой строки.
# Строки необходимо пронумеровать.
# Если слово длинное, выводить только первые 10 букв в слове.
# user_str = input('Введите несколько слов: ')
user_str = 'one two three four five01234567890'
print... |
c39333e2bbcbc99597feeef943832466b3112555 | AlexPatrin/GB | /Less1_easy.py | 1,251 | 3.984375 | 4 | # Задача-1: поработайте с переменными, создайте несколько,
a = 10
b = 'privet'
# выведите на экран, запросите от пользователя и сохраните в переменную, выведите на экран
print(a)
print(b)
c = input()
print(c)
# Задача-2: Запросите от пользователя число, сохраните в переменную,
d = int(input('Input number: '))
# прибав... |
4ad070cba2a1995a50395109f1f64d5abc54972e | ma-haohao/interviewTest | /exception.py | 551 | 3.953125 | 4 | #用户自定义异常类型
class ToolLongException(Exception):
"this is user's exception for check the length of name"
def __init__(self,leng):
self.leng=leng
def __str__(self):
print(("姓名长度是"+str(self.leng)+",超过长度了"))
#手动抛出用户自定义异常类型
def name_Test():
try:
name=input("enter your name:")
... |
ad87ef1dc2c1256be8fb3964803230f40b6901cd | ma-haohao/interviewTest | /iterator.py | 1,182 | 3.921875 | 4 | #codin=uft-8
class Mylist(): #可迭代对象
def __init__(self,num):
self.data=num #上边界
def __iter__(self):
return MyListIterator(self.data) #返回该可迭代对象的迭代器实例
class MyListIterator(): #定义迭代器类,其是MyList可迭代对象的迭代器类
def __init__(self,data):
self.data=data #上边界
self.now=0 #当前迭代值
def _... |
8c4825263e04957d62bada8b95ac7b676e94a957 | AlenaGB/8hw | /3.py | 678 | 3.65625 | 4 | class Error:
def __init__(self, *args):
self.my_list = []
def my_input(self):
while True:
try:
val = int(input('enter the value and press Enter - '))
self.my_list.append(val)
print(f'current list - {self.my_list} \n ')
ex... |
721d2249971f486ccbe1f6c3b56b6f12668df097 | kajalkatiyar/python-game | /dice.py | 371 | 3.890625 | 4 | #import random
import secrets
#min = 1
#max = 6
foo = ['1','2','3','4','5','6']
roll_again = "yes"
while roll_again == "yes" or roll_again == "y":
print ("Rolling the dices...")
print ("The values are....")
# print (random.randint(min, max))
# print (random.randint(min, max))
print (secrets.choice(fo... |
4b959d64bec6abaa2273fd3f135a445d6781f92d | kajalkatiyar/python-game | /vowel.py | 133 | 4.09375 | 4 | def is_vowel(char):
all_vowels = 'aeiou'
return char in all_vowels
letter = input("Enter a letter:")
print(is_vowel(letter))
|
d3b95bbc57a7e67da64538597a257050f3799e7a | motleytech/euler | /problem5.py | 554 | 3.625 | 4 | #!/usr/bin/python
from tools.timeit import timeit
problem = """2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?"""
@timeit
def process():
# take product of p... |
28ddbdd6c1968fca0f4e9602ca5058746a2fe295 | motleytech/euler | /problem19.py | 1,285 | 3.859375 | 4 | #!/usr/bin/python
from tools.timeit import timeit
from pprint import pprint as pp
problem = """You are given the following information, but you may prefer to do some research for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone... |
f49af02dc9fa1a0c98abbfc3471126a9a915abfc | motleytech/euler | /problem17.py | 948 | 3.75 | 4 | #!/usr/bin/python
from tools.timeit import timeit
from pprint import pprint as pp
from tools.general import num2words
problem = """If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) ... |
be43602a66406f4106733b9359aa3358b7209f21 | HenriqueSamii/TP3-Fundamentos-de-Programa-o-com-Python | /tp3IntroPython8.py | 812 | 4.0625 | 4 | #Faça uma funçãoum programa em Python que simula um lançamento de dados. Lance o dado 100 vezes e armazene os resultados em um vetor. Depois, mostre quantas vezes cada valor foi conseguido.
# Dica: use um vetor de contadores (1-6) e uma função do módulo 'random' de Python para gerar números aleatórios, simulando os la... |
4ff05e7e75a3e2c673856f403acb1d4b282f8ac2 | HenriqueSamii/TP3-Fundamentos-de-Programa-o-com-Python | /tp3IntroPython15.py | 1,204 | 3.6875 | 4 | #Usando a biblioteca Pygame, escreva um programa que possui uma função que desenha na tela um estrela de 5 pontas no tamanho que preferir. (código e printscreen)
import pygame
larguraTela = 800
alturaTela = 600
tela = pygame.display.set_mode([larguraTela,alturaTela])
pygame.font.init()
pygame.mixer.init()
clock = ... |
5fe240def6db227bbca26b9b77375b6fb93405f8 | Michael-Tanzer/EG-Challenge | /DataProcessForNN.py | 946 | 3.734375 | 4 | import pandas as pd
def getCurrency(currency):
# gets all the data from the csv related to a given currency
DFrame=pd.read_csv("coin_data.csv")
num=0
for region, df_Type in DFrame.groupby('currency'):
num+=1
if str(region).lower()==currency:
return df_Type
def allCurrenc... |
ca6b96cdcf41fec2fd410ae4012b3efe9532abe9 | tabualhsan/dicts_restaurant_ratings | /dicts-restaurant-ratings/ratings.py | 1,306 | 3.640625 | 4 | """Restaurant rating lister."""
# put your code here
def restaurant_ratings(filename):
# open score file
ratings = open(filename)
# create empty dictionary
ratings_review = {}
# read ratings in file, split lines:
for rating in ratings:
sentences = rating.rstrip()
full_rest... |
408ea92f6ca6318502bb86abbb906b43e994f62c | Jorgeob1/Modelo | /ejercicio 6 factorial.py | 132 | 4.03125 | 4 | multiplicacion = 1
N=int(input("numero"))
for i in range(1, N+1):
print(i)
multiplicacion=multiplicacion*i
print(multiplicacion) |
7c6752a88f66c2943f4291a825df295e6cd1db6f | Jorgeob1/Modelo | /ejercicio numeros iguales.py | 265 | 3.96875 | 4 | a=int(input("primer numero entero"))
b=int(input("segundo numero entero"))
c=int(input("tercer numero entero"))
if (a==b==c):
print(3)
elif ((a==b)or(a==c)or(b==c)):
print(2)
#asi tambien vale
#elif ((a!=b)or(a!=b)or(b!=c)):
# print(0)
else :
print(0)
|
daefa385c338f15d9e9b300963fa6419e3736c15 | horis233/CSC411 | /CSC411A2/q2_2.py | 5,802 | 3.765625 | 4 | '''
Question 2.2 Skeleton Code
Here you should implement and evaluate the Conditional Gaussian classifier.
'''
import data
import numpy as np
# Import pyplot - plt.imshow is useful!
import matplotlib.pyplot as plt
def compute_mean_mles(train_data):
'''
Compute the mean estimate for each digit ... |
ebc4bd0e1f34ddadf4e482e046808743c562180a | clovisdasilvaneto/100DaysOfAlgorithmsAndDataStructures | /data-structures/hacker-rank-exercises/cycle-list.py | 375 | 3.734375 | 4 | #This solution is O(n/2)
def traverse_list(slow, fast):
if (fast == None or fast.next == None):
return False;
if (slow == fast):
return True;
slow = slow.next;
fast = fast.next.next;
return traverse_list(slow, fast)
def has_cycle(head):
if not(head):
return False... |
582e9d0e4df8eaee1dbae2703d180d74087a4a1c | NickGonzalez04/Intro-Python-II | /src/room.py | 1,148 | 3.625 | 4 | # Implement a class to hold room information. This should have name and
# description attributes.
class Room:
def __init__(self, name, description):
self.name = name
self.description = description
self.n_to = None
self.s_to = None
self.e_to = None
self.w_to = None ... |
010cecbc4ce21c683863a1628c08fdc8a04683c6 | Tryssca/pythongame | /pythongame.py | 5,717 | 3.6875 | 4 | #!/usr/bin/python
import pygame #for game creation
import random #for random events in game
import sys #to exit the game upon gameover
pygame.init() #start pygame
gameop = True #for while loop
black = ( 0, 0, 0)
white = ( 255, 255, 255)
red = ( 255, 0, 0)
green = ( 0, 255, 0) #colours
... |
ea84321a0a420d1db3f37f55ea55314149af43f1 | dianajyoo/django | /python3/python-refresher.py | 982 | 3.9375 | 4 | # variable
age = 26
name = 'diana'
print(age)
# conditional
if age > 18:
print("You're officially an adult!")
else:
print("Still young.")
# function
def hello():
print("Hello World!")
hello()
# list
names = ['Fido', 'Freddy', 'Pippa', 'Frankie']
names.insert(0, 'Jane')
del(names[2]) # mutates
len(names) # get... |
ed92f34213dfb09dbcfa5a340723bab3247d423e | BookOps-CAT/Bagel | /bagel/ingest.py | 3,847 | 3.671875 | 4 | from collections import namedtuple
import csv
Row = namedtuple(
"Row",
[
"processing",
"title",
"title_part",
"players",
"duration",
"age",
"central_barcodes",
"crown_barcodes",
"bushwick_barcodes",
"mckinley_barcodes",
"n... |
ea1e6124b2e54ec0d6be5931050e87b9def4e2de | samir-joshi/tmtoolkit | /tmtoolkit/preprocess/_tokenfuncs.py | 16,056 | 3.578125 | 4 | """
Functions that operate on single token documents (lists or arrays of string tokens).
"""
import re
import numpy as np
import globre
from ..utils import require_listlike, require_listlike_or_set, flatten_list, empty_chararray
#%%
def token_match(pattern, tokens, match_type='exact', ignore_case=False, glob_met... |
b0722ce7d3cb5ab89a099c4431c819a274639f41 | de-ritchie/discrete-math | /Math Thinking/1_1_permute.py | 329 | 3.640625 | 4 | def extend(perm, n):
if(len(perm) == n):
print('-----', perm)
for k in range(n):
if k not in perm:
perm.append(k)
#print('b4 ext', perm)
extend(perm, n)
#print('a4 ext', perm)
perm.pop()
#print('pop', perm)
extend(perm... |
aabd86e3aa0546f894b9a25173bab6a2988985d6 | daviditen/arkouda | /arkouda/message.py | 4,633 | 3.53125 | 4 | from __future__ import annotations
from dataclasses import dataclass
from enum import Enum
from typing import Dict
"""
The MessageFormat enum provides controlled vocabulary for the message
format which can be either a string or a binary (bytes) object.
"""
class MessageFormat(Enum):
STRING = 'STRING'
BINARY = ... |
3cb78954d5f06302fc9360fd2987f09114206c8f | bellatrixdatacommunity/data-structure-and-algorithms | /leetcode/string/jewels-and-stones.py | 962 | 3.953125 | 4 | '''
## Questions
### 771. [Jewels and Stones](https://leetcode.com/problems/jewels-and-stones/)
You're given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also ... |
2f79c4b94088313bba40293382c3c16b067fc7dc | bellatrixdatacommunity/data-structure-and-algorithms | /leetcode/string/to-lower-case.py | 474 | 3.859375 | 4 | '''
## Questions
### 709. [To Lower Case](https://leetcode.com/problems/to-lower-case/)
Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase.
Example 1:
Input: "Hello"
Output: "hello"
Example 2:
Input: "here"
Output: "here"
Example 3:
Input: "LOVELY"
Output: "... |
76063f31adbb59376f1edb97b7b93292f104bc0e | bellatrixdatacommunity/data-structure-and-algorithms | /leetcode/array/roman-to-integer.py | 2,431 | 3.78125 | 4 | '''
## Question
### 13. [Roman to Integer](https://leetcode.com/problems/palindrome-number/)
Roman numerals are represented by seven different symbols: `I, V, X, L, C, D and M` .
| | |
|**Symbol**|**Value**|
|:--:|:--:|
|I|1|
|V|5|
|X|10|
|L|50|
|C|100|
|D|500|
|M|1000|
For example, `two` is written as `II` in Rom... |
3a612971615e30ddeddc7f47cc9d459155df6a26 | bellatrixdatacommunity/data-structure-and-algorithms | /leetcode/array/height-checker.py | 1,678 | 3.9375 | 4 | """
## Questions
### 1051. [Height Checker](https://leetcode.com/problems/height-checker/)
Students are asked to stand in non-decreasing order of heights for an annual photo.
Return the minimum number of students not standing in the right positions. (This is the number of students that must
move in order for all st... |
955461e567e4ff3422aa0f6ed2e512c4c861f9ab | bellatrixdatacommunity/data-structure-and-algorithms | /leetcode/binary-search/valid-perfect-square.py | 955 | 3.8125 | 4 | """
## Questions
### [367. Valid Perfect Square](https://leetcode.com/problems/valid-perfect-square/)
Given a positive integer num, write a function which returns True if num is a perfect square else False.
Note: Do not use any built-in library function such as sqrt.
Example 1:
Input: 16
Output: true
Example 2:
I... |
51b521ba26622b6355a104e25ae2b48f9ed67a79 | bellatrixdatacommunity/data-structure-and-algorithms | /hackerearth/circuits/annoying-chemistry-f5fb9556.py | 1,544 | 3.5 | 4 | """
[Annoying Chemistry](https://www.hackerearth.com/challenges/competitive/march-circuits-20/algorithm/annoying-chemistry-f5fb9556/)
Max. Marks: 100
You are given a chemical equation of the following format:
Your task is to calculate the balancing factor b1, b2, and b3 such that the number of atoms of each of the elem... |
270b595ab778eb87a7d46fc3fac6f40360ebf99e | bellatrixdatacommunity/data-structure-and-algorithms | /CLRS/10-Elementary-Data-Structures/10-1-4.py | 687 | 4 | 4 | """
10.1-4
Rewrite ENQUEUE and DEQUEUE to detect underflow and overflow of a queue.
"""
class Queue:
def __init__(self, N):
self.N = N
def enqueue(self, Q, ele):
if len(Q) == self.N:
print("Queue Overflow")
return
Q.append(ele)
def dequeue(self, Q):
... |
73bcc1b5cab5ddd38a7951604bd0fd19cb426039 | bellatrixdatacommunity/data-structure-and-algorithms | /leetcode/array/search-insert-position.py | 804 | 3.953125 | 4 | """
## Questions
### 35. [Search Insert Position](https://leetcode.com/problems/search-insert-position/)
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Example 1:
`... |
f60e3d1e1b2f4234105924b8adecc7a86fb18be4 | bellatrixdatacommunity/data-structure-and-algorithms | /leetcode/minimax/nim-game.py | 1,135 | 3.765625 | 4 | """
[292. Nim Game](https://leetcode.com/problems/nim-game/)
You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you
take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn
to remove the stones.... |
82172ac03a98fc1ccd6e17f9eb9123e730e5c2f8 | bellatrixdatacommunity/data-structure-and-algorithms | /leetcode/string/validate-ip-address.py | 4,185 | 3.953125 | 4 | """
## Questions : Medium
### 468. [Validate IP Address](https://leetcode.com/problems/validate-ip-address/)
Write a function to check whether an input string is a valid IPv4 address or IPv6 address or neither.
IPv4 addresses are canonically represented in dot-decimal notation, which consists of four decimal numbers... |
2015f5b451abe7a95a15e358b79b7317fe7a8d21 | bellatrixdatacommunity/data-structure-and-algorithms | /leetcode/geometry/circle-and-rectangle-overlapping.py | 2,202 | 3.765625 | 4 | """
Questions : MEDIUM
[1401. Circle and Rectangle Overlapping](https://leetcode.com/problems/circle-and-rectangle-overlapping/submissions/)
Given a circle represented as (radius, x_center, y_center) and an axis-aligned rectangle represented as (x1, y1, x2, y2)
, where (x1, y1) are the coordinates of the bottom-left c... |
1a8017da20fa79bdbd9e6e7503e9e78166b4c17d | bellatrixdatacommunity/data-structure-and-algorithms | /leetcode/array/find-the-distance-value-between-two-arrays.py | 2,042 | 4.03125 | 4 | """
Easy
[1385. Find the Distance Value Between Two Arrays](https://leetcode.com/problems/find-the-distance-value-between-two-arrays/)
Given two integer arrays arr1 and arr2, and the integer d, return the distance value between the two arrays.
The distance value is defined as the number of elements arr1[i] such that ... |
6311d6256808b9a85ce9b79afd29f377b0d7db9f | bellatrixdatacommunity/data-structure-and-algorithms | /leetcode/tree/binary-tree-inorder-traversal.py | 1,520 | 3.921875 | 4 | """
Given a binary tree, return the inorder traversal of its nodes' values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [1,3,2]
Follow up: Recursive solution is trivial, could you do it iteratively?
"""
# Solutions
# Recursive Solution
class TreeNode:
def __init__(self, x):
self... |
5719e4d3c405a500611b448e50c8264519645f04 | bellatrixdatacommunity/data-structure-and-algorithms | /leetcode/array/find-common-characters.py | 1,016 | 3.984375 | 4 | '''
## Question
### 1002. [Find Common Characters](https://leetcode.com/problems/find-common-characters/)
Given an array A of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all s... |
0460f89fda75086ed2a7c7fab94800d248978356 | bellatrixdatacommunity/data-structure-and-algorithms | /leetcode/array/check-if-it-is-a-straight-line.py | 2,250 | 4.0625 | 4 | """
## Question
### 1232. [Check If It Is a Straight Line](https://leetcode.com/problems/check-if-it-is-a-straight-line/)
You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane.
Example 1:
Input: coordin... |
0b347a396c2aef1fc646ac8baae9b4d69004d6e3 | bellatrixdatacommunity/data-structure-and-algorithms | /codechef/long-challenge/COVID19.py | 2,553 | 3.71875 | 4 | """
[Coronavirus Spread](https://www.codechef.com/MAY20B/problems/COVID19)
There are N people on a street (numbered 1 through N). For simplicity, we'll view them as points on a line. For each
valid i, the position of the i-th person is Xi.
It turns out that exactly one of these people is infected with the virus COVID-... |
58c09f25db9f2bb35374cfac70a18a7d746a1cc6 | bellatrixdatacommunity/data-structure-and-algorithms | /DataStructures/Array/Array.py | 3,794 | 4.21875 | 4 | class array_operation:
"""All the operations associated with list"""
def __init__(self):
self.array = []
def get(self, index):
if index < len(self.array):
return self.array[index]
return -1
def insert_at_end(self, ele):
self.array.append(ele)
return... |
18f4c257758fa9995536028f95369f3159cf4f24 | bellatrixdatacommunity/data-structure-and-algorithms | /leetcode/linked-list/swap-nodes-in-pairs.py | 3,265 | 3.75 | 4 | """
## Questions
Medium
### 24. [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/)
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked... |
4cfb25197487cc784f9d9953ae84507c91563835 | bellatrixdatacommunity/data-structure-and-algorithms | /leetcode/string/detect-capital.py | 1,056 | 4.03125 | 4 | """
## Questions : EASY
### 520. [Detect Capital](https://leetcode.com/problems/detect-capital/)
Given a word, you need to judge whether the usage of capitals in it is right or not.
We define the usage of capitals in a word to be right when one of the following cases holds:
All letters in this word are capitals, lik... |
b017ef4252a463945c4b8aba610583d98cc765a5 | bellatrixdatacommunity/data-structure-and-algorithms | /leetcode/array/valid-mountain-array.py | 1,282 | 3.96875 | 4 | """
## Question
### 941. [Valid Mountain Array](https://leetcode.com/problems/valid-mountain-array/)
Given an array A of integers, return true if and only if it is a valid mountain array.
Recall that A is a mountain array if and only if:
A.length >= 3
There exists some i with 0 < i < A.length - 1 such that:
A[0] < A[... |
3d8460e71d08dfd3446437d5ac6904822c59f6a2 | gavinchen523/learning_python | /part2.py | 2,046 | 4.21875 | 4 | #!/usr/bin/env python
#DATA type
# 1. Number
num1=3
num2=2
num3=num1/num2
print(type(num1))
print(type(num2))
print(type(num3))
# 2. String
str = 'abcdefasdsfa'
print('string len: ', len(str))
es_str=r'\t'
print('string len: ', len(es_str))
es2_str="""
a
ab
abc
"""
print('string len: ', len(es2_str))
# 3. Boolean
# ... |
061d6edfcd8ddde969849450ce429a9b57457ad4 | umd-coding-workshop/CodeAcademy | /python/lists-and-functions.py | 156 | 3.640625 | 4 | # CodeAcademy course: Lists and Functions
# http://www.codecademy.com/courses/python-beginner-nzzVa
n = [1, 3, 5]
print n[1]
n[1] = n[1] * 5
print n[1]
|
190fbcb44a1d3076c7ba9abd4df12cbf0de29cf5 | exalia/python-test | /exo1.py | 326 | 3.53125 | 4 | class Divisible:
def __init__(self, n):
self.n = n
def run(self):
Somme = 0
for i in range(1, self.n + 1):
if i % 3 == 0 or i % 5 == 0:
Somme += i
return Somme
def get_classes():
li = [Divisible]
return li
print (Divisible(5).ru... |
2087c9753aaa8e60bd2add3256f03431a538d185 | HarleyRogers51295/PYTHON-LEARNING | /1.1 PYTHON/1.4 pythong-numbers.py | 1,445 | 4.21875 | 4 | import math
import random
print("-------------BASICS & MATH--------------")
#integer is a whole number ex. 4, 500, 67, 2........ no decimals
#float has a decimal point ex. 1.521346584 .....
#python auto changes these for you if you do 1 + 1.5 it will be 2.5.
#you can use +, -, /, *, %, **(to the power of!)
print(abs(-... |
a7e2a4bb8c28fa1f5f13bb7a667aa8f82609e6b6 | the-potato-man/lc | /2018/238-product-of-array-except-self.py | 893 | 3.65625 | 4 | '''
Algorithm:
1) Construct a temporary array left[] such that left[i] contains product of all elements on left of arr[i] excluding arr[i].
2) Construct another temporary array right[] such that right[i] contains product of all elements on on right of arr[i] excluding arr[i].
3) To get prod[], multiply left[] and right... |
ec8258fa98e0b115e8930fb74725ed6a3c25e237 | the-potato-man/lc | /2019/go/399-evaluate-division.py | 4,301 | 4 | 4 | '''
Equations are given in the format A / B = k, where A and B are variables represented as strings, and k is a real number (floating point number). Given some queries, return the answers. If the answer does not exist, return -1.0.
Example:
Given a / b = 2.0, b / c = 3.0.
queries are: a / c = ?, b / a = ?, a / e = ?,... |
4359fc500617324b2c02f5199cf8c9bf769c38b8 | the-potato-man/lc | /2018/239-sliding-window-max.py | 1,097 | 4.03125 | 4 | '''
Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right.
You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.
Example:
Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
... |
ade8f044c63fbfac40e25b851ded70da30ab1533 | the-potato-man/lc | /2018/21-merge-two-sorted-lists.py | 776 | 4.125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
# Creating pointers ... |
1196a2e139f0dfee1b96b7f2b445ee1a98f0e3bf | the-potato-man/lc | /2018/652-find-duplicate-subtrees.py | 978 | 3.78125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findDuplicateSubtrees(self, root):
"""
:type root: TreeNode
:rtype: List[TreeNode]
""... |
05f068f11079a09bd0699946baba52325374942d | the-potato-man/lc | /2019/go/685-redundant-connection-ii.py | 2,173 | 3.9375 | 4 | '''
There are two cases for the tree structure to be invalid.
1) A node having two parents;
including corner case: e.g. [[4,2],[1,5],[5,2],[5,3],[2,4]]
2) A circle exists
---------------------------------------------------------------
1) Check whether there is a node having two parents.
If so, store them as can... |
cf297b12b0dd88cff1ec7b8181cde69ded50c990 | the-potato-man/lc | /2018/124-binary-tree-max-path-sum.py | 861 | 3.625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxPathSum(self, node):
"""
:type root: TreeNode
:rtype: int
"""
self.localMax = float("-inf"... |
615cc6f9ca378562f3aaaac8a96b5c4f161732d2 | BartekObudzinski/Python-WSB | /wyklad6/zad4.py | 220 | 3.84375 | 4 | def monotonicznosc(a):
if(a>0):
print("Funkcja rosnąca")
elif(a==0):
print("Funkcja stała")
else:
print("Funkcja malejąca")
monotonicznosc(5)
monotonicznosc(0)
monotonicznosc(-12)
|
a9cab9cac498c4215500fa0f5a12970d071692f1 | uit-inf-1400-2017/uit-inf-1400-2017.github.io | /lectures/10-event-driven-programming/dispatcher.py | 5,731 | 3.6875 | 4 | #!/usr/bin/env python
"""Dispatcher example.
* Demonstrates how to make a simple event dispatcher and how to use it.
* Shows some alternatives for creating event handlers that can be registered with the
dispatcher.
* Shows how the dispatcher can be used with PyGame events and how to add new event types
to PyGa... |
87cee9d43718c10c989e16c6c993abd82d40d4ef | uit-inf-1400-2017/uit-inf-1400-2017.github.io | /lectures/05-summary-and-examples/code/PointRobust.py | 1,947 | 4.34375 | 4 | # Program: RobustPoint.py
# Authors: Michael H. Goldwasser
# David Letscher
#
# This example is discussed in Chapter 6 of the book
# Object-Oriented Programming in Python
#
from math import sqrt # needed for computing distances
class Point:
def __init__(self, initialX=0, init... |
acffbc0e475544c770a40b9a4678a042b4f84fde | uit-inf-1400-2017/uit-inf-1400-2017.github.io | /lectures/03-code/t05.py | 3,402 | 3.90625 | 4 | #!/usr/bin/env python3
# This version adds a new type of moving objects: Circle.
# The interface of the Ball and Circle objects are the same, while the implementation differs.
# This allows us to call move() and draw() on any ball or circle object, ignoring which type of object is
# (see the objs list and the move an... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.