blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
8e424b70ddd2b360283920245693d0160a3ded53
Rammurthy5/random-topic-learnings
/understand_metaclass.py
1,789
4.34375
4
""" Metaclass are the blueprint for Python 'class' ie, python 'class' inherits 'type', which is known as meta class. These concepts are used if you want to tweak the way your class behaves normally. ..date.. March 25, 2020 ..real-time eg.. Say you want a variable "abcd" to be set as 200 everytime you create a ne...
ad7ec710f2ccf44bad3ffeb0a2562f9bd37e211e
Cainuriel/Training-Python-
/POO.py
1,773
4.0625
4
class Vehiculo(): # Los constructores en Python poseen todos el mismo nombre que es el siguiente: def __init__(self): # la encapsulacion de variables se realiza con los dos guiones bajos "__" delante de la variable: self.__ruedas = 4 self.__peso = 1000 self.__enmarcha = False color = "Blanco" def arr...
6c42d12d37757ac0600a8629da14c81a030f49ac
5l1v3r1/CS50-1
/Week 6/Mario, Python/main.py
883
4.09375
4
# My pure solutions is working, however, because of the VM bug, can not accepted ### STARTS HERE ### # num_stairs = 0 # while num_stairs < 1 or num_stairs > 8: # num_stairs = int(input("Height: ")) # # n = num_stairs - 2 # for stairs in range(1, num_stairs): # print(' ' * n, '#' * stairs) # n -= 1 # # pri...
eceeed79765b8df72deafcfe3a5bd3cb84a4dc76
Mayurg6832/HackerRank-Problem-solving
/Sherlock and Array.py
571
3.703125
4
#!/bin/python3 import math import os import random import re import sys # Complete the balancedSums function below. def balancedSums(arr): sm=sum(arr) x=0 for i in arr: if 2*x==sm-i: return 'YES' x+=i return 'NO' if __name__ == '__main__': fptr = open(os.environ['OUTPU...
a6bf50c20a48679fc43ebea195e3bad0a3e0f813
EvansDaniel/Coding-Problems
/python/DP/LongestCommonSubstring.py
495
3.625
4
import sys def longest_common_substring(s1, s2): dp = [[0] * (len(s2) + 1) for i in range(len(s1) + 1)] myMax = -sys.maxint for r in range(1, len(s1) + 1): for c in range(1, len(s2) + 1): if s1[r - 1] == s2[c - 1]: dp[r][c] = dp[r - 1][c - 1] + 1 myMax ...
bf45d49b66c56770a0db4a8377c102d1cd088dea
Sildinho/aprendaPython3DoJeitoCerto
/apy3JeitoCerto_Exerc_43.py
11,388
4.40625
4
# -- coding utf-8 -- """ Exercício 43 - basico de analise e design orientados a objetos - pag: 167 - livro aprenda python 3 do jeito certo by zed shaw - https://learnpythonthehardway.org/ """ """ “Os alienígenas invadiram uma nave espacial e nosso herói precisa percorrer por um labirinto de salas desmoronando par...
1c77eb6e6b9af96d6fd4bf119b4166ff16d554c6
szmuschi/Python
/Lab2/src/11.py
1,055
4.15625
4
# Write a function that receives a variable number of lists and returns a list of tuples as follows: the first tuple contains the first items in the lists, the second element contains the items on the position 2 in the lists, etc. Ex: for lists [1,2,3], [5,6,7], ["a", "b", "c"] return: [(1.5, "a ") ,(5, 6, "b"), (3,7, ...
81a951dd2c4e3475b9ff7bb5a3e4a5b6026379a4
arronm/Intro-Python-I
/src/17_reverselist.py
128
4.21875
4
def reverse_list(l): """Reverses a given list""" return l[::-1] numbers = [1, 2, 3, 4, 6, 5] print(reverse_list(numbers))
7f8fec8dbe1ae58084813cdc3ac77cfe231d8da2
Alex19-91/Python
/Lesson_5/5.5.py
208
3.5625
4
sum = 0 with open('str_5.5.txt', 'w+', encoding='utf-8') as file: file.write(input('Enter your numbers by space:')) file.seek(0) for num in file.read().split(): sum+= int(num) print(sum)
270f1d83c597286959245336e6aefb1026f1353f
DaniilLitvochenko/prog_sem6
/3 семестр/Тема 2/samrab8(2.4).py
666
4.40625
4
import math """ Литовченко Даниил, ИВТ 2 группа 3 подгруппа Вариант 6: Площадь поверхности куба равна s. Найдите его диагональ. Решение задачи оформите в виде функции diagonal(s), которая будет возвращать d. Например, при s=18 функция diagonal(18) вернет значение переменной d, которая равна 3 """ def diagonal(s): ...
631ec9be9ae9f7efd1c260a3a1cabf20978c3bab
Hilldrupca/LeetCode
/python/Top Interview Questions - Medium/Dynamic Programming/longestincreasingsubsequence.py
1,421
3.984375
4
from typing import List class Solution: def lengthOfLIS(self, nums: List[int]) -> int: ''' Returns the length of the longest increasing subsequence in an unsorted list of integers. Only considers strictly increasing subsequences. Params: nums - A list of...
c5fa5783a7ef52477ea27f5efa5daedea6706917
xuancanhit99/Python
/test2/test111.py
296
3.78125
4
a=0 b=113 if a==0 and b==0: print("Vô số nghiệm") elif a==0 and b!=0: print("Vô nghiệm") else: print("Có nghiệm X=", -b/a) year=2016 if (year % 4==0 and year %100 !=0) or year %400==0: print(year," Là năm nhuận") else: print(year, "Không là năm nhuận")
b93a8637a9c0f9f17a0ffc7cc64e5fbfbe91423a
9wilson6/python-course-notes-1
/clases.py
1,321
3.96875
4
# -*- coding: utf-8 -*- """ Created on Fri Oct 6 09:58:43 2017 @author: wilson """ #CLASSES AND OBJECTS class Person: __name='' __email='' def __init__(self, name, email): self.__name= name self.__email= email def set_name(self, name): self.__name=name ...
5221e3023c8c43ae1944ee1f3326a6fd6366f120
CcccFz/practice
/python/design_pattern/basis/1_6_Prototype.py
969
3.5625
4
# -- coding: utf-8 -- import copy class WorkExp: def __init__(self): self.place = None self.year = 0 class Resume: def __init__(self): self.name = 0 self.age = 0 self.work = WorkExp() def setInfo(self, *args): self.name, self.age, self.work.place, self.wo...
7970f43d95a9f98038533f532b0566f78a53a930
Furzoom/learnpython
/app/demo/polygon.py
2,452
3.8125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import wx import math from abc import ABCMeta from abc import abstractmethod class Point(object): def __init__(self, x, y): self.x = x self.y = y def __sub__(self, other): return Point(self.x - other.x, self.y - other.y) def __add__(...
eccd8228bea43c5c840ebeb4c141b7b63f612bbc
JaredTully/C200jttully
/Assignment3/precmetal.py
1,900
3.875
4
#imports import math ###################################### # # DATA # #All values $/ounce abbreviated $/Oz Gold = 1333.20 #up 2.00 Silver = 16.10 #no change Platinum = 825.15 #up 4.25 Palladium = 1344.90 #down 22.80 Au, Ag, Pl, Pa = "Au", "Ag", "Pl", "Pa" # to make use of symbols easier account = 100000 # $100,0...
603df1d88993b5f87507ccfe6c7b6fba36e22b55
21zaber/MAI
/MAI/NA/sem1/21.py
750
3.9375
4
from math import sqrt, e def rf(x): return ((e ** x + 0.5) ** 2.0) / 9 - 1.0 def f(x): return 3 * sqrt(x+1) - e ** x - 0.5 def f1(x): return 3 / (2 * sqrt(x+1)) - e ** x from random import random as rand x = -0.7 eps = 0.00000001 q = 0.7 print('Simple iteration method:') iter_n = 1 fl = True while f...
981c381368be9e2e24c6874b3f6fa74ab533b41e
amityadav341/PythonMiniProject
/turtle/main.py
1,139
4.09375
4
from turtle import Turtle,Screen, pencolor, title import random screen=Screen() colors=["violet","blue","green","yellow","orange","red"] y_pos=[-200,-125,-50,25,100,175] screen.setup(width=500,height=500) all_turt=[] is_on=True user_bet=screen.textinput(title="Make your bet",prompt="which color turtle will win t...
4226c84d311681cd2211aea0eaf67ccbee6253f8
sandwu/leetcode_problems
/专题训练/动态规划/01bags.py
4,531
3.5625
4
""" cw表示当前已经装进去的物品的重量和;i表示考察到哪个物品了; w背包重量;items表示每个物品的重量;n表示物品个数 假设背包可承受重量100,物品个数10,物品重量存储在数组a中,那可以这样调用函数: """ class Solution: def ff(self): self.max_value = float('-inf') self.dfs(0,0,0,10,100) def dfs(self,i,cw,items,n,w): if cw == w or i == n: if cw > self.max_val...
f775e9ecde763bbd21cd57cf1a09323d62cb2a9d
wangwenjun/python_fundamental
/lesson03/formatting.py
296
3.734375
4
import math s=f"the pi value is:{math.pi} and increment 1: {math.pi+1}" print(s) print("="*100) name="Alex" age=100 salary=1000000000.55 s="Hello {}, you are so old {}".format(name,age) print(s) print("="*100) s="My name is %s i am %d years old and my salary: %f" %(name,age,salary) print(s)
604609cb8a94284e9a1a38b767ded9848a31f6c3
babiswas2020/Blind-paractise
/test42.py
393
3.546875
4
class A: def __init__(self,a,b): self.a=a self.b=b def __str__(self): return f"{self.a} and {self.b}" def __call__(self,func): def wrapper(*args): print("Wrapper executed") return func(*args) return wrapper @A(1,2) def function(*args): for i in args:...
02c43e189ea01ca97ccdeecf853a990e597cecbb
syn7hgg/ejercicios-python
/25_3/3_prof.py
157
3.796875
4
# ENTRADA n= int(input("Ingrese un numero: ")) # PROCESAMIENTO suma= (n*(n+1))/2 # SALIDA print("La suma de los N primeros numeros naturales es: ",suma)
d121b291ecbab651f2963904b83d76a4855a5d5e
edufreitas-ds/Datacamp
/01 - Introduction to Python/03 - NumPy/05 - Numpy Side Effects.py
770
3.6875
4
""" As Hugo explained before, numpy is great for doing vector arithmetic. If you compare its functionality with regular Python lists, however, some things have changed. First of all, numpy arrays cannot contain elements with different types. If you try to build such a list, some of the elements' types are changed...
8ebd5beb82d4868cc22eb96852b85d8547251f51
Carowyn/LaunchCode_Assignments
/chapter7_assignment.py
387
4.125
4
def is_prime(num): """Takes a single integer argument (n) and checks whether the integer is prime.""" div = 2 # divided by for i in range(num): while div < num: # while divided by is less than number if num % div == 0: return False ...
edcbdeee22c132df87c6bcceb2b58a8400494871
KuroiGengetsu/MyCodeWars
/python_code/BuildTower.py
424
3.625
4
def tower_builder(n_floors): return [' ' * (n_floors - n) + '*' * (2*n-1) + ' ' * (n_floors - n) for n in range(1, n_floors + 1)] def tower_builder2(n_floors): return [('*' * (i * 2 - 1)).center(n_floors * 2 - 1) for i in range(1, n_floors + 1)] def main(): for i in range(1, 5): ...
8df7bdbdb7bbc12e7eafee0b14c182decc9721c2
SandyHoffmann/ListasPythonAlgoritmos
/Lista 4/SH-PCRG-AER-Alg-04-Ex-13.py
270
4.125
4
fator = 2 inteiro = int(input("Me diga um numero: ")) divisao = inteiro if divisao<2: print("erro") else: while fator<=divisao: if divisao%fator==0: print(fator) divisao = divisao//fator else: fator+=1
60da581beb6e250d117a6dfd5e54fd9d7eeec7f1
shubhamrawat140798/Python_Programming
/For/Pattern1.py
222
3.9375
4
""" Write a PYTHON program to produce following design A B C A B C A B C """ for i in range(0,3): val = 65 for i in range(0,3): print(chr(val),end=' ') val+=1 print("")
05f0b86bca6ab2e278d8c166bf24929019aa58e8
majdikhalil/tictactoe
/Game.py
2,226
4
4
import random import sys def display_board(board): print(' | |') print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9]) print(' | |') print('-----------') print(' | |') print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6]) print(' | |') print('-----------') ...
fd0e2bbf61cc6ba4536813d234beb85c2fcd44e5
shivang17/learnPythonTheHardWay
/ex9.py
438
3.703125
4
# Here's some new strange stuff, remember type it exactly days = "Mon Tue Wed Thu Fri Sat Sun" months = "\nJan\nFeb\nMar\nApril\nMay\nJune\nJul\nAug" four = "4" five = "5" six = "6" print("Here are the days:", days) print("Here are the months:", months) print(f""" There's something on here. With the three...
6d014b011422a21ba4cdaa1835122c28f98b3761
zunzhuowei/python-study
/demo08/prof/prof_demo.py
2,331
4.0625
4
#!/usr/bin/python # -*- coding: UTF-8 -*- from collections import Iterable print(1, list(range(0, 100, 2))) print 2, range(0, 100) print 3, range(100) print(4, list(range(0, 100, 2))[0:25]) # 切片 print(5, list(range(0, 100, 2))[:]) # 甚至什么都不写,只写[:]就可以原样复制一个list: print(6, tuple(list(range(0, 100, 2)))[:3]) # tuple也是一种...
55400f06e9582e58eaa2184e8fe6f13bd103573a
tommypratama/ds
/Building Machine Learning Models in Spark 2/python/m2_demo03_LinearRegression.py
9,836
3.5625
4
# coding: utf-8 # ### Download the Automobile data set # <b>Download link:</b> https://archive.ics.uci.edu/ml/machine-learning-databases/autos/imports-85.data # In[1]: from pyspark.sql import SparkSession spark = SparkSession .builder .appName('Predicting the price of an automobile given a set of features...
8b005335b52e3312f175cd7313e12f92c852dc38
quangthin20/python
/KieuDuLieuBoolean.py
2,783
4.0625
4
'''Kiểu dữ liệu Boolean trong python Boolean là kiểu dữ liệu chỉ có 2 giá trị True/False ''' # So sánh giữa các số num1 = 12**13 num2 = 13**12 print("num1 =", num1) print("num2 =", num2) print(num1 > num2) print(num1 <= num2) print(num1 != num2) print('_'*45) # So sánh chuỗi str1 = "QuangThinDepTrai" str2 = "QTDT" prin...
e6e963896886aa6899c2fdea5bf9b693c7e3d204
green-fox-academy/RudolfDaniel
/[week-02]/[day-05]/Guess_my_number.py
631
3.9375
4
import random def guess(a): lives = 5 origin_nr = random.randint(0, a) while lives > 0: print("I've the number between 0 and " + str(a) + ". You have " + str(lives) + " lives.") guess = int(input("Guess my number: ")) if guess < origin_nr: lives -= 1 print("...
0017ba4a5cc26a2ea88c04697ed8d86128dbaa76
inspectordanno/python_flask_course
/2_refresher/06_advanced_set_operations.py
512
3.8125
4
friends = {"Bob", "Rolf", "Anne"} abroad = {"Bob", "Anne"} local_friends = friends.difference(abroad) print('difference:', local_friends) oneValueTuple = (30,) # need trailing comma for a one value tuple otherOneValuetupe = 30 # no parens also work empty = abroad.difference(friends) print('empty:', empty) total = f...
e9f4135cf6673e73effe2e6924b8ac6318157b9c
jiangshen95/UbuntuLeetCode
/NumberofSegmentsinaString2.py
388
3.859375
4
class Solution: def countSegments(self, s): """ :type s: str :rtype: int """ count = 0 for i in range(len(s)): if s[i] != ' ' and (i == len(s) - 1 or s[i + 1] == ' '): count += 1 return count if __name__ == '__main__': s = inp...
bfcf5822fd766522df703d8ae063a6bce2ccaa0c
Thanh-Truong/playground
/datastructure/merge_sort.py
1,153
4.21875
4
def merge_sort(array): # Special cases if len(array) <= 1: return array # divide left = array[0: len(array)//2] right = array[len(array)//2:] sorted_left = merge_sort(left) sorted_right = merge_sort(right) # merge two sorted arrays i = left_index = right_index = 0 while (...
e318e6a1f179e40c36eaf9dd8f76c4ebe84a83a2
Tetsuya3850/DSA-Primitives
/ArraysStrings/rotate_matrix.py
588
3.9375
4
def rotate_matrix(matrix): # Time O(N^2), Space O(1), where N is the length of the side of the matrix. N = len(matrix) for offset in range(N // 2): for shift in range(N - offset*2 - 1): pos = shift+offset first = matrix[offset][pos] matrix[offset][pos] = matrix[N...
05332d993d2409c30c6be52863a2cb09ddb58927
tainenko/Leetcode2019
/leetcode/editor/en/[1929]Concatenation of Array.py
1,108
3.515625
4
# Given an integer array nums of length n, you want to create an array ans of # length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0- # indexed). # # Specifically, ans is the concatenation of two nums arrays. # # Return the array ans. # # # Example 1: # # # Input: nums = [1,2,1]...
8bf3def3bf7f21da4eddf0850ef7473ee7228d50
wookim789/baekjoon_algo_note
/동빈좌/tip/string/basic_string.py
164
3.890625
4
# 파이썬의 문자열은 리스트와 같이 처리됨 a = "hello" b = "world" print(a + b) print(a + " " + b) print(a, b) print(a * 3) print(a[0:-1])
65b2bb07428e0b0d6cb6ff26e3c5a5643498fdef
wingkitlee/ASIAASummerSchool2014
/Examples/demo_hist2d_2.py
1,723
3.5
4
""" Example script for plotting histogram """ # import every function from numpy module # can use the function directly from now from numpy import * # import pylab module # use pylab.function to call import pylab # generating data # number of data points in each dimension N = 4000 # sigma of normal distribution sig...
6269342c4bbce958c961f9a877ccf8c8c77a9966
milinhbeo72/Change
/Change2.py
2,080
3.75
4
def main(): purchase_price = input("Purchase price: ") paid_amount_money = input("Paid amount of money: ") offer_change = int(paid_amount_money) - int(purchase_price) if offer_change <= 0: print("No change") else: print('Offer change:') a = offer_change // 10 ...
c49b6ff2657cc0e79b07d2b5d046cb516cb3fde6
Akash671/geeksforgeeks
/Reverse_words_in_a_given_string.py
569
3.515625
4
"""author akash kumar""" class Solution: def reverseWords(self,s): # code here # s=str(input()) s="."+s S="" n=len(s) c=n-1 d=0 for i in range(n): if s[n-i-1]==".": if i==d: S+=s[n-i:c]+s[n-1] else: ...
7a0bd9b291ebdc4418a5491fce622d3ba1606bf9
priyankabb153/260150_daily_commits
/functional_programming/itertools.py
1,008
4.53125
5
""" itertools The function count counts up infinitely from a value. The function cycle infinitely iterates through an iterable (for instance a list or string). The function repeat repeats an object, either infinitely or a specific number of times. takewhile - takes items from an iterable while a predicate function ...
b838cdab22aeff0d6b09db9eec412435c4798976
Alex760164/home_work
/home_work_12/home_work_12.py
987
4.15625
4
""" Пользователь вводит, отдельно, строку `s` и один символ `ch`. Необходимо выполнить поиск в строке `s` всех символов `ch`. Для решения НУЖНО использовать только функцию `find()`(rfind()), операторы `if` и `for`(while). """ s = input('Введите строку: ') ch = input('Введите символ для поиска: ') print('ОТВЕТ:') idx =...
ea2290a30220a6bc3c873ebb8a4c5ba02fb5e4bb
shourya192007/A-dance-of-python
/MySql/Sqlite with python/python_sqlite.py
406
3.828125
4
import sqlite3 conn = sqlite3.connect("school.db") cur = conn.cursor() cur.execute(""" CREATE TABLE IF NOT EXISTS STUDENTS ( admission_no INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, standard INT ) """) cur.execute("INSERT INTO STUDENTS(admission_no, name, standard) VALUES (2, 'Rajat',13)") data = cur...
db965cec47a9e4180911a65fdedb04cffa816fee
Fulvio7/curso-python-guppe
/guppe/exercicios_secao_7/pt_1/ex_20.py
730
3.859375
4
""" 20- Preencha um vetor de 10 posições com números inteiros entre 0 e 50. Preencha um segundo vetor apenas com os números ímpares presentes no primeiro. Imprima os dois vetores, com 2 elementos por linha """ numeros, impares = [], [] for i in range(10): numeros.append(int(input(f'Digite o {i+1}º número: '))) ...
17a31086e733d8144a89ffedb0ed03c8af09f98e
FrankMwesigwa/lessons
/python/tests.py
168
3.875
4
def my_function(): phone_no = input("type your phone number") if len(phone_no) == 10: print("True") else: print("False") my_function()
52ce10edca657105eda244c8a2a16f0837d24403
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/hexadecimal/4bbb4a1da8624e6d8ecb48a20e06ca62.py
220
3.625
4
def hexa(num): hex = '0123456789abcdef' res = 0 for power,value in enumerate(num[::-1].lower()): if value not in hex: raise ValueError('not a valid hex input') res += hex.index(value) * (16**power) return res
26e370112c6df5516b80172c9bb44b500745deec
vandanagarg/practice_python
/learning_python/decorator/new_decorator.py
691
3.90625
4
#decorator example3 def hello(): return "VAndana" def other(some_func): print("Other code here") print(some_func) other(hello()) def new_decorator(original_func): def wrap_func(): # func that needs to be added in original func print("Some extra code, before the original func") or...
50d013b2b4b97e403bad235f0293dd4c60f8fd90
thakur-nishant/Simple-Python-Programs
/minIntegertMultipleOfN.py
771
3.6875
4
""" Give an positive integer n, find out the smallest integer m, such that all digits in m multiply equals to n. For example, n = 36, return 49. n = 72, return 89. You can assume there is no overflow. """ def mult_num(num): result = 1 for i in num: result *= int(i) return result def min_num_combi...
73719da3427094d3906de458785e83889e991bd7
Radzihowski/python
/realpython.com/ch09-tuples-lists-and-dictionaries/6-store-relationships-in-dictionaries.py
1,196
4.6875
5
# 9.6 Exercises # 1. Create an empty dictionary named captains captains = {} # 2. Using square bracket notation, enter the following data into the dictionary one item at a time captains["Enterprise"] = "Picard" captains["Voyager"] = "Janeway" captains["Defiant"] = "Sisko" # 3. Write two if statement that check if "E...
924d10dbcb063ce39600c45569409421fed03d9f
winder/adventofcode_2016
/10/d10.py
2,780
3.671875
4
#!/usr/bin/env python3 import sys import re import pprint pp = pprint.PrettyPrinter(indent=4) def get_low(bots, bot_id): if len(bots[bot_id]) != 2: raise ValueError('Bot is empty, cannot get low') return bots[bot_id][0] def get_high(bots, bot_id): if len(bots[bot_id]) != 2: raise ValueEr...
fd2d6da9c3aac49a67ecfd011a43b6e91cb8addf
formazione/python_book
/snippets/002.py
289
4.03125
4
import argparse # Create the parser and add arguments parser = argparse.ArgumentParser() # def single_word(string): # # Check input does not contain spaces # return string parser.add_argument('argument1', # type=single_word ) args = parser.parse_args() print(args.argument1*2)
15a6eef28032e0fc207a23c153036f4c18c49f77
wheejuni/algorithm_bootcamp
/연습문제/codility/tape_equilibrium.py
827
3.59375
4
def solution(array): differences = [] min_diff = 0 for i in range(1, len(array) - 1): iter_array = array[:] compare_array = split(iter_array, i) differences.append(calculate_difference(compare_array, iter_array)) min_diff = differences[0] for difference in differences: ...
d75e132ec63c38844e0ab05c4752d06365d9d545
JayantGoel001/Open-Source
/Week2/13.py
126
3.625
4
def triplets(n): return [(a, c - a, c) for c in range(2, n) for a in range(1, c // 2 + 1)] n = int(input()) triplets(n)
f3bc7b9f98e2a1c9dd010ffebf629b2554043c3b
zlw10100/blog
/design_patterns/factory_method/src/operators.py
674
3.875
4
# !/usr/bin/env python # -*- coding: utf-8 -*- # 'author':'zlw' """操作符模块""" from abc import ABCMeta, abstractmethod class AbstractOperator(object, metaclass=ABCMeta): def __init__(self, x, y): self.x = x self.y = y @abstractmethod def handle(self): pass class Add(Abs...
15e56dc157e507e4b21d9398c20fd09a9313ab92
arslanaarslan/Hangman
/Topics/Loop control statements/Cat cafés/main.py
472
3.96875
4
cafe_names = [] number_of_cats = [] while True: word = input() if word == "MEOW": break else: name_and_number = word.split() cafe_names.append(name_and_number[0]) number_of_cats.append(int(name_and_number[1])) index_of_max = 0 max_value = 0 for index, number in...
8e6293fcb33e2626a8cd935e3e230e5fb68f40dc
arkitpawar/healthcare_credit
/rough.py
854
3.84375
4
import csv with open('data.csv', 'r') as csv_file: csv_reader = csv.reader(csv_file) data = list(csv_reader) headers = data[0] data = data[1:] def match_rows(speciality = None, city = None, state = None, zip_code = None): for row in data: # ['2', 'B', 'Vision', 'Trenton', 'HD', '...
0bd1bed565dfcd570c82137bb5936a578039216a
georgiosdoumas/LearnPythonProgramming2018
/chap03/page104_odd_even_numbers.py
296
3.59375
4
from itertools import compress N = 10 data = range(10) even_selector = [1, 0] * (N//2) odd_selector = [0, 1] * (N//2) even_numbers = list(compress(data, even_selector)) odd_numbers = list(compress(data, odd_selector)) print(odd_selector) print(list(data)) print(even_numbers) print(odd_numbers)
eb13a64d07bec0cbfda8e8e81139b3369ef2da09
raphaeldiscky/python-leetcode-solutions
/Array/350 - Intersection of Two Arrays II.py
562
3.640625
4
from typing import List class Solution: def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: dic = {} stack = [] for i in nums1: if i in dic: dic[i] += 1 else: dic[i] = 1 for i in nums2: if i in di...
e985b36d9802688b1de05c41001d226d4aef486f
JohnAssebe/Python
/transposition_cipher.py
335
3.71875
4
def transition_cipher(plain_text,key): cipher_text=['']*key for i in range(key): current_index=i while current_index<len(plain_text): cipher_text[i]+=plain_text[current_index] current_index+=key return ''.join(cipher_text) print(transition_cipher('Common sense is not ...
7c2a182610b4aa1996b64fc0760a83e705a11c3a
shaniavina/Leetcode_Python
/107_binary_tree_level_order_travesal_2.py
827
3.859375
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 levelOrderBottom(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ ##...
5f9db5a9c31196348e0191b707d428587ae13020
sanislav/homework
/coursera/algorithms_2/02/p_01/clustering.py
5,530
3.625
4
''' In this programming problem and the next you'll code up the clustering algorithm from lecture for computing a max-spacing k-clustering. This file describes a distance function (equivalently, a complete graph with edge costs). It has the following format: [number_of_nodes] [edge 1 node 1] [edge 1 node 2] [edge 1 cos...
856c54ba76b4b1218a54b31004362b87104df152
lijun-szy/python
/py自动化/122_IPy_多网络计算方法.py
832
3.578125
4
from IPy import IP # 两个网段是否存在包含 IP('10.0.0.0/24') < IP('10.0.0.0/16') # 判断IP地址和网段是否包含于另一个网段中 '192.168.1.100' in IP('192.168.1.0/24') # 判断两个网段是否存在重叠 返回1代表重叠,0不重叠 # IP('192.168.0.0/23').overlaps(192.168.1.0) # IP('192.168.1.0/23').overlaps(192.168.2.0) # 根据输入的IP或者网段地址返回网络、掩码、广播、反向解析、子网数、IP类型等信息 ip_s = input("Please in...
3abc1777261a765773e613d2a5a582b38b8d9580
kyeguy00/cse210-student-mastermind
/mastermind/game/move.py
557
3.96875
4
class Move: """The Move class. The responsibility of it is to keep track of the players. Stereotypy: Information Holder Attributes: _code (int): Code to be guessed. """ def __init__(self, code): """The class constructor. Args: self (...
b73ec03af4f4c8665095b65e0aded8a408a9f493
ChaningBlake/novel_role_filler_generalization
/scripts/combo2letters.py
971
3.875
4
#!/usr/bin/env python3 ''' October 17th 2019 @author: Blake Mullinax This script reads the output of testSentences.r through stdin and converts the combinations into letters to be used for training an encoder/decoder. ''' import sys if len(sys.argv) != 3: print() print("Usage %s [# in training set, # in testing set...
c0ae554a655d13f0b7e7f9cefc87637b1b0bedb3
mittal-umang/Analytics
/Assignment-2/StringLetters.py
521
4.40625
4
# Chapter 8 Question 6 # Write a function that counts the number of letters in # a string using the following header: # Write a test program that prompts the user to enter a string and displays the number # of letters in the string. import re def countLetters(s): return len("".join(re.findall("[a-zA-Z]", s))) ...
2e9a0d53f1f2131e315ad2a1ce7cd42df481a4af
araschermer/python-code
/algorithms_and_data_structures/is_prime.py
2,486
4.34375
4
# a prime number is ony divisible by itself and the unit # one is not prime, since it is the unit # the basic implementation pf such a method would look like: from nose.tools import assert_false, assert_true from time import time from math import sqrt, ceil def is_prime_v1(n): "Return True if n is prime, otherwis...
175317e57342b8816dd6f379673d639a9670e13e
rawcrazy/rawcrazy
/lab2-9.py
1,439
3.921875
4
def getphone(): valid_num=False empty_str='' while not valid_num: ph_num=input("enter phone number") if len(ph_num)<11 or ph_num[5]!='-': print("invalid number") else: k=0 valid_num=True ph_num_digits=ph_num.replace('-',empty_str)...
b099fe600b3cf7da3f1221ec8bcaa13618af49e2
venkateshnvr/Venkatesh
/functions.py
267
3.671875
4
def function(a,b=20): print("add the function:",a+b) print("sub the function:",a-b) print("mltipication the function:",a*b) print("madulo the function:",a%b) print("th power:",a**b) return function(10,20) function(20,30) function(5)
413e66c9c2fac24fb283ed5b0cfecdcd587d8023
drewlamur/project-euler
/euler_p16.py
697
3.796875
4
#!/usr/bin/env python #Power digit sum #Problem # 16 import time import pdb print "-" * 50 print "starting exercise 1" print "-" * 50 print """numbers = [int(i) for i in str(2**1000)] print reduce(lambda a, b: a + b, numbers)""" t1 = time.time() numbers = [int(i) for i in str(2**1000)] print reduce(lambda...
fcd2aa95ae5d00075e5b10f99144b912d3d67c97
J-woooo/Python_Coding_Test
/6장/6-2.py
252
3.734375
4
n = int(input()) students = [] for i in range(n): student, grade = input().split(" ") students.append((student, int(grade))) students = sorted(students, key=lambda student: student[1]) for student in students: print(student[0], end=' ')
3460c9c8342c442e19668781787d08cb544ebcd3
Code-Institute-Submissions/survey-data-analysis
/run.py
5,507
3.703125
4
# Importing gspread API and credentials to be able to open # and read from the google sheet import gspread from google.oauth2.service_account import Credentials SCOPE = [ "https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive" ...
22d98a92fc0a09bbcf1aa0489c4d2582d74bda83
sivaneshl/python_data_analysis
/intro_data_science_python/advanced_python_pandas/assignment3/assignment3.0.py
12,867
3.84375
4
import pandas as pd import numpy as np pd.options.display.float_format = '{:.8f}'.format # Question 1 # # Load the energy data from the file Energy Indicators.xls, which is a list of indicators of energy supply and renewable # electricity production from the United Nations for the year 2013, and should be put into a...
591c86e1bd3805f36e26baf202ac9c8ab1292bd0
mronian/patel-opensoft16
/colorExtractor.py
2,482
3.71875
4
def getColors(image,legend_corners,legend_text_corners,off): """ Returns the set of color tuples in the Image Input: Image Legend_Corners : List of tuples of coordinates of x-y Text_Box_Corners : List of tuples of tuples of coordinates x-y in ...
1e0dc90b316dcf0ed7dc3428d9a176e110e11f34
sjhhh3/Leetcode
/amcat4.py
489
3.5625
4
area = [[1,1,1,1],[0,1,1,1],[0,1,0,1],[1,1,9,1],[0,0,1,1]] ans = [] def dfs(area, i, j): if i < 0 or i >= len(area) or j < 0 or j >= len(area[0]) or area[i][j] not in (1,9): return 0 area[i][j] = "#" b = 0 or dfs(area, i + 1, j) t = 0 or dfs(area, i - 1, j) r = 0 or dfs(area, i, j + 1) ...
61a44848ff8d13365185c85bb426a52e952acc75
LeeHann/C_study
/day19/ex02.py
434
3.59375
4
#%% 지역 변수의 전역 변수 사용 a=5 def scope_test() : global a a = 1 b = 7 print(a, b) scope_test() print(a) # %% 재귀 함수 count = 5 def recur_test() : global count if count > 0: count = count - 1 print(count) recur_test() recur_test() # %% 변수의 함수화 def hello() : print('hello') a = hello a() # %% 함수 안 함수 d...
7a1531e5a09867da6e2511e68ce94f08a3189257
weifo/interview_preps
/algorithms/01strs.py
440
3.78125
4
def sort(s): charlist=list(s) length=len(s) j=length-1 answer=0 for i in range(j): while(i<j and charlist[i]=='0'): i+=1 while(i<j and charlist[j]=='1'): j-=1 if i<j: answer+=1 charlist[i],charlist[j]=charlist[j],cha...
69fba294a9348f049ea7c918fd4c701fb46c17a2
ai2-education-fiep-turma-2/05-python
/solucoes/Karen/Aula_2/Exercicio_2.py
514
3.890625
4
#!/usr/bin/python3 idade=int(input("Qual a sua idade?")) peso=int(input("Qual o seu peso?")) dormiu=int(input("Quantas horas você dormiu nas últimas 24 horas?")) if (16 < idade < 69): if (peso > 50): if (dormiu >= 6): print ("\nParabéns, você está apto para doar sangue!") else: ...
0ae2f2c0398b6b584d13350195a48cb59528d940
bencummings/goo-py
/solutions/01_string_a.py
2,234
4.25
4
""" Completed solutions for the first set of basic string exercises featured within Google's Python course. Usage: python 01_string_a.py """ def donuts(n): """ Conditionally outputs (prints) the quantity of donuts. """ prefix = "Number of donuts: " if n < 10: return prefix + str(n) ...
416ac8718a751902b465d8782134655faba15ce9
zhanglintc/leetcode
/Python/Flatten Binary Tree to Linked List.py
1,241
4.15625
4
# Flatten Binary Tree to Linked List # for leetcode problems # 2014.08.25 by zhanglin # Problem Link: # https://leetcode.com/problems/flatten-binary-tree-to-linked-list/ # Problem: # Given a binary tree, flatten it to a linked list in-place. # For example, # Given # 1 # / \ # 2 5 # /...
4f87f35bfb3b438babd1114064f5124f9f7ef7ca
KristofferFJ/PE
/problems/unsolved_problems/test_294_sum_of_digits_-_experience_23.py
412
3.59375
4
import unittest """ Sum of digits - experience #23 For a positive integer k, define d(k) as the sum of the digits of k in its usual decimal representation. Thus d(42) = 4+2 = 6. For a positive integer n, define S(n) as the number of positive integers k < 10n with the following properties : Find S(1112) and give ...
3219e24b0623d8597bbc545bff7ead2602e4fffb
jingyiZhang123/leetcode_practice
/recursion_and_backtracking/39_combination_sum.py
1,116
3.625
4
""" Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times. Note: All numbers (including target) will be positive integers. The solution s...
4b1c683f5fa98fd38cc994341ef1a24f8571bd14
tfio17/Python_Basics
/chaos.py
310
3.859375
4
# # ## Tom # # ## Zelle ch 1.6 pg 13 # chaos # a simple program demonstrating chaotic behavior def main(): print("This program illustrates a chaotic function") x = eval(input("Enter a number between 0 and 1: ")) for i in range(10): x = 3.9*x*(1-x) print(x) main()
6613cee940911ad0f17c3d4dc71a57eb4a901a1f
philipsdoctor/tech_review_questions
/problem3.py
1,830
3.984375
4
# The prime factors of 13195 are 5, 7, 13 and 29. # What is the largest prime factor of the number 600851475143 ? import math def get_prime_factors(number_to_factor): """ returns a list of prime factors for a given number """ prime_factors = [] while True: try: next_prime = return...
0879add97dcfb4bb7d1b81574cfcd21b94e9661b
ditesh/pyfun
/answers/magic/math.py
252
3.6875
4
# Return n*(n-1)*(n-2)*...*1 def fact(n): retval = 1 for i in range(1,n+1): retval *= i return retval # Return n+(n-1)+(n-2)+...+1 def sums(n): retval = 0 for i in range(1,n+1): retval += i return retval
0d525948048184bdafd7fb3f5d7b3b6f25464002
adosib/PyLearn
/Corey_Schafer_Beginner_Tutorial/Strings.py
462
4.34375
4
# Formatted strings greeting = 'Hello' name = 'Ado' message = '{}, {}. Welcome!'.format(greeting, name) # {} is a placeholder print(message) # F strings # Does the same as above message_ = f'{greeting}, {name}. Welcome!' print(message_) # The advantage is that you can call methods on the variable easily within the p...
35429fe039ac5294efd591e72090307882e6d9cd
theChad/ThinkPython
/chap19/exercises.py
2,711
4.28125
4
# Section 19.4 Exercise # Use 'all' fuction for uses_all from 9.3 def uses_all(word, required): """True if word uses all letters in required. word, required: strings (or any collection) """ # required comes last, because that's the string we want # to run through in its entirety. The first part jus...
3eb10f0c88ca69b6dec631711afe73fd4f93475f
dykim822/Python
/ch12/sort2.py
161
3.78125
4
import numpy as np a = np.array([[4,3,5,7],[1,12,11,9],[2,15,1,14]]) print(a) print(np.sort(a, axis=1)) # axis = 1, axis=-1, 행 정열 print(np.sort(a, axis=0))
2b8719fc1dd7bc32e451519b3b296aa4eb323f76
kalebjuliu/Fundamentals-PythonExercises
/3/guessing_game_one.py
529
4.0625
4
import random random_num = random.randint(1,10) count = 0 def check_num(guess): if random_num > int(guess): print("Your guess is too low") elif random_num < int(guess): print("Your guess is too high") else: print("Your guess is correct !!") print(f"And it only took you {count} tries") whil...
f829518bca48acd50a0b04b506ecddaa2d2f5875
amoghaddam1/WeatherScraper
/db_operations.py
4,324
3.515625
4
""" This module holds DBOperations which handles interactions with the database """ from dbcm import DBCM class DBOperations(): """ DBOperations handles interactions with the database. """ def __init__(self): """ Initializes the DBOperations Class. """ self.app_databas...
1317a897b48ea162f93439c478e3b47032ee2238
Aleti-Prabhas/HackerRank
/if_else.py
240
3.828125
4
import math import os import random import re import sys x=int(input()) if(x%2==1): print("Weird") elif(x<=20): if(x>=2 and x<=5): print("Not Weird") else: print("Weird") elif(x%2==0): print("Not Weird")
b44ffdeb5ba764239963014d59a2756782b11854
ericschorling/digital_crafts_python
/python_1/degree_conversion.py
86
3.65625
4
temp_entered = int(input("Temperature in C?")) print("%d F" % (temp_entered*(9/5)+32))
994fa44aa3d68fd0b5f89d0ba5ec54b2f81150df
ghostshot/Advent-Of-Code
/day5.py
1,203
3.5625
4
""" AdventOfCode.com Day 5: Doesn't He Have Intern-Elves For This? """ import re def isNiceOLD( inString ): #1. Contains 3+ vowels (aeiou) if re.search('([aeiou]).*[aeiou].*[aeiou]', inString) is None: return False #2. Contains 1+ letter twice in a row if re.search('(\\w)\\1+', inString) is N...
476f801f4cb8adf018659e04acbc8964556dbfd0
hawkestalon/stocks-nlp-backend
/sentiment/nlp/sentiment.py
2,801
3.546875
4
import spacy from nltk.stem import WordNetLemmatizer import gensim import re import nltk def count_sentiment(spacy_text_blob): ''' This function uses spacytextblob sentiment analysis to get a count of the number of positive or negative posts. Note: We use the adage 'no news is good news' So neutral posts ...
27b1e5a65d71a33e1d9e7ce4dfa4454f6c0d566d
Ashish94720/GUI-Calculator
/calculater.py
4,013
4
4
import tkinter as tk from tkinter import * window = tk.Tk() window.geometry("312x324") window.resizable(0,0) window.title("Calculater") def btn_click(item): global expression expression = expression +str(item) input_text.set(expression) def btn_clear(): global expression expression="" input_t...
fe19daa7439a9ec2274fd332bbe473983a0d2048
balasarjeeth/shiny
/ntimes.py
135
3.765625
4
def repeat(string,length): cur , old = 1, string while len(string) < length: string += old[cur-1] cur = (cur+1)%len(old) return string
4fd16429e40a3018fbbdaaeaf29ed0b27bfe786f
xianzhixianzhixian/Python
/com/yufeng/selflearning/func_return.py
123
3.578125
4
#!/usr/bin/python #Filename:func_return.py def maximum(x,y): if x>y: return x; else: return y; print (maximum(2,3))
381c15f5790a79d7b6584f19c685bd13eedf4ccc
Sai-Ram-Adidela/hackerrank
/challenges/basic data types/finding_the_percentage.py
639
3.609375
4
""" Title : Finding the Percentage Subdomain : HackerRank/Python3/Challenges/Basic Data Types Domain : Python Author : Sai Ram Adidela Created : 23 April 2018 """ if __name__ == '__main__': n = int(input()) ls = list() my_dict = dict() for i in range(n): a = input() ls = a.sp...
ce930524bafb55391dc8b473c358f07f9a278d11
wz1990911/w
/03-答辩项目.py
5,909
3.75
4
list1 = [] import random import time def print_name(): time.sleep(1) print("1------添加参与活动的人名") print("2------删除不想参加的人名") print("3------打印人员名单") print("4------查找人名") print("5------修改人名") print("6------娱乐模式") print("0------退出系统") def print_diao(): time.sleep(1) print("欢迎来到节日娱乐系统".c...