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
0e6b1edba6cc8b19d81a97ba4af49a79f41bca5c
TomasHalko/pythonSchool
/School exercises/day_2_exercise_5.py
789
4.28125
4
dictionary = {'cat': 'macka', 'dog': 'pes', 'hamster': 'skrecok', 'your_mom': 'tvoja mama'} print("Welcome to the English to Slovak translator.") print("---------------------------------------------") print("English\t - \tSlovak") print("---------------------------------------------") for key,value in dictionary.item...
63398d597945f473ce64fb7ba34c14c50886872a
xueyuanl/leetcode-py
/problems/62_unique_paths.py
1,086
3.75
4
class Solution(object): """ use mathematical method, but not a good way to understand. """ def uniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int """ res = 0 for i in range(1, n): # 5 apples given 3 person, there are C...
0ba4badd663634f611472aa8ce98e76240a959ba
xueyuanl/leetcode-py
/problems/75_sort_colors.py
549
3.59375
4
class Solution(object): def sortColors(self, nums): """ :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ red, white, blue = 0, 0, 0 for i in range(len(nums)): if nums[i] == 0: red += 1 ...
873f768a87213dd429e9a24defda98d5d6a2f634
xueyuanl/leetcode-py
/problems/1315_sum_of_nodes_with_even-valued_grandparent.py
1,083
3.75
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 sumEvenGrandparent(self, root): """ :type root: TreeNode :rtype: int """ sel...
bc2661efbca776c22cc110b8cb078a676d7af5b9
xueyuanl/leetcode-py
/problems/170_two_sum_III_-_data_structure_design.py
779
3.921875
4
class TwoSum(object): def __init__(self): """ Initialize your data structure here. """ self.s = [] def add(self, number): """ Add the number to an internal data structure.. :type number: int :rtype: None """ self.s.append(number) ...
e14b24d3bf6b5a477a7515e0f0c3d5e444a96dd9
xueyuanl/leetcode-py
/problems/346_moving_average_from_data_stream.py
931
4
4
class MovingAverage(object): def __init__(self, size): """ Initialize your data structure here. :type size: int """ self.sum = 0 self.list = [] self.size = size def next(self, val): """ :type val: int :rtype: float """ ...
504c4dd0d0a70126742bb8726b2c0d924e21abf9
xueyuanl/leetcode-py
/problems/1474_delete_N_nodes_after_M_nodes_of_a_linked_list.py
674
3.703125
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def deleteNodes(self, head, m, n): """ :type head: ListNode :type m: int :type n: int :rtype:...
cdcd97777ca7474f2fae83449925044fa7017f05
xueyuanl/leetcode-py
/problems/15_3_sum.py
1,088
3.578125
4
class Solution(object): """ refer to: https://leetcode-cn.com/problems/3sum/solution/pai-xu-shuang-zhi-zhen-zhu-xing-jie-shi-python3-by/ """ def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ length = len(nums) if length < 3:...
9edb0ecf195ad8d48b57982b6baffa47eb107196
xueyuanl/leetcode-py
/problems/543_diameter_of_binary_tree.py
1,138
3.890625
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): """ a better solution: https://www.polarxiong.com/archives/LeetCode-543-diameter-of-binary-tree.html """ def ...
748541593f18737b89398d2e1363ba46a5654123
xueyuanl/leetcode-py
/problems/538_convert_BST_to_greater_tree.py
810
3.828125
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): """ refer: https://leetcode.com/problems/convert-bst-to-greater-tree/discuss/100506/Java...
9bef037f2b721f1e024822b9f272b57ae1f1e255
Hatosabre/nlp100
/src/01.preparation/03.py
236
3.59375
4
STR = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics." rep_str = STR.replace(",", "") def len_str(x): return str(len(x)) word_list = "".join(map(len_str, rep_str.split())) print(word_list)
f784a73f5284194a9a5d8a6d13e258441153e508
Hatosabre/nlp100
/src/01.preparation/08.py
435
3.875
4
import re STR = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can." def cipher(sent): decode_list = [] for x in sent: if re.match("[a-z]", x): decode_list.append(chr(219 -ord(x))) else: decode_list.a...
7eef96729d1cff6f0605764f529da8c97bb88217
MIT-STARLab/deconfuser
/deconfuser/orbit_fitting.py
18,864
3.671875
4
import numpy as np class OrbitGridSearch: """ A class for grid-searching over orbital elements that fit 2D points (in an image) with an orbit. Because this is exhaustive search, the minimum error is guaranteed to be found within specified tolerance. The search is over a 3D space, (a, ex, ey), where: ...
7265ea38cd157f595842c3ef9b309107ce72703a
FalseFelix/pythoncalc
/Mood.py
381
4.1875
4
operation=input("what mood are you in? ") if operation=="happy": print("It is great to see you happy!") elif operation=="nervous": print("Take a deep breath 3 times.") elif operation=="sad": print("kill yourself") elif operation == "excited": print("cool down") elif operation == "relaxed": print("dr...
e661ac04d764a895c9266a1107a5ad7b007360e6
bhavnagit/Hacktoberfest2020
/Python/DS_ALGO/Array/Array_Move_Element_to_End.py
531
3.96875
4
import numpy as np def move_element_to_end(arr,to_move): i=0 j=len(arr)-1 while i<j: while i<j and arr[j]==to_move: j-=1 if arr[i]==to_move: arr[i],arr[j]=arr[j],arr[i] i+=1 return arr #Test Case 1 array1=np.array([1,2,3,5,7,2]) print(move_element_to_end(array1,2)) #Test Case 2 array2=np.array([1,2,0,5,...
88acbb0a3b8de36e788b0562a1ba198cf85d1263
Tomdango/photowall-backend
/common/database.py
4,620
3.625
4
import sqlite3 import random from string import ascii_letters, digits class AbstractDatabaseTable(): """ Abstract Class for SQLite3 Tables """ def __init__(self): self._conn = sqlite3.connect("data/photowall.db", check_same_thread=False) class PeopleTable(AbstractDatabaseTable): """ SQLite...
71444953b357a2266b26877ff911ac0e924c00fc
pedropaixaob/selenium-course
/aula_09_a1.py
1,114
3.859375
4
""" Waits Dois tipos de espera: explícitos e implícitos Aqui trataremos de implícitos, explícitos apenas no próximo arquivo - Implícitas: espera todos os eventos, navegação, com um tempo padrão browser.implicitly_wait(30) PRÓS: - Funciona em cenários Flaky - Espera até acontecer algo CONTRAS: - Segura a aplicação p...
a8853792e977e8519badcd019a6e6bf32b907307
pedropaixaob/selenium-course
/aula_05_a1.py
482
3.640625
4
# atributos: globais, css, o DOM # find: id, class, name # elementos web: input, form from selenium.webdriver import Firefox firefox = Firefox() url = 'http://selenium.dunossauro.live/aula_05_a.html' firefox.get(url) # div_1 = firefox.find_element_by_tag_name('div') daria o mesmo resultado div_py = firefox.find_elem...
3559573a780b283de4e61fec0afe2913be45eef3
bitsapien/daily-coding-problem
/30-Aug-2020-product-of-elements-in-array.py
632
4.09375
4
# Problem # Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. # For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the...
6d89ea465f281e20ced859f84950573d1a4d3c0a
kkonrad33/kolokwium_wd2
/qwerty.py
1,189
3.578125
4
# Zadanie 1 def kropka(imie, nazwisko): print(f'{imie}.{nazwisko}') kropka("Konrad", "Kisiel") # Zadanie 2 def skrot(imie, nazwisko): print(imie[0].title() + "." + nazwisko.title()) skrot("konrad", "kisiel") # Zadanie 3 def rok(fst, lst, age): curr = fst + lst birth = int(curr) - ...
84fe99b67c7fcd7b9826bd3a2515ad939858348b
wcleonard/PythonBridge
/Data Type/string_methods.py
3,047
3.734375
4
# @Time : 2019/4/18 4:40 # @Author : Noah # @File : string_methods.py # @Software: PyCharm # @description: string methods from pprint import pprint string = "Because constants are an important building block for constructing expressions, it is important to be able to write constant values for each of the basic ...
fc080b5de22363064f268a18b5fd5767d3fc170f
wcleonard/PythonBridge
/Algorithm/sort/heap_sort.py
2,472
4.375
4
# @Time : 2019/4/21 0:49 # @Author : Noah # @File : heap_sort.py # @Software: PyCharm # @description: python -m doctest -v heap_sort.py # 利用堆这种数据结构所设计的一种排序算法 # 堆是一个近似完全二叉树的结构 # 并同时满足堆积的性质: # 每个结点的值都大于或等于其左右孩子结点的值,称为大顶堆 # 每个结点的值都小于或等于其左右孩子结点的值,称为小顶堆 # heapify函数作用是将待排序序列构造成一个大顶堆,此时整个序列的最大值就是堆顶的根节点 def heapify(u...
c5eeaa2abd70682043ed2c27cb1d5a0049769cf0
wcleonard/PythonBridge
/Design Pattern/Command design pattern/reality command pattern.py
1,265
3.796875
4
# @Time : 2019/4/21 22:13 # @Author : Noah # @File : reality command pattern.py # @Software: PyCharm # @description: 以证券交易所的例子来演示命令模式的实现 from abc import ABCMeta, abstractmethod # 提供抽象类Order和抽象方法execute class Order(metaclass=ABCMeta): @abstractmethod def execute(self): pass # 实现接口的具体类 class B...
dcf55ec33588ff943ef8a19e5b6349371649ffee
Yang-yc/Python
/05_高级数据类型/yc_06_元组.py
305
3.71875
4
info_tuple = ("张三", 18, 1.75) # 1、取值和取索引 print(info_tuple[0]) # 已经知道数据的内容,希望知道该数据在元组中的索引 print(info_tuple.index("张三")) # 2、统计计数 print(info_tuple.count("张三")) # 统计元组中包含元素的个数 print(len(info_tuple))
239eeab3311645823b526a9f32ba22382eb3d105
Yang-yc/Python
/05_高级数据类型/yc_03_列表的数据统计.py
465
3.75
4
name_list = ["张三", "李四", "王五", "张三"] # len(lenth长度)函数可以统计列表中元素的总数 list_len = len(name_list) print("列表中包含 %d 个元素" % list_len) # count方法可以统计列表中某一个数据出现的次数 count = name_list.count("张三") print("张三出现了 %d 次" % count) # 从列表中删除第一次出现的数据,如果数据不存在,程序会报错 name_list.remove("张三") print(name_list)
54cbedf68408d4bde873a36c1b996f77211d39e2
Yang-yc/Python
/05_高级数据类型/yc_21_遍历字典的列表.py
425
4.09375
4
student = [ {"name": "小美"}, {"name": "阿土"} ] # 在学员列表中搜索指定的姓名 find_name = "张三" for stu_dict in student: print(stu_dict) if stu_dict["name"] == find_name: print("找到了 %s" % find_name) # 如果已经找到,应该退出循环,而不再遍历后续的元素 break else: print("抱歉,没有找到 %s" % find_name) print("循环结束")
e60cbc13b4dea3bc7b79828f4c0e7dc2e90a3e86
MCaetanoPJ/Reconhecimento-Facial
/Versao_0.2/(1)Detector_Facial.py
1,807
3.5625
4
# Importa o OpenCV2 import cv2 # Define qual webcam será usada vid_cam = cv2.VideoCapture(0) # Informa o que deve ser procurado na tela usando o Haarcascade face_detector = cv2.CascadeClassifier('Modelo_XML/haarcascade_frontalface_default.xml') # Para cada rosto crie um novo ID face_id = 4 # Contador de rostos coun...
48a55a93c804c8cf69f49398174eba01dda8a454
Aurel37/TDLog_jeu
/test_error_gestion.py
2,559
3.90625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import unittest import main """ The tests are realised with the text document in the folder of the programm, the .txt documents used are 'TheForest', 'test_char_map' and 'test_dim_map' to run this file go in your terminal and go in the folder where the programm is then w...
ad0bc702fd681397c8ccc4e9ae938d83d9db1850
Tchouanga12/facial-detection
/models.py
3,552
3.59375
4
## TODO: define the convolutional neural network architecture import torch from torch.autograd import Variable import torch.nn as nn from torch.nn import Sequential, MaxPool2d, Conv2d, BatchNorm2d, ReLU import torch.nn.functional as F # can use the below import should you choose to initialize the weights of your Net i...
0a00cb2ea5dc62c2c9f937fbb8907f86e2d0b3f9
nehasutay/C-programs
/Python assignment 19052020/1 22 333 triangular pyramid.py
152
3.765625
4
for r in range(1,4): for t in range(1, 5-r): print(" ",end=" ") for c in range(r,0, -1): print(" ",r,end=" ") print()
4eb96e85bb721f552fcd4a0a730d6e4f3e018c1b
nehasutay/C-programs
/Python assignment 18052020/1 22 333 4444.py
136
3.875
4
n=int(input("Enter number of rows")) for num in range(1,n+1): for i in range(num): print(num,end='') print()
f7cb575bcf043ef64de44682e64b5b70b4fea28e
nehasutay/C-programs
/Python assignment 06052020/To check whether all item of a list is equal to given list.py
215
4.03125
4
list1=['neha','neha','neha','neha'] temp=list1[0] equal=True for x in list1: if temp!=x: equal=False break; if equal: print("Equal") else: print("Not Equal")
a1287424579f044c7840d192194fd595d5bc6a07
nehasutay/C-programs
/Python Program/cone surface area.py
134
4.125
4
r=int(input('Enter radius')) s=int(input('Enter the value of surface')) area=3.142*r*s+3.142*r*r print('Cone surface area=',area)
bc0626f7da9dce22421b7e200742e0cd108a824c
nehasutay/C-programs
/Python assignment 05052020/Prog.to generate group of 5 cosecutive numbers in list.py
176
3.921875
4
l=[] for i in range(0,3): n=int(input("Enter a value")) for j in range(n,n+5): l.append(j) print(l)
fa7d20ac651a948be83b77f3ed1d854ed76ed735
nehasutay/C-programs
/Python assignment 05052020/Convert list of multiple integer into single integer.py
137
4.03125
4
l=[] print("Enter values to concatenate") for i in range(0,3): val=input() l.append(val) print("Value is:",l[0]+l[1]+l[2])
f61d28f501b697ca5e478fbc0520a4bd40771053
wenzzel/wenzzel
/python-master/fybhp/practice12/practice12.py
324
3.6875
4
# -*- coding:utf-8 -*- import re list = [] file = open('filter_words.txt','r') content = file.read().decode('gbk') allwords = content.split() #print allwords yourword = raw_input('>').decode('utf-8') for mingan in allwords: if mingan in yourword: yourword = re.sub(mingan,'*'*len(mingan),yourword) print your...
44b89115afcebd496bc7fdc60ac0eb511f553e59
IntroProgramacion-P-Oct20-Feb21/trabajofinal-1bim-DenisCuenca
/Semana 6/Taller/Ejemplo1.py
123
3.65625
4
numero = 11 if (numero % 2)==0: print("El número %d es par\n"%(numero)) else: print("El número %d es impar\n"%(numero))
003028e3f87c0b2f1c76a10a12ec1d9e40e7961d
IntroProgramacion-P-Oct20-Feb21/trabajofinal-1bim-DenisCuenca
/Semana 7/Taller/Problematicas/Problema02.py
179
3.609375
4
# 2 6 12 20 30 42 56 72 90 110 aumento = 4 numero = 2 cadena = "" while numero <= 110: cadena = ("%s%d "%(cadena,numero)) numero = numero + aumento aumento += 2 print(cadena)
4dc64530123ff5fc92b6cb7b7333db4154be26ee
IntroProgramacion-P-Oct20-Feb21/trabajofinal-1bim-DenisCuenca
/Semana 4/taller 4/Algoritmo-1.py
154
3.8125
4
base = float(input("Ingrese la base de su trinágulo:")) altura = float(input("Ingrese la altura del triángulo: ")) area = (base * altura)/2 print(area)
7da5bf442bc42d05b1f0b0cd5b1409f4944fdd01
rifqirosyidi/functional-programming
/03 The Filter Function.py
1,396
3.65625
4
import collections from pprint import pprint Scientist = collections.namedtuple("Scientist", field_names=[ "name", "field", "born", "nobel" ]) immutable_scientist = ( Scientist(name="Van", field="math", born=1987, nobel=True), Scientist(name="Gery", field="math", born=1970, nobel=False), S...
3ffb97cb147be71404fe692a1073056576998fd9
yhoazk/hckrnk
/leap_year/leapiness.py
624
3.9375
4
#!/usr/env python3 def is_leap(year): leap = False if (((year)%4)==0) and (((year)%100 == 0) and (((year%400)) == 0)): leap = True return leap leap = lambda y : (((y)%4)==0) and (((y)%100 == 0) and (((y%400)) == 0)) #year = int(input()) # ======================================================...
5aeb7227c5a657ab0ae6f1858527ccfdb64bc866
yhoazk/hckrnk
/katas/AoC/2019/d1/day1b.py
813
3.78125
4
from fuel_calc import fuel_calc # calculate the fuel needed to take the fuel def fuel2fuel(mass): if mass == 0: return 0 else: m = fuel_calc(mass) # print("mass fuel: {}".format(m)) return m + fuel2fuel(m) def non_rec_fuel2fuel(mass): tot = 0 mass = (mass // 3) - 2 # o...
a4e9bc288eb9238db940a1348568bc7099ddf638
CamDavidsonPilon/Playground
/ChangeExtension.py
1,427
3.9375
4
import glob import sys import re import os def extender( old_extn, new_extn): """ This script changes files with file type old_extn to have a new file type new_extn. Note that a Unix is case-sensitive, eg ".JPG" != ".jpg", but on Windows it doesn't matter. """ p = re.search("""['"]{0,1}\....
a0017215ea657bcb89421a4dae698cc9626c501c
CamDavidsonPilon/Playground
/GeneticAlgorithm4SubwayLayouts/Symmetric_matrix_class.py
2,403
3.96875
4
class Symmetric_matrix(object): matrix=None size=None def __init__(self,size): def zero(m,n): # Create zero matrix new_matrix = [[0 for row in range(n)] for col in range(m)] return new_matrix self.matrix=zero(size,size) self.size=size ...
4c354f524913a8954ea67a5fc2fafe827d6a8c65
Ashi12218604/Python
/regexp/regexp_17.py
579
3.671875
4
/* Anchors Description Write a pattern that matches all the dictionary words that start with ‘A’ Positive matches (should match all of these): Avenger Acute Altruism Negative match (shouldn’t match any of these): Bribe 10 Zenith Execution Time Limit 10 seconds */ import re import ast, sys string = sys.std...
66f05d94a4b7343fca07115bd73a90a5af03dc10
Ashi12218604/Python
/regexp/regexp_19.py
569
3.890625
4
/* Anchors Description Write a regular expression that matches any string that starts with one or more ‘1’s, followed by three or more ‘0’s, followed by any number of ones (zero or more), followed by ‘0’s (from one to seven), and then ends with either two or three ‘1’s. Execution Time Limit 15 seconds */ import ...
733d0c4974a89ba93a79d043369b1622a5f4f95d
KCHoHo/lab4
/lab4-exercise4.py
968
3.921875
4
#!/usr/bin/env python3 import sqlite3 id = 1 type = ['door', 'temperature', 'door', 'motion', 'temperature'] zone = ['kitchen', 'kitchen', 'garage', 'garage', 'garage'] #connect to database file dbconnect = sqlite3.connect("exercise4db.db"); dbconnect.row_factory = sqlite3.Row; cursor = dbconnect.cursor(); #cursor.exec...
50bbc8f5dc6b2731ac88e3ce0b339bdbbb640d23
pzelnip/MiscPython
/operator_overloading/better_ex_using_mixins.py
1,881
3.875
4
''' Additionally Python supports operator overloading, and (in Python 3) if you define one of the "magic methods" you get it's converse defined as well (so for example, if you define __eq__, then you get a sensible __ne__ defined which uses it). Again, this is Python 3 only. Taking all these ideas further, you can c...
734576551c9163654f77af70d15629779ed7da88
pzelnip/MiscPython
/gotchas/emptylist_in_init.py
1,031
3.921875
4
''' A classic Python gotcha, the empty list to init problem ''' class Bad(object): def __init__(self, listIn=[]): ''' Very bad practice, the empty list is created once, and the same list reference will be assigned upon creation of each Bad instance ''' self.mylist = listIn...
04b4dcdfcf2a53d8dbd41d5cad4af5465d85cba1
pzelnip/MiscPython
/properties/proper_propex.py
1,454
3.78125
4
''' The propex.py example shows the somewhat more verbose way of defining properties, however, using decorator like syntax the overhead of writing properties can be reduced. This file is equivalent to the propex.py example but using decorators rather than explicit calls to property(). Created on 2012-02-01 @author:...
b189c4c522a5a2e9a7c9d86d889a30c9afe51f63
adityakumar2809/tkinter-swotting
/basics.py
846
3.71875
4
import tkinter def tkinterSetup(): root = tkinter.Tk() return root def createLabel(root, text): my_label = tkinter.Label( master=root, text=text ) return my_label def main(): running_status = { 'basic': False, 'grid': True } # BASIC if running_...
d4033d61c6730c67f3166edb76f4c399c4c7f0b1
sidhant-gupta-004/Python
/bob.py
276
3.78125
4
import os while 1 == 1: a = raw_input() if a != '': c = a[-1] if c == '?': print 'Sure.' elif c == '!': print 'Whoa, chill out!' else: print 'Whatever.' else: print 'Fine. Be that way!'
903ad69eec10d1f57c7eee025d170486a63d3a31
Quibrick/tic_tac_toe
/tic_tac_toe.py
3,770
3.953125
4
def main(): count_1gr = 0 count_2gr = 0 count_1st = 0 count_2st = 0 count_1diag = 0 count_2diag = 0 count_1diagdeut = 0 count_2diagdeut = 0 order = 0 round = 0 step = 0 board = [] p1 = input('Player 1 = ') p2 = input('Player 2 = ') for i in rang...
77c7d0b6d34a2ecef158567c9caf0e653610e0f3
BereniceAlexiaJocteur/SPOJ
/CANDY3.py
227
3.59375
4
n = int(input()) for i in range(n): nbkids = input() nbkids = int(input()) s = 0 for i in range(nbkids): s = (s + int(input())) % nbkids if s == 0: print("YES") else: print("NO")
9d1e272243443a7dd62865afbdf33bd9994eb99e
BereniceAlexiaJocteur/SPOJ
/PRIME1.py
1,176
3.9375
4
import math def potential_primes(): # Make a generator for 2, 3, 5, & thence all numbers coprime to 30 s = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29) for i in s: yield i s = (1,) + s[3:] j = 30 while True: for i in s: yield j + i j += 30 def range_sieve(lo, hi):...
aebfb9c81cbf13d2d623886f4a140c6d71e9a564
BereniceAlexiaJocteur/SPOJ
/NSTEPS.py
381
3.5
4
nb_items = int(input()) for i in range(nb_items): x, y = input().split(" ") x = int(x) y = int(y) if x == y: n = x//2 if 2*n == x: print(2*x) else: print(2*x-1) elif x-y == 2: n = y//2 if 2*n == y: print(x+y) else: ...
2a3c601e5fe2b1dfee7c081a87204d88f7a7dc0e
gafur-demirci/Python_Exercise
/kareAlan.py
147
3.59375
4
kenar = float(input("Karenin kenar uzunluğunu giriniz= ")) kareAlan = kenar**2 print(f"Kenar uzunluğu {kenar} olan karenin alanı = {kareAlan}")
56a6498d04a67147497674199ad354de21dde68e
debowin/algos.py
/Divide and Conquer/closest_point_pair.py
4,499
3.8125
4
""" To find closest pair of points amongst given set of points in a geometric plane. """ import math def read_input(filename): """ read input from file and return set of points. """ points = [] infile = open(filename, 'r') for line in infile.readlines(): coords = line.split(',') ...
cfa6398af53bb638834a2dea05febcd85b66b929
Dibbo-56/Python_Programming
/python code/inheritance 4.py
410
4.03125
4
class Parent: def __init__(self,var1,var2,s): self.var1 = var1 self.var2 = var2 print(s) class Child(Parent): def __init__(self,var3,s): super().__init__(4,5,s) # Equivalent --> super(Child, self).__init__(4,5,s) self.var3 = var3 obj_p = Parent(1,2,"Parent") obj_c = ...
dd60d5752ad350d37be2bda76b1343831f23202a
Dibbo-56/Python_Programming
/uva python solve/10924 - Prime Words.py
694
3.578125
4
prime = {1: 1} for i in range(2, 1050): isprime = True for j in range(2, int(i**0.5) + 1): if i % j == 0: isprime = False break if (isprime): prime.update({i: 1}) else: prime.update({i: 0}) while (True): try: str = input() ...
78f038431bd8fde00e8c53cc340657b154b4ab61
Dibbo-56/Python_Programming
/python code/built_in_extend.py
253
3.859375
4
class Contact(list): def __init__(self): print("List Created") class Test: C = Contact() def __init__(self,num): self.C.append(int(num)) obj1 = Test(1) obj2 = Test(2) obj3 = Test(3) for i in Test.C: print(i)
c3eaa5bc60a456ef2d8f40b5616fd11d02c4cbca
Dibbo-56/Python_Programming
/python code/inheritance 5.py
725
3.9375
4
class ContactList(list): def search(self, name): matching_contacts = [] for contact in self: if name in contact.name: matching_contacts.append(contact) return matching_contacts class Contact: all_contacts = ContactList() def __init__(self, name, email): ...
20b4b1e4590ec30986cd951656926c9777e9b35b
kingdayx/pythonTreehouse
/hello.py
1,232
4.21875
4
SERVICE_CHARGE = 2 TICKET_PRICE =10 tickets_remaining = 100 # create calculate_price function. It takes tickets and returns TICKET_PRICE * tickets def calculate_price(number_of_tickets): # add the service charge to our result return TICKET_PRICE * number_of_tickets + SERVICE_CHARGE while tickets_remaining: ...
b48b35647bc515f931d77bd85a776662cada2938
darshikasingh/tathastu_week_of_code
/day1/program3.py
180
3.921875
4
a = int(input("ENTER THE VALUE OF a: ")) b = int(input("ENTER THE VALUE OF b: ")) a = a+b b = a-b a = a-b print("AFTER SWAPPING") print("VALUE OF a =", a) print("VALUE OF b =", b)
6bb6ae0cb5373c6619deda59adfbf5a33263419e
darshikasingh/tathastu_week_of_code
/day 3/program3.py
271
4.34375
4
def duplicate(string): duplicateString = "" for x in string: if x not in duplicateString: duplicateString += x return duplicateString string = input("ENTER THE STRING") print("STRING AFTER REMOVING DUPLICATION IS", duplicate(string))
6a09c2092e636a991164ab3c0b635eaf4dd7cdb6
ricklixo/estudos
/DSA_Arquivos_Parte01.py
815
3.828125
4
# Abrindo o arquivo para leitura arq1 = open('arquivos/arquivo2.txt', 'r') # Lendo o arquivo print(arq1.read()) # Contar o número de caracteres print(arq1.tell()) # Retornar para o início do arquivo print(arq1.seek(0,0)) # Ler os primeiros 10 caracteres print(arq1.read(10)) # Abrindo arquivo para gravação# arq2 =...
6ef96375c12d962aef6b7472846de7f9bbf5b0d1
ricklixo/estudos
/DSA_Break.py
761
3.875
4
# Utilizando BREAK e PASS para interromper ou continuar o loop. counter = 0 while counter < 100: if counter == 4: break else: pass print(counter) counter += 1 # Utilizando continue para pular a letra H e dar prosseguimento a verificação for verificador in 'Python': if ve...
d8ef7293096c868efccf77244f6b29427ff02501
ricklixo/estudos
/DSA_ExerciciosCap02.py
2,380
4.0625
4
# Exercício 1 - Imprima na tela os números de 1 a 10. Use uma lista para armazenar os números. ex01 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print('Resposta01: ') for i in ex01: print(i) # Exercício 2 - Crie uma lista de 5 objetos e imprima na tela ex02 = ['Abacaxi', 'Maçã', 'Pera', 'Uva', 'Laranja'] print('Respo...
a73608c93aa696a37f326e75f93014cb7a823acf
happy-programming/coding-challenges
/src/linked_list_cycle_detection.py
1,237
3.953125
4
""" https://www.hackerrank.com/challenges/detect-whether-a-linked-list-contains-a-cycle/problem Detect a cycle in a linked list. Note that the head pointer may be 'None' if the list is empty. A Node is defined as: class Node(object): def __init__(self, data = None, next_node = None): self.dat...
8b0f9e1616c0bce68ba3a3b87b589baff817a0a3
mrniktarasov/2020-2-deep-python-N-Tarasov
/HW3/MedianFinder.py
546
3.609375
4
import heapq class MedianFinder: def __init__(self): self.nums = [] def add_num(self, num: int) -> None: self.nums.append(num) self.nums.sort() def find_median(self) -> float: l = len(self.nums) if l > 0: med1 = int((l - 1) / 2) if l % 2 =...
ae03b35e0011063715e476d27f22e6a34e493ff4
taesu-park/PycharmProjects
/Baekjoon/14891_톱니바퀴.py
795
3.625
4
def check_left(n,d): if n < 0: return if board[n][2] != board[n+1][6]: check_left(n-1, -d) rotate(n, -d) def check_right(n,d): if n > 3: return if board[n][6] != board[n-1][2]: check_right(n+1, -d) rotate(n, -d) def rotate(n,d): t = [0]*8 if d == ...
8cb118625ea5c5526a20159cae7cdee051289503
andrew-gallin/CS50
/pset6/sentiments/analyzer.py
1,359
3.53125
4
import nltk class Analyzer(): """Implements sentiment analysis.""" def __init__(self, positives, negatives): """Initialize Analyzer.""" self.positives = set() self.negatives = set() #self.tokenizer = nltk.tokenize.TweetTokenizer() pfile = open(positives, "r"...
9ee3689715eb1a9bf310be4addd02e1973edb162
syeomans/other-tools
/sudoku.py
6,884
4.53125
5
"""Solve a sudoku from a file and print the solved puzzle to the console Uses the Sherlock Holmes method of deduction: "Once you eliminate the impossible, whatever remains, no matter how improbable, must be the truth." This script keeps track of all possibilities for each cell on the board and by process of eliminatio...
f0192dad6ddc8b5b89b2efb20ec8cc881ac41c70
konstantinschulz/alpaca
/scoring/evaluator_url.py
392
3.546875
4
import re from parsing.webpage_data import WebpageData def evaluate_domain_ending(data: WebpageData) -> float: """Evaluates the webpage URL's domain ending. Returns 1 if the domain ending is .org, .edu or .gov, 0 otherwise.""" if re.search(r"\.gov[./]", data.url) or re.search(r"\.org[./]", data.url)...
bb62403136e8af65bfecf341f083bb6c1db0b2de
annalyha/iba
/For_unit.py
949
4.28125
4
#Реализуйте рекурсивную функцию нарезания прямоугольника с заданными пользователем сторонами a и b на квадраты # с наибольшей возможной на каждом этапе стороной. # Выведите длины ребер получаемых квадратов и кол-во полученных квадратов. a = int(input("Длина стороны a: ")) b = int(input("Ширина стороны b: ")) ...
b25f650cbded865e9f2583b92ba4bf783620e083
mathur15/PythonProjects
/GUI practice/GUI_practice.py
696
3.984375
4
from tkinter import * window = Tk() label = Label(window,text = "KG") e1_value = StringVar() e1 = Entry(window, textvariable = e1_value) e1.grid(row = 0,column = 1) def convert(): grams = float(e1_value.get()) *1000 pounds = float(e1_value.get()) * 2.25 ounces = float(e1_value.get()) * 35.274 t1.ins...
5582bba5df65bb72886831a42a0a2eafc1bc92c1
jordanopensource/data-science-bootcamp
/MachineLearning/Session1/regression.py
2,567
3.78125
4
#This is meant for an interactive Python shell #Tested on jupyter #Created by abulyomon@gmail.com for JOSA's Data Science Bootcamp #Load the data import pandas cars = pandas.read_csv("AlWaseet.csv") #Take a look cars.describe() ###LINEAR #Visualize import matplotlib.pyplot as plt plt.xlabel("Milage in KM") plt.ylabel...
cbdf8523b0e3b7fc25b4b5f5d055214e60d34e95
raikkon88/Private-Key-Modular-Crypto-System
/SanchezPifarreMarc/encode.py
1,180
3.59375
4
#!/usr/bin/python3 # Autor : Marc Sànchez Pifarré # Programa de codificació # IN : # - bookName -> Nom de fitxer a codificar # - encodedFile -> Nom de fitxer a on desar el text codificat # - password -> Paraula de pas o clau per a la codificació # OUT : # - A encodedFile hi ha el text de bookName xifrat amb la clau ...
a917ddf759c04868c68534f446ac65e1c7841c36
cbisaillon/natural_language_processing
/tests/bigrams.py
522
3.734375
4
from nltk.tokenize import word_tokenize from nltk import bigrams, trigrams text = "She reached her goal, exhausted. Even more chilling to her was that the euphoria that she thought she'd feel " \ "upon reaching it wasn't there. Something wasn't right. Was this the only feeling she'd have for over five " \ ...
8b7f6b084ebb0756c2a4ac24a779fa6aea105ec0
vrashi/python-coding-practice
/triangle.py
200
4.09375
4
#program to find the aea of a triangle base = int(input("enter the base of triangle")) height = int(input("enter the height of triangle")) print("area of the triangle is "+ str((1/2) * base * height))
b15f207ad94ebec1fd8365a66a54563c1589e958
vrashi/python-coding-practice
/upsidedowndigit.py
228
4.25
4
# to print the usside-down triangle of digits row = int(input("Enter number of rows")) a = row for i in range(row+1, 0, -1): for j in range(i+1, 2, -1): print(a, end = " ") a = a - 1 print() a = row
55395696241fbe5016661fbd1f4d191543fe84ce
vrashi/python-coding-practice
/sumofdigit.py
170
4.125
4
#program to find sum of all the digits of an integer n = int(input("enter a number")) s = 0 while n>0: remainder = n % 10 s = s + remainder n = n//10 print(s)
ab8e482de5397a00a951aa167491d2f3bc8b4275
vrashi/python-coding-practice
/startriangle.py
173
3.890625
4
#to print a triangle of astrics row = int(input("enter number of rows")) for i in range(row, 0, -1): for j in range(i, 0, -1): print("*", end = " ") print()
06d4be5592319a0f47e386a2773e5a2c05a6a1ed
uwseds-sp18/homework-3-ucalegon206
/homework3.py
591
3.671875
4
# File: homework3.py # Author: Andrew Smith # Date: 4/17/2018 import sqlite3 import pandas as pd import os.path def create_dataframe(db_path): if not os.path.exists(db_path): raise ValueError('path to database not found') conn = sqlite3.connect(db_path) lang = ['us', 'gb', 'fr', 'de', 'ca'] ...
43ec05874c2da644e9faef1f2c12b202469112ec
Wangtongzhi/python1
/dog.py
475
3.671875
4
class Dog(object): def __init__(self,name): self.name = name def game(self): print("蹦跳玩耍") class TianGou(Dog): def game(self): print("天上飞起来了啊") class Person(object): def __init__(self,name): self.name = name def playwithdog(self,dog): print("%s和%s一起玩耍" % (self...
57c374a543d0f190aedba09ae96f81cb7d67639b
jpleyvat/excercism
/python/high-scores/high_scores.py
331
3.546875
4
def latest(scores): return scores[-1] def personal_best(scores): return max(scores) def personal_top_three(scores): three_highest = [] for i in range(3): try: three_highest.append(scores.pop(scores.index(max(scores)))) except ValueError: break return thr...
a302b262c53864f16087bbf56314ec6c0f95fcca
techscientist/django-genericimports
/example_project/genericimports/exceptions.py
1,140
3.921875
4
# -*- coding: utf-8 -*- class RowDataMalformed(Exception): """ This exception should be trown if the data that is supposed to get into the database has failed for not being the correct data. Example: Input expects string but gets integer instead. """ def __init__(self, value): ...
3e40ff33bb45ba2a2545b824df7e196e9007129b
jorgerf05/Pokedex_Py
/Pokedex.py
2,682
3.609375
4
import sqlite3, os import pandas as pd directory = os.path.dirname(__file__) #Obtiene la ruta donde se encuentra el archivo .py y lo guarda como string en directory os.chdir(directory) #cd hacia el directorio donde está el archivo .py conexion = sqlite3.connect("pokedex.sqlite")#abrimos conexión con la base de datos (...
b0c136c41a7f80d1498eb7428821e8568c5921f1
mgitgrullon/algorithms-in-py
/phone_number/phone.py
182
3.53125
4
def create_phone_number(n): string = '' for val in n: string += str(val) # '1234' result = "(" + string[:3] + ") " + string[3:6] + "-" + string[6:10] return result
c5c6d88b79760d9e3911fb2fe93a27953f9d38ea
cblair28/389Rfall18
/week/2/writeup/stub.py
4,063
3.609375
4
""" If you know the IP address of the Briong server and you know the port number of the service you are trying to connect to, you can use nc or telnet in your Linux terminal to interface with the server. To do so, run: $ nc <ip address here> <port here> In the above the example, the $-sign...
394e5870361f046e78b91c28e4a0b9584e2cb158
os-utep-master/python-intro-Jroman5
/wordCount.py
1,513
4.125
4
import sys import string import re import os textInput ="" textOutput ="" def fileFinder(): global textInput global textOutput if len(sys.argv) is not 3: print("Correct usage: wordCount.py <input text file> <output file>") exit() textInput = sys.argv[1] textOutput = sys.argv[2] if not os.path.exists(textInp...
9b3dd9b236a3cd882173bb897751a0aba2cef978
andrestamayo/2017sum_era1_kol3
/test_veli_matrix.py
3,391
3.515625
4
import unittest from matrix import Matrix class MyTest1(unittest.TestCase): """docstring for MyTest1.""" def setUp(self): self.l= [[1,2],[3,4]] self.m = Matrix(self.l) self.m2=Matrix([1,2],[3,4]) def test_init(self): #it only create the matrix in a propper way when you provide the ...
0008d5d1d0598ec37b494351fe76f7d0fd49011b
AdityanBaskaran/AdityanInterviewSolutions
/Python scripts/evenumbers.py
371
4.125
4
listlength = int(input('Enter the length of the list ... ')) numlist = [] for x in range(listlength): number = int(input('Please enter a number: ')) numlist.append(number) numlist.sort() def is_even_num(l): enum = [] for n in l: if n % 2 == 0: enum.append(n) return enum print (...
80e989ba4625e9063c11f83040e79e5cb532332e
aayushborkar14/python_notes
/pig_latin.py
218
3.734375
4
def pig_latin(word): first_letter = word[0] if first_letter in "aeiou": word += 'ay' else: word = word[1:] + first_letter + 'ay' return word new_word = pig_latin('ello') print(new_word)
42b8157b721a7b583c3661b4b1d31b2d48860d1d
aayushborkar14/python_notes
/error_handling.py
581
3.921875
4
try: f = open('testfile.txt', mode='r') f.write("Hello World!") except TypeError: print("Hey, you have a type error") except OSError: print("Hey, you have an OS error") finally: print("I always run") print("Will this get executed") def ask_for_int(): while True: try: resul...
bffda11eab99c3a84bf92c339c53b30a722207d0
aayushborkar14/python_notes
/magic_dunder.py
494
3.78125
4
class Book: def __init__(self, title, author, pages): self.title = title self.author = author self.pages = pages def __str__(self): return f"{self.title} by {self.author}" def __len__(self): return self.pages def __del__(self): print(f"{self.t...
0e357f53012ebf8e42121bab5136cabd13bb3788
A00431429/MCDA2
/Data mining/pawannotes/dev.cs.smu.ca/~pawan/5580/notes/python/workshop 2_code/pandas_sample.py
1,120
4.09375
4
import pandas as pd # %% read file into a df t = pd.DataFrame.from_csv("data/titles.csv", index_col=None) # %% print sample head and tail print(t.head()) print(t.tail()) # %% How many movies are listed in the titles dataframe? print(len(t)) # %% What are the earliest two films listed in the titles dat...
1e13540d768268e056f65e034b234a7c1d68bfc4
FilipCernatic/TestRep
/calc2.py
406
4.09375
4
#This chunk of code computes the sine function up to an arbitrary accuracy def factorial(n): if n==0: return 1 else: return n*factorial(n-1) def sin(x,n): result = 0 for k in range(1,n+1): result += ((-1)**(k-1))*(x**(2*k-1))/(factorial(2*k-1)) return result print("sin(x), Taylor series expansion.") x = f...
de7a1d2a721aa4842942ec44d5d01f067e601dc4
Jocapear/TC1014
/WSQ06.py
559
3.9375
4
import random counter = int(1) number = random.randint(1,100) print("Try to find the number i´m thinking. It´s between 1 and 100") innum = int(input("Give me your number")) while innum != number: counter = counter + 1 if(innum > number): print(innum," is HIGHER than my number") innum = int(input...
e9741e14864c9005a628a75da45532e32d4c3697
Jocapear/TC1014
/WSQ05.py
224
4.125
4
f = float(input("Give me your temperature in F°")) c = float(5 * (f - 32)/9) print(f,"F° is equivalent to ",c,"C°.") if(c>99): print("Water will boil at ",c,"C°.") else: print("Water will NOT boil at ",c,"C°.")