blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
3815c6e69d38d1380917ed90ad028e2b20c97c9e
emmaloo/Comp-Class
/cypher.py
1,053
3.859375
4
alphaboot = 26 def getType(): while True: print('Are you going to encrypt or decrypt?') mode = input().lower() if mode in 'encrypt e decrypt d'.split(): return mode else: print('Enter "encrypt" or "e" or "decrypt" or "d".') def getMessage(): print('Message:') return input() def getKey(): key = 0 w...
9c79d6c1a57525ed63b7dc1e01a7abcb2e60af7a
Eacaen/diff_Code_Learn
/python/源代码/第四章/4_3.py
3,103
4.21875
4
dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"} print (dict) print (dict["a"]) # 打印键a对应的值 dict = {1 : "apple", 2 : "banana", 3 : "grape", 4 : "orange"} print (dict) print (dict[2]) #字典的添加、删除、修改操作 dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"} dict["w"] = "watermelo...
364f43ef65b5fe296f4cdfd4d9b08c244471a15d
Eacaen/diff_Code_Learn
/python/源代码/第十七章/17_9.py
626
3.53125
4
import threading import random, time class ThreadLocal(): def __init__(self): self.local = threading.local() #生成local数据对象 def run(self): time.sleep(random.random()) #随机休眠时间 self.local.number = [] for i in range(10): self.local.number.append(random.choice(range(10)))...
4bcf6420379dd97b8aff6f2c7b2cd3e47ce09629
Eacaen/diff_Code_Learn
/python/源代码/第十七章/17_8.py
568
3.671875
4
import threading import time class ThreadDemo(threading.Thread): def __init__(self, index, create_time): #线程构造函数 threading.Thread.__init__(self) self.index = index self.create_time = create_time def run(self): #具体的线程运行代码 time.sleep(1) #休眠1秒钟 print ((time.time()-self.crea...
6a2e329248c64ae2bbdd5ee4792b8d6911b794dc
Eacaen/diff_Code_Learn
/python/源代码/第三章/3_6.py
202
4.09375
4
# for in语句 for x in range(-1, 2): if x > 0: print ("正数:",x) elif x == 0 : print ("零:",x) else: print ("负数:",x) else: print ("循环结束")
dc95d4d1ef52a632b83cee6c1dfe48735e4d2fbe
Eacaen/diff_Code_Learn
/python/源代码/第四章/4_2.py
2,133
4.5
4
list = ["apple", "banana", "grape", "orange"] # 定义列表 print (list) print (list[2]) list.append("watermelon") # 列表末尾添加元素 list.insert(1, "grapefruit") # 列表中插入元素 print (list) list.remove("grape") # 列表中移除grape print (list) list.remove("a") # 列表中移除...
0118f3a81fb9ed5d717fee92f8ecf19dc5d1dbaf
Eacaen/diff_Code_Learn
/python/源代码/第八章/8_15.py
734
4
4
class Factory: # 工厂类 def createFruit(self, fruit): # 工厂方法 if fruit == "apple": # 如果是apple则返回类Apple return Apple() elif fruit == "banana": # 如果是banana则返回类Banana return Banana() class Fruit:...
88651570afcf9c0eea71aeec5cd2b69914d23fce
Eacaen/diff_Code_Learn
/python/源代码/第五章/5_5.py
283
4.21875
4
# 传递可变参数 def search(*t, **d): keys = d.keys() values = d.values() print(keys) print (values) for arg in t: for key in keys: if arg == key: print ("find:",d[key]) search("one", "three", one="1",two="2",three="3")
ee0cdf494431008d12a1669258acc850b17c54e2
Eacaen/diff_Code_Learn
/python/源代码/第十二章/12_4.py
663
3.6875
4
from tkinter import * root = Tk() root.title("顶层窗口") f1 = Frame(root) # 定义框架 Label(f1, text="标准输入框: ").pack(side=LEFT, padx=5, pady=10) e1 = StringVar() # 定义输入框内容 Entry(f1, width=50, textvariable=e1).pack(side=LEFT) # 基本的输入框 e1.set('输入框默认内容') # 设置一般输入框默认内容 f1.pack() f2 = Frame(root) # 定义框架 e2 = StringVar() Label...
1ad5a82af79df065fd92a5b2b4be0d476cb20c28
Eacaen/diff_Code_Learn
/python/源代码/第五章/5_10.py
251
3.65625
4
# 嵌套函数 def func(): x = 1 y = 2 m= 3 n = 4 def sum(a, b): # 内部函数 return a + b def sub(a, b): # 内部函数 return a - b return sum(x, y) * sub(m, n) print (func())
baca9f2f71705965e12ea831c411699355337431
timjinx/Sample-Repo
/Codewars/parityOutlier.py
404
3.890625
4
def findOutlier(integers): ofound = 0 efound = 0 ocnt = 0 ecnt = 0 for el in integers: if (el % 2 == 1): ofound = el ocnt += 1 else: efound = el ecnt += 1 return(efound if ocnt > ecnt else ofound) print("The outlier is %s" % findO...
dffba0f916052b38a24c178172576196b838dcd5
prathmeshranaut/python-graphs
/bellman_ford.py
841
3.640625
4
# Bellman Ford Algorithm finds distance between a node and # other nodes in a graph with negative weights def bellman_ford_distance(graph: dict, start: str): dist = {x: 99999 for x in graph} dist[start] = 0 for i in range(len(graph)): for key in graph.keys(): for node in graph[key]: ...
a6232bfa66d1f9d6537ddf9cd1776227f770b567
Kenstogram/opensale
/saleor/payment/gateways/stripe/utils.py
1,880
3.671875
4
from decimal import Decimal # List of zero-decimal currencies # Since there is no public API in Stripe backend or helper function # in Stripe's Python library, this list is straight out of Stripe's docs # https://stripe.com/docs/currencies#zero-decimal ZERO_DECIMAL_CURRENCIES = [ 'BIF', 'CLP', 'DJF', 'GNF', 'JPY',...
80643d7e0d6a61f11fffe7fb4100d613480beca0
vladciocoiu/chess
/pieces.py
16,243
4
4
import pygame import board pygame.init() global whiteKing global blackKing global currentPiece global fiftyMove # this function initializes the board and the starting pieces on their starting squares def initGame(): board.initBoard() global whiteKing global blackKing global currentPiece # the cu...
e9804974ab4940bf4307642ee368f90da889628c
kenzoyan/vis-ForceDirectGraph
/quadT.py
2,339
3.609375
4
import random import math import time class Node: def __init__(self,x,y): self.x=x self.y=y class Rectangle: def __init__(self,x,y,w,h): self.x=x self.y=y self.w=w self.h=h def contains(self,Node): return (Node.x>=(self.x-self.w) ...
889f01b5ed59122a4e3e9ec3537f437a6675fd72
CodeNameMS/CodeName_MS_Python
/class_13.py
4,124
3.578125
4
#append() : 제일 뒤 값에 추가 (무조건 맨 뒤) #pop() : 제일 뒤 값을 빼고 빼낸 값을 리스트에서 삭제 (로또) #sort() : 항목 정렬 #reverse() : 항목 순서를 역순으로 (역순 정렬은 sort 후 reverse) #index() : 지정한 값을 찾아 그 위치를 반환 #insert() : 지정된 위치에 값 삽입(삽입한 위치부터 리스트의 인덱스가 뒤로 밀림) #remove() : 리스트에서 지정한 값을 제거, 지정한 값이 여러 개일 경우 첫번째 값만 삭제(값을 삭제) #extend() : 리스트 뒤에 리스트를 추가, 더하기(...
24f95f3364dfa0611c1d42270c07c5b672732ff1
apoorvaanand1998/project-euler
/30.py
1,420
3.5625
4
def pow_sum(n, e): res = 0 while (n > 0): res += (n % 10)**e n //= 10 return res ans_list = [] for i in range(2, 360000): if i == pow_sum(i, 5): ans_list.append(i) print(ans_list, sum(ans_list)) ##################################################################################...
8c8526b3be18a87161d99e7a5e2c1a06c50a4234
apoorvaanand1998/project-euler
/31.py
697
3.578125
4
######################################################################################################################## # How many different ways can 2 be made using any number of coins? 1p, 2p, 5p, 10p, 20p, 50p, 1 (100p) and 2 (200p) # #################################################################################...
667f69a9f9ce1f9639c0ae630263583e60ae091f
HoanggAnhHao/hoanganhhao-fundamentals-C4E25
/session1/turtle_intro.py
187
3.84375
4
from turtle import * shape("turtle") speed(0) for i in range(300): for j in range(4): forward(100) left(90) left(7) print("bye bye") mainloop()
90f8890de60f5f436ec8edddecddb3f4c3573113
paliwalshubham/Rock-Paper-Scissor
/rockpaperscissor.py
4,783
3.96875
4
#import random #name1 = str(input("enter name")) ##rock =1 #paper =2 #scissor =3 #x=y=z=0 # #while True: # print("Press 1 Rock 2 Paper 3 Scissor") # user1 =int(input("choose choice")) # comp =[1,2,3] # random.shuffle(comp) # computer = random.randint(1,3) # # # if user1==compu...
3d5c6cde9ef30827930d724b7085519c05704ff5
itsMagondu/micropilot-entry-challenge
/itsmagondu/test_count_zeros.py
377
3.5
4
import unittest from count_zeros import CountZeros class TestCountZero(unittest.TestCase): def test_count_zeros(self): numbers = [1, 0, 5, 6, 0, 2] self.assertEqual(CountZeros(numbers), 2) def test_invalid_data(self): numbers = 'invalid data type' with self.assertRaises(TypeError): CountZero...
127f905ba8c2834a8f686a57c753f748b112f42c
buxizhizhoum/tool_scripts
/app/bin/file/iter_file.py
386
3.78125
4
#!/usr/bin/python # -*- coding: utf-8 -*- """ iter file line by line until there is an blank line or at the end of file """ def process_line(line): print(line) if __name__ == "__main__": with open('mydata.txt') as fp: # second args of iter() is guard. if value yield from iter = '\n', stop fo...
d5b2215cafdfb711d3b3233ddd33c050efe02dfb
buxizhizhoum/tool_scripts
/app/bin/sleep_interval.py
835
4.09375
4
#!/usr/bin/python # -*- coding: utf-8 -*- """ provide a function that could sleep some time depends on the running time of certain function. t_start is the time before function runs t_end is the time after function runs INTERVAL is the interval expected between each running of the function. """ import time import dat...
9f62f997a3f5c086df5103754a1ab4105ec407b6
buxizhizhoum/tool_scripts
/app/bin/generator_instead_of_list.py
958
4.40625
4
#!/usr/bin/python # -*- coding: utf-8 -*- """ An example from effective python, telling about consider generators instead of list, item 16. It becomes easier when use for loop, when encounter yield, return one value. """ def index_words_iter(text): """ append change to yield? :param text: :return: ...
ca3dd3e45da0b6c7915a57b8c9e180153a876c5c
buxizhizhoum/tool_scripts
/app/bin/dict_comprehensions.py
218
4.28125
4
#!/usr/bin/python # -*- coding: utf-8 -*- """ dict comprehension this module is used to change all of the values in a dict to None """ tmp = {"a": 1, "b": 2, "c": 3} res = {k: None for k, v in tmp.items()} print res
e5b9814512ff3c3c73d75e894eab45c9f4b8c4d0
esencik/Yslovia
/5.py
129
3.84375
4
a = 10 b = 5 w = float(input('введите число')) if a and b > -0: print("число положительное")
320e9d9bae61e4a02a68bad4f4b87c74cdf58eda
bhanuprakashbalusu/Python-Fundamentals
/ListsTuplesSets.py
7,533
4.8125
5
# Lists and Tuples allows us to work with sequential data. Sets are unordered collection of values with no duplicates # Lists: courses = ['History', 'Math', 'Physics', 'CompSci'] print(courses) # prints entire list # for length of the list we use len() print(len(courses)) # prints 4 # to access the list...
22d0eaba9f369542cced16a8b9068c6a53e8fc64
KrupaH/string-matching
/source/rk.py
1,040
3.890625
4
#Module to find matches using enhanced Rabin-Karp algorithm import math """ Parameters: S = String P = Pattern q = a prime number """ def rabinKarp(S,P,q): n = len(S) m = len(P) #If word is smaller than keyword if n<m: return 0 elif n==m and P==S: return 1 d = 256 #Number of c...
2af121dae98226df307f16ae2c83240dfa0ea38a
zeal706/python_test
/Four part.py
3,207
4.3125
4
magicians = ['alice', 'david', 'carolina'] for magician in magicians: print(magician) magicians = ['alice', 'david', 'carolina'] for magician in magicians: print(magician.title()+", that was a great trick!") print("I can't wait to see your next trick,"+magician.title()+".\n") print("Thank you, everyone. Tha...
ddc63ee80645a8d636eda6c0bf76dc45d53be93f
zeal706/python_test
/nine.py
10,174
3.984375
4
class Dog(): """一次模拟小狗的简单尝试""" def __init__(self, name, age): """初始化属性name和age""" self.name = name self.age = age def sit(self): """模拟小狗被命令时蹲下""" print(self.name.title()+" is now sitting.") def rool_over(self): """模拟小狗被命令时蹲下""" print(self.name.ti...
22f257578867014bc6fef8462d9b3057cd30bdad
NickLarson/Assorted-Python
/input_sanitize.py
920
4.21875
4
import string ##Designed for use in prevention of code injection and for keeping assorted inputs clean... a test prompt is at the bottom## valid_chars = string.ascii_letters + string.digits class sanitized_string(str): """This will sanitize a string for use and prevention of code injection.""" def __init__(se...
dbc9593784580ce73e756026a865f42a2c102301
lutfiex/cfiotclass
/capture/face_r.py
3,222
3.8125
4
# This is an example of running face recognition on a single image # and drawing a box around each person that was identified. import face_recognition from PIL import Image, ImageDraw import numpy as np # Load a sample picture and get the feature. hank = face_recognition.load_image_file("C:/Users/Lutfi/Down...
a8093e452d9bf71716c19707f3f72524efb88620
vmaddara/izdruka
/virknes.py
1,841
3.96875
4
''''vards = input("Kā tevi sauc? ") print("Labdien, " + vards) vecums = int(input("Cik tev ir gadu? ")) #0000 #print("Jums ir " + vecums + " gadi.") print(f"Jums ir {vecums} gadi.") print(f"Jūsu dzimšanas gads ir {2021 - vecums}.") dzimGads = 2021 - vecums print(f"Jūsu dzimšanas gads ir {dzimGads}.") gradi = int...
f5ba19691193d088b24e32a203a09bd4f75a61dc
gzero-1/python-oop
/homework/parking/parking.py
541
3.578125
4
class Parking: price = 10 def __init__(self): self.__timer = 0 def add_time(self, time): self.__timer += time def car_in(self): return self.__timer def car_out(self, check_in_time): total_time = self.__timer - check_in_time bill = f"car came in at: {check_i...
567ce94c27a849d28d9055ea6f384f6fb8adca9e
gzero-1/python-oop
/homework/complex/complex.py
1,440
3.984375
4
class ComplexNumber(object): ADD = "+" SUB = "-" MUL = "*" def __init__(self, real, imaginary): if type(real) is int or type(real) is float: self.real = real else: raise TypeError(f"{type(real)} is not supported") if type(imaginary) is int or type(imagin...
c3232cb9703e28691e7101f555757eecf0575f46
sachinsehrawat/python_selenium_pytest
/Selenium/selenium_01.py
811
3.671875
4
#Import the webdriver from selenium from selenium import webdriver #Create a driver object and provide the executable file path for the browser driver = webdriver.Chrome(executable_path="C:\\Python Automation\\Python Training\\chromedriver.exe") #Maximize the window driver.maximize_window() #Open a URL driver.get("h...
c5d3a95c70c091ec34f720d8299df47f14c334d3
sagitta1969/lesson_3
/lesson_3.1.py
240
3.90625
4
def division(x, y): if y == 0: print("деление на ноль") else: return x / y a = int(input("введите х: ")) b = int(input("введите у больше нуля: ")) print(division(a, b))
bebc4d02b371c1e055dd0d4c1b7559d9e6427c4b
Capoaleman/Advent-of-code-2020
/Day6_2020.py
858
3.9375
4
# December 6th Advent Calendar of Code 2020 # https://adventofcode.com/2020 # By Capoaleman def count_answers(form): # Returns the total of yes answer, 1 per question return len(set(form)) def every_yes(form): # Returns the total of yes answer, 1 per question per group new_group = set(fo...
61673b0d165c3ce6b67d7bbeec26a4201388c2a9
Capoaleman/Advent-of-code-2020
/Day5_2020.py
1,280
3.625
4
# December 5th Advent Calendar of Code 2020 # https://adventofcode.com/2020 # By Capoaleman def binary_partition(li, code): # Parts the list and returns the desired half if code == "F" or code == "L": return li[:len(li)//2] else: return li[len(li)//2:] def get_seat_id(seat):...
b4ae9f0372b2a4a21c86132ba4bfff8733ed919e
larturi/python-argenprop-callejero
/modulos/ficheros.py
439
3.65625
4
class Fichero: def __init__(self, nombre): self.nombre = nombre def write(self, texto): fichero = open(self.nombre, 'wt') fichero.write(texto) fichero.close() def append(self, texto): fichero = open(self.nombre, 'at') fichero.write(texto) fichero.clo...
f2a4b6f502a23d5b226950f85a539136a88285ab
zhongzh1992/pythonPractice
/re_test.py
711
3.609375
4
import re txt = "1925年牛顿被苹果砸到头后发现了万有引力。" ans = re.search("^1925年", txt) print(ans) ans = re.search("[1-2][0-9]{3}", txt) print(ans) ans = re.findall(r"\d+年", txt) print(ans) url = "http://www.baidu.com?p=111&password=123" ans = re.findall("www..+.com", url) print(ans) mail = "-------mailzhon@163.com-----" ans = re...
b84ac6d92b00d5dcbf95efe62238710a82db31af
oliverwreath/DataScience
/set2/5.Fixing Turnstile Data.py
2,002
3.859375
4
import csv def fix_turnstile_data(filenames): ''' Filenames is a list of MTA Subway turnstile text files. A link to an example MTA Subway turnstile text file can be seen at the URL below: http://web.mta.info/developers/data/nyct/turnstile/turnstile_110507.txt As you can see, there are numerous data points inclu...
1142ebbb73c99df4d806d4210e5fd4d2b4bed142
zhanzelin/design-patterns
/python/TemplateMethod.py
2,569
4.34375
4
""" 模板方法模式 结构中只存在父类与子类之间的继承关系:先定义一个类模板,在模板类中定义各种操作的顺序(骨架),但并不实现这些操作,这些操作由子类来操作; 将一些复杂流程的实现步骤封装在一系列基本方法中,在抽象父类中提供模板方法来定义这些基本方法的执行次序框架; 通过其子类来覆盖某些具体的执行步骤,从而使得相同的算法框架可以有不同的执行结果; 在本例中模板为钓鱼方法,决定了抽象方法的调用顺序,这在父类中实现、由子类实例调用; 抽象方法为钓鱼方法的每个步骤(准备鱼饵、选择出行方式、选择钓鱼地点),这在子类中实现,由钓鱼方法内部调用。 """ import abc """ 钓鱼模...
0a083b72273536be5ba948740a4effb92b420edc
zhanzelin/design-patterns
/python/Factory.py
3,397
3.90625
4
""" 工厂模式家族: 包括简单工厂模式、工厂方法模式、抽象工厂模式 """ import abc import random """ 简单工厂模式 产品类的实例由工厂类的静态方法创建(传入需要创建的产品类型,返回产品) 在课程工厂中传入课程类型(基础、进阶),返回基础或进阶课程的实例 """ class BasicCourse(object): def get_labs(self): return "basic_course: labs" def __str__(self): return "BasciCourse" cl...
53e25ee8a27391dc082d80daa724f81edf4bbf11
model1235/linearRegression
/tf/mnist.py
1,056
3.5625
4
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data",one_hot=True) batch_size = 100 n_batch=mnist.train.num_examples // batch_size x = tf.placeholder(tf.float32,[None,784]) y = tf.placeholder(tf.float32,[None,10]) W=tf.Variable(tf.zeros([...
7b021ba1dbef38cdbf9d041d130d739d699c48df
sashulkin/DS_2
/4.tuple.py
777
3.84375
4
# *** Кортеж (tuple) *** # неизменяемый тип (immutable) тип коллекции (структур данных) my_tuple = (10, 20, 30, 30, 30) # чтение данных из кортеди num = my_tuple[-1] # нельзя менять значения # my_tuple[0] = 100 # нельзя удалять значения # del my_tuple[0] # *** методы кортежей *** # метод который возвращает коли...
2e4b75cdfc6ff3b806a70883c8baa4bf78f08593
niallcampbell/PythonPractice
/CommonDivisors.py
741
4.0625
4
# Common divisors # Given two numbers entered by the user, return: 1. number of common divisors, 2. a list of the common divisors def commonDivisors(): print("Please enter two numbers separated by a single space") print("For example: 2 10") print() rawNumbers = input("Your numbers: ") listNumber...
c134b6355c1fb0ada2547fa29096517b9bfb9c10
MollyDepew/Python-Assignments-
/characters.py
851
4.15625
4
#Molly Depew #CS21 #Assignment 9 ex 2 #create a program that find the number of # lowercase letters, uppercase, spaces, and digits in the file def main(): infile = str(input('Enter the file name: ')) try: doc = open(infile,'r') file = doc.readlines() except IOError: prin...
13d2134db0cefd6b9ad0e1921f32634d0fe02ee9
markku63/mooc-tira-s20
/Viikko_14/roundtrip.py
805
3.546875
4
from math import inf class RoundTrip: def __init__(self,n): self._n = n self._dm = [[inf]*n for _ in range(n)] for i in range(n): self._dm[i][i] = 0 def add_route(self,a,b): self._dm[a-1][b-1] = 1 def check(self): for k in range(self._n): for...
3cdc953ef442ccc3ee2ce7dc410f8e602730ac4a
markku63/mooc-tira-s20
/Viikko_6/subtrees.py
870
4.09375
4
from collections import namedtuple def count(node): if not node: return 0 elif not node.left and not node.right: return 1 else: return 1 + count(node.left) + count(node.right) def diff(node): if not (node and (node.left or node.right)): # Tyhjä solmu tai lehti r...
d16f69db18040ea8352d749fa7cd62d795cac82d
markku63/mooc-tira-s20
/Viikko_12/courseplan.py
1,266
3.75
4
class CoursePlan: def __init__(self): self._reqs = {} def add_course(self,course): self._reqs[course] = [] def add_requisite(self,course1,course2): self._reqs[course1].append(course2) def _dfs(self, course, visited, tsort): if visited[course] == 2: retu...
25c46d77b42f4a105a6c976949f51371da02ce40
markku63/mooc-tira-s20
/Viikko_13/newroads.py
1,357
3.703125
4
class UnionFind: def __init__(self, n): self._n = n + 1 self._vanhempi = [i for i in range(self._n)] self._koko = [1]*self._n def _edustaja(self, x): while x != self._vanhempi[x]: x = self._vanhempi[x] return x def yhdista(self, a, b): a = self._...
7c18cc1041b51ee7740f341b5dac48218eb83bb1
markku63/mooc-tira-s20
/Viikko_5/robot.py
618
3.796875
4
def move(cur, c): if c == "L": return (cur[0] - 1, cur[1]) elif c == "R": return (cur[0] + 1, cur[1]) elif c == "U": return (cur[0], cur[1] + 1) elif c == "D": return (cur[0], cur[1] - 1) else: raise ValueError("No such direction: " + str(c)) def count(s): ...
dbc9c765b8356ab7fc98f79d93d25416e6fefbe9
markku63/mooc-tira-s20
/Viikko_4/fliptwo.py
348
3.59375
4
from collections import deque def solve(n,k): pakka = deque([i+1 for i in range(n)]) for i in range(k): a = pakka.popleft() b = pakka.popleft() pakka.append(b) pakka.append(a) return pakka[0] if __name__ == "__main__": print(solve(4,3)) # 4 print(solve(12,5)) # 11 ...
b8931452488e6f7208993142279f75d0137ed18c
TTTechnoPro/EVC-COMSC20
/14.3 HW #10.py
1,788
4.125
4
#!/usr/bin/env python3 #Question1 ''' ValueError NameError IOError SyntaxError TypeError These are common exceptions ''' #Question 2 class Student: def __init__(student_id, student_name,student_class): self.student_id = student_id self.student_name = student_name self.student_class = stud...
b9fff91a2a29aee9bdc180cccc85d8676af0c3e9
TTTechnoPro/EVC-COMSC20
/9.2 Lab #6.py
1,049
4.21875
4
#!/usr/bin/env python3 #Question 1 def longestValue (string): newString = "" startingoff = "" for i in string: if i>startingoff: newString += i startingoff = i return newString # print(longestValue("abcdefgzab")) #Question 2 def is_Palindrome (string): string = str...
d8d19b2abc8797dda965ea5c52f8917e27ed906f
TTTechnoPro/EVC-COMSC20
/7.3 HW #4.py
1,435
4.34375
4
#!/usr/bin/env python3 #Question 1 print("This is a program that will print out a rectangle ") length=int(input("What is the length of your rectangle ")) width=int(input("What is the width of your rectangle? ")) pattern=input("What pattern do you want to use ") for i in range(width): print(length*pattern) #Quest...
e5f3604a7c3c3f353aeffce946fe08a632bc841e
anieshchawla/algorithms
/checking.py
189
3.578125
4
import collections # A = collections.OrderedDict() # B = collections.OrderedDict() A=dict() B=dict() A['a'] ="A" A["b"] ="B" A["c"] = "C" B["c"] = "C" B["b"] ="B" B['a'] ="A" print (A==B)
7a3fa4e17db228ee0a2287bb4091b26566eb07d7
anieshchawla/algorithms
/row_sort.py
255
3.546875
4
nums=raw_input().split(" ") n=int(nums[0]) m=int(nums[1]) element=[] for x in range(n): element.append(map(int,raw_input().split(" "))) k=int(input()) print element element.sort(key=lambda x: x[k]) for y in element: for z in y: print z, print " "
24b5a19d195a0c4c89be03212eb9f14501f9bb56
anieshchawla/algorithms
/encoding_tlv.py
4,468
3.6875
4
'''This is the code for encoding the packet into TLV form for sending NDN packets via controller''' class TLV(): def splitN(self,string,N): _string_reverse = string[::-1] _string_tok_rev= [_string_reverse[start:start+N] for start in range(0,len(string),N)] _string...
39e053b99d2eb2ef0a7526ae74d4568421691462
jalexanderbryant/python-practice
/quick-hacks/cat.py
1,390
3.5
4
#V1: cat a.txt b.txt c.txt # Initialize parse arg # add arguments # For each file in the file argument # open the file # iterate over each line in the file: # Print the text # V2: cat a.txt b.txt c.txt > d.txt # Open a file stream for a new file # Write the outputs of the previous files into the new fil...
1f88b949efa28e803228f7d2bec846513b3490da
jalexanderbryant/python-practice
/old/problems/challenges.py
2,062
4.21875
4
def sum_with_for(numbers): sum = 0 for num in numbers: sum += num return sum def sum_with_while(numbers): sum = 0 i = 0 while i < len(numbers): sum += numbers[i] i += 1 return sum def sum_with_recursion(numbers): # if base case=> numbers is empty if len(numbers) == 0: # return 0 ...
a47ab237b3ab185f775ce676ea38686a7a4a355d
jalexanderbryant/python-practice
/old/dsa/time.py
141
3.609375
4
from time import time start_time = time() for i in range(0, 10): print(i) end_time = time() elapsed = end_time - start_time print(elapsed)
da55a8322aaf3ed98ffec4579988e4900774ad22
jalexanderbryant/python-practice
/old/dsa/dynamic-arrays/test_dynamic_array.py
802
3.75
4
from dynamic_array import DynamicArray import sys def test_dynamic_array(): new_array = DynamicArray() assert new_array._capacity == 1 # should be equal to 1 assert new_array._n == 0 # should be empty new_array.append(None) assert new_array._capacity == 1 new_array.append(None) ...
d0096f8471cd0523fab925bfbe8dd37139aed1fd
KimRaicho/calculator
/login_details.py
162
3.53125
4
login_dict = {} filename = 'login.txt' def save_login_details(): with open(filename, 'w') as f: for login in login_dict: f.write(login)
402123729f115a770d9ac03104f920faf62d0aa8
Viccari073/exercises_collections
/exer_colecoes_03.py
455
4.03125
4
""" Ler um conjunto de números reais, armzenando-o em vetor e calcular o quadrado das componentes deste vetor, armazenando o resultado em outro vetor. Os conjuntos têm 10 elementos cada. Imprimir todos os conjuntos. """ conjunto = [] for n in range(1, 11): numeros = int(input(f'Digite o {n}º número: ')) ...
440aac5ed3c0b4510eac226570fc80a1cd40df52
MeghanaIyer/MalariaCollab
/malaria.py
4,156
3.53125
4
#!/usr/bin/python3 """ o Title: Running Exercise 1 o Date: 09.10.2020 o Author: Mara Vizitiu o Description: A common task for bioinformaticians is to merge data from several files into one. You have a FASTA file (malaria.fna) with multiple DNA sequences. You want to annotate them, that i...
d1a3f34e05ce611bfec95702dd65aa4b491a4901
nevergiveupyang1989/leetcode
/py/minDepthOfBinarytree.py
1,593
3.84375
4
#! /usr/local/bin/python #--*---:coding:utf-8---*--- import unittest class TreeNode: def __init__(self,val): self.val = val self.left = None self.right = None class Solution: def minDepth(self, root): if root is None: return 0 return min(self.minDepth(root....
53485a428be4f7ebee23eabbba76f0b46d720632
nevergiveupyang1989/leetcode
/py/maxProfit.py
468
3.515625
4
#usr/local/bin/python class Solution: def maxProfit(self, prices): if prices == []: return 0 max_ = 0 min_ = prices[0] for i in xrange(1,len(prices)): max_ = max(max_, prices[i]-min_) min_ = min(min_, prices[i]) return max_ if __name_...
307f583954ef193bde7a4941b6ee4f7b717cb1d7
kiraweigel/ps-pb-hw3
/fibonacci.py
1,461
3.984375
4
fibonacci_list = [1, 1] #последовательность фибоначчи sum_of_even_numbers = 0 #сумма всех четных элементов fib1 = 1 fib2 = 1 fib_sum = 0 #Создаем список с послеедовательностью фибоначчи while fib2 <= 10000000: fib_sum = fib1 + fib2 fib1 = fib2 fib2 = fib_sum if fib2 <= 10000000: fibonacci_list....
473f41a3f3f05db3df1e3995065496a0e6964443
sunsx512/csdn-python-study
/day10/day10.py
411
3.765625
4
print("hello 第二章!!") edward=['Edward Gumby',42] john=['John Smith',50] database=[edward,john] # database是一个由数据库中所有人员组成的列表。 print(database) greeting='Hello' print(greeting[0]) greeting='Hello' print(greeting[-1]) fourth=input('请输入年份:') print(fourth[3]) #a=input('请输入a:') #b=input('请输入b:') a=1....
0c91454784808c11955b114d5f6ccc0ffd13b9db
sunsx512/csdn-python-study
/day3/day3.py
568
3.828125
4
import math #模块 x=math.floor(32.9) print(x) x=math.ceil(32.9) print(x) ''' >>> floor(32.9) Traceback (most recent call last): File "<pyshell#41>", line 1, in <module> floor(32.9) NameError: name 'floor' is not defined ''' x=int(32.9) print(x) # ceil()上取整函数,floor()下取整函数,在模块math中,无法直接使用,需使用关键...
9e792fca614f742f7778c2881d5dc27c712829d9
AnakinCNX/PythonChallenges
/challenge_23.py
463
3.9375
4
# fir is a type of tree... # ask user for lawn size fir circle in meters num = int(input("Please enter the size of the lawn in meters: ")) # your spelling sucks below # used funtion to calculate and print turf needed # Turf is word for grass (artificial or natural) # What is the geometric calculation that you would n...
7c9ace87c45ccfeeea695927d1bb68a14e8c196b
AnakinCNX/PythonChallenges
/challenge_14.py
467
4.1875
4
# ask user for sentence sentence = input("Please type down a sentence: ").lower() # are you missing an input? # no: "the" will be "hard-coded" # create list from sentance # what method creates a list from a string? list = sentence.split() # count how many times the word, "the" is in the sentance! the_the_counter =...
2e5f1d2bc5ec24bb00dd21741f999386243e7af9
AnakinCNX/PythonChallenges
/challange_6.py
685
4.40625
4
#ask the user its name name = input("What is your name? ") #if its the same as you print your cool a = "jeff" msg = "Nice to meet you {}" if a == name: print ("You're cool") else: # add the user's name to the print command below # like Nice to meet your, Jeff! # Remember, or lookup, the following String Methods: #...
b6644a41ba01d8e132e5591dde3d6a79d8f9fdd7
kevenescovedo/p1-linguagem-de-programa-o
/exercicio1.py
2,372
4.25
4
"""**1.** Desenvolva todas as funções a seguir: a) Função com retorno com parâmetro. Faça um programa contendo uma função/método que leia uma matriz. Na passagem de parâmetro use quantidade de linhas e colunas e ao final retorne a matriz. b) Faça uma função/método que mostre uma matriz. Na passagem de parâmetro...
f76eef8a8bade6d5d3d56fc728b081c208b80d57
zuoshifan/driftscan_scripts
/v_dist.py
7,496
3.734375
4
#!/usr/bin/env python """Calculate v baselines distribution. :Authors: Shifan Zuo :Date: 2015-01-08 :email: sfzuo@bao.ac.cn """ import argparse import numpy as np import h5py # import matplotlib # matplotlib.use('Agg') # from matplotlib import pyplot as plt def unique(ar, return_index=False, return_inverse=False, ...
8c9598c2cc79fd8b3bb341e8dd2d6b25c37b361c
Nirol/LeetCodeTests
/Algorithms_questions/med/Trie.py
2,408
4.28125
4
class Trie(object): def __init__(self): """ Initialize your data structure here. """ self.char = '' self.children = [] self.word_finished = False def insert(self, word): """ Inserts a word into the trie. :type word: str :rtype: No...
2e202e3d498ed5f970b9ed98bbe3321e2ae1f9ca
Nirol/LeetCodeTests
/Algorithms_questions/ez/reverse_int.py
679
3.65625
4
import math class Solution: def reverse(self, x: int) -> int: ans=0 flag_minus=0 if x < 0 : flag_minus = 1 x= int(math.fabs(x)) num_digits = len(str(x)) while x: digit = x % 10 ans = int(ans + digit*(math.pow(10,num_digits-1))) ...
c406e1c50ac940f5aaf4e31ffbf49a3d02aa2d2f
Nirol/LeetCodeTests
/ez/climbStairs.py
681
3.578125
4
class Solution: def climbStairs(self, n): """ :type n: int :rtype: int """ # FIBBONACI SOL if n == 1 : return 1 first = 1 second =2 for i in range (3,n): third = first+second first= second seco...
0409415a9feb9936b0e17d3bfcf39052bc9c6a1f
Nirol/LeetCodeTests
/mid+new_tricks/Poor_Pigs.py
1,400
3.609375
4
import math class Solution(object): def poorPigs(self, buckets, minutesToDie, minutesToTest): """ :type buckets: int :type minutesToDie: int :type minutesToTest: int :rtype: int """ pigs = math.log(buckets, 1+ math.floor(minutesToTest // minutesToDie)) ...
0a4f7924ce3c8ba81afeda0588b84f35066eaa0b
Nirol/LeetCodeTests
/Algorithms_questions/ez/sqrt.py
398
3.59375
4
class Solution(object): def mySqrt(self, x): """ :type x: int :rtype: int """ if x==0: return 0 if x<=2: return 1 for i in range(2,x): if i * i > x: return i - 1 if i*i == x: retur...
777a20520db9483b9fb75f134695055a8d954bb4
Devin-Uner/slothintelligence
/new_info.py
1,435
3.5
4
#!/usr/bin/python import cgi form = cgi.FieldStorage() # ##snippet 1o ##### read in all the data all_users = {} file = open("user_data.txt", "r") for line in file: # print 'line.split(" ")[0], line.split(" ")[1]' all_users[line.split(" ")[0]] = line.split(" ")[1] file.close() ##snippet 1c ##### print "Conten...
71e8192b558abc381ee0f3d5e8e686e8bed58024
AnnabellaZhang/LeetCode
/script/9_isPalindrome.py
722
3.84375
4
#Palindrome Number:https://leetcode.com/problems/palindrome-number/description/ #Solution: class Solution: def isPalindrome(self, x): """ :type x: int :rtype: bool """ x = str(x) return x == x[::-1] #Complicated: class Solution: def isPalindrome(self, x): ...
67002365860efd86b9d1acd2637d02ed160e2eda
vt-sailbot/sailbot-18
/src/track_logger.py
1,182
3.671875
4
import ship_data, captain import time import math file_name = "tracks/log_" + str(math.floor(time.time())) file = open(file_name, 'w') captain = None def setup(c): """ Instantiates a captain object. Keyword Arguments: c -- captain object Side effects: -Changes the global variable captain """ global ca...
1e441ebbc6615f971b315cfa00a8b6043ba6b69b
vt-sailbot/sailbot-18
/src/servo.py
1,578
3.515625
4
import Adafruit_BBIO.PWM as pulser import time class ServoController: """ Sets up and manages a servo """ def __init__(self, pin, name, angle_limits): """ Instantiates a new servo with implementation details Keyword arguments: self -- The caller, the new instance ...
c2592b970c7555fdbd59a71f031649c8eed5d1d9
Bongo9911/cs232
/proj07/cpu.py
13,093
3.515625
4
import time import threading # for Lock from ram import MMU MAX_CHARS_PER_ADDR = 4 # Time to delay between executing instructions, in seconds. DELAY_BETWEEN_INSTRUCTIONS = 0.2 # Interrupt device ids SOFTWARE_TRAP_DEV_ID = 0 TIMER_DEV_ID = 1 # KBRD_DEV_ID = 1 # SCREEN_DEV_ID = 2 # REASONs for software traps. EN...
8d909b90a59cce51160c8310d681220165e54169
l3kn/generative_cfg
/generative_cfg/turtle.py
1,742
3.5
4
import math import numbers import random from .vec import Vec2 class Turtle(): def __init__(self, backend): self.position = Vec2(); self.direction = Vec2(0.0, -1.0); self.__scale = 1.0; self.drawing = True self.backend = backend # Used to (re)store the turtles sta...
cd3d0c3c6aa1f77ab70ca8d68d6c0677635773f3
ruben-jimenez/python-basic
/python-exercises/02-odd-or-even.py
613
3.953125
4
""" Exercise from: https://www.practicepython.org/solution/2014/02/15/02-odd-or-even-solutions.html Code created by Ruben Jimenez """ def run(): num = int(input('Enter a number to check: ')) check = int(input('Enter a number to divide by: ')) if num % 4 == 0: print(num, 'is a multiple of 4...
e6a24398e339aadb91448c8005651a94971b84fe
ruben-jimenez/python-basic
/python-exercises/03-list-less-than-ten.py
606
3.984375
4
""" Exercise from: https://www.practicepython.org/exercise/2014/02/15/03-list-less-than-ten.html Code created by Ruben Jimenez """ def run(): num = int(input('Enter a number and the program will return a list with numbers less than this: ')) a = [1,1,2,3,5,8,13,21,34,55,89] b = [] c = [] ...
95644fd2ce10a256e596d647adc2078f09d20992
ruben-jimenez/python-basic
/python-exercises/24-draw-a-game-board.py
517
3.875
4
""" Exercise from: https://www.practicepython.org/exercise/2014/12/27/24-draw-a-game-board.html Code created by Ruben Jimenez """ def printboard(size): lines = " --- " separator = "| |" for x in range(size): if x == 0: print((lines*size) + "\n" + (separator*size) + "\n" + (l...
64501bf75af438fc7b0beb729532855e7ad9c698
kazumi21/hacker_rank
/python/easy_sum.py
475
3.5625
4
# Hacker Rank: Easy sum def get_user_input(): T = int(input()) N = [] m = [] for i in range(T): line = input().split() N.append(int(line[0])) m.append(int(line[1])) return {'N':N,'m':m} def calc_sum(N, m): return (((N/2)%m)*((N+1)%m))%m def expression(): inputs = ...
565f097497e681d957a5612c56dee95ba8862320
themcaffee/game-of-life
/food.py
461
3.609375
4
FOOD_COLOR = (0, 255, 0) FOOD_WIDTH = 10 FOOD_HEIGHT = 10 class Food: def __init__(self, row, column): self.color = FOOD_COLOR self.width = FOOD_WIDTH self.height = FOOD_HEIGHT # Set position in grid self.row = row self.column = column # Calculate and set po...
696291eb1caca61f6d8647080aa523fddfd0cd7a
jackeiel/riddler
/2020_01_10/classic.py
4,491
4.65625
5
#!usr/bin/env/python ''' In Jewish study, “Gematria” is an alphanumeric code where words are assigned numerical values based on their letters. We can do the same in English, assigning 1 to the letter A, 2 to the letter B, and so on, up to 26 for the letter Z. The value of a word is then the sum of the values of its le...
7b4f576e99cc9f49d8fc1d530d125633cf6e2ce9
dohee479/PROGRAMMERS
/Level 1/2016년.py
383
3.75
4
def solution(a, b): week = ['THU', 'FRI', 'SAT', 'SUN', 'MON', 'TUE', 'WED'] month_day = [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] sum_day = 0 for month, day in enumerate(month_day): if month < a: sum_day += day elif month == a: sum_day += b answer =...
ee6acb843c7db00d02fc7b411541f33494fc9e76
btoll/howto-algorithm
/python/recursion/fibonacci.py
658
4.125
4
# Recursive def fibonacci(n): if n < 2: return n return fibonacci(n - 1) + fibonacci(n - 2) # Recursive, memoized def fibonacci(n): c = {} def fib(n): if n < 2: return n if not c.get(n): c[n] = fib(n - 1) + fib(n - 2) return c.get(n) retur...
1945b8fe858bcd38a1f0f7b89b1868030b40adcd
btoll/howto-algorithm
/python/60-questions/tree-bt-bst/merge_two_binary_trees.py
2,820
3.875
4
import ipdb class TreeNode: def __init__(self, value): self.value = value self.left = None self.right = None def bfs(root): queue = [root] visited = [] while queue: node = queue.pop() visited.append(node.value) if node.left: queue.insert(0...
116ad0d4ec56413f498787b7b0ad9705b7c4caca
btoll/howto-algorithm
/cracking-the-code-interview/IX_interview-questions/data-structures/chapter1/string_rotation.py
143
3.84375
4
def rotate(s1, s2): if len(s1) haystack = s1 + s1 return is_substring(s2, haystack) print(rotate("waterbottle", "erbottlewat"))
8c19f9418f9f87f31c0abb58f28e65a967b92a1a
btoll/howto-algorithm
/python/misc-questions/reverse_array.py
192
4.0625
4
def reverse_array(arr): l = len(arr) for i in range(l >> 1): arr[i], arr[l - 1 - i] = arr[l - 1 - i], arr[i] return arr print(reverse_array([1, 2, 3, 4, 5, 6, 7, 8, 9]))
c5cd385c11beb93b3c3154a86a0c008fda8d0fd7
btoll/howto-algorithm
/python/matrix/count_negative_elements.py
786
3.765625
4
import ipdb import numpy # https://www.techiedelight.com/count-negative-elements-present-sorted-matrix/ list1 = [-7, -3, -1, 3, 5] list2 = [-3, -2, 2, 4, 6] list3 = [-1, 1, 3, 5, 8] list4 = [ 3, 4, 7, 8, 9] def count(matrix): c = 0 for row in matrix: if row[-1] < 0: c += len(row) ...