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
6a33a7b2a844101761a970dc21673f9306acb4c7
Rinkikumari19/codechef_questions
/hardness_carbon_code.py
521
3.5625
4
T = int(input("any number")) for i in range(T): # hardness,carbon,tensil = map(int, input().split()) A = input() A = A.split() hardness = int(A[0]) carbon = float(A[1]) tensil = int(A[2]) if hardness>50 and carbon<0.7 and tensil>5600: print(10) elif hardness>50 and carbon<0.7 and tensil<=5600: print(9) eli...
28ab6cf75d8127e6ce5ccd7e4ea4fb8262381d3b
Rinkikumari19/codechef_questions
/code_fac.py
304
3.59375
4
T = int(input()) for i in range(T): count = 0 user = int(input()) num = 5 while user >= num: a = user//num count = count + a num=num*5 print(count) # input # 6 # 3 # 60 # 100 # 1024 # 23456 # 8735373 # Sample Output: # 0 # 14 # 24 # 253 # 5861 # 2183837
b08a80b3cfcf833a1c73816c1be5968d1614db62
Rinkikumari19/codechef_questions
/table.py
128
4
4
b = 1 a=int(input("number")) c= "*" d = "=" while b<=10: print(a,c,b,d,(a*b)) b=b+1 # It will print table of any number
33155d6d16aef9cd74969fd132f6c62d6bd0f747
Rinkikumari19/codechef_questions
/bin_decimal.py
186
3.578125
4
# list = [1,0,1,0] # lenght = len(list) # i = 0 # a = 1 # sum = 0 # while i <= (lenght): # sum = sum+(2**i*(list[lenght-a])) # i = i+1 # a=a+1 # print('decimal num:-',sum)
098512024c64fa6bfa98f839cc0246772ed2178d
Rinkikumari19/codechef_questions
/new_file.py
223
3.640625
4
N = int(input()) count = 0 while N > 0: d = N%10 count = count + 1 N = N//10 if count == 1: print('1') elif count == 2: print('2') elif count == 3: print('3') else: print('More than 3 digits')
84c75ebff4d3a896e8d5b2fc311884b61bce58c3
Rinkikumari19/codechef_questions
/user_in_list.py
163
3.671875
4
num = [1,2,3,4,5,6,7] user = int(input("number")) i=0 while i<len(num): if user == num[i]: print("yes") break i=i+1 else: print("nahi")
968ffb5c3325887b10e4a4326f7dfb0bd65de26d
lukassn/CodeQuests
/URI/inPython/multiplos_13_URI_1132.py
583
3.515625
4
# coding: utf-8 def multiplosDe13(i, j): multis = [] cont = 1 x = 0 while x <= j: if x == cont * 13: multis.append(x) cont += 1 x += 1 return multis def somaDosMultisDe13(a, i): somaDosMultis = 0 for o in range(len(a)): if a[o] >= i: somaDo...
f6e62bbae2a4ac1ecb78aafd5de346f0b8545eb9
lukassn/CodeQuests
/URI/inPython/sort_simples.py
512
3.8125
4
#coding: utf-8 def insertionsort(A): for j in range(1,len(A)): key = A[j] i = j-1 while (i > -1) and key < A[i]: A[i+1]=A[i] i=i-1 A[i+1] = key return A n1, n2, n3 = map(int, input().split()) sequencia_inicial = [n1, n2, n3] sequencia_c...
ffdea039a3d9f4d88224d1d88e592777f1877289
lukassn/CodeQuests
/URI/inPython/1091.py
451
3.65625
4
#coding: utf-8 while (True): k = int(raw_input()) if k == 0: break ent = raw_input().split() n = int(ent[0]) m = int(ent[1]) for i in range(k): ent2 = raw_input().split() x = int(ent2[0]) y = int(ent2[1]) if(x==n or x==m or y==n or y==m): print "divisa" elif(x>n an...
cecbc3a1cae6c2787e897a18dfdc9a46afad78fe
lukassn/CodeQuests
/URI/inPython/mes_1052.py
384
3.75
4
#coding: utf-8 x = int(input()) if x == 1: print('January') elif x == 2: print('February') elif x == 3: print('March') elif x == 4: print('April') elif x == 5: print('May') elif x == 6: print('June') elif x == 7: print('July') elif x == 8: print('August') elif x == 9: print('September') elif x == 10: print('October')...
0650da9a1986135e35996256e52496abe748e761
singh-l/neutral-lilt-parade
/src/linear_example.py
1,324
3.875
4
from preprocessing import bag_of_words, sanitize from linear import predict # Example prediction: # Service was bad. (negative) # First, we clean up the sentence and get a bag of words representation. instance = bag_of_words(sanitize('Service was bad.')) # Then, we set up our prediction weights. # The weights b...
15759273991888f07d03c6fa595d67060a562df3
evgenytihonov/Basic_Python
/Lesson_5/Tihonov_Evgeny_dz_5.1.py
246
4.0625
4
def odd_num_generator(end): end = int(end) for num in range(1, end + 1): if num % 2: yield num n = int(input('До какого числа считать нечетные числа? ')) print(*odd_num_generator(n))
3bd5debd4340abed6b750f405ac83326a3f0a76c
evgenytihonov/Basic_Python
/Lesson_5/Tihonov_Evgeny_dz_5.2.py
219
4.125
4
def odd_num(): upper = 1 + int(input('До какого числа считать нечетные числа? ')) lower = 1 for i in range(lower, upper): if i % 2: print(i) odd_num()
3186be214a5fc4d66383ad812d71bf9cec8a4113
jcf3/PycharmProjects
/Activity/CSCI 156/Exam/fossumexam3.py
2,755
4.0625
4
__author__ = 'Fossum' employees = dict() def employeeinput(dictionary): name = input("Please enter the employees name (first last): ") tuple1 = name.split(" ") tuple2 = tuple1[1], tuple1[0] wage = float(input("Please enter the employees hourly wage: ")) startyear = int(input("Please enter the ye...
b1dd2c589cb5a38902b2830b64440b75a8099028
jcf3/PycharmProjects
/Activity/CSCI 156/Chapter 12/12.2.1.py
249
3.875
4
__author__ = 'Fossum' l = [[1, 2], [1, -1], [5, 8], [-4, -2], [4, 3]] m = [] for i in range(len(l)): maxi = max(l[i]) m.append((maxi, l[i])) print(m) m.sort(reverse=True) print(m) l1 = [] for maxi, pair in m: l1.append(pair) print(l1)
b3784988eeb78f42e814ef68dc225618275ed425
jcf3/PycharmProjects
/Activity/CSCI 156/Chapter 9/9.2.1.py
317
3.890625
4
__author__ = 'Fossum' def loop(n): b = "" c = input("Please enter a string: ") while c != "q" and c != "Q": b += c + "\n" c = input("Please enter a string or enter 'q' or 'Q' to quit: ") n.write(b) with open('9.2.1.txt', 'w+', encoding='utf-8') as a: print(a.name) loop(a)
3b8bdaafd6f4d64fac50f744dde5a257576c8cee
lynnagara/twitter-bot.py
/process_tweet.py
3,103
3.546875
4
import re import os from pathlib import Path import pickle import utilities def sanitize_tweet(tweet): return strip_multi_spaces(strip_quotes(replace_space_chars(strip_urls(tweet)))).rstrip() def strip_multi_spaces(text): pattern = r' +' return re.sub(pattern, ' ', text) def strip_quotes(text): pattern = r'"...
60fe2aa32f9b680e8958d3dff31d403b00d0bc2e
107295/uniHat
/pyUniHat.py
1,053
3.625
4
import sys validatedNumber = [0]; years = 0; yearWeights = []; yearUnits = []; def cls(): print("\n" * 100) def checkCmd(x): if(x == ".q"): print("Quitting...") sys.exit(0) elif(x == ".u"): print("Undoing...") def checkNumber(y): while True: checkCmd(y) try: output = int(y) validatedNumber[0] = ...
194aae130e759a8e44f26fe7859cec6aa5d615f6
JJCraig/Hold-em-Odd-Calculator
/Deck.py
977
3.703125
4
import random def populateDeck(): deckOfCards = [0] * 52 for x in range(0, 52): deckOfCards[x] = x return deckOfCards def printCard(cardNumber): if cardNumber < 0 or cardNumber > 51: print('card number our of bounds') return #get suit suitTemp = cardNumber/13 ...
d22ee0216cf1edc691663f8d23cfdd830cfe097b
YashV27/PythonAssignment
/q1.py
462
4.03125
4
#!/usr/bin/python def make_bricks(small,big,goal): q=goal/5 if big>q: q=big if small>=goal-q*5: print True else: print False while(True): try: small=int(raw_input("no. of small bricks\n")) big=int(raw_input("no. of big bricks\n")) goal=int(raw_input("Ent...
99712f1099235001db4da9372bdc66de1fdce696
pnaim/FinalProject
/Final Project New.py
6,261
4.40625
4
# Name: Pasha Pradana Naim # Student ID: 2201814701 # Purpose: Final Project def help_function(): print('''Welcome to help center. You need to follow the instructions thoroughly. You can type whatever commands you like, but there are some commands which cannot be functioned. Make sure that the command is...
ec73e567ad4ee58049368bcb8d77dbfc9b827d78
myroslavrozum/misc_stuff
/commander_lambda/3_1_old.py
5,577
3.71875
4
def isValidMove(maze, move): (y, x) = move return not (x >= len(maze[0]) or y >= len(maze) or x < 0 or y < 0 or maze[y][x] == 1) def setTheWall(m, wall, state=0): (y, x) = wall tmp = [] for row in m: tmp.append(row[:]) tmp[y][x] = state return tmp def findValidMoves...
00adb3b43ecca496b583d838e4513932c4173f2e
ChmlGr/python-exercise
/part1/src/commons/test.py
466
3.546875
4
import unittest from . import commons class PalindromeTest(unittest.TestCase): def test_is_palindrome(self): self.assertEqual(commons.is_palindrome('tacocat'), True) self.assertEqual(commons.is_palindrome('taco-cat'), True) def test_is_palindrome_phrase(self): self.assertEqual(commons...
f8c4ed7581f1d14ba77a6b3d972089ed5e0a5f8c
tomyuan520/angry-birds-python
/project1.py
5,050
4.03125
4
#symotion-prefix# ################################# # Imports # ################################# import math import turtle ############################################### # Function that builds the structure, ground, # # slingshot, and draws the (X,Y) locations # # until the projectile hit th...
29e4867e0423003a1c66c6170f565f4e749e6364
curt-mitch/advent_of_code_2020
/day1.py
487
3.859375
4
from collections import defaultdict # https://adventofcode.com/2020/day/1 # find two values that sum to 2020 with open('day1_input.txt') as f: array = [int(line) for line in f] def default_value(): # use a dict to store value and differences return None values = defaultdict(default_value) answer = None ...
1e7a9229018182c0aaadf4bc8675f356e6f2b895
titoeb/python-desing-patterns
/python_design_patterns/singleton/singleton_allocator.py
1,510
3.796875
4
"""The singleton design pattern. Some components make only sense to be once in a system: - Database connection - Object Factory When the initializer is expensive you may only want to have these components once. Therefore, you don't want anyone to copy it, change it and create it only lazy when someone needs it. """ fro...
a2180fb2c112c0f1914f9be93e6cd07c9834a261
titoeb/python-desing-patterns
/python_design_patterns/factories/abstract_factory.py
2,253
4.53125
5
"""The abstract Factory The abstract factory is a pattern that is can be applied when the object creation becomes too convoluted. It pushes the object creation in a seperate class.""" from __future__ import annotations from enum import Enum from abc import ABC # The abstract base class. class HotDrink(ABC): def c...
4313feab624055e660fd3739d18923008b56b7aa
titoeb/python-desing-patterns
/python_design_patterns/factories/exercise.py
237
3.5
4
class Person: def __init__(self, id, name): self.id = id self.name = name class PersonFactory: idx = 0 def create_person(self, name): self.idx += 1 return Person(id=self.idx - 1, name=name)
03138c75ca67110ce5db1837d612938c416cd856
titoeb/python-desing-patterns
/python_design_patterns/composite/ex.py
866
3.734375
4
from collections.abc import Iterable class Additive: @property def sum(self): return Additive._sum(0, self) @staticmethod def _sum(aggregate: int, elements: Iterable): for elem in elements: if hasattr(elem, "__iter__"): aggregate = Additive._sum(aggregate, ...
490bfd37ebfa51bcf4eaf3019f0fdf6c542e5127
titoeb/python-desing-patterns
/python_design_patterns/bridge/ex.py
1,235
3.734375
4
from abc import ABC class Shape: def __init__(self, renderer): self.name = None self.renderer = renderer class Triangle(Shape): def __init__(self, renderer): super().__init__(renderer) self.name = "Triangle" def __str__(self): return self.renderer.render_triangle...
e268bd076c6278f672e56747c04b1d88df979caa
Tornado-6/Stock-Market-Prediction-Using-Deep-Learning
/News/kernel.py
5,776
3.515625
4
# coding: utf-8 # In[ ]: #importing the pandas package import pandas as pd #reading the dataset into dataframe data = pd.read_csv("/Users/T/Desktop/ML/Stock-Market-Prediction-Using-Deep-Learning/News/input_data.csv",header=0) print(data.head(0)) train = data.iloc[:,2] print(train[1]) # Using TextBlob for NLP and...
a5b637195c6ff2ff1bb59e10bda85680be01284b
youirepo/leetCodeSolns
/easy/strings/countAndSay.py
1,712
3.625
4
class Solution: """ Function to return next string in sequence. The algorithm uses two pointers to count occurences of characters in the string. One static and one moving. The pointers start off at the same position. The moving pointer compares the character with th...
0fda6fcf48f4d2ef9a361c168cb418891a6062f9
17e23052/Noughts-and-Crosses
/main.py
3,462
4.03125
4
from time import sleep player1 = "X" player2 = "O" player = player1 board = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]] def instructions(board): #These below are the instructions. print("Welcome to Noughts and Crosses!") sleep(2) print("Player 1 will be crosses. Player 2 will be noughts....
6c18530af9ae7b47ba6a88bdb0cb1a6d98d51e34
Akmaralka/seminar2
/mybox.py
1,175
3.59375
4
from myboxiterator import MyBoxIterator class MyBox: def __init__(self): self.data = [] def __len__(self): return len(self.data) def __str__(self): return str(self.data) def add(self, item): assert item != None self.data.append(item) def delete(self, name...
4960443aecc8f9d4e853ea8f6f4d593d35b6191d
Janikus/determiniaCS
/5 Aplicaciones del Operador Módulo/3. cifrado cesar.py
206
3.875
4
k = int(input("Introduce value for k: ")) plain = input("Introduce a plain text: ") cipher = "" for i in range(len(plain)): cipher += chr(((ord(plain[i]) + k - 65) % 26) + 65) print(cipher)
5b10d1fb58817cf68db2dfaa886ed5f21b16f839
chrisholyoake/Election_Insights_using_Pandas
/PyPoll/main.py
3,073
3.578125
4
#!/usr/bin/env python # coding: utf-8 # In[2]: #dsependencies import os import pandas as pd # In[4]: filepath = "Resources/election_data.csv" #pull in CSV data df = pd.read_csv(filepath) df.head() # In[6]: #total votes totalVotes = df["Candidate"].count() print(totalVotes) # In[8]: allCandidates = df["C...
5b25a168ba13c3dcf06c94122656cb3ff2353955
AlPus108/Python_lessons
/Decorators/4_speed_test.py
5,143
3.84375
4
# Как использовать декоратор для тестирования скорости выполнения какого-то кода # Мы уже проверяли скорость выполнения кода в разделе Генераторы # Мы тестировали скорость выполнения суммирования при помощи list и при помощи generator expression # Тогда мы использовали модуль time from time import time # список star...
40ebb1c18d99312a137284a081c4bf835b15fc96
AlPus108/Python_lessons
/File_work/Input_Output.py
18,535
4.1875
4
# Ввод и вывод в языке Пайтон # input() - ввод # В инпуте в круглых скобках ф-и можно вводить сообщения и подсказки для пользователя. x = input('Введите что-нибудь ') # и использовать то, что ввел пользователь, в нашем коде (присвоить переменной). # output() - вывод # Также мы можем выводить что-то print('Распечатай...
db546df2cabf2b53be384907793f94cb5cd99fb8
AlPus108/Python_lessons
/Tasks_02.py
2,755
4
4
# Задачи на циклы и операторы условия # Задача 1 # Вывести на экран циклом пять строк из нулей, причем каждая строка должна быть пронумерована for i in range(1, 6): print(i, 0,0,0,0,0) # Задача 2 # Пользователь в цикле вводит 10 цифр. Найти количество введенных пользователем цифр 5 x = 0 for i in range(10): ...
a5fa5c8e3314f669eaee16227e3c06770520da90
AlPus108/Python_lessons
/Moduli/second.py
2,613
3.65625
4
# 3 Пришли из файла first.py # С самого начала делаем импорт модуля first import first print('Top level is second.py') # вызываем ф-и из импортированного модуля first first.function_1() # копируем блок if_else из модуля first и вставляем сюда и меняем в тексте first на second if __name__ == '__main__': # если п...
0432dc8db840f6e8ee81f1dcc8f91466405a6ae2
AlPus108/Python_lessons
/Pocket/my_math_module.py
3,050
3.546875
4
# № 1 в пакете # В связке с: # 1 my_muth_module.py # 2 main_exe.py # Здесь мы создадим свой небольшой модуль с арифметическими операциями и ф-ей вычисления чисел Фибоначчи. # И в дальнейшем научимся инициализировать из него эти модули и ф-и. # Ф-и арифметических операций def my_add(x,y): return x + y def my_sub...
7b0126b6fe426a304beb5f7021d6566c3be853a6
AlPus108/Python_lessons
/OOP_22/igra_v_kosti_8.py
4,678
3.921875
4
# Игра в кости-2. Усложняем предыдущий код # Импортируем из предыдущего кода модуль Dice from random import random from Python_lessons.OOP_22.igra_v_kosti_7 import Dice # Создаем новый класс и наследуем его от импортируемого класса Dice class Dice_dif(Dice): ''' Усложняем игру Допишем режимы игры в кос...
c9f6fcc5e92490c6c115e37737e2cda02b322fd1
XanderVi/checkio-mission-date-time
/editor/initial_code/python_3
620
3.84375
4
def date_time(time: str) -> str: #replace this for solution return time if __name__ == '__main__': print("Example:") print(date_time('01.01.2000 00:00')) #These "asserts" using only for self-checking and not necessary for auto-testing assert date_time("01.01.2000 00:00") == "1 January 2000 yea...
a862ed66616b3292777ed1379fc14e0596e2b05f
42azimut/Modu_Python_Algorithm
/sum.py
255
3.671875
4
# 1부터 n까지 "연속한"한 숫자의 합을 구하는 알고리즘! #입력 n #출력 1부터 n까지의 더한 값! def sum(n): total = 0 for i in range(1,n+1): total += i return total print(sum(10)) print(sum(100))
209f917defbfb362659f486022493c0f35ff10ef
42azimut/Modu_Python_Algorithm
/07_search.py
405
4.03125
4
# 리스트에서 특정 숫자 "위치(인덱스)" 찾기 # 입력 리스트a, 찾는값 x # 출력 찾으면 그 인덱스, 못찾으면 -1 def search_list(a, x): n = len(a) for i in range(0, n): if (x == a[i]): return i return -1 v = [17, 92, 18, 33, 58, 7, 33, 42] print(search_list(v, 18)) print(search_list(v, 33)) print(search_list(v, ...
7a596983a4bb7ffdd37d7b7894623c6e08078850
ppesh/SoftUni-Python-Developer
/Python-Fundamentals/EXAM/02-Problem.py
587
3.75
4
# 02. Problem # Tests """ 3 ##>|no|NO|!!!?<### ##>123|yes|YES|!!!<## $$<111|noo|NOPE|<<>$$ 5 aa>111|mqu|BAU|mqu<aa ()>111!aaa!AAA!^&*<() o>088|abc|AAA|***<o asd>asd|asd|ASD|asd<asd *>088|zzzz|ZzZ|123<* """ import re pattern = r"(.+)>(\d{3})\|([a-z]{3})\|([A-Z]{3})\|([^><]{3})<\1" n = int(input()) for i in range(n...
19c204f4a454118f16ff79745be72ddd27091bd7
ppesh/SoftUni-Python-Developer
/Python-Fundamentals/MIDEXAM/03-Inventory.py
979
3.890625
4
# 03. Inventory def check_item_exist(journal_list, item_searched): return True if item_searched in journal_list else False journal = input().split(", ") command = input() while not command == "Craft!": command_type = command.split(" - ")[0] item = command.split(" - ")[1] if command_type == "Collect...
085c064b0e3247bdf8c26acaa16531f71d0e9391
ppesh/SoftUni-Python-Developer
/Python-OOP/10-Testing/02-Vehicle/test/test_vehicle.py
1,368
3.78125
4
from unittest import TestCase, main from project.vehicle import Vehicle class VehicleTests(TestCase): def setUp(self): self.vehicle = Vehicle(10.0, 100.0) def test_vehicle_initialized(self): self.assertEqual(self.vehicle.fuel, 10.0) self.assertEqual(self.vehicle.capacity, 10.0) ...
e07e8d28a95cb35001d61ec541dd715dcb292ec4
ppesh/SoftUni-Python-Developer
/Python-Advanced/06-File-Handling-Exercise/03-File-Manipulator.py
1,924
3.796875
4
# 03. File Manipulator import os while True: command = input().split("-") if command[0] == "End": break elif command[0] == "Create": filename = command[1] with open(filename, "w") as file: file.write("") elif command[0] == "Add": filename = command[1] file_content = command[2] with open(fi...
b0e805e3b1244231e9601e3ed4db7f4066bfaacc
ppesh/SoftUni-Python-Developer
/Python-Advanced/04-Comprehensions-Exercise/10-Matrix-Modification.py
505
3.71875
4
# 10. Matrix Modification n = int(input()) matrix = [[int(x) for x in input().split()] for _ in range(n)] while True: line = input() if line == "END": break tokens = line.split() row = int(tokens[1]) col = int(tokens[2]) value = int(tokens[3]) if 0 <= row < n and 0 <= col < n: if tokens[0] == "Add": mat...
957b0d2c4c7c782003a8d20392ccb9129f3c406f
ppesh/SoftUni-Python-Developer
/Python-Fundamentals/02-Data-Types-and-Variables/06-Triples-of-Latin-Letters.py
312
3.8125
4
# 06. Triples of Latin Letters n = int(input()) a_small_letter_ascii = ord('a') for first_char in range(0, n): for second_char in range(0, n): for third_char in range(0, n): print(f"{chr(97 + first_char)}{chr(97 + second_char)}{chr(97 + third_char)}") # 97 = a
aff9bb7cdb2409e90b1af1790eb86f5651ba7911
ppesh/SoftUni-Python-Developer
/Python-Advanced/05-Functions-Advanced-Exercise/02-Sort.py
122
3.625
4
# 02. Sort numbers_from_input = input().split() numbers = map(int, numbers_from_input) print(sorted(numbers))
f7ac29b6d62fcc85770a50b955f3c0836f093db6
ppesh/SoftUni-Python-Developer
/Python-Advanced/02-Tuples-and-Sets-Exercise/02-Sets-of-Elements.py
266
3.921875
4
# 02. Sets of Elements n, m = tuple([int(x) for x in input().split()]) set_n = set() set_m = set() for _ in range(n): set_n.add(input()) for _ in range(m): set_m.add(input()) set_intersection = set_n & set_m for element in set_intersection: print(element)
8fa18a7e81c79eb5189d76d7fd8108da1c806aec
ppesh/SoftUni-Python-Developer
/Python-Fundamentals/08-Text-Processing/07-String-Explosion.py
350
3.65625
4
# 07. String Explosion text = input() result = "" strength = 0 for char in range(len(text)): char_in_text = text[char] if char_in_text == ">": strength += int(text[char + 1]) result += char_in_text elif not strength == 0: strength -= 1 else: result += ...
ff7730e47b6d173de3f0c0cf175c543311b149fd
ppesh/SoftUni-Python-Developer
/Python-OOP/02-Classes-and-Instances/02-Circle.py
467
4.3125
4
# 02. Circle class Circle: pi = 3.14 def __init__(self, radius): self.radius = radius def set_radius(self, new_radius): self.radius = new_radius def get_area(self): area = self.pi * self.radius * self.radius return area def get_circumference(self): circumference = 2 * self.pi * self.radius ...
07bd0aea4c2e3b105e5b3c1243bb961fc480fe93
cestella/software_engineering_curriculum
/calculator/src/lexer.py
6,622
4.71875
5
OPS = ["+", "-", "*", "/"] OPS_WITHOUT_SUBTRACTION = ["+", "*", "/"] def is_numeric_char(char): """ Determines if a character is a numeric character (i.e. a character which may appear in a number). Parameters ---------- char : char The character to be evaluated ...
a0346b8d78238a85ae5d66d43d01605eb236aeef
20111AFRANKRF/M03
/ejercicio-calendario/calendario.py
1,120
3.9375
4
# coding: utf-8 import calendar def my_range(inici,fi,increment): while inici <= fi: yield inici inici = inici + increment # Informacion que queremos mostrar info=input("De quin mes vols veure el calendari?") info2=input("De quin any vols veure el calendari?") # monthrange nos dira el dia que de l...
6e570dbb6b29e77f37421e97f9aded01c6e7aba2
bwright-01/BrickSmash
/heart.py
585
3.84375
4
# Definition of the game's Heart class # # This class contains all relevant information related to the heart # It sets the hearts X and Y coordinates when initialized to the input coordinates # # The heart class also contains the variable lost, which keeps track of if a heart object # represents a life the player has l...
15bb0dfe25d1113920d17666e5a37b18fbf1ad8f
FlowerbeanAnsh/python_problems_2
/exceptions_wrong_dict_input.py
305
3.96875
4
#wrong dict input by the user try: n = int(input("enter the range:")) dct={} for i in range(n): keys = input("enter the keys:") values = input("enter the values:") dct.update({keys:values}) print(dct) except ValueError: print("please enter the valid range")
9fd0574ae06a3aa4c704702dbc741b977a4341cb
FlowerbeanAnsh/python_problems_2
/func.calculate.py
570
4.1875
4
def calculate(a,b): if op=='+': c=a+b return c elif op=='-': d=a-b return d elif op=='*': e=a*b return e elif op=='/': f=a/b return f elif op=='%': g=a%b return g else: return False f=float(input("enter the f...
9705a2ac0981b6efd528303b8ff00136af905c94
FlowerbeanAnsh/python_problems_2
/func_prime_or_not.py
213
4.09375
4
def prime_or_not(n): for i in range(2,n): if n%i==0: return "it is not a prime no" else: return "it is a prime no" n=int(input("enter the no:")) out=prime_or_not(n) print(out)
a482f7437393c140fcb88b76e4b6a493fbb74bcb
FlowerbeanAnsh/python_problems_2
/set__union.py
171
3.875
4
s1=set(map(int,input("enter the elements of first set=").split())) s2=set(map(int,input("enter the elements of second set=").split())) s=s1.union(s2) print("union is=",s)
85c68c124227b4f3ea1eee6b1b73d8b9bbd8c9ff
FlowerbeanAnsh/python_problems_2
/string_traverse_by recursion.py
139
3.546875
4
def my_fun(s): if s=='': return '' print(s[0]) return my_fun(s[1:]) + s[0] st='hello python' out=my_fun(st) print(out)
9779083378f76aa9d8cc5c2c9d6e686a1a393713
FlowerbeanAnsh/python_problems_2
/file_handling-read.py
132
3.53125
4
#read and readline f= open("student.txt","rt") #content=f.read(2) #print(content) for line in f: print(line,end='') f.close()
4c6cfcebf84e442987c8ecf6ad70a0f2508a0c40
dgeorge10/suitable-puzzles
/recommendation/solution.py
6,538
3.5
4
#!/usr/bin/env python3 import sys from heapq import nlargest import json from math import * ratings = {} rest = {} visited = [] #function jaccard #calculate the similarity index between two teammated by their ID's #parameters- ratings, id1, id2 #ratings - the dictionary of ratings that got established in init() #id...
6e0793dfdc41f916ef69f0866ae2e7d9201cf6ba
desseling/activity-assistant
/hass_api/testing/asyncio_stuff.py
1,864
3.640625
4
""" parallelism: multiple operations at the same time mutiprocessing: means to spreading tasks over a cpu concurrency: broader term than parallelism multiple taks have ability to run in overlapping manner conc =!=> parallel threading: multiple thread take turns exec. task...
b87a8803ccbf82f0d54f76951f09a999a86a5176
iamlearning1/Python-Algorithms-And-Data-Structure
/binary-search.py
546
3.875
4
from math import floor def binary_search(arr, num): start = 0 end = len(arr) - 1 mid = floor((start + end) / 2) while num is not arr[mid] and start <= end: if num < arr[mid]: end = mid - 1 else: start = mid + 1 mid = floor((start + end) / 2) if arr[...
c8ffd325f10e4545f09ada1ff0b4acdbdd6fd7a2
iamlearning1/Python-Algorithms-And-Data-Structure
/stack.py
1,116
4.0625
4
class Node: def __init__(self, val): self.val = val self.next = None def __repr__(self): return f'{self.val}, Next: {self.next}' class Stack: def __init__(self): self.start = None self.end = None self.size = 0 def __repr__(self): return f'Sta...
7e2b9234cf944ad8d58234964177f7c6f7c439ab
Aurametrix/Alg
/HASH/tree.py
1,036
3.765625
4
class Node(object): "A decision-tree node." def evaluate(self, env): "My value when variables are set according to env, a dictionary." abstract def __call__(self, if0, if1): """Return an expression whose value is if0's or if1's, according as self's is 0 or 1.""" retur...
711f65d90f9ec403a141d69831f688d541d9f243
Aurametrix/Alg
/ML/knn_scikit.py
2,127
3.8125
4
import numpy as np import matplotlib.pyplot as plt import pandas as pd url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data" # Assign colum names to the dataset names = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'Class'] # Read dataset to pandas dataframe dataset ...
b0a5655ed6f5d8a2b4c363cecd73d8541e9526c8
Aurametrix/Alg
/REGEX/pampy.py
535
3.859375
4
from pampy import match, _ x = [1, 2, 3] match(x, [1, TAIL], lambda t: t) # => [2, 3] match(x, [HEAD, TAIL], lambda h, t: (h, t)) # => (1, [2, 3]) match(x, 3, "this matches the number 3", int, "matches any integer", (str, int), lambda a, b: "a tuple (a,...
963484b3b672c52aedafc7cdbce3093e05afaf76
Aurametrix/Alg
/MATH/f.py
5,450
3.5625
4
# -*- coding: utf-8 -*- import re def U(s): if type(s) is unicode: return s return s.decode('utf8') def is_alphabetically_correct(s): return set(s) <= set(u'0Sabcdefghijklmnopqrstuvwxyz′(+⋅)=~<∧∨⊃>∀∃:') def is_numeral(s): return bool(re.match('S*0$', U(s))) assert all(is_numeral(x) for x in...
fab990029feb70cf3b59010f1f749f1ad3a51627
Aurametrix/Alg
/PROBLEMS/dumbcoin.py
731
4
4
def dumb_hash(message): """ An INSECURE hash function that you should not use in the real world. Returns an hexadecimal hash """ return md5(message) def mine(message, difficulty=1): """ Given an input string, will return a nonce such that hash(string + nonce) starts with `difficulty` o...
1f5ca2daee6966bbf355e912229693cd57224ed8
Aurametrix/Alg
/Search/binary.py
279
3.78125
4
binary_search(A, target): lo = 1, hi = size(A) while lo <= hi: mid = lo + (hi-lo)/2 if A[mid] == target: return mid else if A[mid] < target: lo = mid+1 else: hi = mid-1 // target was not found
f1bd4c65d2f7e7a1a7d8ac0e122ac1da8249a26e
Aurametrix/Alg
/AUDIO/txt-spch.py
1,310
3.625
4
import speech_recognition as sr import pywapi from gtts import gTTS while True: a = sr.Recognizer() with sr.Microphone() as source: print("say something") audio=a.listen(source) try: print("You said: " + a.recognize_google(audio)) # change it when you finish the program. except...
3b846fa547bdfee36bcbffd8ebcd074a7048bc96
siva2k16/PythonImageProcessing
/Assignment3/1- Kmeans clustering.py
485
3.71875
4
from sklearn.datasets import make_circles import matplotlib.pyplot as plt import numpy as np from sklearn.cluster import KMeans #create sample test circles data = make_circles() X = data[0] plt.figure(1) plt.scatter(X[:,0],X[:,1]) #Apply Kmeans cluster with K value 2 model = KMeans(n_clusters=2) model.fit(X) labels...
545a950fec29f13b45e5fe44911e60eb5b56d22c
siva2k16/PythonImageProcessing
/Assignment1/13 - Problem5Exercise4.py
909
3.5625
4
#4. Average the input image with its mirror image. # 30/08/2015 Draft Version import cv2 #Define and implement mirror function def mirrorImageExample(): sourceImage=cv2.imread('einstein.jpg') destImage=sourceImage.copy() destImage=cv2.flip(sourceImage,1) #Display Mirrored Image #cv2.imshow('mir...
448a08ca2a23308e9c9debcea27f78e5046a52c8
DiegoMeruoca/Python7-Listas
/Media Simples.py
663
3.96875
4
notas = [] # Cria a lista notas vazia print("Digite as notas do aluno, digite fim para sair.") # Mensagem while True: # Enquanto verdadeiro (Loop infinito) nota = input("Nota:") # Lê a nota digitada if nota.upper() == "FIM": # Se for digitado fim break # Encerra o loop infinito notas.app...
4b996ed86c35907c53153e4dcf4306864ba3fffc
DiegoMeruoca/Python7-Listas
/Par e Impar.py
490
3.65625
4
V = [9, 8, 7, 12, 0, 13, 21, 44] # Cria a Lista P = [] # Cria uma lista vazia para os pares I = [] # Cria uma lista vazia para os Impares for e in V: # Para cada elemnto na lista V if e % 2 == 0: # Se o resto da divisão de elemento por 2 é 0 P.append(e) # Adiciona o elemto na lista P else: ...
aa4678638365410fa4c2f4ac0bab6f66d2959153
ManishGaurav/Python
/PyCrypto/AsymmetricCiphers.py
7,160
3.515625
4
#!/usr/bin/env python3 import Crypto.PublicKey.RSA as CCRSA import Crypto.Cipher.PKCS1_OAEP as CCOAEP """ A wrapper class for textbook-RSA Encryption/Decryption """ class RSA: def __init__(self, keysize=2048): # RSA keysize is a multiple of 256 bits, and no smaller than 1024 bits self.keysize = ...
b5e204e59349928a666b381c99c20c27654eb04b
mikeorr/WebHelpers2
/webhelpers2/misc.py
5,379
3.859375
4
"""Helpers that are neither text, numeric, container, or date. """ import itertools import sys import traceback import types import warnings import six def choose_height(new_width, width, height): """Calculate a proportional height for scaling an image. Given the image's existing width and height and propose...
a77b244413679b4d2a87c43cf027375c9b364f63
IkErules/python-examples
/paradigmen/imperativ.py
198
3.75
4
""" Imperatives Beispiel in Python """ # For-Loop und if: sag dem Computer was und wie er es tun soll... studierende = ["florian", "andre"] for x in studierende: if x == 'florian': print(x)
e478a72a1c2b6f8d8ccdfb7762c90ccf9f87f71c
IkErules/python-examples
/operator_overloading/overload.py
810
3.640625
4
# PCP Python Bericht # # Operator overloading # class Rechteck: # Konstruktor def __init__(self, breite, hoehe): if (breite <= 0): raise ValueError('Breite von einem Rechteck muss grösser 0 sein') self.__w = breite self.__h = hoehe @property def w(self): re...
909dbe6e460eb1390d90656af8b644e482b95188
kendewitt/stripvocab
/stripvocab.py
738
3.796875
4
import re input_text = open("stripvocab.txt", "r").read() input_text = re.sub(r'[^a-zA-Z\n\s\']', '', input_text) input_text = re.sub(r'\'s', "", input_text) input_text = list(dict.fromkeys(input_text.split())) words_to_remove = open("wordstoremove.txt", "r").read().splitlines() words_to_remove_capitalized = [] for i...
e98c7137ea6e56273fb9269b03570125c6828f9a
Alysonn2n/Calculadora
/calculadora.py
6,446
3.765625
4
import sys, random, math #x = valor inicial; y = juros; z= tempo #definições da calculadora def optionx(x,y,z): diferenca = x/y juros = (z/100) + 1 tempo = math.log(diferenca, juros) return print("O montante será de: " + str(x)+ ' reais.' + "\nCom um valor inicial de: " + str(y) + " reais" + ...
5165fdbe1fe5afb716f927807a50dc2d540fa99f
logan-schaufler/Python-Data-Structures-and-Algorithms
/Sorting_And_Searching/Searching/binary_search_recursive.py
340
3.71875
4
def binary_search_rec(a_list, item): if len(a_list) == 0: return False else: midpoint = len(a_list) // 2 if a_list[midpoint] == item: return True elif item < a_list[midpoint]: return binary_search_rec(a_list[:midpoint], item) else: return binary_search_rec(a_list[mi...
b8d37c7228f87d6f6107fd8c244964d527261632
LSSTC-DSFP/LSSTC-DSFP-Sessions
/Sessions/Session10/Day5/model_selection/.totallynothiddensolutions/exponentialmodel.py
1,833
3.734375
4
class ExponentialModel(Model): """ Simple exponential model for mis-centering. """ def __init__(self): # Define any hyperparameters for the a1 prior here. # E.g., for uniform, something like "self.min_a1 = value" and "self.max_a1 = value" # More sophisticatedly, you could make th...
484c02f0022a2af8645941f84a5236452f27e88f
Morrino/RedBird
/RedBird.py
3,049
3.8125
4
#!/usr/bin/env python3 # coding=utf-8 from rooms.room import Room from worlds.world import World, RandomWorld new_line = "\n" red_bird_title = """ ____ _ ____ _ _ | _ \ ___ __| | | __ )(_)_ __ __| | | |_) / _ \/ _` | | _ \| | '__/ _` | | _ < __/ (_| | | |_) | | | | (_| | |_| \_\___|\__,_| |...
afc39eb252dc3956a856e2d027ec28fa7f870b8f
danielkychen/TCP_Actuator
/Bootstrap.py
1,943
3.78125
4
# -*- coding: utf-8 -*- """ Created on Wed May 22 12:25:21 2019 @author: Daniel This module contains functions for Bootstrap hypothesis testing based on Efron (1993) """ import numpy as np import random from matplotlib import pyplot from statistics import mean def boot_paired(x, y, N): Mean...
4fa4db024b8b94b279b725f87d42895dd84706f5
Hana-42/Hana-CS-01
/CS07-7.py
252
3.84375
4
A=int(input('คะแนนสอบ=')) if (A <=10): print("ไม่ผ่าน") elif (A<=20) print("ปรับปรุง") elif (A<=30) print("ดีมาก") else: print("ข้อมูลไม่ถูกต้อง")
69e4966a8ca6600668535ddd308e0ef410bbc44a
GonBri/Election-Analysis
/PyPoll.py
1,053
4
4
# The data we need to retrieve. # 1. The total number of votes cast # 2. A complete list of candidates whoe received votes # 3. The percentage of votes each candidate won # 4. The total number of votes each candidate won # 5. The winner of the election based on popular vote. # Import the datetime class from the dateti...
bb3e53141113269a4bc9f2d3f7bb73a63c20a6fc
xtianbong/physical-computing
/stepper_test_2018.py
1,152
3.734375
4
#!/usr/bin/python # Terry Sturtevant, May 10, 2017 import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) stepper_pins=[5,6,13,19] GPIO.setup(stepper_pins,GPIO.OUT) stepper_sequence=[] stepper_sequence.append([GPIO.HIGH, GPIO.LOW, GPIO.LOW,GPIO.LOW]) stepper_sequence.append([GPIO.LOW, GPIO.HIGH, GPIO.LOW,GPIO.L...
208e24345acc079e50ce4b27191acdea16062ffd
YiliaHuiMeng/Python
/for循环/for.py
84
3.8125
4
#!/usr/bin/env python3 a = ["i","love","shiyanlou"] for i in range(3): print(a[i])
80be0b0042d2836e4cfd1cc846d623792246c377
gelafin/algorithm-class-portfolio
/GetTeslaHelpers.py
670
3.5
4
# Author: Mark Mendez # Date: 05/27/2021 # Description: Defines helper methods shared between bottom-up and top-down solutions to GetTesla def calculate_min_survival_hp(destination_max_hp): """ Calculates min hp needed to survive a GetTesla puzzle given the max hp possible at the destination Helper for Ge...
0283fd9a97487ee83261807555d21c15b3894773
liutongl5/LPTHW
/ex10.py
1,309
3.75
4
print "I am 6'2\" tall" #escape double-quote inside string print 'I am 6\'2" tall' #escape single-quote inside string tabby_cat = "\tI'm tabbed in." persian_cat = "I'm split\non a line." backslash_cat = "I'm \\ a \\ cat." fat_cat = """ I'll do a list: \t* Cat food \t* Fishies \t* Catnip\n\t* Grass """ print ...
be6d735dfe4d43456534176bb1cd8a20e1b2ea25
niksonnn/parsing
/parscsv.py
972
3.53125
4
import csv def write_csv(data): filename = "nams.csv" with open(filename, "a", encoding = "utf8") as f: writer = csv.writer(f) #delimiter, dialect writer.writerow((data['name'], data['surname'], data['age'])) def write_csv2(data): filename = "nams.csv" with open(filename, "a", encodin...
51b3e2b97cfcfacd0f623b6c2ebccf2092593d0c
whqnloyd/MyTest
/tesorflow/NN_one_layer.py
1,969
3.609375
4
import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # 载入数据集 mnist = input_data.read_data_sets('MNIST_data/', one_hot=True) # 设置模型 w = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) x = tf.placeholder(tf.float32, [None, 784]) y = tf.nn.so...
51300ee745b51136d15fb2279bd4354a894260b6
whqnloyd/MyTest
/web and database/SQlite test.py
666
3.96875
4
import sqlite3 print('creating connection...') conn = sqlite3.connect('data/test.db') print('creating cursor...') cursor = conn.cursor() #print('creating form...') #cursor.execute('create table user (id varchar(20) primary key, name varchar(20))') #print('inserting record...') #cursor.execute('insert into user (id, na...
c175dccc7fa5542772d3ab0e81be5773f5e0fa2d
carson0513/AE401-20200720
/random.py
248
3.53125
4
# -*- coding: utf-8 -*- """ Created on Mon Aug 3 17:33:36 2020 @author: a0970 """ import random x=random.randint(1,10) c=input("猜一個數字") c=int(c) if x ==c: print("猜對了") else: print("猜錯了˙")
9080fdd3d9bc764d2e48e34b8ad3282f8fcf13d6
Nihilnia/reset
/Day 3 - list Comprehension.py
1,032
4.25
4
# LIST COMPREHENSION listem = [1, 2, 3, 4, 5] yeniListem = [] for f in listem: yeniListem.append(f) # print("Eski liste:", listem) # print("Yeni liste:", yeniListem) #ListComp. nihilList = [f for f in listem] print("Nihil list:", nihilList) listeDemet = [(1, 2), (3, 4), (5, 6)] recepList = ...