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
df5ab36d6ec8b87e0ddef2b5b1b9f29f1f98a986
manusoler/code-challenges
/sololearn/easy.py
9,112
3.859375
4
import re import math from functools import reduce from utils.decorators import challenge # Challenges @challenge(name="Popsicles", level="Easy", desc=""" Given the number of siblings that you are giving pospsicles to, determine if you can give them each an even amount or if you shouldn't ...
74b4f4975aff361161aaa469e959a1652b22a77d
manusoler/code-challenges
/projecteuler/pe_9_special_pythagorean_triplet.py
723
4.3125
4
import functools from math import sqrt from utils.decorators import timer """ A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a**2+b**2=c**2 a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product ab...
f395a28cb6571f49f0405346b041bb5133d882a1
kanybek740/Chapter1_Part2_Task25
/task25.py
238
3.65625
4
stroka = 'python lang is the most powerfull and lkjlkjlkjsd' liststroka = stroka.split() longest = 0 for i in range(1, len(liststroka)): if len(liststroka[longest]) < len(liststroka[i]): longest = i print(liststroka[longest])
8808b0b38036174a6861737895e6bb29a255e9d5
piupiu094/Python
/Задание 1.5.py
287
3.5625
4
with open('test3.txt', 'r', ttt='utf-8') as f: empl = {line.split()[0]: float(line.split()[1]) for line in f} print(f'Average salary = {round(sum(empl.values()) / len(empl), 3)}\n' f'Employees with salary less than 20k {[e[0] for e in empl.items() if e[1] < 20000]}')
c4993c05f305b3e304fd61a2e2037bddaf663214
piupiu094/Python
/ДЗ2/Задание 5.2.py
236
3.765625
4
my_list = [7, 5, 3, 3, 2] N = int(input('Введите новый элемент в виде натурального числа - ')) i = 0 for n in my_list: if N <= n: i += 1 my_list.insert(i, float(N)) print(my_list)
de7f31e247b295ed2c973f9d65cb9b0198bcce2c
mmpatterson/python-challenge
/PyBank/main.py
2,264
3.765625
4
import os import csv # Establish file path for test file csvpath = os.path.join('..', 'PyBank', 'budget_data.csv') # Establish file path for output file output_path = os.path.join("..", "PyBank","budget_output.csv") with open(csvpath) as csvfile: csvreader = csv.reader(csvfile, delimiter = ',') with open(outpu...
ab110fc6c142c9981d0e034eba28dbae82a5afa6
dersenok/python3_Les2
/venv/HomeworkLes2/Les_2_HW_8.py
717
4.125
4
# 8. Посчитать, сколько раз встречается определенная цифра в # # # введенной последовательности чисел. Количество вводимых # # # чисел и цифра, которую необходимо посчитать, # # # задаются вводом с клавиатуры. n = int(input("Сколько будет чисел? ")) d = int(input("Какую цифру считать? ")) count = 0 for i in range(1, ...
43e69ee4abc4f87cd1f58604d5e33e82810c3430
luqiaoyu/leetcode
/python/lc9.py
844
3.671875
4
# 9. Palindrome Number # Revert half of the number # aware of overflow # 300ms 59.73% class Solution: def isPalindrome(self, x): """ :type x: int :rtype: bool """ if (x < 0 or (x % 10 == 0 and x != 0)): return False rev = 0 while (x > rev): ...
2ce428036b4aac8c923508102c0229531a620c76
luqiaoyu/leetcode
/python/lc49.py
1,606
3.515625
4
# 49. Group Anagrams import collections # Categorize by sorted string # setdefault # 用''' '''里的OK: 124ms class Solution: def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ result = [] d = {} for x in strs: d.setd...
ed7ee8fb624defcaff4f7c8488a11ea17d8603a3
luqiaoyu/leetcode
/python/lc56.py
1,383
3.796875
4
# 56. Merge Intervals # Definition for an interval. class Interval: def __init__(self, s=0, e=0): self.start = s self.end = e # 80ms 33.12% # O(nlogn) class Solution: def merge(self, intervals): """ :type intervals: List[Interval] :rtype: List[Interval] """ ...
cae8bb77c6063b2cfc60689217497631a4914484
vivek111/Pywork
/strformat.py
163
3.640625
4
import random x=random.randint(0,1) s="{who} turned {age} this year" if x==0: s=s.format(who="She",age=50) else: s=s.format(who="he",age=40) print(s)
c9b54eb41e627d60df2d7c0d5e907eb1a8413dbd
vivek111/Pywork
/pwencrpt.py
1,295
3.734375
4
#list= [('a','m'), ('b','o'), ('c','q'), ('d','s'), ('e','u'), ('f','w'), ('g','y')] print("a,b,c,d,e,f,g") pasword=input("Enter the password using above alphabets\n") temp=pasword pwlist=[] encrpt=tuple() x=0 while x<len(temp): if temp[x]=='a': encrpt=(temp[x],'m') elif temp[x]=='b': encrpt=(t...
ff191b9bb4b1244f2698fbe1ef28ae46ff21bef3
vivek111/Pywork
/Assignment-5.py
1,409
3.921875
4
import collections mark=collections.namedtuple("mark","m1 m2 m3 m4 m5 perc") print(" Students Records ") x=input("Enter the no of students\n") x=int(x) temp=tuple() record=[] k=0 for k in range(0,x): print("Student",k+1,"\n") name=input("Enter the name...
b9bc7f83da64079d8b2fbe95c52aac48b5a5e9da
arnoldkoua/program_affich_100premiers
/program_affich_100premiers.py
805
3.640625
4
# Creer deux programme avec la boucle for et la boucle while qui affiche les 100 premiers nombres entiers premiers. # Avec la boucle for : #Lire la saisie de l'utilisateur min = int(input("Entrez le min : ")) max = int(input("Entrez le max : ")) for n in range(min,max + 1): if n > 1: for i in range(2,n)...
e8a642d9d30bb869e4511ed01c10cdddeb5388f0
jesselakeallen/python
/lessons6-10/median.py
480
4
4
def bigger(a,b): if a > b: return a else: return b def biggest(a,b,c): return bigger(a,bigger(b,c)) def median(a,b,c): if biggest(a,b,c) == a: return bigger(b,c) if biggest(a,b,c) == b: return bigger(a,c) else: return bigger(a,b) # example def median2(a,b,c): big = bigg...
6007705e4bb47f3cc2b0f4d3fab7c3c61a8ff5e8
jesselakeallen/python
/lessons1-5/break.py
152
3.6875
4
while countdown >= 0: if False: break print countdown countdown = countdown - 1 while countdown >= 0: print countdown countdown = countdown - 1
10bebdf74dd9b9d43b4c123ae3731eac9d5bd483
ajackal/python_tutorials
/Lesson 4/for_loops_list.py
65
3.671875
4
items = [1, 3, 5, 2, 7, 9] for item in items: print item + 5
15fb239543cde47e2170b43a449994faebd66e46
LiliRassh/Python-examples
/DZ_0507_sale.py
4,308
3.609375
4
''' 1 ВАРИАНТ Напишем пять функций, которые рассчитывают для каждого покупателя необходимый параметр. На вход функции получают словарь из ключей - имена покупателей, и значений — списки с суммами. Все функции возвращают словарь по всем покупателям и соответствуещее значение одного из ...
a74a6a536400bdfa19d34838a5e6673331fb6447
rustyworks/one-problem-a-day
/day-4/string_manipulation.py
542
4.09375
4
class StringManipulation: def swapcase(self, s: str) -> str: if not s: return s else: return self.swapchar(s[0]) + self.swapcase(s[1:]) def swapchar(self, s: str) -> str: if s in 'abcdefghijklmnopqrstuvwxyz': return s.upper() else: ...
5f3f6a69e1a0dc39988958e8c86721fcf40bc1ce
giubrocchi/EstudosPython
/retangulo.py
371
3.96875
4
l = int(input("digite a largura: ")) a = int(input("digite a altura: ")) j = a while(j > 0): i = l if(j == a or j == 1): while(i > 0): print("#", end = "") i = i-1 else: print("#", end = "") while(i > 2): print(" ", end = "") i = i-1 ...
ee8cb66c37d3da5fbca09c7d8ac0d2d7ea3d9692
yangyohan123/python
/pythontest/0110/tupleex1.py
621
3.859375
4
''' Created on 2020. 1. 10. @author: GDJ-19 변경불가 리스트 ''' tp1 = (10,20,30) print(tp1) #tp1.append(10) print(tp1[0],tp1[1],tp1[2]) #tp1[0] = 100 list = list(tp1) # 튜플을 리스트로 변환 print(list) list.append(40) tp1 = tuple(list) # 리스트를 튜플로 변환 print(tp1) # 튜플과 리스트는 같음을 알 수 있다 print("tp1의 크기",len(tp1),"list의 크기...
37e60c98dee25d390a52c5c803999aaa63c4d56d
yangyohan123/python
/pythontest/0110/exam1.py
580
3.8125
4
''' Created on 2020. 1. 10. @author: GDJ-19 리스트문제: aa,bb 매열을 생성하고, aa 배열은 0부터 짝수 100개를 저장하고 bb 배열은 aa 배열의 역순으로 값을 저장하기. aa[0] ~ aa[9], bb[99] ~ bb[90] 값을 출력하기 ''' #0,0 1,2 2,4 3,6 aa = [] bb = [] value = 0 for i in range(0,100) : aa.append(value) aa[i] = i*2 bb.append(aa[i]) bb.reve...
76dc06ec73796e9d7acbf27115681a4ad12cf2f6
yangyohan123/python
/pythontest/0115/classex1.py
908
3.59375
4
''' Created on 2020. 1. 15. @author: GDJ-19 클래스예제 ''' # 기본 생성자 : __init__(self) : 구현된 생성자가 없는 경우 # 시스템이 제공하는 생성자 class Car : color = "" speed = 0 def __init__(self,v1,v2): # 생성자 self.color = v1 self.speed = v2 def upSpeed(self, value)...
d3c3a3cf50793588756306288b30433842460b60
littlejoe1216/Chapter-6-Exercies
/Python Chapter 6 Exercises/Chp 6 Excercise 4.py
596
4.21875
4
#Exercise 4: #There is a string method called count that is similar to the function in the previous exercise. #Read the documentation of this method at https://docs.python.org/3.5/library/stdtypes.html#string-methods #and write an invocation that counts the number of times the letter a occurs in "banana". word ...
f60e0ced7baecd77b7d7ec08a4753ee3b7932454
JuanCarlosLeonel/Controle_horasCostura
/horasfinalizacao2.py
2,251
3.921875
4
## INTERFACE GRÁFICA EM ANDAMENTO from tkinter import * class Calculadora(object): def __init__(self, instancia): # Colocar entrada de texto self.form = Entry(instancia) self.form.pack() # botão calcular self.calc = Button(instancia, text="Calcule", fg = 'blue', c...
c1ec4c07524fa85bec6086a4b8da2c928ec568a1
eddycheong/adventofcode2017
/adventofcode/inverse_captcha.py
343
3.625
4
def inverse_captcha(digits, step): sum = 0 length = len(digits) for i in range(length): sum += int(digits[i]) if digits[i] == digits[(i + step) % length] else 0 return sum def inverse_captcha_next(digits): return inverse_captcha(digits, 1) def inverse_captcha_halfway(digits): return inverse_captcha(...
e3ddbeb215a0d6419b2ae83f2a0933ffc6fcb459
mmengote/CentralParkZoo
/sketch_181013b/sketch_181013b.pyde
971
4.34375
4
#this library converts the random into integers from random import randint #lists of animals included in the simulation #divided into two types, the zoo animals will have a starting state position of zoolocation. #local animals will have a starting position of something else. zoo_animals = ["Penguins", "Zebra...
9839b07dd172c50688dd81a0665e1b0a5cba7f6c
pepperchini/curly-funicular
/test.py
136
3.53125
4
young = True famous = False if young and famous: print('You must be rich!') else: print('There is always the lottery...')
d99ab83f5163077a079bbf145c8eef4b01a3c3a3
mcjo163/momo-is-you
/game/entities.py
1,017
3.578125
4
from enum import Enum, auto # Abstract class encompassing all entities which can be in a level's board class Entities: pass class Objects(Entities, Enum): MOMO = auto() WALL = auto() ROCK = auto() FLAG = auto() WATER = auto() # Abstract class encompassing all text elements class Text(Entit...
c9efbd7958f58d6be21252c2a8fe2a2f432794bb
Helberte-AC/aula-python
/untitled/Aula 4.py
1,473
3.765625
4
#print('Aula 4') # Comando for n° primo. # a = int(input('Entre com o n°: ')) # div = 0 # for x in range(1, a+1): # resto = a % x # print(x, resto) # if resto == 0: # div += 1 # if div == 2: # print('n° {} é primo' .format(a)) # else: # // print('n° {} é primo'.format(a))// # a = int(input('...
3c6f13fde41a232f06ca149725f122a1609d28cf
Jovian2000/raad-eens
/raad-eens.py
1,226
3.6875
4
import random print("Raad het getal tussen 1 en 1000") guess = -1 ronde = 1 point = 0 while ronde <= 20: print("Ronde " + str(ronde)) number = random.randint(1,1000) kans = 1 while number != guess: guess = int(input(str(kans) + ": ")) if guess < number: pri...
3e1d3fc02a334a46824b77e7699643db0e4c5564
GinnyJourney/Getting-started-with-python
/Question1.py
541
3.921875
4
def cal_sqrt(n,lastGuess): """ Calculates square root of n. Args: n: a radicand lastGuess: an initial integer necessary to start the calculate Returns: nextGuess: the square root of the radicand, n """ nextGuess = (lastGuess + (n / lastGuess)) / 2 while (n...
207ba3d95f19ba43665806fba963b9e4db9c0ebe
Manoj-Paramsetti/Brutter-2
/main.py
7,399
3.84375
4
try: def caller(): user = input("=>") user = user.lower() while(user != "exit"): if (user == "generate"): getter() elif (user == "help"): helper() elif (user == "about"): storyTeller() user = inpu...
4f03b52ca0f1f596bfe78b065f44ee8eb0f3b10c
markcharyk/data-structures
/tests/insert_sort_tests.py
1,085
4.125
4
import unittest from data_structures.insert_sort import insertion_sort class TestInsertSort(unittest.TestCase): def setUp(self): """Set up some lists to be sorted""" self.empty = [] self.single = [5] self.sorted = [1, 2, 3, 10] self.unsorted = [8, 1, 94, 43, 33] def te...
c8d43eb54cf07c1a7ab7c6d9ef43714142fff473
markcharyk/data-structures
/tests/heap_tests.py
6,402
3.65625
4
import unittest from data_structures.heap import Heap, Node class TestInsert(unittest.TestCase): def setUp(self): self.h = Heap() def test_empty(self): self.h.insert(5, 'Five') self.assertEqual(self.h.heap[0].val, 'Five') def test_left(self): self.h.insert(5, 'Five') ...
d049b6ebf2b5b66d8462f5ef0f3aada36c43db12
markcharyk/data-structures
/data_structures/make_month.py
496
3.8125
4
import calendar def make_month(year, month): return Month(year, month) class Month(object): def __init__(self, year, month): self.template = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'] weekday, self.last = calendar.monthrange(year, month) self.template = self.template[weekday - 1::] +...
9689a252589118db6d6623abb196aff8c3efa9ab
vielma24/playground
/bank.py
1,337
4.40625
4
#!/usr/bin/python '''Program will intake customer information and account information. Account management will also be added.''' from datetime import date #******************************************************************************* class person: """ Returns a ```Person``` object with the given name, DO...
65c7d244300b0ce24c1b3cfc875ced71278672f4
UWO-Aero-Design/Drop-Algorithm
/Neural Network Demo/my_math.py
1,657
3.5
4
from cmath import * def calc_angle_diff_between(a,b): a_phase = phase(complex(a[0],a[1])) b_phase = phase(complex(b[0],b[1])) return (b_phase-a_phase) * 180 / pi def dot(a,b): if min(len(a),len(b)) == 2: return a(0)*b(0) + a(1)*b(1) elif len(a) == len(b) == 3: retur...
9d625b9f273e27a48db58a2694b0b8e1eb537063
dolapobj/interviews
/Data Structures/Array/MaximumProductSubarray.py
1,155
4.3125
4
#Maximum Product Subarray #LC 152 """ Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product. Example 1: Input: [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6. Example 2: Input: [-2,0,-1] Output: 0 Explanation: The ...
ee3e31dee80c431cbd45326f38c619582f284151
dolapobj/interviews
/Data Structures/LinkedList/findIntersection.py
971
3.8125
4
#Find Intersection of Two Linked Linked Lists #LC 160 """ Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5] Output: Reference of the node with value = 8 """ #Find which list longer, and skip forward in the longer list such that #both lists are the same length. #then move together at once, and when b...
a6b5aa3fd686babed3e12c79f9d6b914f90c0168
dolapobj/interviews
/Data Structures/Trees/KthSmallest.py
987
3.859375
4
#Kth Smallest Element in BST #LC 230 """ Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Example 1: Input: root = [3,1,4,null,2], k = 1 3 / \ 1 4 \ 2 Output: 1 Example 2: Input: root = [5,3,6,2,4,null,null,1], k = 3 5 / \ 3 6 / ...
0bdac984c6c2f440f282ae657bcb6552273a992a
dolapobj/interviews
/Data Structures/Trees/LowestCommonAncestor.py
956
3.734375
4
#Lowest Common Ancestor of BST #LC 235 """ Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendan...
034a3d9edff5afec5ccd4be357227e8f26b43b4e
kvschaik/test
/Week 2/fruit.py
298
4.09375
4
words = ["Orange", "Apple", "Banana", "Watermelon", "Peach"] index = 0 fruit = input("What is your favorite fruit? ").title() for word in words: if fruit in words: print("I don't like " + fruit + " I prefer blueberries" ) break else: print("Nice! I like " + fruit + " too!" ) break
57566e7e8cf555b3a1a7a59041cbc333258db580
lucky-promethean/parallel-resistors
/parallel-r.py
180
3.96875
4
#! /usr/bin/python def para(r1, r2): return(r1*r2/r1+r2) print("enter parallel resistances") r1=float(input("r1: ")) r2=float(input("r2: ")) print ("Req= ",r1*r2/(r1+r2))
50a5ba1c70f2b9e89973a27568fc7e63611831d9
namoavighna20/Python-Projects
/Beginner Level/Fibbonaci_series.py
185
3.875
4
s=int(input("Enter the number:")) a=0 b=1 if s<0: print("Invalid output") elif s==0: b=a else: for x in range(2,s+1): c=a+b a=b b=c print(b)
1ba60a1c73d9aeef5a4dfa192577aa58d6b16528
Damon0626/Leetcode-
/025-Reverse Nodes in k-Group.py
1,117
3.6875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseKGroup(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ new_head...
cc8b3d933d04d932dfc7a080652c4c323cc079e3
Damon0626/Leetcode-
/098-Validate Binary Search Tree.py
795
3.921875
4
# -*-coding:utf-8-*- # @Author: Damon0626 # @Time : 19-2-25 下午10:39 # @Email : wwymsn@163.com # @Software: PyCharm ''' 检验一棵树,是否是二叉搜索树 条件: 左子树上所有结点的值均小于它的根节点的值 右子树上所有结点的值均大于它的根结点的值 左、右子树也分别为二叉排序树 ''' # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None sel...
cfc8ea1a3f166345f5907903e66fad7a7d58b33e
Damon0626/Leetcode-
/021-Merge Two Sorted Lists.py
793
3.9375
4
# -*-coding:utf-8-*- # @Author: Damon0626 # @Time : 19-2-21 下午8:50 # @Email : wwymsn@163.com # @Software: PyCharm # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def mergeTwoLists(self, l1, l2): """ :type l1: ListNo...
649eaf326c57b178e4e8723b566aa8290237f4bd
Damon0626/Leetcode-
/101-Symmetric Tree.py
688
3.96875
4
# -*-coding:utf-8-*- # @Author: Damon0626 # @Time : 19-2-28 下午10:14 # @Email : wwymsn@163.com # @Software: PyCharm # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isSymmetric(self, root: TreeNode) -> bool: if n...
0adc12330ef3d90fe3b7e109dbb26fb1e234c59f
Damon0626/Leetcode-
/111-Minimum Depth of Binary Tree.py
645
3.703125
4
# -*-coding:utf-8-*- # @Author: Damon0626 # @Time : 19-2-27 下午10:27 # @Email : wwymsn@163.com # @Software: PyCharm # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # 注意当结点只有一个左叶节点或右结点,此时父结点的最小深度不是0,而是2 class Solution: def ...
2ed4879f5b51eae964b2767cb80c20e2db8c63e0
Damon0626/Leetcode-
/024-Swap Nodes in Pairs.py
995
3.8125
4
# -*-coding:utf-8-*- # @Author: Damon0626 # @Time : 19-2-14 下午7:20 # @Email : wwymsn@163.com # @Software: PyCharm # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution(object): def swapPairs(self, head): # pre->a->b->b.next ==> pre->b->a->b...
318079c2f7cc70cefe8da29f0835164416a49b45
Damon0626/Leetcode-
/190-Reverse Bits.py
1,097
3.984375
4
# -*-coding:utf-8-*- # @Author: Damon0626 # @Time : 19-4-2 下午8:24 # @Email : wwymsn@163.com # @Software: PyCharm ''' everse bits of a given 32 bits unsigned integer. Example 1: Input: 00000010100101000001111010011100 Output: 00111001011110000010100101000000 Explanation: The input binary string 0000001010010100000...
4d17776eb2dd0857e8b30a7267d9cd943f819365
mehdirezaie/f2py
/ex2/hw_python.py
330
3.5
4
#!/usr/bin/python """ Pure Python module to do matrix multiplication (c) Mehdi Rezaie """ import math, sys,numpy def mul(x,y): t = numpy.shape(x) z = numpy.zeros((t[0],t[0])) for i in range(t[0]): for j in range(t[0]): for k in range(t[0]): z[i][j] += x[i][k]*y[k][...
900553822503cfcfa99fc38a5534f3359fd5dfbf
sywh/algorithms
/Searching/BST.py
5,701
3.609375
4
class Node: def __init__(self, key, val, N) -> None: self.key = key self.val = val self.left = None self.right = None self.N = N class BST: def __init__(self) -> None: self.root = None def put(self, key, val): self.root = self._put(self.root, key, v...
fcb86f34a96eb9a6d333b5f60cce62ad96d70843
mashanwhut/ms1911_new
/day3_multiprocess/ex2_multi_Process.py
2,214
3.75
4
''' 创建多进程multiprocessing.Process ''' ''' 练习1: ''' from multiprocessing import Process import time,os def fun1(): time.sleep(2) print('吃饭') print(os.getppid(),'----------',os.getpid()) def fun2(): time.sleep(3) print('睡觉') print(os.getppid(),'----------',os.getpid()) def fun3(): time.sleep...
dc6b9826a35a20945e8e9afaab58f1c2a22ee70d
tonetheman/pymem_201704
/ct_3.py
426
3.5
4
from contextlib import closing # If you have something (aka any class that can close) # use a built in or make your own class SomeCoolClass: def __init__(self): print "constructor on SomeCoolClass called" def close(self): print "cool class close got called" sc = SomeCoolClass() with closing(sc): print "doin...
d2f2d5017786bd9d35bada4775da7cb732035310
tonetheman/pymem_201704
/start_4.py
267
3.890625
4
# object oriented turtle # crummy example :( # skip this example import turtle wn = turtle.Screen() bob = turtle.Turtle() bob.forward(30) # point here is that loop might not be the best way to do this :() # THIS DOES NOT WORK IN DEFAULT OSX 2.7 wn.mainloop()
97d136bf4b3b2c729241746afe18572fe88e51b2
juliusedqvist/encryption
/texttonumber.py
933
3.890625
4
from encrypt import encrypt, clearMes letters = [" ","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] def findlet(n): """ Translate nums to letters """ for i in letters: if letters[n] == i: return i def findnum(a): """Finds...
a4c49a300be5cee52750b9185df2b1987816bcf3
DennySim/shop_list
/shop_list.py
4,510
3.671875
4
# Первый вариант # def create_menu_dict(): # with open('recipes_list.txt') as dishes: # cook_book = {} # for dish in dishes: # dish = dish.strip().lower() # ing_quantity = int(dishes.readline().strip()) # for i in range(ing_quantity): # ing...
7f4717d951ad45f24a9473caa931f97607713151
sndp2510/PythonSelenium
/basic/_09StringLiteral.py
160
4.125
4
st="Hello" print(st) str1="Bye" print(str1) print ("Add Operator with String") str3 = st + str1 print ("Multiply Operator with String") print(str3*5) print()
cbaef4e5507c55a2ea3e1c42ecea0f0fa081999c
sndp2510/PythonSelenium
/basic/_08primeNumTable.py
463
3.75
4
flag=False sRange = 3 eRange = 10 #Find Whether Number is prime or Not for i in range(sRange,eRange): for j in range(2,i): if(i%j ==0): flag=True break if(flag==True): pass else: print(">>>",i) for k in range(1,11): print ("%d" %i, e...
4076f61a183fac23c05fbf162dde7289caff5a74
sndp2510/PythonSelenium
/basic/_04Geometry.py
432
4.28125
4
sideCount=int(input("Enter Number of side: ")) if(sideCount==1): print("Its square") side=int(input("Enter length of side : ")) print("Area of the square is : " , (side*side)) elif(sideCount==2): print("Its Rectangle") length = int(input("Enter length of side : ")) breadth =int(input("Enter len...
b62c813c3342205a55163450478f44d4eb660498
MaximusWudy/ProcessAutomation
/PythonSelenium/PythonBasics/ExceptionsPython.py
950
3.8125
4
ItemsInCart = 0 # 2 items will be added to cart # 1st way: Use 'rise Exception' keywords if ItemsInCart != 2: # raise Exception("Products Cart count not matching") pass # 2nd way: use assert(), condition must be True # assert(ItemsInCart == 2) # will return AssertionError # Try.. Catch...: when ex...
d60ccaf31fe2c293d566effaf936c5c17e6064e3
ksu-is/Commute-Traffic-Twitter-Bot
/Practice/user_funct.py
1,027
4.28125
4
## will create text file for new users with info on each line. (not able to do OOP yet reliably so this is the best I've got) # do you have an account? user_ask = input("Before we start, lets specify what user this is for\nHave you used this program before?\nType 'y' or 'n' only: ") if user_ask.lower() == "n": ...
a00c92fbecdd0889098cd95618c88db4563d4c48
jeraas/SolydPython
/Solyd/Python/Exs/ex03.py
260
3.953125
4
from random import randint convidados = [] for convidado in range(1, randint(2, (5 + 1))): nome = str(input('Digite o nome do convidado: ')) convidados.append(nome) print('\n') print('\n') print('Convidados: ') for nome in convidados: print(nome)
8797bd98260d7de3345c66b110c4c3a685c4f58e
jrluecke95/python-mapping
/friend_counter.py
526
3.765625
4
ramit = { 'name': 'Ramit', 'email': 'ramit@gmail.com', 'interests': ['movies', 'tennis'], 'friends': [ { 'name': 'Jasmine', 'email': 'jasmine@yahoo.com', 'interests': ['photography', 'tennis'] }, { 'name': 'Jan', 'email': 'jan@hotmail.com', 'interests': ['movies',...
7ab55bfd2bf7a9b80579dd06b5de8c8b36912ae1
keerthu1604/Python-my-captain
/Assignment 2.py
3,730
4.34375
4
# Tic-Tac-Toe Program using # random number in Python # importing all necessary libraries import numpy as np import random from time import sleep # Creates an empty board def create_board(): return(np.array([[0, 0, 0], [0, 0, 0], [0, 0, 0]])) # ...
baf963edd78aa2912552ec31d663c9cc33045f87
monroy8888/MINTIC
/reto-semanal/reto2.py
5,867
3.796875
4
def cambiar_contraseña(): print("cambiando contraseña".center(30,"*")) def Ingresar_coordenadas_actuales(): print("Ingresar coordenadas actuales".center(30,"*")) def Ubicar_zona_wifi_cercana(): print("Ubicar zona wifi más cercana".center(30,"*")) def Guardar_archivo_ubicacion_cercana(): print("Guardar...
1e3cc57af263476e1346cccf480a6ed62e7c891d
jenshurley/python-practice
/python_early_examples.py
1,836
4.125
4
# Initial variable to track game play user_play = "y" # While we are still playing... while user_play == "y": # Ask the user how many numbers to loop through user_number = input("How many numbers? ") # Loop through the numbers. (Be sure to cast the string into an integer.) for x in range(int(user_num...
0be835d18fae63f8b63fbae296f65250f8b38ac4
koaning/scikit-fairness
/skfair/common.py
1,752
4.4375
4
import collections def as_list(val): """ Helper function, always returns a list of the input value. :param val: the input value. :returns: the input value as a list. :Example: >>> as_list('test') ['test'] >>> as_list(['test1', 'test2']) ['test1', 'test2'] """ treat_sing...
0c7c59663b56d782b93278e552b9b6981884116d
KKshitiz/Corona-Scraper
/scraper.py
1,898
3.578125
4
from requests import get from bs4 import BeautifulSoup import csv #url from which the data for coronavirus is scraped. world_url="https://www.worldometers.info/coronavirus/" india_url="https://www.business-standard.com/article/current-affairs/coronavirus-in-numbers-latest-covid-19-cases-and-deaths-in-india-and-world-...
ca5a4fbbc0d7f930dd41aeafd69a96c17ac6addf
Neology92/ai-learn
/digits_recognition.py
1,321
3.53125
4
from neural_network import NeuralNetwork import numpy as np from mnist import MNIST neural_network = NeuralNetwork([784,16,10]) mndata = MNIST('./data/digits_recognition') X_train, train_labels = mndata.load_training() X_test, test_labels = mndata.load_testing() # Normalize data from sklearn.preprocessing import ...
3f49f8abaa778e8baa240771f06d35b464d7a7b0
Lasharus/Speeding
/Speeding.py
910
3.5625
4
class HighSpeed(object): def Speeding(self, x): if x <= 50: print("Pass") return "Pass" elif x <= 55: print("10 euros") return "10 euros" elif x <= 60: print("20 euros") return "20 euros" elif x <= 65: ...
8916c29db82bd59472c96b194b521959890b80aa
eldorbaxtiyorov/python-darslar
/11-if-elif-else/javoblar-11-dars-03.py
294
3.5
4
""" 25/11/2020 Dasturlash asoslari #11-dars: if-elif-else Muallif: Anvar Narzullaev Web sahifa: https://python.sariq.dev """ x = float(input("Birinchi sonni kiriting: ")) y = float(input("Ikkinchi sonni kiriting: ")) if x == y: print(f"{x}={y}") elif x < y: print(f"{x}<{y}") else: print(f"{x}>{y}")
fa11a1fd485aa528f6d9f118e7a391558121dc6a
eldorbaxtiyorov/python-darslar
/40-amaliyot/findMatches.py
610
3.5625
4
from uzwords import words def isIn(text, word): toReturn = True word = list(word) for t in text: if t in word: word.remove(t) else: toReturn = False return toReturn def findMatches(word, allWords=words): word = word.lower() matches = [] for w in al...
baff011e44729bb76852c8f3327f3465b836abad
eldorbaxtiyorov/python-darslar
/19-functions/javoblar-19-04.py
525
3.59375
4
""" 16/12/2020 Dasturlash asoslari #19-dars: FUNCTIONS (FUNKSIYALAR) Muallif: Anvar Narzullaev Web sahifa: https://python.sariq.dev """ # Foydalanuvchidan ikkita son olib, ulardan kattasini konsolga chiqaruvchi funksiya yozing. # Agar sonlar teng bo'lsa "Sonlar teng" degan xabarni chiqaring. def solishtir(x, y): ...
ea223ff16cc8d165abc11b1edc559bf1ce8c0138
ii0/Python_DataStructures_and_Algorithms
/Sequential_Search/Sequential_Search.py
490
3.96875
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Bruce Zhang def sequentialSearch(alist, item): pos = 0 found = False position = None while pos < len(alist) and not found: if alist[pos] == item: found = True position = pos else: # 下标顺序增长 ...
fab122415ebc42e9ca83915b27637562e3d0f7a8
ii0/Python_DataStructures_and_Algorithms
/Tree/BinaryTree.py
1,219
4.0625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Bruce Zhang """ 树的嵌套列表实现 [root, left, right] 根是myTree[0],左子树myTree[1],右子树myTree[2] """ # 创建仅有根节点的二叉树 def BinaryTree(r): return [r, [], []] # 将新节点插入树中作为其直接的左子节点 def insertLeft(root, newBranch): t =root.pop(1) if len(t) > 1: root.insert(1, [new...
aeb198fcf8e1859a8c7368d9ecc711fd6612ceaa
Jiwan88/Python_Hypeskill
/Simple Banking System/app.py
5,247
3.625
4
import random import sqlite3 import database db_file = 'card.s3db' global checksum connection = database.connect() class Bank: def __init__(self): self.card_no = None self.pin = None self.option = None self.system = True self.log_in_status = False def...
2565a50386cdbd939a2b256f639b7f6562dca160
vwxyzjn/tensorflowbyexample
/examples/matrix_multiplication/matrix_multiplication.py
585
3.546875
4
import tensorflow as tf # Taken from https://www.tensorflow.org/guide/eager # Eager execution works nicely with NumPy. NumPy operations accept tf.Tensor arguments. # TensorFlow math operations convert Python objects and NumPy arrays to tf.Tensor objects. # The tf.Tensor.numpy method returns the object's value as a Nu...
8f8d4c213e749a2c02aed9c2510de9b777dcb3fe
Wonjuseo/Project101
/1/1-4. mnist.py
3,103
3.5625
4
# tensorflow를 사용할 것이기에 import 합니다. import tensorflow as tf # MNIST data를 받아옵니다. MNIST data는 0~9까지의 숫자들 입니다. # 본 Code에서는 MNIST data를 학습하고 새로운 입력(숫자)를 판단해내는 방법을 설명합니다. from tensorflow.examples.tutorials.mnist import input_data # one-hot encoding을 합니다. 예를들어 숫자가 1이라면 [1, 0, 0, 0, 0, 0, 0, 0, 0, 0] 이 됩니다. # 숫자가 2라면 [0, 1...
713e454c4fdbb72a544a1eea5828800f85c81e65
bpa/advent-of-code
/2015/python/day2.py
477
3.625
4
#!/usr/bin/env python3 from aoc import * def part1(input): total = 0 for d in delimited(input, 'x', int): d = sorted(d) total += sum([2*a*b for (a, b) in itertools.combinations(d, 2)]) total += d[0] * d[1] return total def part2(input): total = 0 for d in delimited(input...
8fda2c526c83a45cdd5de939c674ce75b06161fb
bpa/advent-of-code
/2022/python/day3.py
690
3.609375
4
#!/usr/bin/env python3 from aoc import * def priority(common): if common.isupper(): return ord(common) - ord('A') + 27 else: return ord(common) - ord('a') + 1 def part1(input: str): answer = 0 for pack in input.splitlines(): size = int(len(pack) / 2) common = (set(pa...
c489c4d2c29f77a37db5eb9dbec24d6ac492a445
nwoodbury/pyson-dilemma
/dilemma/player.py
7,032
3.859375
4
class Player: """Base class for all players that play in the tournament. Parameters ---------- me : str in {'Row', 'Column'} (case sensitive) Whether this player is the row or the column player. Class Variables --------------- me : str in {'Row', 'Column'} (case sensitive) ...
7e1ee9ed74ac28646b311879bc482cde871ea08f
Azoad/Coursera_py4e
/chapter10/ex_10_02.py
497
3.828125
4
"""Find most hours""" fname = input('Enter a file name: ') fhand = open(fname) counts = dict() for line in fhand: if not line.startswith('From '): continue line = line.split() line = line[5] line = line.split(':') line = line[0] counts[line] = counts.get(line, 0) + 1 prin...
7a5d6f9bdd12a2aa3d4d1ce7c50723742a23cd46
Azoad/Coursera_py4e
/chapter7/ex_07_01.py
220
4.375
4
"""Take a file as input and display it at uppercase""" fname = input('Enter the file name: ') try: file = open(fname) except: print('Error in file!') quit() for line in file: print(line.strip().upper())
f3beb3d68acfcc761e90be0dd64d1e609719fde6
Azoad/Coursera_py4e
/chapter12/assignment2.py
615
3.640625
4
""" Scraping Numbers from HTML using BeautifulSoup """ from urllib.request import urlopen import ssl from bs4 import BeautifulSoup # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE url = input('Enter - ') html = urlopen(url, context=ctx).re...
7b6fd1b192bf2fdacb41ce57cef67bd6ca3db41c
Azoad/Coursera_py4e
/test.py
1,944
4.1875
4
print('this is the first one:') print('let\'s do this!') print('add 5 and -3') f = 5 t = -3 print('addition of',str(f),'and',str(t),'is :',str(f+t)) print('-----------------------------') print('this is the second one:') x = 'It is not America but it is Bangladesh' lens = len(x) print('Length of \'' +x+ '\'...
657289646d99d5ae62220f5f8d5086fc7b5fcbca
Azoad/Coursera_py4e
/chapter11/Fine-TuningStringExtraction.py
244
3.5625
4
"""Take certain things after a space""" import re x = ('From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008') y = re.findall('^From (\S+@\S+)', x) print(y) y = re.findall('^From \S+@\S+', x) print(y) y = re.findall('\S+?@\S+', x) print(y)
c469d51fd41cdda38fd2b50949c40a73b0a85a99
ahmad-algsham/RealTimeSentimentDashbaurd
/Statistics/percentage.py
1,109
3.53125
4
""" this code to calculate the percentage polarity """ import pandas as pd import codecs # read data that want to calculate df = pd.read_csv(codecs.open('../data/data_SA.csv', 'rU', 'utf-16'), delimiter='\t') pos_correct = 0 neg_correct = 0 nat_correct = 0 total = 0 for row in df['sentiment']: # print(row) ...
4bee0be7152b4760edc42c15d9fba68ffe6db13d
victorrayoflight/Foudil
/Examen 2019-02-18/11.py
78
3.53125
4
count = 0 while count < 10: print("Bienvenue dans Python") count += 1
6dafc193f5e2f1731df5462295131e2cee3236b8
victorrayoflight/Foudil
/Examen 2019-02-18/6.py
582
4.15625
4
x = True y = False z = False # False OR True == True # True OR False == True # True OR True == True # False OR False == False # True AND True = True # True AND False = False # False AND True = False # False AND False = False # False XOR True == True # True XOR False == True # True XOR True == False # False XOR False...
29986c604ddc6c33e9cbed158b4e553877ec082a
victorrayoflight/Foudil
/Course.py
7,241
4.0625
4
#!/usr/bin/env python3.6 if 'c' in "Victor": print('Letter "c" exist in word "Victor"') fic = open('Names.txt', 'r') # open a file for reading content = fic.read() print(content) def affiche(): print("Salut") affiche() print("Bonjour " * 4) """Shows type of variable and its conversion.""" age = input("SVP ...
b54c7f4f679316a6dbe46883837bca78881541e3
victorrayoflight/Foudil
/Examen 2019-03-14/08.py
293
3.59375
4
#!/usr/bin/env python3 t1 = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] t2 = ['Janvier', 'Fevrier', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Aout', 'Septembre', 'Octobre', 'Novembre', 'Decembre'] t12 = [] for i in range(len(t1)): t12.append(t2[i]) t12.append(t1[i]) print(t12)
49977b6a10816753ef30597dc70ac8d53e59f1ac
rubenjimenez75/mycode
/oop-intro/dice.py
565
4.0625
4
#!/usr/bin/env python3 import random player1_dice = [] player2_dice = [] for i in range(3): ## number of times it will roll, or run through the loop player1_dice.append(random.randint(1,6)) # randint, will roll through integers 1 thru 6 player2_dice.append(random.randint(1,6)) print("Ruben rolled" + str(play...
d9dc9bd81bb009f5ec5fb8f3358276dffb8ff4bc
AstaTus/titanic
/utils.py
404
3.734375
4
import re p = r"M[ri]s*\."; pattern = re.compile(p) def NameChange(name): arr = pattern.findall(name); l = len(arr); if l == 0: return 3; elif arr[0] == 'Mr.': return 0; elif arr[0] == 'Mrs.': return 1; elif arr[0] == 'Miss.': ...
7f86feb97b5f49ea485a7750a387cd8019ca0e96
paisap/holbertonschool-machine_learning
/supervised_learning/0x05-regularization/1-l2_reg_gradient_descent.py
895
3.640625
4
#!/usr/bin/env python3 """ that updates the weights and biases of a neural network using gradient descent with L2 regularization """ import numpy as np def l2_reg_gradient_descent(Y, weights, cache, alpha, lambtha, L): """ that updates the weights and biases of a neural network using gradient descent with L2 ...
ab80a9290ffef72f2911c04d2cf9279bfd38c003
paisap/holbertonschool-machine_learning
/unsupervised_learning/0x01-clustering/1-kmeans.py
2,199
4.09375
4
#!/usr/bin/env python3 """Performs K-means on a dataset""" import numpy as np def kmeans(X, k, iterations=1000): """ Performs K-means on a dataset Args: X: is a numpy.ndarray of shape (n, d) containing the dataset - n is the number of data points - d is the number of dimensions for...
72ae263481af8240f0063b98a0465d713750940e
ransom3910/RasberyPi-Python
/First_Project.py
4,519
3.53125
4
import time # Needed for timers import gpiozero # Needed to control GPIO pins import threading # Needed so that both objects can run their light test at the same time and # allow the menu to run while the lights are running # GPIO PIN Assignments for each LED s1_g = 8 s1_y = 7 s1_r = 25 s2_g = 11 s2...
5e3fb682e81e912dbf81008caa299ccb286387bc
ad-freiburg/reproducibility-example
/inverted_index.py
11,741
3.75
4
""" Copyright 2017, University of Freiburg Chair of Algorithms and Data Structures. Hannah Bast <bast@cs.uni-freiburg.de> Claudius Korzen <korzen@cs.uni-freiburg.de> Theresa Klumpp <klumppt@cs.uni-freiburg.de> """ import math import re import argparse import pickle DEFAULT_B = 0.75 DEFAULT_K = 1.75 class InvertedI...