blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
cc9568c77617cd203dd523bf8a5c6c574470b56b
Yumina9/2019-LIKELION-WINTER-STUDY
/13일차/class_modeling.py
762
3.75
4
class Human(): person = Human() person.name = '철수' person.weight = 60.5 def create_human(name, weight): person = Human() person.name = name person.weight = weight return person Human.create = create_human person = Human.create("철수", 60.5) def eat(person): person.weight += 0.1 print("{}가 ...
f99317059be2e5d8d7e1ab3708b93e99dfe06c3f
Yumina9/2019-LIKELION-WINTER-STUDY
/12일차/while.py
432
3.796875
4
selected = None #아무 값도 들어있지 않다. while selected not in ['가위', '바위', '보']: selected = input('가위, 바위, 보 중에 선택하세요>') print('선택된 값은: ',selected) patterns = ['가위', '보', '보'] length = len(patterns) i=0 while i < length: print(pattern[i]) i=i+1 #실습 numbers = [1,2,3] length = len(numbers) i = 0 while i<length: ...
e81a263534f3f6bde6ac07347d46df8ea1019284
Yumina9/2019-LIKELION-WINTER-STUDY
/9일차/random.py
340
3.6875
4
#실습 import random list = ["빨","주","노","초","파","남","보"] random_element = random.choice(list) import random random_number = random.randint(2,5) print(random_number) import random list = ["빨","주","노","초","파","남","보"] # 여기에 코드를 작성해 보세요. random_number = random.shuffle(list) print(list)
9b33b22bc00863b4bd2c06895bc5568c1ee13bfe
Yumina9/2019-LIKELION-WINTER-STUDY
/13일차/make_class.py
800
3.71875
4
class Human(): person1 = Human() person2 = Human() a = list() a #[] isinstance(a,list) #True list1 = [1, 2, 3] list1 #[1, 2, 3] list1.append(4) list1 #[1, 2, 3, 4] person1.language = '한국어' preson2.language = 'English' print(person1.language) #한국어 print(person2.language) #English person1.name = '서울시민' person2.n...
ad17808d8648a3bb6e11263f12a07fb1e441e8a0
Yumina9/2019-LIKELION-WINTER-STUDY
/9일차/dict_loop.py
494
4
4
ages = {'Tod':35, 'Jane':23, 'Pual':62} for key, value in ages.items(): print('{}의 나이는 {}입니다.'.format(key,value)) #실습 days_in_month = {"1월":31, "2월":28, "3월":31, "4월":30, "5월":31} for key in days_in_month: print(key) days_in_month = {"1월":31, "2월":28, "3월":31, "4월":30, "5월":31} #출력 형식은 아래 print함수를 참고하세요...
75df159106594545a3e92c47ec87dbde14e02a76
ranglang/Machine-Learning
/kNN/kNN.py
1,799
3.515625
4
from numpy import * import operator import numpy as np def createDataSet(numofNeighbors): neighbors = np.random.rand(numofNeighbors,2) # assign A1 to the first neighbor, A2 to the second neighbor,... names = ['']*numofNeighbors for i in range(0,numofNeighbors): names[i]= 'A'+str(i) ...
4c84cde5aacd116611f050a0b51f30bf82802b2f
akashdoppalapudi/python-for-avengers
/circle.py
515
4.09375
4
import math class Circle: def __init__(self,radius): self.radius = radius def circumference(self): c = 2*math.pi*self.radius return c def area(self): a = math.pi * self.radius**2 return a def __str__(self): return "circle of radius " + str(self....
656f34a46174941a27f44fba1120b468761e3a0c
akashdoppalapudi/python-for-avengers
/lengthoflastword.py
139
3.765625
4
s = input() words = s.split(' ') while '' in words: words.remove('') if len(words) == 0: print(0) else: print(len(words[-1]))
0322941d9e59be89dcc3436f686b5115f264a29d
j2538318409/demo02
/day2_1/find.py
563
3.609375
4
if __name__ == '__main__': str1 = "abcabcabc" str2 = "abcdefg" a = 0 arr1 = {} for b in str1 : # val = 要查找的字符串.count(key) # 字典名[key] = val arr1[b] = str1.count(b) print(arr1) for s in arr1: if arr1[s] > 1: #字典名[key] == value print("有...
622968dfe7f4faaf1fa6e0a38657ad268ac9c390
j2538318409/demo02
/myfun/find.py
343
3.859375
4
class MyException(ZeroDivisionError): pass try: print("你的分母为零了,") #手动抛出异常 raise MyException except MyException as a: print("catch MyExcetion") except ValueError as v: print(v) except Exception as e: print(e) else: print("try except else") finally: print("finally")
0ec78a90c1144100ec541f7185f4a33c5b458628
j2538318409/demo02
/day2_1/mydict.py
590
3.578125
4
if __name__ == '__main__': mdict = {"name":1,"password":2} print(type(mdict)) #用这种遍历方式取出的是健 for kv in mdict: print("type is {0}".format(type(kv))) print(kv) #取出字典的值 for v in mdict: print("madict[{key}]={val}".format(key = v,val = mdict[v])) for k,v in mdict....
115d58327ad830a2ddfea1d1d326da29f5ef3f95
j2538318409/demo02
/day2_1/mdict.py
702
4
4
if __name__ == '__main__': mdict = {"name":"kor","age":"12"} #通过变量名拿到属性值 print(mdict["name"]) #通过属性名修改值域 mdict["name"] = "fand" print(mdict) #删除键值对 del mdict["name"] print(mdict) #str()返回一个字符串型的字典 a = str(mdict) print(type(a)) print(mdict) for m in mdict : ...
f4c613bfdc2add6a38c825c03240399cbd7abcb3
j2538318409/demo02
/myfun/exam.py
559
3.75
4
if __name__ == '__main__': pass birth1 = input("请输入第一个的生日") birth2 = input("请输入第二个的生日") find1 = birth1.strip(":") find2 = birth2.strip(":") if int(find1[0]) > int(find2[0]): print("第二个年龄大") elif int(find1[0]) == int(find2[0]): if int(find1[0]) > int(find2[0]): pri...
67ac56be2bc00c35d0cb1dba4b35944eb2b04993
alexpujols/evalSearchingAlgorithms
/evalSearchingAlgorithms.py
7,038
3.640625
4
##!/usr/bin/env python ''' :::::: :+: :+: +:+ +:+ +#++:++#++::::::: +#+ +#+ :+: #+# #+# +:+ ### ###+:++#"" +#+ #+# ...
a33ee4298c53a706ea3a03dc6bfe3ff18678e508
saidtop/dom_peir
/dom8.1.py
182
3.90625
4
def increment(a): return a + 1 def decrement(a): return a - 1 print(decrement(int(input("декремент:")))) print(increment(int(input("инкремент:"))))
8e5aef65fb257bc0e552d417dbb0b84a38efaa3d
saidtop/dom_peir
/8.5.py
421
3.765625
4
def a(a, b , c ,): D = b*b - 4*a*c if D < 0: print('Действительных корней нет') return elif D == 0: print('есть 2 одинаковых корня') X = -b/(2*a) return X else: print('2 различных корня') x1 = (-b + D**0.5)/(2*a) x2 = (-b - D**0.5)/(2*a) return x1, x2 y1, y2 = a(int(input("a:")),int(...
9b428a7da952bad5169ea2c55ef9b4a3f74a46a1
mugunthanramesh/SpeechSearch
/learn_speech_recognition.py
3,808
3.59375
4
import speech_recognition as sr #speech to text import pyttsx3 #offline text to speech import bs4 as bs #web scrapping import urllib.request #web scrapping import webbrowser as web #web browser usage import cv2,re #cv2 - image operation import datetime,os #functioning with os #...
5d9caf15407bdfc5af90d7dee8af9825379ebcf6
aapaetsch/cmput-396-codes
/A1/a1p4.py
1,927
3.53125
4
# Transposition Cipher filecipher # Adapted from https://www.nostarch.com/crackingcodes (BSD Licensed) import time import os import sys import a1p1 import a1p2 def main(): #strings for the input and output text inputFile = 'mystery.txt' outputFile = 'mystery.dec.txt' #do we want to encrypt or decrypt t...
4240549064236f14d11bed590042256fcc103ef8
aapaetsch/cmput-396-codes
/A9/a9p2.py
2,350
3.5
4
from a9p1 import ngramsFreqs, cleanText def keyScore(mapping, ciphertext, frequencies, n): #returns the n-gram score (floating point number), #computed given that a mapping, ciphertext (given as a string) #an ngram frequency dictionary (such as is returned by your ngramsFreqs function) #and the n-gram parameter n...
083a97b34f0ac1423c9ccdc934b6b82d0a9c20e9
baraamoh/cos
/activity_picker.py
595
3.578125
4
# import special libraries already built in python import random, urllib2 # list of options to select from possible_activities = ['a','b','c'] the_url="https://raw.githubusercontent.com/bellcodo/congenial-octo-meme/master/activities.lst" list_raw_text=urllib2.urlopen(the_url).read() #print "DEBUG: "+str(list_raw_tex...
f8bf887270cf56739b581398cb3299d09844dcf1
matheushjs/ElfLibC
/string/string/encoding.py
4,351
4.1875
4
#!/usr/bin/python3 """ The idea is to create hashtables for all characters present in latin1 encoding We need the hashtables: latin1 -> utf8 utf8_lower -> utf8_upper utf8_upper -> utf8_lower utf8 -> latin1 """ def ts(strr): """Changes a string of the form b'\xc3' into the form "\xc3" """ ret...
787d79fcd60b6141deaa38b8bbbe94ca7a7eef7a
zhou0/Family-Law-Doc-Generator
/numeralizar.py
16,037
3.984375
4
import random def numeralizar(string): """Toma un número y lo convierte en palabras""" string=str(string) string=string.replace('.','') string=string.replace(' ','') remanente='f' if string[0] == '0': string = string[1:] if '-' in string: remanente=string[-1:] ...
53b76dd079eff09a38682dbd0b041b119d2e95b9
YAKOVLENKO/ITIB_labs
/lab4.py
3,589
3.734375
4
# Изучение алгоритма обратного распространения ошибки (метод Back Propagation) import numpy as np import matplotlib.pyplot as plt import pandas as pd def GetDerivative(out): return (1 - out ** 2) / 2 def GetActivation(net): out = (1 - np.exp(-net)) / (1 + np.exp(-net)) return out, GetDeriv...
48ded77911e4f9e63e254d4cc5265e02f8f593e1
BrimCap/BoredomBot
/day.py
1,010
4.3125
4
import datetime import calendar def calc_day(day : str, next = False): """ Returns a datetime for the next or coming day that is coming. Params: day : str The day you want to search for. Must be in [ "monday" "tuesday" "wedn...
77e6f6bade0489808436415a2c4ade909456c2fc
mossimokim/FSND-P2-Tournament
/tournament.py
4,974
3.6875
4
#!/usr/bin/env python # # tournament.py -- implementation of a Swiss-system tournament # import psycopg2, random, math VERBOSE = True def connect(): """Connect to the PostgreSQL database. Returns a database connection.""" return psycopg2.connect("dbname=tournament") def deleteMatches(): """Remove all...
a8e029eba058be5c873c4f4a6716cc59d43e3937
algorithmWithPython/awp
/mzhao/lessons/tree/dfs.py
2,630
3.609375
4
# depth first search (DFS) class Node: def __init__(self, key, left=None, right=None): self.val = key #self.children = [] # incase you want more than 2 children self.left = left self.right = right def printInorder(root): if not root: return printInorder(root.left) ...
b6653dac6c6ebc5f03a0398749e54753192c1d1b
algorithmWithPython/awp
/mzhao/lessons/backtracking/queens.py
1,133
3.578125
4
def queens(numberOfQueens): chess_board = [ ['-']*numberOfQueens for _ in range(numberOfQueens)] def dfs(row): # base case if row == numberOfQueens: print_chess_table() return for c in range(numberOfQueens): good_spot =True for...
f8c85d905f9708e12cd904d9ffce4771a30eace0
JustCode31/pechka
/pechka.py
2,242
4.0625
4
import time x=0 starttime=int(input("введите время включения ")) temp=int(input("напишите начальную температуру ")) maxtemp=int(input("напишите максимальную температуру ")) # print("просьба далее время указывать в минутах") speedg=int(input("напишите сколько градусов поднимается за минуту ")) wait=int(input("на...
1e3e0ed5cf60d1620f8f9106b57b494b4825286b
manoj-hans/Leetcode-Solutions
/valid-parentheses/valid-parentheses.py
399
3.75
4
class Solution: def isValid(self, s: str) -> bool: stack = [] map_ = { ")":"(", "]":"[", "}":"{" } for char in s: if char in map_ and stack and stack[-1] == map_[char]: stack.pop() else: stack...
951f20aaea66bb13a4dfab9914d7797f37e112f4
ivandumas/actividad1
/matrix/nMatrix.py
1,237
4.09375
4
import sys, random def createNMatrix(n): mat=[] for i in range(n): row=[] #temporary list to store the row for j in range(n): row.append(random.randint(0,10)) #add the input to row list mat.append(row) #add the row ...
2139f4ef20e16edef0f9afac75c084353ccf6bb3
nokane/LeetCode
/py/addTwoNumbers.py
1,844
3.78125
4
""" You are given two linked lists representing two non-negative numbers. 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 list. Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Definition for singly-linked list. class ListNod...
5c28616fa06cfebd1942f01c9effeb69924be71e
nokane/LeetCode
/py/isPalindrome.py
400
3.96875
4
""" Determine whether an integer is a palindrome. Do this without extra space. """ def isPalindrome(x): """ :type x: int :rtype: bool """ if (x == 0): return True elif (x < 0) or (x % 10 == 0): return False y = 0 while (x > y): y = (y * 10) + (x % 10) ...
3c5a0785d6a15647b1772b1b4dd56b3be3757d42
papri-entropy/pyplus
/class7/exercise1e.py
566
3.890625
4
#!/usr/bin/env python """ 1e. Create a variable named "trust_zone". Assign this variable to be the first "zones-security" element in the XML tree. Access this newly created variable and print out the text of the "zones-security-zonename" child. """ from pprint import pprint from lxml import etree with open("show_...
85c51214e25e9e60fa0f86b323b24feb2d0ab26f
papri-entropy/pyplus
/class7/exercise4b.py
523
3.8125
4
#!/usr/bin/env python """ 4b. Use the find() method to find the first "zones-security-zonename". Print out the zone name for that element (the "text" of that element). """ from pprint import pprint from lxml import etree with open("show_security_zones.xml") as f: xml_str = f.read().strip() xml_data = etree.fro...
ad1ae0039c48c95c13268cfd96241e93a858d57b
papri-entropy/pyplus
/class7/exercise4c.py
710
4.15625
4
#!/usr/bin/env python """ 4c. Use the findall() method to find all occurrences of "zones-security". For each of these security zones, print out the security zone name ("zones-security-zonename", the text of that element). """ from pprint import pprint from lxml import etree with open("show_security_zones.xml") as ...
cd7e676fc5f575b777f772be115fe44491077100
DanielPullan/be-less-fat
/archive/big-fat-script.py
2,440
3.84375
4
## Be Less Fat by Dan Pullan (https://danielpullan.co.uk/projects/be-less-fat) ## Weight loss data and visualisations ## 17/07/2019 ## We're all about the metric system here. 🇪🇺 ## Weight - kilograms (kg), height - metres (m), calories (kcal) ## For help - python3 miffler.py help ## For Metallica - python3 miffler....
407a76261937bf3c048f6b7317c9b928483b1bc3
bartdag/pydsl2
/simpledsl/simpledsl/timeprint.py
2,440
4.0625
4
from collections import deque from datetime import datetime class State: """This is an internal class that keeps track of the program flow.""" def __init__(self): self.out_stack = deque() self.state_stack = deque() self.global_state = {} self.skip = True def output(self, s...
9688004f15e6c4ce2c8a1e9ea6580b0c2360614d
collinsdaniel/curso-python
/conta.py
1,215
3.6875
4
from data import Data class Conta: def __init__(self, numero, titular, saldo, limite): print("Construindo objeto ... {}".format(self)) self.__numero = numero self.__titular = titular self.__saldo = saldo self.__limite = limite def extrato(self): print("Saldo ...
e0e0d097adba29f9673331887f6527caa5b3d2ad
fr3d3rico/python-machine-learning-course
/study/linear-regression/test4.py
2,734
4.53125
5
# https://www.w3schools.com/python/python_ml_polynomial_regression.asp # polynomial regression import matplotlib.pyplot as plt x = [1,2,3,5,6,7,8,9,10,12,13,14,15,16,18,19,21,22] y = [100,90,80,60,60,55,60,65,70,70,75,76,78,79,90,99,99,100] plt.scatter(x, y) plt.show() import numpy as np import matplotlib.pyplot...
72f0cc91a76987f6d435334005b0a5ca8db23e70
atbolsh/primitive_abundant
/primitiveabundant3/code/primes2.py
7,929
4.125
4
#!/usr/bin/python '''This module is designed to provide prime sieves and do basic operations necessary for other number theory functions, such as generating prime factorizations and lists of proper divisors. The backbone for the number theory modules; imported by the other modules''' def lim(n): '''This useful func...
d2810da32d8429a566d6f03169bac83c21eb86bd
rlheureu/arctic
/utils/retaildata_utils.py
2,639
3.5625
4
''' Created on May 10, 2017 @author: shanrandhawa ''' import re def sticks_and_capacity(title): """ Returns a tuple of the number of: number of memory sticks, capacity of each stick """ title = title.lower() nstitle = "".join(title.split()) match = re.match(r".*(\d+)x(\d+)g", nstitl...
f00819de5b0629f0856f6428427cfdc4316c69af
chenjiayu1502/dataStructure
/quickSort.py
532
4.0625
4
def quickSort(nums): ''' nums: list ''' if len(nums)<2: return nums i=0 j=len(nums)-1 act=0# 0 for j 1 for i target=nums[0] while(i<j): if act==0: if nums[j]<target: nums[i]=nums[j] act=1 i+=1 else: j-=1 else: if nums[i]>target: nums[j]=nums[i] act=0 j-=1 else: ...
f698858a3d28ecdd025f0cfc7a45ecacf81f5a43
sarinda94/pyforneteng
/Week3/show_ip.py
1,981
3.53125
4
# Import pprint for prettier printing import pprint show_ip_int_brief = """ Interface IP-Address OK? Method Status Protocol FastEthernet0 unassigned YES unset up up FastEthernet1 unassigned YES unset up up FastEthernet2 u...
ce8e3476c79e4027888f38da4d56f415144770c7
zhamiila824/problems
/problem5.py
472
3.984375
4
# Smallest multiple # 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? def divisible(n): for i in range(1, 20): if n % i != 0: retur...
4884503e1a81bfd9dc90fc46a67994a5b0111ee2
harelartman/matrix
/matrices.py
1,074
3.515625
4
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ # First assignment - matrices # Programmer - Harel Artman import numpy as np #smallest matrix list1 = np.array([[1,2], [3,4]]) list2 = np.array([[5,6], [7,8], [9,10]]) FirstSmall = min(np.size(list1,0), np.size(list2,0))...
32bcdb315f665c513dff605dcb3e0ae93d6b58b3
gblorem/python-lesson1
/solution_3.py
1,188
3.828125
4
# -*- coding: utf-8 -*- '''3. Узнайте у пользователя число n. Найдите сумму чисел n + nn + nnn. Например, пользователь ввёл число 3. Считаем 3 + 33 + 333 = 369.''' # Не стал вставлять проверки на ввод цифр. Мало времени ) # В предыдущем решении проверка есть, принцип тот-же n = int(input('Введите число n:\n> ')) va...
13a6bbc5b5e1f7df4b56d7ee54ebc6f9b0188a05
jav/aicomp
/rating/elo_rater.py
637
3.609375
4
class EloRater: """ Accepts player rating and player scores and returns two new suggested ratings for the players. Example: call with getRatings((1000,1000),(1,0)) to simulate two new players where one player won against the other. """ @staticmethod def getRatings(ratings, ...
6b2b9b64f74d27a9fe63b67a634f62d693ded62a
Raptors65/python-scripts
/MyScripts/Math/a_magic_triangle.py
517
3.609375
4
from itertools import permutations remaining_numbers = (4, 5, 6, 7, 8, 9) vertices = (1, 2, 3) for permutation in permutations(remaining_numbers): for vertex1 in range(1, len(remaining_numbers) - 1): for vertex2 in range(vertex1 + 1, len(remaining_numbers)): if (sum(permutation[:vertex1]) + vertices[0] + verti...
6a096249120225cfd201cf89303951f25e34f9b3
Raptors65/python-scripts
/MyScripts/Math/Prime Numbers/prime_tests.py
1,439
3.78125
4
import itertools import math def wheel_factorization(n): # Making the sieve array. A = [True] * (n + 1) # Storing the precalculated wheel. wheel = [2, 4] # Variable to store the iteration index. wheel_index = 0 # Variable to store the current number being tested. i = 5 # Looping until the sqrt of n. while ...
17d0d64391a734b53907c6edd8beae1dc9f8486e
Raptors65/python-scripts
/MyScripts/days_left_of_school.py
1,522
3.65625
4
import datetime as dt # Constants (change each year) last_day = dt.date(2019, 6, 27) holidays = [dt.date(2018, 9, 3), dt.date(2018, 10, 5), dt.date(2018, 10, 8), dt.date(2018, 11, 16), dt.date(2018, 12, 7), dt.date(2018, 12, 24), dt.date(2018, 12, 25), dt.date(2018, 12, 26), dt.date(2018, 12, 27), dt.date(2018, 12, 28...
3a91ddf135a99b0cc21dcc8ce0fdb6d32d2383a3
Raptors65/python-scripts
/MyScripts/bitarray.py
5,278
3.6875
4
# TODO: # • implement __setitem__ for slices, __delitem__ # • implement list methods (e.g. insert) # • implement __repr__, __str__, etc. # • implement __add__ # • add more ways to initialize list # POSSIBLE IMPROVEMENTS: # • optimize extend to not have lots of calls to # append # INFO: # • Items are accessed by usi...
bbbee6f7f57fc6bbe947adec782aa31960ec05ee
morgen01/MasterStudies
/statistical_programming/kMeans_Morgenstern.py
1,781
3.5
4
# -*- coding: utf-8 -*- # ******************************************************************** # # SU19-CPSC-51100-002, Summer-2 2019 # # NAME: Group 2: Christina Morgenstern, Seth Gory, Amy Noyes # # PROGRAMMING ASSIGNMENT #2 – k-Means Clustering # # 7/...
2acc1a0f4938ae855c248936796802beb77a5626
dumblob/manual-websocket
/emoji_ternarize.py
408
3.703125
4
#!/usr/bin/env python3 import gmpy2 def to_ternary(byte): return gmpy2.digits(byte, 3).zfill(6) def to_emoji(digit): if digit == "0": return ":cactus:" if digit == "1": return ":hash:" if digit == "2": return ":pig:" def emojiternarize(string): out = "" for byte in string.encode("utf-8"): out += " ".join([to...
d5f5465033a01fb850d65a8feb49ec28943bbaff
mobi12/study
/python/change.py
119
3.515625
4
#! /usr/bin/python #coding: utf-8 x = input("输入数字:") print "八进制:%o" % x print "十六进制:%x" % x
948873d15028ddef7c6a0e00c11b423257e0cc3c
nix1947/cookbook
/languages/python/basic/function.py
416
3.796875
4
""" when to use function ? To break large program into smaller ones. To improve reusability. Tips on function ~~~~~~~~~~~~~~~~~ """ def sum(a, b): return a + b # By default return None # TIP: Never return None from function, rather throw exceptions. def divide(x, y): try: result = ...
44c4644c125e019ccf3b293bda30145645ebc956
pegaster/PUM-informatics
/4 functions/A.py
314
3.71875
4
# modified Euclidean algorithm def gcd(a, b): while (a != 0) and (b != 0): if a > b: a %= b else: b %= a return a + b def lcm(a, b): return (a * b) // gcd(a, b) if __name__ == "__main__": nums = input().split() print(lcm(int(nums[0]), int(nums[1])))
ac7786ce8e2cce1271620aaa7985187f41b8d4c5
pegaster/PUM-informatics
/3 cicle/I.py
444
3.5
4
def isSimple(num): for j in range(2, num): if num % j == 0: return False return True nums = input().split() start = int(nums[0]) end = int(nums[1]) result_list = [] for i in range(start, end+1): if i <= 2: result_list.append(i) else: if isSimple(i): res...
d75a4ff77ccb967429ad4cbd0106e26cbf38c252
pegaster/PUM-informatics
/5 recursion/B.py
173
3.75
4
def find_max(y, m=0): if y == 0: return m return find_max(y // 10, y % 10 if m < y % 10 else m) if __name__ == "__main__": print(find_max(int(input())))
f6242852b019b24a2721124bc3a36e6efa6c78f6
pegaster/PUM-informatics
/2 branch/E.py
177
3.671875
4
import math position = input().split() x = float(position[0]) y = float(position[1]) check = y < math.sin(x) and 0 < y < 0.5 and math.pi > x > 0 print('YES' if check else 'NO')
f61ccd478ce2fea2f18fd34ea696d2ab1c3fcb3a
YozhPy/python-KPI-labs
/lab16.py
182
3.859375
4
a = int(input("Give me first number: ")) b = int(input("Give me second number: ")) for num in range(a,b): if all(num%i!=0 for i in range(2,num)): print(num, end = " ")
6e0d96b1c9ef0550548e566f9c4bddf9f44978e4
YozhPy/python-KPI-labs
/lab5.py
611
3.875
4
# Task 88 import sys try: n = int(input("Please, enter your number: ")) except ValueError: print("You must enter only a number!!!") sys.exit() n_2 = str(n**2) n = str(n) if '3' in n_2: print("Task A. The square of this number contains 3") else: print("Task A. The square of this number doesn't contain...
dcadedbd775acd0b7f18718e68a2b18b60dc72d5
YozhPy/python-KPI-labs
/lab7.py
362
3.6875
4
#Task 115(B) import sys try: n = int(input("Please, enter an amount of members in this numerical series: ")) except ValueError: print("You must enter only a number!!!") sys.exit() sum = 0 if n<1: print("This number must be more than 0") else: for k in range(1, n+1): sum+=1/(pow((2*k+1),2)) print("S...
66eec9ddc4296a01ed2fe75ea08819cdc0034d5d
SjoerddzHu/TICT-V1PROG-15
/les08/practice8_3.py
608
3.59375
4
def code(invoerstring): nieuwestring='' for kar in invoerstring: nieuweASCII = ord(kar)+3 nieuwekar = chr(nieuweASCII) nieuwestring += nieuwekar return nieuwestring def uncode(invoerstring): nieuwestring='' for kar in invoerstring: nieuweASCII = ord(kar)-3 nie...
2efbc98657f9d39ec308105a5772e3cbcc44e118
SjoerddzHu/TICT-V1PROG-15
/les03/pracitce3_4.py
89
3.5
4
list = ["maandag","dinsdag","woensdag "] for char in list: print(char[0] + char[1])
b8c84fe6819ab0b353eb3f96eaf0d5d209b78449
SjoerddzHu/TICT-V1PROG-15
/les02/practice2_1.py
166
3.8125
4
letters = ('A', 'C', 'B', 'B', 'C', 'A', 'C', 'C', 'B') alphabet = ['A','B','C'] list = list() for chr in alphabet: list.append(letters.count(chr)) print(list)
c622b62cf48c25a0a93765c82bec5f504131c920
mathmed/clean-architecture-python
/src/presentation/contracts/controller_contract.py
914
3.53125
4
from typing import Type, Dict from abc import ABC, abstractmethod class HttpRequest: def __init__(self, header: Dict = None, body: Dict = None, query: Dict = None, url_param: str = None): self.header = header self.body = body self.query = query self.url_param = url_param def __r...
97c76f3a241fde616fdc7557b5da745d904cc31d
DaMacho/data-science-school-5th
/day20 advanced topics/argparse_example/argparse_ex2.py
259
3.796875
4
# -*- coding: utf-8 -*- import argparse parser = argparse.ArgumentParser() # 정수형임을 암시 parser.add_argument("square", help="calculate square value of the number", type=int) args = parser.parse_args() print args.square ** 2
c98fce087e02836367305a93b2585243309ed3c9
DaMacho/data-science-school-5th
/day20 advanced topics/argparse_example/argparse_ex5.py
324
3.609375
4
# -*- coding: utf-8 -*- import argparse parser = argparse.ArgumentParser() # 파라미터의 개수를 2개로 설정 parser.add_argument('--number', help='numbers to be added', nargs=2) args = parser.parse_args() print type(args.number) print sum([int(i) for i in args.number]) #python argparse_ex5.py --number 3 4
107590855ab9d82cdf276e6b73f1b8d68785c0ec
Makhmadziyoev/Crypto
/GENERAL/atbash.py
779
3.65625
4
# АТБАШ # arr1 = [chr(x) for x in range(65, 91)] # arr2 = [x for x in arr1] # arr2.reverse() alfRU = ['А', 'Б', 'В', 'Г', 'Д', 'Е', 'Ж', 'З', 'И', 'Й', 'К', 'Л', 'М', 'Н', 'О', 'П', 'Р', 'С', 'Т', 'У', 'Ф', 'Х', 'Ц', 'Ч', 'Ш', 'Щ', 'Ъ', 'Ы', 'Ь', 'Э', 'Ю', 'Я'] print(len(alfRU)) arr2 = [x for x in alfRU] arr...
70b5f53e973ec9f0091a80ac28e555e6a8661bef
AlexFradle/rpg-game
/misc/line_collision_demo.py
4,174
4
4
import pygame import math from random import randint from typing import Iterable pygame.init() def line_collide(line_1_coords: Iterable, line_2_coords: Iterable) -> tuple: """ Line-Line Collision using the equation: (x1 - x3)(y3 - y4) - (y1 - y3)(x3 - x4) t = ----------------------------...
196b56833df05e8603743edf6a71f8c7fb86867a
ursu1964/Algorithms-Implementations-Using-Python
/Graph/kruskal’s_algorithm(MST).py
1,557
4.03125
4
from Graph.graph import Graph def krushkal_algo(graph): edge_count = 0 mst_list = [] # List to maintain MST(Minimum Spanning Tree). num_nodes = graph.number_of_nodes check_list = [] # A List To Identify Cycles. for i in range(num_nodes): check_list.append({i}) # print(check_list) ...
5aba743e0555b3038a6d5129eed56e63ff3bc9b0
ursu1964/Algorithms-Implementations-Using-Python
/Divide And Conquer/min_max_algorithm(divide_and_conquer).py
1,203
4.09375
4
#!/usr/bin/env # Python script to find maximum and minimum element from array using divide and conquer. # Run Time Complexity: Worst case O(n), Average Case: log(n) import math def find_min_max(given_array, starting_index, ending_index): global maximum # Global Variable Declaration To Make Changes In This Scop...
0f511b18f43bda9d5703a6cec0a1ff7a7044abe0
massinat/ML
/part2.py
2,007
3.875
4
""" Classification related to part 2. KNN classification with variable K and euclidean distance. Votes are distance weighted. @Author: Massimiliano Natale """ from knn import KNN from resultHelper import ResultHelper """ Trigger the classification. Create the output file and the chart to visualize the result. """ if...
ad9c66d14c94c653820a8dc4221891335c786373
Nischalkhadgi/Tkinter-GUI
/tkinter.py
467
3.546875
4
from Tkinter import * root = Tk() topFrame = Frame(root) topFrame.pack() bottomFrame = Frame(root) bottomFrame.pack(side=BOTTOM) button1 = Button(topFrame, text="Button1",fg="blue") button2 = Button(topFrame, text="Button2",fg="orange") button3 = Button(topFrame, text="Button3",fg="red") button4 = Button(bottomFram...
562a9b29a433aebf4db63c7dc13979804bbc8a92
Fanniek/intro_DI_github
/menu_editor.py
1,455
3.84375
4
from menu_manager import MenuManager def load_manager(): instance = MenuManager() # print("hey") return instance def show_user_menu(): choice_user = input("(a) Add an item\n(d) Delete an item\n(v) View the menu\n(x) Exit\n>>>") if choice_user == "a": add_item_to_menu() elif choi...
0b33cfc469f55189aad47931fc3b2ff6523f6aa3
Fanniek/intro_DI_github
/decorators-Mar12.py
1,592
3.671875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Mar 12 18:01:01 2019 @author: fannieklein """ import time #def my_decorator(my_func): # def wrapper(): # my_func() # my_func() # my_func() # return wrapper # #@my_decorator #def first_name(): # print("Fannie") # #first_...
02e08da64766c262406de320027d2d53b5e3dfa2
Fanniek/intro_DI_github
/lambda.py
1,305
4.53125
5
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 26 19:20:40 2019 @author: fannieklein """ #Exercise 1: mylist =[" hello"," itsme ","heyy "," i love python "] mylist = list(map(lambda s: s.strip(), mylist)) #print(mylist) #Explanattion of Exercise 1: #This function should use map function --> ma...
24a2cad42ee045b58222481f4ea2656c2479e036
sengseiha-sam/game_disk_battle
/boad.py
465
3.546875
4
array_of_board =[] rows = 6 cols = 7 for i in range(rows): array_of_board.append([]) for j in range(cols): array_of_board[i].append(0) def setSign(row,col,sign): newarray = array_of_board rows = 6 cols = 7 for i in range(rows): for j in range(cols): ...
239fdcef1bfc2e8e2f9fb3e14a55e09ececa2817
LambertoD/inventory_keeper
/inventory.py
1,471
4.03125
4
class Inventory(object): """This class maintains an inventory of products with quantities It maintains state for a product inventory and a back-order inventory. """ def __init__(self): self.entries = {} self.back_order = {} self.back_order_status = {} def add(self, name, ...
e1cd26632fc3e6e16705fe65e71c208dbe5eb8aa
danong/leetcode-solutions
/solutions/add_two_numbers.py
1,022
3.703125
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ a_ptr...
c29d8347981f50fb00ea62bbff75c573291129e3
danong/leetcode-solutions
/solutions/sort_colors.py
710
3.515625
4
class Solution: def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ next_0 = 0 next_2 = len(nums) - 1 for idx in range(len(nums)): while nums[idx] == 0 or nums[idx] == 2: ...
dfb6d570fb32d143a554c86b18ff93cbd4f30aa2
danong/leetcode-solutions
/solutions/container_with_most_water.py
651
3.71875
4
"""https://leetcode.com/problems/container-with-most-water/""" class Solution: def maxArea(self, height): """ :type height: List[int] :rtype: int """ left = 0 right = len(height) - 1 max_volume = 0 while left < right: cur_height = min(heig...
91bf3ec1eeced67dd138084dc1c78488299053a3
danong/leetcode-solutions
/solutions/word_ladder.py
1,340
3.640625
4
from collections import deque, defaultdict def build_word_dict(word_list): d = defaultdict(list) # key: placeholder str, value: list of words wlen = len(word_list[0]) for word in word_list: for i in range(wlen): placeholder = '{}_{}'.format(word[:i], word[i+1:]) d[placehol...
c2538d0463b8767376d5f1a9d53dda605816acbc
danong/leetcode-solutions
/solutions/tic_tac_toe.py
1,417
4.0625
4
import random class TicTacToe: """TicTacToe game instance human plays against AI human player uses 'x' ai player uses 'o' board indices are: 6 7 8 3 4 5 0 1 2 """ def __init__(self, player_first: bool = True) -> None: self.board = [' '] * 9 self.valid_moves...
da5948b342c7daf3da0d83e86f4f9d059269ee6e
ChaosGuru/Python-levels
/level19.py
328
3.75
4
""" The same object var1 is var2 - True if tow vars are the same object """ class Greetings: def __init__(self, greeting): self.greeting = greeting def greet(self): print(self.greeting) if __name__=='__main__': g1 = Greetings("Hello, World") g2 = g1 if g2 is g1: g2...
93bdf478b1bc08811cd08c3701b1f3275d3212f3
ChaosGuru/Python-levels
/level10.py
564
3.890625
4
""" Looping for var in seq - fixed number of loops while cond - you are not sure how many loops you need break - stop loop continue - go to the next loop range(2) - == [0, 1] _ - when you do not need variable """ def greet(): print("Hello, World") if __name__=='__main__': for _ in range(1)...
6b1099760d1c1d70819bd731e64853ff58436524
wander0220/pythonStudy
/중첩if.py
200
3.75
4
num=int(input("숫자를 입력하세요 ")) if num%2==0 : if num==0: print("숫자는 0 입니다.") else : print("양수입니다") else : print("홀수입니다")
762e8c75a0f4066ca3f715472ece3bfab6406336
wander0220/pythonStudy
/Code04-02.py
470
3.640625
4
money,c50000,c10000,c5000,c1000=0,0,0,0,0 money=int(input("교환할 돈은 얼마인가요 : ")) c50000=money // 50000 money %= 50000 c10000=money //10000 money %=10000 c5000=money //5000 money %= 5000 c1000=money //1000 money %= 1000 print("50000원 ====>", c50000,"장") print("10000원 ====>", c10000,"장") print("5000원...
3bb57320bd9e8533a344a44d48eeb7e7bdc5f565
nishtha-kalra/dynamic_programming
/fib.py
433
3.96875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Feb 2 15:24:26 2019 @author: nishtha """ fib_cache = {} def fibonacci(n): if n in fib_cache: return (fib_cache[n]) if n <= 0: value = 0 elif n == 1: value = 1 else: value = fibonacci(n-1) + fibonacci(n-...
354df210bbfc1168d3683779e2fdc022dd5bc10f
cerealkill/light_karma
/loader.py
728
3.5
4
# -*- coding: utf-8 -*- class Loader: """ General class for objects that read data from Excel, PDF, CSV, Word and any other unstructured data sources and parse it into an structured data object that is saved to disk in a python pickle file. :arg file_path: String containing file path to load :ar...
fe4952c3cadc4c1f541a10d18a8a39f75cfdd42f
ivov/fdi
/FDI/3_9.py
605
4.125
4
# Leer un número correspondiente a un año e imprimir un mensaje indicando si es # bisiesto o no. Se recuerda que un año es bisiesto cuando es divisible por 4. Sin # embargo, aquellos años que sean divisibles por 4 y también por 100 no son bisiestos, # a menos que también sean divisibles por 400. Por ejemplo, 1900 no...
3b61406540cf5b470664d7d78c9b27bd7ef0b96f
yamazki/python_extend_list
/extendList/extend_list_test.py
568
3.53125
4
import unittest from extend_list import ExtendList class TestExtendList(unittest.TestCase): """test class of extend_list.py """ def test_value_of(self): extend_list = ExtendList([0,1,2,3,4,5,6]) expected = [0,1,2,3,4,5,6] actual = extend_list.list_value() self.assertEqual(expected, actual...
8ad71cb6e4e52fc454528ad87e4ecf657a6e406f
userddssilva/ESTCMP064-oficina-de-desenvolvimento-de-software-1
/distances/minkowski.py
513
4.125
4
def minkowski(ratings_1, ratings_2, r): """Computes the Minkowski distance. Both ratings_1 and rating_2 are dictionaries of the form {'The Strokes: 3.0, 'Slightlyt Stoopid: 2.5} """ distance = 0 commonRatings = False for key in ratings_1: if key in ratings_2: distance += ...
99566d61fc688390a35b1090cb4b5cb6fb32f716
arrowandbead/TronEmmetMalcolm
/Tron/ab_cutoff.py
3,335
3.765625
4
def alpha_beta_cutoff(asp, cutoff_ply, eval_func): """ This function should: - search through the asp using alpha-beta pruning - cut off the search after cutoff_ply moves have been made. Inputs: asp - an AdversarialSearchProblem cutoff_ply- an Integer that determines when to...
0bbfb8d56109e0fd40d1462c9b97494cedd8f0eb
allenbronshtein/Optimization-Scheduler
/Components/schedule.py
8,393
3.546875
4
import gui # GRADE 0 - 59 for bad . less clashes -> higher score # GRADE 60 - 99 for good . less windows and more function -> higher score # GRADE 100 for optimal BAD = 0 GOOD = 1 OPTIMAL = 2 EVENING_START_TIME = 14 def format_day_time(str): try: date = str.split(" ") day = date[0].strip() time = date[1]...
a70c150bcc2cef07c1d5ccb58ed5430eb677900d
radekwarowny/test_driven_development
/mytests.py
2,276
3.90625
4
import unittest from mycode import get_greetings, Rick, Morty, Citadel """ Basice unittest implementation """ class FirstTestClass(unittest.TestCase): # tests checks if the output is uppsercase def test_upper(self): self.assertEqual('rubiks code'.upper(), 'RUBIKS CODE') class HelloWorldTest(unitte...
76dda92c8447abbd6bcc619d2bc4bc5ae4bfcef0
pusidun/cicn2-py
/02_Singleton/singleton_02.py
521
3.6875
4
# /usr/bin/env python3 # -*- coding: utf-8 -*- from functools import wraps def singleton(cls): _instance = {} @wraps(cls) def get_instance(*args, **kw): if cls not in _instance: _instance[cls] = cls(*args, **kw) return _instance[cls] return get_instance # test if __name_...
f64018698d6d7e36dfd898bebd9281ad23cd3d78
hamidehAziz/PycharmProjects
/FirstProgram/attack.py
520
3.5625
4
#import random from Classes.enemy import Enemy enemy1 = Enemy(200,49) enemy1.getHp() enemy2 = Enemy(400, 60) enemy2.getHp() ''' playerhp = 250 enemyatkl = 50 emenyatkh = 90 while playerhp > 0: damage = random.randrange(enemyatkl, emenyatkh) playerhp = playerhp - damage if playerhp <= 30: ...
e2ef93c89de62091eb63aca9561658e1243e174e
charromax/Ejercicios-en-codigo
/ordenarMenorAMayor.py
1,137
3.921875
4
# En un proceso anterior se cargó en memoria un arreglo # unidimensional de 80 elementos reales. Se pide exhibirlo por # pantalla ordenado de menor a mayor. #--------------------------------------------------------------------------- import random list = [] for i in range(0, 5): # genera una lista de 80 reales aleat...
cdb445af1c0c491b9b7567892078ed887f28a5d0
charromax/Ejercicios-en-codigo
/ejercicio6.py
1,332
3.796875
4
# Las comisiones por ventas en una empresa se liquidan de # acuerdo con las siguientes condiciones: # - para importes menores que $500: el 5% del importe; # - para importes iguales o mayores a $ 500 pero menores que $1000: el 6,5% del importe; # - para importes iguales o mayores que $1000: el 6,5% del importe más $60....