blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
c831efd2c779d46b9959e5cc317f2a46cbfd7766
Jeremy277/exercise
/pytnon-month01/month01-class notes/day11-fb/demo03.py
843
3.875
4
''' 封装 ''' class Wife: def __init__(self, name=None, age=None): self.name = name #私有成员:以双下划线开头 # self.__age = age # self.set_age(age) self.age = age @property #拦截读取 age = property(get_age, None) def age(self): return self.__age #设置写入方法age.setter(写入方法) ...
286d3019f532899549c55b15e4b0561e41e30ef9
grieff/dice-rolling
/dice-roll.py
1,108
4.53125
5
# Dice Rolling Simulation # Python 3.0 # Rolls a number of dice, with x sides, depending on the user input import random # ROLL FUNCTION def roll(die, sides): r = 0 # While loop based on number of dice selected while r < die: # Store the random roll to variable rolls rolls = random.randin...
a65720775df47fc20c736b5218a8ef5f0a9573df
tyut-zhuran/python_learn
/基础/多线程同步.py
703
4.0625
4
#同步是指定执行的顺序 import threading import time def test1(): if lock1.acquire(): print("------test1-------") time.sleep(0.5) lock2.release() def test2(): if lock2.acquire(): print("-------test2------") time.sleep(0.5) lock3.release() def test3(): if lock3.acquire(): print("--------test3--------") time....
7ae5b57385892b4c6b5f525a161ec569ac1fb947
Ahmad-Hassan-03kml/Python-Practice-codes-Begginers-to-Pro
/function_referrence.py
236
3.609375
4
def func( pr1 ): print("list before eddit {}" .format(pr1)) # 20 pr1 = [1,2,3,4,5 ,6,7,7] print("list after eddit {}" .format(pr1)) # 20 #end of func pr1 = 20 func(pr1) print(pr1)# 20
efbd9906eb13bdcae7c44ce32352d8fdabd7d499
astraldawn/misc_code
/interview/worked_solutions/python_notes.py
5,080
4.0625
4
# Functionality in external library # 2D array declaration - using numpy # Code? # xrange vs range # xrange: generator like object # range: list # ( ) generator, [ ] list comprehension # The difference between == and is # ==: if the objects referred by the variables are equal # is: variables point to the s...
f65823f74d5d9cd00c7206198c6d7495663bbe5b
MatthewRatajczyk/Simple-Work-Automation
/AutomateMonthlyReports/Source Code/AutomateReports.py
1,995
3.53125
4
from tkinter import filedialog from tkinter import * import tkinter.simpledialog import pandas root = Tk() # initialdir is where we wrtie the file to csv_file = filedialog.askopenfilename(initialdir = "",title = "Select Disk Utilization.CSV",filetypes=[("CSV Files",".csv")]) inputData = pandas.r...
67ad21b39e5518f55ea69cf85609d39b837d0c8b
johnkle/FunProgramming
/Leetcode/数组字符串/1470重新排列数组.py
457
3.59375
4
class Solution(object): def shuffle(self, nums, n): res = [0]*2*n for i in range(n): res[i*2] = nums[i] res[i*2+1] = nums[n+i] return res class Solution(object): def shuffle(self, nums, n): res = [] left = 0 right = n while left < ...
1de6112fe1b81ff461474cd5dcc513cf6d773b3f
ramdharam/python_progs
/fibonocci.py
188
4.125
4
def fibonocci(num): if num==1: return 1 elif num==0: return 0 else: return ( fibonocci(num-1) + fibonocci(num-2) ) if __name__ == "__main__": print(fibonocci(6)) #1 1 2 3 5 8
a05a301cfe2cc7e32f08ea28f326c160e06f9533
z0x010/medusa
/medusacode/python_process_demo/process_02_process.py
1,382
3.515625
4
#!/usr/bin/env python # coding:utf-8 """ In multiprocessing, processes are spawned by creating a Process object and then calling its start() method. (Process follows the API of threading.Thread) """ from multiprocessing import Process from multiprocessing import Queue, Pipe from multiprocessing import Lock, RLock, Ev...
48fa2b4c18571b78c299137416b1889b56f72f6d
iacopoff/nsgaii
/vic/plot_sa.py
7,938
3.53125
4
import networkx as nx import numpy as np import itertools import matplotlib.pyplot as plt # Load Sensitivity Analysis results as dictionary SAresults = np.load('SAresults_test.npy').item() # Get list of parameters parameters = list(SAresults['S1'].keys()) # Set min index value, for the effects to be considered signifi...
36ec91dc30d62a56f3d3be5cf51a4155a0324148
FUNsys/sirabasu_scraping
/course.py
3,069
3.5
4
#!/usr/bin/env python # coding: UTF-8 class Course(object): def __init__(self): self._name = '' self._thema = '' self._lecture_content = '' self._schedule = '' self._grade = '' self._textbook = '' self._note = '' self._remark = '' self._target = '' self._annual = '' self._semesta = '' self._un...
a4ce45add728ebcab7d09b6c85fc63c020e05f08
24apanda/python_useful
/function.py
384
3.84375
4
# -*- coding: utf-8 -*- """ Created on Thu Dec 15 21:48:45 2016 @author: apanda88 """ ###########prime Number########## max = 10 count=0 for i in range(2,max+1): for j in range(2,i+1): if (i%j==0 and i !=j): count=1 break if(count==1): print( i,"Opposite...
5a1f9e48b15a36fabbea639408fd42a7a96f0bad
dusty-phillips/pyjaco
/tests/strings/zipstring.py
132
3.96875
4
s1 = "hello" s2 = "world" s3 = "abcd" s4 = zip(s1,s2,s3) for item in s4: print "----" for val in item: print val
e0a47fb4329f890a9f05f8461d49fbc828e14dee
zakir360hossain/MyProgramming
/Languages/Python/Learning/regular expression/regex1.py
572
4.46875
4
import re def main(): # 'match' matches the entire string. 'search' look for specific words or character in the string line = "I think I know it" matchResult = re.match('think ', line, re.M | re.I) if matchResult: print("Match found" + matchResult.group()) else: print("No match was...
8fc6d2a8049230432ea9ddf5f7187c07d8127961
maalik-mcburrows/Week-1-Exercises
/DC Week 1/ex_8_tip_calc.py
838
4.15625
4
bill_amount = float(input("Total bill amount? ")) service_lvl = input("Level of service? Good/Bad/Fair? ").lower() # set .lower because this will return the users answer in all lower case which is essential for the code to be able to read the if statements if service_lvl == "good": tip_amount = bill_amount * 0.2 ...
1c645965634fe542f2e047be4c8de81658d1c4ed
donRumata03/Experiments
/AstronomyProject/measurements.py
2,766
3.625
4
import json import math import numpy as np from typing import * from datetime import date, timedelta n_days = 48 initial_date = date(2020, 9, 24) """ Day index starts from zero for the first measurement day and is [0, n_days) In GoogleDocs(https://docs.google.com/spreadsheets/d/1F_DoQ4brBQePHNCiOVG615uoBIPiO2jD...
bace6854513e0a07c65432d186c5e8ceabb7ba85
linch433/diffi_helman
/main.py
971
3.953125
4
import random import math def is_prime(a): if a == 2: return True elif (a < 2) or ((a % 2) == 0): return False elif a > 2: for i in range(2, a): if not (a % i): return False return True def CheckIfProbablyPrime(x): return pow(2, x - 1, x) == 1 ...
5c5361fbe1ea81d405a3c2d5c61ea88ba3111e21
nikhil-shukla/GitDemo
/pythonProject/oopDemo/InheritanceDemo1.py
294
3.640625
4
#SingleLevel Heritance class Base: name="nikhil" def baseMethod(self): print("I'm in base class") class Child(Base): company="nik" def childMethod(self): print("I'm in child class") c= Child() c.childMethod() #b= Base() c.baseMethod() print(c.name,c.company)
1f48171c91e2ecf8c05cd1da446db601a87b8cb4
crato-thaissa/crato-thaissa.github.io
/python/inicio.py
2,956
4.09375
4
a = 1 + 2 print(a) # Tipos básicos a = 1 # inteiros b = 1.2 # ponto flutuante c = "c" # string d = 'Hello mundo' # string e = d[3] # "caractere" print(a,b,c,d,e) # Operadores Aritméticos: + - + / // & ** # a <op>= b ======= a = a <op> b x = 1 + 2 # soma y = 4 - 3 ...
80e75012aa401ac7c5d504b1efefcafeefc744c5
zhuolikevin/Algorithm-Practices-Python
/Google/numberOfIsland.py
875
3.515625
4
class Solution: def numberOfIsland(self, matrix): if not matrix or not matrix[0]: return 0 count = 0 m = len(matrix) n = len(matrix[0]) for i in range(m): for j in range(n): if matrix[i][j] == 1: count += 1 s...
298fab86703c4ade18560ef901cb048f33bde0c7
yllausac/programmers
/연습장.py
65
3.578125
4
array = ['a', 'b', 'c', 'd', 'e'] print(array[::-1]) ##내일
162fffb5977c1aab6768de347f43f8251ef9bd1e
vwinkler/LDE-Solver
/tests/TrivialEquationTests.py
684
3.5
4
import unittest from LinearDiophanticEquation import LinearDiophanticEquation from DiophanticSum import DiophanticSum class TrivialEquationTests(unittest.TestCase): def setUp(self): self.equation = LinearDiophanticEquation() self.equation.addVariable("x1", 1) self.equation.addVariable("x2",...
f1246ca7561ec4fb8ff2f9a05c786208ecda6c9c
Yensj/learn_python
/age.py
555
4.0625
4
#... user_age = float(input("Укажите ваш возраст: ")) if user_age < 7: print('Скорее всего вы посещаете детский сад') elif 7 <= user_age < 18: print('Скорее всего вы ходите в школу') elif 18 <= user_age < 23: print('Скорее всего вы учитесь в институте') else: print('Скорее всего вы работаете') #n_chec...
469e0f7baf4be6dcd467e3110ac922b3ca7ad5bc
da1907/AlgorithmWithPython
/withPython/Programmers/week02/올바른괄호.py
321
3.578125
4
def solution(s): for i in s: if i == '(': stack.append(i) else: if len(stack): stack.pop() else: return False if not len(stack): return True else: return False stack = [] s = list(input()) print(solution(s))...
f247d4432a3d7764f3213621c3106964044713b2
fatecspmanha182/IAL-002-algoritmos_e_logica_de_programacao
/Resolução-Exercícios-Parte1/ALP_Lista1-07 (sem lista).py
476
4
4
""" Dada uma lista de números reais terminada pelo número 99.99, imprima cada número lido. No final, imprima a média aritmética de todos os números da lista (É claro que o nº 99.99 não faz parte da média). """ lista = n = cont = 0 while n != 99.99: n = float(input("Digite um elemento para lista (caso queira parar...
49a7634a42dd5818ef238f5a76c9ac0cbdeb558d
sanvedj/MayuriC2WT
/Daily Flash/week 4/day 1/18-DailyFlash_Solutions/3_Feb_Solutions_One/Python/program5.py
214
3.859375
4
def powerOf10(under,upper): while upper!=0: under = 10*under upper = upper - 1 return under num = input("Enter the number : ") ans = (powerOf10(10,num)-(9*num)-10)/9 print(ans)
00944b1b7af980ca2de2f8323dbb14e4d5204c39
b96705008/py-lintcode-exercise
/basic/ch2/sqrt2.py
730
4.34375
4
""" Description Implement double sqrt(double x) and x >= 0. Compute and return the square root of x. Notice You do not care about the accuracy of the result, we will help you to output results. Example Given n = 2 return 1.41421356 """ from __future__ import division def sqrt(x): if x == 0.: return 0. elif x =...
f817e534466fa3338ac319d44fd7d17467f0e7f3
jkfer/LeetCode
/Accounts_Merge.py
1,714
3.859375
4
# https://leetcode.com/problems/accounts-merge/ # 721 # Medium - Failed """ Refered solution: Must spend more time to understand DFS solution. """ import collections class Solution: def accountsMerge(self, accounts): email_to_name = {} graph = collections.defaultdict(set) for acc in acco...
675f5a2e4872029d91aa1303ff228e59748bd517
supermitch/Chinese-Postman
/chinesepostman/my_iter.py
436
3.96875
4
"""Iterator related helper functions.""" def flatten_tuples(iterable): """ Flatten an iterable containing several tuples, into a single tuple. Sum all tuples, which "extends" them, with empty tuple as start value. """ return sum(iterable, ()) def all_unique(iterable): """Returns True if all ...
e2f8d709a76f7bb2677ba2721d038f0c03a42d34
jayeshhiray1/PythonBasicsCode
/Scope_LifetimeVariables.py
645
3.9375
4
def my_func(): x = 10 print("Value inside function:",x) x = 20 my_func() print("Value outside function:",x) #user defined function def add_numbers(x,y): sum = x + y return sum #Global vs. Local variables num1 = 5 num2 = 6 print("The sum is", add_numbers(num1, num2)) total = 0; # This is global variable. # F...
868987ee02a2528060bb9a85b8907b5548b475cf
daydreamboy/HelloPython
/python_basic/13_argparse_arguments_set_variable_name.py
524
3.5625
4
# Usage: # $ python3 13_argparse_arguments_set_variable_name.py -v 1 -s 3 import argparse # Create the parser my_parser = argparse.ArgumentParser() # Add the arguments # Note: dest to rename variable name for the argument my_parser.add_argument('-v', '--verbosity', action='store', type=int, dest='my_verbosity_level...
0f844c9b80e20250f51b7b9c8b5d4f3ce308f02c
mdelmas/adventOfCode2019
/day5/part2.py
1,710
3.71875
4
import math def add(a, b): return a + b def multiply(a, b): return a * b operations = { 1: add, 2: multiply } def runIntcodeProgram(program): i = 0 while i < len(program): opcode = program[i] % 100 if opcode == 99: break if opcode == 1 or opcod...
4b32d1a8fcf1aefd547f9ab82d9b0dd5a84123c3
robbintt/PythonScraper
/json_aggregator_test_old/json_data_aggregator.py
4,368
3.703125
4
import json import os import md5 """ Purpose: This module is designed to combine all the json files in a directory into one json file. """ directory_to_use = "./sfbay_data_052013/" ### include a trailing / output_path_and_filename = "./sfbay_data_052013.json" def import_file ( json_file_name, directory_to_use )...
165fc82345e16c57527fd629e0ef572fb091636c
mikeyii/pyimgbot
/grabPixels.py
2,100
3.75
4
#!/usr/bin/env python3 # grabpixels.py - grab pixels and save them with name from pymouse import PyMouse from PIL import ImageDraw, ImageGrab from string import Template m = PyMouse() retina = True def isYes(value): return value.lower() in ('y', 'yes') def savePixel(): x, y = m.position() im = ImageGrab...
f22cd99f4430523b8320bd4a7416c4ce45e1cb61
SUPERPANDA-ORANGE/leetcode
/two sum/two_sum.py
624
3.671875
4
class Solution: """ @param: numbers: An array of Integer @param: target: target = numbers[index1] + numbers[index2] @return: [index1 + 1, index2 + 1] (index1 < index2) """ def twoSum(self, numbers, target): # write your code here list1 = [] for index in range(len(numbers)...
109b446b6866d1210a767d35f37ad6b25b835d3b
luginin-Ivan/dz-by-algoritm-
/18.py
174
3.765625
4
a = int(input("введите a :")) b = int(input("введите b :")) c = int(input("введите c :")) min=a if min>b: min=b elif min>c: min =c print(min)
55e88070c73c02f933c8abf3bafef1aff8ef90ec
Th0rt/study-programing-skill
/chapter4/question12.py
1,079
3.765625
4
def count_root(threshold, tree): return _count_root(threshold, tree.root) def _count_root(threshold, node, interims=[], root_count=0): if node is None: return root_count interims.append(0) # node単体の値を計算対象に入れるため、0を加える equals, smalls = add_and_filter( nums=interims, additional=node.val...
d9c16334cae02d7ba2379cbef76b5a082a3140ee
EMI322585/ILZE_course
/PYTHON/list_functions.py
1,654
3.703125
4
import json def print_introduction(): print("Ja vēlaties apskatīt sarakstu, nospiediet R (Read)") print("Ja vēlaties pievienot piezīmi, nospiediet A (Add)") print("Ja vēlaties iziet no saraksta, nospiediet X (Exit)") print("Ja vēlaties izdzēst kādu piezīmi, nospiediet D (Delete)") print("Ja vēlatie...
a4d68e273a655c76ac0aac68a2d92b4c15aa5757
KendallWeaver/3670ScriptingForAnimationAndGames
/Nov 15 Lecture/Nov15LectureScript.py
1,204
4.09375
4
#Classes #Other Classes can inherit attributes from other classes. #dot operator can access components from other classes to use. import maya.cmds as cmds #you have class variables and instance variables #self is a special work to create an instance #its referring back to the template itself #so feet = 4 is...
50fa7aba73e43848677698f646ea10b5abb67d34
montse139/Lottery
/lottery.py
389
3.640625
4
import random numbers = [] amount_numbers = [] print "Welcome to the Lottery numbers generator!" user_numbers = int(raw_input("Please enter the amount of random numbers that you would like to have: ")) for i in range(user_numbers): amount_numbers.append(i) for i in range(1,100): numbers.append(i) print random...
41cddb365ff1bdcd28670f0b344a8f2e6a684295
muyawei/DataAnalytics
/Data_analystic/test/read_text.py
466
3.8125
4
# coding:utf-8 f = open("foo.txt") # 返回一个文件对象 line = f.readline() # 调用文件的 readline()方法 while line: print line, # 后面跟 ',' 将忽略换行符 # print(line, end = '')   # 在 Python 3中使用 line = f.readline() f.close() for line in open("foo.txt"): print line, f = open("c:\\1.tx...
4f8a1083ff281ffe89d98a8202803669370dd3db
Achyu02/CompetitiveProgramming
/Week1/Day1/apples.py
1,492
3.875
4
def get_maximum(stock_prices): if len(stock_prices) < 2: raise ValueError('Minimum of 2 prices') minimum = stock_prices[0] maximum = stock_prices[1] - stock_prices[0] for i in xrange(1, len(stock_prices)): present = stock_prices[i] profit = present - minimum maximum =...
0136a499188854124db0c33462c19340ee5a5911
ukoloff/sorts.py
/algo/bubble.py
313
3.890625
4
# # Bubble sort # def sort(array): for i in range(1, len(array)): swapped = False for j in range(len(array) - i): if array[j] > array[j + 1]: swapped = True array[j], array[j + 1] = array[j + 1], array[j] if not swapped: break
f5917ad3d88f72824b7c86a1726616a7c74c3d27
sidv/Assignments
/Shanu_Abraham/16_aug_assigment_16/string_10_files.py
678
4.15625
4
# Write the above string into 10 files data3.txt,data4.txt and so on.. string = "A computer is a machine that can be programmed to carry out sequences of arithmetic or logical operations automatically. Modern computers can perform generic sets of operations known as programs. These programs enable computers to perfor...
5769f17439f6672335ba2781b6121e54d5ab5da0
kryptn/euler
/p36.py
203
3.546875
4
def palendrome(n): n = str(n) if n == n[::-1]: return True return False def answer(limit): return sum([x for x in xrange(limit+1) if palendrome(x) and palendrome(bin(x)[2:])])
2e5014838b9e44b85b4ec5638df5c47c5b1df818
ronny-souza/Lista-Exercicios-05-Python
/Exercicio03.py
325
3.859375
4
# QUESTÃO 03 - Crie uma função que receba do usuário a base (b) e o expoente ​(n), e calcule e retorne ​b​^n. def calculoPotencia(base, expoente): return base**expoente base = int(input("Digite o valor da base: ")) expoente = int(input("Digite o valor do expoente: ")) print(calculoPotencia(base, expoente))
f9eacc43ab2bde0bee2419b7775de855db7a5698
zipxup/ZeroToHero_Python
/HelloWorld/DisplayText.py
590
3.546875
4
print('The capybara is the worlds largest rodent') print("It's a beautiful day in the neighborhood") print('It"s a beautiful day in the neighborhood') print('It\'s a beautiful day in the neighborhood') print("""Hickory Dictory Dock! The mouse ran up the clock I finally find a good video to learn python""") #\\ is us...
cd7b277f59f9e49839edb72772b661219ec4c45a
zjxpirate/Daily-Upload-Python
/Binary_Trees/******Binary_Trees_is_symmetric.py
691
4.09375
4
from Binary_Trees_node import BinaryTreeNode def is_symmetric(tree): def check_symmetric(subtree_0, subtree_1): if not subtree_0 and not subtree_1: return True elif subtree_0 and subtree_1: return (subtree_0.data == subtree_1.data and check_symmetric(subtree_0.left, sub...
0de3301077d96c59425ddecdd4306db9fb24e5af
YinongLong/Data-Structures-and-Algorithm-Analysis
/problems/interviews-questions-analysis/judge_pop_order.py
466
3.5625
4
# -*- coding: utf-8 -*- from __future__ import print_function class Solution(object): def IsPopOrder(self, pushV, popV): stack = [] pop_idx = 0 for item in pushV: stack.append(item) while stack and stack[-1] == popV[pop_idx]: stack.pop() ...
d65f5c3eab3d0a687dc4668a99b434c3f9061713
nikita2697/python_practice
/tut_14.py
308
3.9375
4
#while loop """" i=0 while(i<45): print(i,end=" ") i=i+1 #break and continue if i==42: break """ j=0 while(True): #print("enter number") j = j + 1 num= int(input("enter number")) if(num>10): print("num grater than 10") break else: continue
76e62f7ac5b738a99ec1144b759623f9ab5324a4
Aasthaengg/IBMdataset
/Python_codes/p02383/s433411245.py
563
4.0625
4
def north(d): return [d[1], d[5], d[2], d[3], d[0], d[4]] def east(d): return [d[3], d[1], d[0], d[5], d[4], d[2]] def south(d): return [d[4], d[0], d[2], d[3], d[5], d[1]] def west(d): return [d[2], d[1], d[5], d[0], d[4], d[3]] numbers = list(map(int, input().split())) directions = list(input()) ...
ac8aa5c4d6a25a71a9797779113d2381d456ae7d
ngr/sandbox
/python/performance/pattern_search.py
1,233
3.71875
4
""" Benchmark speed of searching the substring in data using different approaches. """ import random import re import string import sys import time from collections import defaultdict PATTERN = 'hello world elisha and nick 123 BAZOOKA' DATA_SIZE = 1000000 NUM_TESTS = 1000 NUM_DATASETS = 10 if sys.version_info < (3,...
898889d64cd7ed95fcf1f8612c11ea536cb639d5
qiyon/leetcode
/algorithms_001-050/005_Longest-Palindromic-Substring/py_solution.py
723
3.5
4
##leetcode submission begin ----------------------- class Solution: # @param {string} s # @return {string} def longestPalindrome(self, s): subStr = "" for i in range(0, len(s)): for k in range(0,2): tmp = self.getSubStr(s, i, i+k) if len(tmp) > le...
0d5a6b11ca60f8f45f50bf2d5d60ea4f544cfa61
xLuis190/Python-School-work
/anagrams.py
141
3.796875
4
def isAnagram(word1,word2): word1 = sorted(word1.lower()) word2 = sorted(word2.lower()) return "".join(word1) == "".join(word2)
7dd9b4487eaab12819da3dbc1954fe00698db59a
richierh/LearningPy
/GUIExamps/MyOwnProject/Model/objectdb.py
492
3.640625
4
#!usr/bin/env python # -*- coding: utf-8 -*- def insert(): # Will insert data return True def delete(): # Will delete data return True def erase(): # Will erase data return True class Cup: def __init__(self): self.__color = "hello" self._content = None # protected variable ...
d36f757509b3875639eedf853a2ff788f09e994b
muhammadmuzzammil1998/CollegeStuff
/MCA/Data Structures/Stack_pop_linkedlist.py
2,370
4.15625
4
class LinkedList: class Node: def __init__(self, data): self.data = data self.next = None def __str__(self): return str(self.data) def __init__(self): self.head = None def append(self, data): if self.head == None: self.head =...
3a52ac0ded59e4f41b4ac075d3f4a44f9ed23db8
lolilo/coding_exercises
/raw_input_from_terminal/arithmetic_progression.py
1,895
4.0625
4
# user_input = raw_input() # arithmetic progression. # two lines of raw input (stdin), first one being length of given progression, second the arithmetic progression # find the missing number and print it to stdout # Enter your code here. Read input from STDIN. Print output to STDOUT #user_input = user_input.split(...
86ae392fe301f37d3507499c72914a3c1b331f09
kmprashanthi/DataStructuresPractise
/chk_arr_sort.py
154
3.765625
4
def sorted_array(A): if len(A)==1: return True return ( A[0]<=A[1] and sorted_array(A[1:])) A = [1,2,3,10,5,6,7] print (sorted_array(A) )
ba416e47609c529d9f40edaaed023bf6759047c7
AndriiDiachenko/pyCheckIo
/1_Elementary/split-pairs.py
469
4.5625
5
''' Split the string into pairs of two characters. If the string contains an odd number of characters, then the missing second character of the final pair should be replaced with an underscore ('_'). Input: A string. Output: An iterable of strings. Example: split_pairs('abcd') == ['ab', 'cd'] split_pairs('abc') == [...
913d44d328637cc90b58c22aa5565fb1125ba0d8
xzpjerry/learning
/Coding/playground/sorting/linear_find_small.py
418
3.546875
4
#!/usr/bin/env python3 ''' Author: Zhipeng Xie Topic: Effect: ''' import random def test(datal): current_smallest = [datal[0]] for num in datal: if num > current_smallest[0]: current_smallest.pop() current_smallest.append(num) return current_smallest[0] if __name__ == '_...
f95899b13618e5afc9778ae333499451b5b911b6
Crismarquez/nlp
/utils/util.py
14,014
3.546875
4
""" This is the documentation for this module """ import random from typing import List from typing import Optional from typing import Dict import re import string import numpy as np import pandas as pd np.random.seed(0) def gen_vocabulary(corpus: List[str]) -> List[str]: """ get the corpus vocabulary ...
719a920ca1f1be6fb3c3eab10bd718a3c82987d3
j-bro/comp479-project2
/src/main/python/collection/collection.py
1,885
3.59375
4
class CollectionInfo: def __init__(self, document_count=0, token_count=0, avg_doc_length=0): """ Class representing the collection info of a collection. :param document_count: the number of documents in the collection. :param token_count: the total number of tokens in the collecti...
67e2c1b5c55402291bda1efbfb47b4342846dd20
wsbrandow/Minor-Python-Projects
/List Median Finder.py
228
3.640625
4
def median(x): xsort = sorted(x) if len(xsort) % 2 == 0: right = len(xsort) / 2 left =(len(xsort) / 2) - 1 return (xsort[right] + xsort[left]) / 2.0 else: return xsort[len(xsort) / 2]
f9418dd9f10869570e937264b1f85cf984322cfa
techkids-c4e/c4e5
/Pham Quang Huy/26.6.2016/List_assignment1.py
531
4.125
4
color_list = ['Blue','Red','Black','Pink','Brown','Yellow'] print('My color list: ') print(color_list) print('Color_list at index 3: ',color_list[3]) i = input('Enter a number for 0-5: ') i = int(i) print('Your color: ',color_list[i]) print(color_list) for color in color_list: print(color) fav_color = input('Whats ...
2c9e176857eb46615f894edc7cec076325540a6c
AdamZhouSE/pythonHomework
/Code/CodeRecords/2840/60678/261461.py
305
3.546875
4
def countLuckyNum(string): count = 0 for i in string: if i == '4' or i == '7': count += 1 return count nANDk = input().split() n = int(nANDk[0]) k = int(nANDk[1]) nums =input().split() count = 0 for i in nums: if countLuckyNum(i) <= k: count += 1 print(count)
38adf9c060437b7097324986f7a2c0cd03b5f99b
noahfp/Project_Euler
/p063.py
283
3.71875
4
import math def power_digits(n, d): return [i**n for i in range(int(math.ceil(math.pow(10,(d-1)/float(n)))), int(math.ceil(math.pow(10,d/float(n)))))] # testing gives 9^21 largest power which is still 21 digits long. print sum([len(power_digits(n,n)) for n in range(1, 22)])
7d88ff4bef4119e9b77552109dc7132624a09db6
anton-dovnar/checkio
/ElectronicStation/words_order.py
2,057
4.15625
4
#!/home/fode4cun/.local/share/virtualenvs/checkio-ufRDicT7/bin/checkio --domain=py run words-order # You have a text and a list of words. You need to check if the words in a list appear in the same order as in the given text. # # Cases you should expect while solving this challenge: # # a word from the list is not i...
10cf227b643a0e70977c365f4fc36693c390626b
Pradas137/Python
/Examen/figuras_recursive.py
2,956
4.03125
4
def printstack(n, indent=0): if n > 0: printstack(n-1, indent+1) print(' '*indent + '* '*n) #printstack(3) printstack(3,5) #printstack(3,1) """ def draw_triangle(n): if n == 0: return '' else: return ("*" * n + '\n') + draw_triangle(n - 1) def main(): num = int(input("En...
2cb30a07cc8413bc72d12f4e1f7e9e34247ce9d2
Demoleas715/PythonWorkspace
/Notes/DistanceTable.py
161
3.609375
4
''' Created on Oct 8, 2015 @author: Evan ''' m=1 print("%10s %20s" % ("Mile:", "Kilometer:")) while m<10: k=1.609*m print("%10d %20f" % (m, k)) m+=1
5a25a910a2690359e89f937908a27940785d5a10
amrinder07/CAP930Autumn
/tuple.py
222
3.8125
4
#Tuples are immutable, store heterogeneous data me=("amrinder","male",23) print(me) print(me[1]) print(len(me)) print(me[:3]) print("male" in me) a1=123,'abc',69.69 print(a1) a,b,c=a1 #unpacking print(b)
e16c41fb112c8f763b123b352598906ca11915a3
MadWookie/Survivor-Bot
/utils/utils.py
278
3.765625
4
def wrap(to_wrap, wrap_with, sep=' '): return f"{wrap_with}{sep}{to_wrap}{sep}{wrap_with}" def unique(it, key): new = [] added = [] for i in it: k = key(i) if k not in added: new.append(i) added.append(k) return new
f07678c16dc8ecbea9bc0e114f3c17f54e41a6ce
from0to100/guess_num
/guess_answer.py
705
3.9375
4
# 產生一組隨機整數1~100 # 讓使用者重複猜 # 告知結果比答案大/小 # 答對的話終止程式,並印出答對了 # 印出答了幾次,讓使用者自己輸入起始和結束值 import random start = input('請輸入起始值:') end = input('請輸入結束值:') start = int(start) end = int(end) x = random.randint(start, end) count = 0 print('請從', start, '~', end,'間猜一個數字') while True: count += 1 # count = count + 1 num = input('請輸入數...
2f0c489ff3f8cb4527b4202610e873e96a471fc9
joshuaknight/myprograms.com
/game/passage.py
1,262
3.59375
4
import forest class Passage(object): def start(self): print "\nAfter,Which you enter a dark passage and near a bush you find a shotgun" print "\nYou Take the shotgun,and go along the passage" print "\nYou are tired from walking and see a shelter" print "\nYou Go and take rest in the Shelter,Where you meet a O...
da482ab10a752cd0e055843318f81877b92c6f16
TheoWckr/TaxiSolver
/brutforce_algorythm.py
425
3.515625
4
import math import random import gym env = gym.make('Taxi-v3') epis = 1 turn = 0 allR = 0 for i in range(epis): wait = True r = 0 while(wait) : s = env.reset() next_move = random.randint(0,5) s1, r, d, _ = env.step(next_move) if d == True: print('Won') ...
1a9c2695fd3f195efd29be801ff73d4cd185f6e4
Dinaim/Week3-task9
/task9.py
501
4.0625
4
# Напишите функцию которая принимает число 'N' и # возвращает квадраты всех натуральных чисел кроме числа 'N', в порядке возрастания # например если число 'N' = 4 ,то должен выйти список из чисел: 0,1,4,9 def Number_N(): a = int(input()) new_list = [] for num in range(a): new_list.append(num**2) ...
9587cd8cb1feaa250856098b0fb048aeea8b1489
chathuraw/slbiobot
/scripts/inserter
718
3.734375
4
#!/usr/bin/env python # This script reads a list of twitter screen names from NEW_FILE and # populates them in USER_LIST_FILE if they're missing there import os USER_LIST_FILE='users.txt' NEW_FILE='new.txt' fh = open(USER_LIST_FILE, 'r') fnew = open(NEW_FILE, 'r') orig=[] while 1: name = fh.readline().strip()...
9e1a9b3f57c9dab0c5a1657216c5e041f055a051
tjatn304905/algorithm
/APS/6.Queue/queue.py
931
4.125
4
class Queue: def __init__(self): self.data = [] def enqueue(self, elem): self.data.append(elem) def dequeue(self): return self.data.pop(0) def is_empty(self): return not bool(len(self.data)) # 삭제 없이 단순히 맨 앞의 data 값을 리턴 def get_front(self): if self.is_e...
1fad13d7b9ceabf329cbc0f37ee11c7fb69ef3a6
elsud/homework-repository
/homework12/models.py
8,076
3.671875
4
"""Creating dabase main.db using SQLAlchemy and creating tables homework, homework_results, students, teachers in it. Also start session which should be closed. """ import datetime from sqlalchemy import ( Column, DateTime, ForeignKey, Integer, Interval, String, create_engine, ) from sqlalc...
c8231fdd48c7bc221dea3980f9fff5801760325a
matuse/PythonKnights
/Ch13/test.py
176
3.703125
4
import string line = "I! want. to, eat# some@ and$ then% some^ please?" for word in line.split(): print word.strip(string.punctuation).lower()
9bf6e9ef3f7487815562455940b630e76b3cf752
xcrema/python_workspace
/Input print Sum of three numbers/untitled16.py
318
3.875
4
# -*- coding: utf-8 -*- """ Created on Thu Oct 8 11:25:04 2020 @author: Achyut Statement Write a program that takes three numbers and prints their sum. Every number is given on a separate line. Example input 2 3 6 Example output 11 """ a = (input()) b = (input()) c = (input()) print(int(a) + int(b) + int(c))
5a036f5bb1906fa46344e96a09a3052676f1e971
andrewteece/Data-Structures
/mbox.py
279
3.625
4
fhand = open('mbox-short.txt') for line in fhand: line = line.rstrip() if not line.startswith('From ') :continue words = line.split() email = words[1] pieces = email.split('From') print pieces[0] #print "There were", pieces,"lines in the file with From as the first word"
a3910bf7f2bed827710c108209129e990e38b35c
Xinyuan-wur/algorithms-in-bioinformatics
/graphs/assignment3_skeleton.py
3,621
3.90625
4
#!/usr/bin/env python """ Author: Xinyuan Min Student nr: 950829573070 Script to: """ # Import statements # Implement your functions here def is_eulerian(graph): # use set() to get every distinct node in graph vertices = set() for key_value in graph.items(): vertices.add(key_value[0]) for...
6936bc798f8d1ad679ca75dbaf7fda90f5e09b77
MarkGasse/Huiswerk-TCTI-V2ALDS1-11_2018-
/week5/week5_1.py
6,407
3.5
4
class myqueue(list): def __init__(self, a=[]): list.__init__(self, a) def dequeue(self): return self.pop(0) def enqueue(self, x): self.append(x) class Vertex: def __init__(self, data): self.data = data def __repr__(self): # voor afdrukken return str(self...
f56e46a1e3603481980ac2c51d95663ef2b778a5
sujiea/hackerrank-codility
/cba.py
379
3.65625
4
import re def solution(S): # write your code in Python 3.6 print(re.search(r"(?!$)a*b*", S).groups(0)) if re.match(r"(?!$)a*b*", S).span()[1] == len(S): return True else: return False print(solution("aabbb")) print(solution("a")) print(solution("b")) print(solution("aa")) print(soluti...
0ff1842d2cef8e1189d217725783094a7f56bcf7
rahil1303/dictionary_usingPython
/3_Update_and_Insert.py
173
4.0625
4
### Insert myDict = {"name": : "Eddy", "age" : 26} myDict['age'] = 27 print(myDict) ### Update myDict = {'name' : 'Eddy', 'age' : 26} myDict['city'] = London print(myDict)
32bef534ae031cddd4b94bc12aee2860bd2decb7
kashyap79/Python_beginner
/one.py
170
3.578125
4
print("Hello World") def add(a,b): return a+b def sub(a,b): return a-b def multiply(a,b): return a*b print"Bye World" def square(x): return x**2
90bb69bd2731ffdabc4b2c1ed951856be5a68d77
arun777888/classes
/while loop.py
2,594
4.03125
4
#reverse num ''' num= int(input("enter a number =")) num1=num rev= 0 while(num!=0): rem=num%10 rev=rev*10+rem num=num//10 print(rev) if num1==rev: print('num is pallindrome') ''' # factorial of num ''' num= int(input("enter a number =")) fact=1 while (num>0): fact=fact*num ...
95e269801b0891dcaa05229255ae828f83118d81
rprtest/LearnPython
/report_generator.py
2,419
3.75
4
# i2p - Homework - 9 - File Manipulations and Exceptions # By: Roopa Prakash, submitted on: 07/04/2016 import csv from datetime import date def main(): # Sets to store unique values of oc member, region and office data_oc_member = set() data_region = set() data_office = set() # Open the contributio...
4dcac4cd194c25cb68a0d1aa5e4df24e6c735ef2
monkeybuzinis/Python
/6.string/14.py
229
3.84375
4
#14 s=input("write your name: ") new='' for i in range (1,len(s)): if(s[i-1]==" " and s[i].isalpha()): new+=s[i].upper() else: new+=s[i] if(s[0].isalpha): print(s[0].upper()+new) else: print(new)
45d1fcc08aa1ef9edfdab599bafc095f569d11e0
AlexLinGit/SICP-and-Other-Code
/Python Crash Course Exercises/chapter 9 - classes/electric_car_m.py
1,527
4.125
4
from cars import Cars class ElectricCar(Cars): """Represents aspects specific to electric cars""" def __init__(self, make, model, year): """Initializes attributes of the parent class""" super().__init__(model, make, year) self.battery = Battery() def fill_gas_tank(self): """Electric cars d...
0efa684de14be0d88a3c9f73735586dae2b039c4
iamzin/Study-Algorithm
/python/programmers/반복문/[12981_반복문_영어끝말잇기_1]천재승.py
544
3.578125
4
def solution(n, words): word_list=[] for i in range(0,len(words)): # 번호 number=i%n+1 # 차례 cnt=i//n+1 # 탈락조건 if len(words[i])==1 or (i>0 and words[i-1][-1]!=words[i][0]) or (words[i] in word_list): return [number,cnt] # 새로운 단어가 나오면 리스트에 넣어준다. ...
302fa80e70577b1208f230be138e116d4afb193f
dhalik/Econ102Quiz
/encode.py
1,446
3.53125
4
import struct; # Needed to convert string to byte import sys; import os.path; if (len(sys.argv) != 2): print("Run this utility as python encode.py <questionFile.xml>") sys.exit(0) filename = sys.argv[1] if (not os.path.isfile(filename)): print("File passed does not exist or is unusabl...
e81f88238850c81caa1f5979de7859bf837a072f
HBinhCT/Q-project
/hackerrank/Data Structures/Truck Tour/solution.py
788
3.875
4
#!/bin/python3 import os # # Complete the 'truckTour' function below. # # The function is expected to return an INTEGER. # The function accepts 2D_INTEGER_ARRAY petrolpumps as parameter. # def truckTour(petrolpumps): # Write your code here pump = 0 check = 0 for i in range(len(petrolpumps)): ...
9bd186c344342ee48762c8da440b7f23c2214751
binchen15/python-tricks
/collections_demo/demo_OrderedDict.py
451
4.34375
4
from collections import OrderedDict #dict subclass that remembers the order in which that keys were first inserted. # order is not sort. # it can be used in conjunction with sorting to make a sorted dictionary d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2} print("order by name") od = OrderedDict(sorted(d.item...
a8f3afc912b923234b89973728a4fb03bfd276d5
best738/automate-your-page
/Project 2 Notes/Project_2_python.py
3,100
4.15625
4
def generate_concept_html(concept_title, concept_description): html_text_1 = """ <div class="concept"> <div class="concept_title"> """ + concept_title html_text_2 = """ </div> <div class="concept_description"> <p> """ + concept_description html_text_3 = """ </p> </div> </div>""" full_html = html_text_1 ...
5d2f625c5929ceb77aa801770935878a3b906d91
mnmhouse/php_scraping
/scrapy_web/scrapy.py
1,227
3.578125
4
from urllib.request import urlopen from urllib.error import HTTPError from bs4 import BeautifulSoup import sys url = "http://www.pythonscraping.com/pages/warandpeace.html" # # import re # # pages = set() # def getLinks(pageUrl): # global pages # html = urlopen('http://www.sina.com') # bsObj = BeautifulS...
417320d54018187b4eb91097abe43022a96f8813
xiaxiaochao1103/test_demo
/study_ex/20200123.py
10,940
4.125
4
#!/usr/bin/python # -*- coding: UTF-8 -*- # 86、找到某dict种包含指定key的dict.根据drink找到他的上级dict,即eat,并返回eat的内容 # dict_data = { # "name": "smith", # "age": 22, # "hobby": { # "read": "book", # "watch": "video", # "eat": { # "food": "中国菜", # "drink": "water", # ...
8b30d86175b2eb7b9e0c757da4fb33aaf01d6360
alejamorenovallejo/retos-phyton
/Ejercicio/Retos/Reto2.py
2,132
3.859375
4
respuesta = "s" while respuesta == "s" or respuesta == "S" or respuesta == "si" or respuesta == "SI": #Declaracion de Variables cotizacion=[] suma = 0 #Solicitud NIT,Nombre y Valor for indice in range(5): nit = input("Ingrese el NIT: ") while nit == '': nit = input("Ingr...
65f97399be1c7e6375f45a2cb80213f7e6adaf09
dennerepin/StochNetV2
/stochnet_v2/utils/errors.py
793
3.5
4
class ShapeError(Exception): """Exception raised for errors in the input shape. Attributes: message -- explanation of the error """ def __init__(self, message='Wrong shape!'): self.message = message class DimensionError(Exception): """Exception raised for errors concerning the di...
7cc301e602806d8e8fa38a198c678a6e57924f55
ParalogyX/combinations_permutations
/combperm.py
9,746
4.125
4
# -*- coding: utf-8 -*- """ Created on Sat Jan 16 11:36:21 2021 Functions to calculate combinaions and permutations @author: vpe """ import itertools def factorial(n): """ Calculates factorial of n Parameters ---------- n : int Positive integer. Returns ------- factorial : ...