blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
046c8f695ebefbe7fb30651c7b6444610702d93e
Whatsupyuan/python_ws
/10. 第十章_02-异常except/10_1004_test01.py
349
3.921875
4
def plus(): try: num1 = int(input("Please input first number..")) num2 = int(input("Please input second number..")) # python 3.6 捕获多个异常,不能使用 , 号分隔 except TypeError: print("error.") except ValueError: print("valueError") else: return num1 + num2 print(plus())
1622d36817330cc707a1a4e4c4e52810065aa222
Whatsupyuan/python_ws
/4.第四章-列表操作/iterator_044_test.py
1,306
4.15625
4
# 4-10 players = ['charles', 'martina', 'michael', 'florence', 'eli'] print("The first three items in the list are" ) print(players[:3]) print() # python3 四舍五入 问题 # 官方文档写了,round(number[, ndigits]) values are rounded to the closest multiple of 10 to the power minus ndigits; # if two multiples are equally close, round...
6eec6a9e295edab7320b350776335b60ce1080ae
Whatsupyuan/python_ws
/9.第九章-类class/09_class_0910_testRandom.py
305
3.78125
4
from random import randint # 生成 1 到 6 之间的随机数 x = randint(1, 6) print(x) class Die(): def __init__(self, sides=6): self.sides = sides def roll_die(self): print(randint(1, 6)) die = Die() print("开始投掷骰子") for num in range(1, 11): die.roll_die()
975d3f6ea1518c2e1f8d3939da09bbaf66b4acb3
Whatsupyuan/python_ws
/5.第五章-if/if_0230_test.py
471
4
4
# 5.2.1 str1 = "print info" str2 = "print name" print(str1 == str2) # 5.2.2 print(str1.lower() == str2) # 5.2.3 int1 = 100 int2 = 110 print(int1 == int2) print(int1 != int2) print(int1 > int2) print(int1 < int2) print(int1 >= int2) print(int1 <= int2) # 5.2.4 if int1 == int2 or int1 <= int2: print(1) if int1 != ...
98d23e0af9f04e9ba50bdf07a6f04bec5b1e2d57
Whatsupyuan/python_ws
/4.第四章-列表操作/iterator_044_split.py
461
3.71875
4
players = ['charles', 'martina', 'michael', 'florence', 'eli'] split_arr = players[0:1] print(split_arr) split_arr = players[1:] print(split_arr) # 内容指向一直的 list , 则两个list不能相互独立 new_players = players new_players.insert(0,"yuan") print(new_players) print(players) ; print() # 复制列表 [:] , 复制之后的列表是独立的内存指向 new_players = ...
134d4811b1e629067e1f711f145fff9b889617aa
Whatsupyuan/python_ws
/6.第六章-字典(Dictionary)/06_dic_0603_iteratorDictionary.py
734
4.28125
4
favorite_num_dic = {"Kobe": 24, "Jame": 23, "Irving": 11} # 自创方法,类似于Map遍历的方法 for num in favorite_num_dic: print(num + " " + str(favorite_num_dic[num])) print() # 高级遍历方法 items() 方法 print(favorite_num_dic.items()) for name,number in favorite_num_dic.items(): print(name + " " + str(number)) print() # key获取 字典 中的...
9c54989a85bd5020fe1407b3ea1a90046034c8b4
Whatsupyuan/python_ws
/7.第七章-用户输入input和while循环/07_input_0201_while_0705test.py
237
4
4
# 电影院 while True: info = int(input("岁数?")) if info == 888: break if info < 3: print("免费") elif info > 3 and info < 12: print("10美元") elif info > 15: print("15美元")
81ba73b968e2676a4d6d4485dce939b5c1e3443e
Whatsupyuan/python_ws
/4.第四章-列表操作/test.py
736
3.953125
4
# 4-3 # for num in range(1,20): # print(num) def iteratorMethod(list): for val in list: print(val) numArr = list(range(1, 1000 * 1000 + 1)) # iteratorMethod(numArr) # print(min(numArr)) # print(max(numArr)) # print(sum(numArr)) # numArr = list(range(1,20,2)) # iteratorMethod(numArr) # numArr = lis...
689e63b9210d28d7d709c06806b607e4b1d22831
Whatsupyuan/python_ws
/9.第九章-类class/09_class_0905_extend.py
636
3.765625
4
''' 父类 , 子类 继承 ''' class Car(): def __init__(self , name , series): self.name = name self.series = series def carInfo(self): print(self.name + " " + self.series) class ElectriCar(Car): def __init__(self , name , series ): # super() 必须写成方法体形态 , 与JAVA不同 super().__ini...
3d36ddfcdb53ea51d3e0b1b44ac347ec35c58c18
Whatsupyuan/python_ws
/3.第三章-列表/list_03_sorted.py
262
3.828125
4
# list排序 cars = ['bmw', 'audi', 'toyota', 'subaru'] ; sorted_cars = sorted(cars); print("排序之后列表 : " + str(sorted_cars)); print("原始列表 : " + str(cars)); # sorted 反响排序 print("sorted倒序排列:" + str(sorted(cars,reverse=True))) ;
8a042aa4d931d9ed16594b4f3988ad35d6222325
Whatsupyuan/python_ws
/10. 第十章_02-异常except/10_1003_pass.py
923
3.703125
4
def countWord(fileName): if fileName: try: with open(fileName) as file: content = file.readlines() # except 之后要捕获的异常可以不写 # 程序一样会执行 except FileNotFoundError: # pass 当程序出现异常时 , 什么操作都不执行 pass else: wordsCount = 0 ...
4804a7005c71ed635bbd1dbff0be64ff46cd78ad
Whatsupyuan/python_ws
/10. 第十章_01-文件操作File/10_file_1007_test.py
210
3.703125
4
flag = True while flag: name = input("Pleas input your name ... ") if name and name == 'q': flag = False continue with open("guest.txt", "a") as file: file.write(name + "\n")
3d999ca8f12348a3cb229be5af0f9cdba4ccc0b2
ArvindAROO/algorithms
/sleepsort.py
1,052
4.125
4
""" Sleepsort is probably the wierdest of all sorting functions with time-complexity of O(max(input)+n) which is quite different from almost all other sorting techniques. If the number of inputs is small then the complexity can be approximated to be O(max(input)) which is a constant If the number of inputs is l...
5ff98430566fb288495995803076102ae131d7f8
artheadsweden/python_adv_april19
/Day1/Print.py
528
3.609375
4
from functools import wraps def print_with_start(original_print): @wraps(original_print) def wrapper(*args, **kwargs): pre = "" if "start" in kwargs: pre = kwargs['start'] kwargs.pop('start') original_print(pre, *args, **kwargs) return wrapper print = pri...
f5703afe5db60099c947aafae9847b96e3b3b9a7
noeldelgadom/devF
/easy:P/easy2.py/product.py
454
4.03125
4
# -*- encoding: utf8 -*- lista1=[1,2,4,5,9,4] lista2=[6,1,2,3,1,4] print "sumar de las listas" for i in range(len(lista1)): print lista1[i]+lista2[i] print "" print "Resta de las listas" for i in range(len(lista1)): print lista1[i]-lista2[i] print "" print "Divicion de las listas" for i in range(len(lista1)): ...
0ebdd0da9d050cd2f5f70738697a84e26a385b35
Dedlipid/PyBits
/basechanger.py
408
3.734375
4
def f(): n=int(raw_input("Enter number ")) b=int(raw_input("Enter base ")) l=[] if n == 0 : print "0 in any base is 0" else: while n > 0: l.extend([n % b]) n /= b l = l[::-1] if b <=10: l = ''.join(str(e) for e in l) else : l = ' '.join(str(e) for e in l) ...
77d4482ba88837a3bca6280a08320a2b0eb70aac
KD4N13-L/Data-Structures-Algorithms
/Sorts/merge_sort.py
1,591
4.21875
4
def mergesort(array): if len(array) == 1: return array else: if len(array) % 2 == 0: array1 = [] half = (int(len(array) / 2)) for index in range(0, half): array1.append(array[index]) array2 = [] for index in range(half, ...
e9225939223ee4486cd867bfe1018e5788716e4a
AngiesEmail/ARTS
/ProgrammerCode/mergeTwoSortedLists.py
757
3.515625
4
class ListNode(Onject): def __init__(self,x): self.val = x self.next = None def mergeLists(l1,l2): dummy = result = ListNode(l1.val) node1 = l1.next node2 = l2 while node1 != None and node2 != None: if node1.val <= node2.val: result.next = node1 node1...
7c3abbae1e51ca3e6b12f151000b2e06d01b6ded
iagoguimaraes/introducaopython
/aula2/decisao.py
1,067
4.09375
4
def ex_16(): primeiro_numero = float(input('Digite um número: ')) segundo_numero = float(input('Digite outro número: ')) if(primeiro_numero > segundo_numero): print('O número {} é maior.'.format(primeiro_numero)) elif(segundo_numero > primeiro_numero): print('O número {} é maior....
6e0f318c5fcbccfc8e04a6c0866b04e8b84a76f4
cristigavrila/Python-Basics
/string_null_bool.py
114
3.859375
4
#a string with 0 is still true in boolean condiion s = '0' if s: print('true') else: print('False')
2ab2af6ab1a063d85753251cd3a7e7575f4a40c2
k-j-m/KenGen
/kengen/model.py
4,931
3.734375
4
class Model(object): def __init__(self, classes, package): self.classes = classes self.package = package class ClassElement(object): """ ClassElement class contains a description of a class in our data model. Please note that I've made sure to keep this class completely unaware ...
5b21093884fa7272edafaabf4dfab40581f8e29e
njdevengine/nltk-exploration
/nltk-chapter-3.py
2,568
3.671875
4
from urllib import request url = "http://www.gutenberg.org/files/2554/2554-0.txt" response = request.urlopen(url) raw = response.read().decode('utf-8') type(raw) len(raw) raw[:100] #tokenize the text, splitting all words and punctuation import nltk, re, pprint from nltk import word_tokenize tokens = word_tokenize(raw)...
fd284f5ceefa02965d794923ecac5e367e461184
FireHo57/mud_wizard
/mudWizard/game/game_object_base.py
277
3.609375
4
from abc import ABCMeta class game_object_base: """ This class is abstract! it makes sure that every (visible) object has a looks like method on it. """ def looks_like(self): raise NotImplementedError( "You haven't implemented looks_like()!" )
26f3a1474e7b23a69abcc233bac02684266a1c67
Tomek189/day2
/Zmiennap.py
179
3.796875
4
a=3 b=4 x=b/(2.0+a) print("zmienna a:{} zmienna b:{}".format(a,b)) print("{:.17}".format(x)) print(True) print(False) print (True==True) print(True!=False) print(True!=False)
f7d79acd5833d909c9fb4f81268da7f5b5f58994
Rahix/frequency-bands
/gen_data.py
1,113
4
4
# Simple python script to add new entries def gen_entry(): ob = input("Operating Band: ") ul = input("Uplink(UL) lower: ") uu = input("Uplink(UL) upper: ") dl = input("Downlink(DL) lower: ") du = input("Downlink(DL) upper: ") dm = input("Duplex Mode: ") ne = input("Note(Leave empty for no ...
f02d5df44baa691d9b8b8beb4609785764e80a46
kaylalee44/Computing-Kids
/info_extract.py
5,960
3.828125
4
import pandas as pd from bs4 import BeautifulSoup from urllib.request import urlopen import csv def jobsUpdated(file_name): """ Goes through a data set file and looks through all the job listings for the date it was posted. If the days posted was 1, 7, 14, or 21 days ago, then the counter goes up. Prints ...
c68ca2b8fbd9f772b509bda0cb4a226e94bac90d
kaylalee44/Computing-Kids
/test.py
757
3.515625
4
import requests from urllib.request import urlopen import re from bs4 import BeautifulSoup url = "https://www.indeed.com/jobs?q=data+scientist&l=WA&explvl=entry_level&start={}" # page_response = requests.get(url, timeout=3) # soup = BeautifulSoup(page_response.content, 'html.parser') html = urlopen(url) #connects to ...
3b563267fbc6c016985e4b8c7e5c657b7cd0f2e3
OctopusHugz/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/1-last_digit.py
282
3.8125
4
#!/usr/bin/python3 import random number = random.randint(-10000, 10000) ld = abs(number) % 10 if number < 0: ld = -ld print("Last digit of {:d} is {:d} and is ".format(number, ld), end='') print("greater than 5" if ld > 5 else "0" if ld == 0 else "less than 6 and not 0")
3d57998b7d52f7ff65567e000ca0eb6aefec57b3
OctopusHugz/holbertonschool-higher_level_programming
/0x06-python-classes/100-singly_linked_list.py
2,867
4.03125
4
#!/usr/bin/python3 """This module implements a class Node that defines a node of a singly linked list.""" class Node: """This class Node assigns data and next_node.""" def __init__(self, data, next_node=None): """This function initializes an instance of the Node class and assigns the public attribute...
7d5484155698ffad5a8413aed26d70e69a627db6
OctopusHugz/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/models/base.py
3,748
3.796875
4
#!/usr/bin/python3 """This module implements the Base class""" import json import os import csv class Base: """This is the Base class's instantiation""" __nb_objects = 0 def __init__(self, id=None): """This function creates the Base instance""" if id is not None: self.id = id ...
84c103cbb20b0f72d368d731eef4dcec402d872e
OctopusHugz/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/tests/test_rectangle.py
3,023
3.6875
4
#!/usr/bin/python3 """This module implements the TestRectangle class""" import unittest # from models.base import Base from models.rectangle import Rectangle class TestRectangle(unittest.TestCase): """This is an instance of the TestRectangle class""" def test_rectangle_instantiation(self): """This fu...
c621bf99110cfda89e2b6196bd363155569883eb
OctopusHugz/holbertonschool-higher_level_programming
/0x0B-python-input_output/8-load_from_json_file.py
279
3.546875
4
#!/usr/bin/python3 """This module implements the load_from_json_file function""" import json def load_from_json_file(filename): """This function loads a JSON object from a file filename""" with open(filename) as fp: text = fp.read() return json.loads(text)
ab64f97d2ab84c34fe1af4c973abba878038559b
OctopusHugz/holbertonschool-higher_level_programming
/0x0B-python-input_output/6-from_json_string.py
231
3.5
4
#!/usr/bin/python3 """This module implements the from_json_string function""" import json def from_json_string(my_str): """This function returns the Python object represented by a JSON string""" return json.loads(my_str)
379f87707f737e0b2daabbff27120cd6767fbbe7
dgoffredo/pattern
/pattern.py
8,376
3.765625
4
"""simple pattern matching""" from collections import defaultdict import collections.abc as abc def match(pattern, subject): """whether `subject` matches `pattern`""" return Matcher()(pattern, subject) class Matcher: def __init__(self, num_variables=0): self.vars = tuple(Variable() for _ in ra...
c10ae32a117863a4df1df1d4a2666f0caa8e943e
MetalSeed/python3_demo2
/base_syntax/base/the_list.py
499
3.671875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2019-04-26 21:39:07 # @Author : MetalSeed (=.=) # @Link : # @Version : $Id$ classmates = ['Michael', 'Bob', 'Tracy'] print('len(classmates) =', len(classmates)) print('classmates[0] =', classmates[0]) print('classmates[2] =', classmates[2]) print('classm...
3ce4f43aeb0732eddd88177beb3a5c55e99c9a86
darshanmest47/Pythonoops
/oops/methodoverloading.py
562
3.875
4
# In Python a method is said to be overloaded if it can perform multiple tasks # General method overloading example (not supported in python) class Methodover: def one(self,num1): print(num1) def one(self,num1,num2): print(num1,num2) def one(self,num1,num2,num3): print(num1,num2,n...
835584228978e6a4f5275ef9c4f4635683348dec
darshanmest47/Pythonoops
/oops/methodoverpython.py
527
3.609375
4
# method overloading python style class Methodovpython: def results(self, num1=None, num2=None, num3=None, num4=None): if num1 != None and num2 != None and num3 != None and num4 != None: return num1 + num2 + num3 + num4 elif num1 != None and num2 != None and num3 != None: r...
2cc4cc80205a7b5350e254bb7ec0137fa33a8041
darshanmest47/Pythonoops
/oops/sort.py
314
3.65625
4
list1= [1,3,2,5,100,0] for i in range(len(list1)): pos1 = list1.index(list1[i]) for j in range(len(list1)): pos2= list1.index(list1[j]) if list1[i] > list1[j]: temp = list1[pos1] list1[pos1] = list1[pos2] list1[pos2] = temp else: pass print(list1) # [100, 5, 3, 2, 1, 0]
33aa49cd41a89f73924aa29990eaa46fff43f55e
joel-jaimon/Certificate_Maker
/generate_certificates.py
1,193
3.5
4
#check installation of Pillow: def install_Pillow(package): import importlib try: from PIL import Image print("PIL already installed \n") except ImportError: print("Pillow not installed \n Installing Pillow... (Make sure you have an active internet connection.)") import pip...
04a50ca364fbff8ad7367adb31625d00352f69c8
srikanthpragada/python_14_dec_2020
/demo/assignments/char_freq.py
148
3.828125
4
s = "how do you do" used_chars = [] for ch in s: if ch not in used_chars: print(f"{ch} - {s.count(ch)}") used_chars.append(ch)
36c15c15ede4798c5dd4fc837bd668e6371f4dc1
srikanthpragada/python_14_dec_2020
/demo/basics/for_demo.py
87
3.5
4
for n in range(1, 10): print(n) for n in range(10, 0, -1): print(n, end= ' ')
348b24c93c33437d0431ecc6dcefd1b3056bf451
srikanthpragada/python_14_dec_2020
/demo/basics/factorial.py
134
4.3125
4
num = int(input("Enter a number :")) fact = 1 for n in range(2, num + 1): fact = fact * n print(f"Factorial of {num} is {fact}")
e4d5faad45457275d81cfe4be1e0d2fa6c9369ac
srikanthpragada/python_14_dec_2020
/demo/funs/prime.py
170
3.671875
4
def isprime(n): for v in range(2, n//2 + 1): if n % v == 0: return False return True print(isprime(11), isprime(35), isprime(3939391113))
8b931447c65e8fa149b275a1c8c841b9bd534b52
srikanthpragada/python_14_dec_2020
/demo/funs/line_with_defaults.py
225
3.578125
4
def print_line(length=10, char='-'): for n in range(length): print(char, end='') print_line() print("\nSrikanth Technologies") print_line(char='*') # Keyword arguments print() print_line(20, '.') # Positional
c3d980ccde2ec6c45f9f74eb20cc137a7e631697
jakubsolecki/MOwNiT
/lab2/zad_6.py
2,204
3.5
4
import numpy as np import time def add_vectors(v1, v2): if len(v1) == len(v2): start = time.time() for i in range(len(v1)): v1[i] += v2[i] end = time.time() return v1, end - start else: print("You shouldn't add vectors of different lengths") def cross_mult...
97a9e78a34d68244e5f4c14b3b35130d4cd82870
jakubsolecki/MOwNiT
/lab3/zad_2.py
965
3.5
4
import sympy as sp import math from lab3.zad_1 import to_table def lagrange_polynomial(x_values, y_values): if len(x_values) != len(y_values): exit("There must be exact same number of x and y values") return -1 x = sp.symbols('x') y = 0 for k in range(len(x_values)): i = 1 ...
571a7eb8101ba3438e83a58b132d5d35d661625a
parwisenlared/BiologicallyInspiredCW
/Scripts/PSO_2_configurable.py
9,170
3.828125
4
# Import modules import numpy as np import random import pandas as pd import matplotlib.pyplot as plt import time import NN_2 class PSO: def __init__(self, n_networks): """ The PSO object contains an input n_networks which is the number of neural networks that are to be initialised. ...
c5bbd43328a8c5d6e5133d72827cbbf94c219c26
AdaptiveStep/pokerhands
/Cards/testpairs.py
5,930
3.734375
4
#!/usr/bin/env python # -*- coding: utf8 -*- import random #Skapar en ordnad kortlek class Cards(list): def __init__(self,shuffled="no"): self.pointer = 0 #used in check for wins. #1 representerar Ess, .., 13 representerar kung siffror = range(1,14) # H = hjärter...
911d4753a01ab601346e3bc2f3b483a61d21c7ae
bspindler/python_sandbox
/classes.py
1,180
4.3125
4
# A class is like a blueprint for creating objects. An object has properties and methods (functions) # associated with it. Almost everything in Python is an object # Create Class class User: # constructor def __init__(self, name, email, age): self.name = name self.email = email self...
87510f359917c5655e65b842d39c5e6d97656701
kaynat149/CPS-3320
/hangman.py
846
3.9375
4
from random import choice word = choice(["Binary", "Bitmap", "Driver", "Editor", "Google", "Laptop", "Parser", "Router", "Python", "Update"]) guessed = [] wrong = [] tries = 6 while tries > 0: out = "" for letter in word: if letter in guessed: out = out + letter else: ...
7f3a1e22abc5ad919d8681847bad9097f41b631d
haitaka/mad
/src/main/python/test.py
271
3.578125
4
N1 = 10 N2 = 20 M = 24 delta = 10**(-3) def x(i): t = i - N1 if t in range(-N1, 0): return - float(t) / float(N1) elif t in range(0, N2): return float(t) / float(N2) if __name__ == '__main__': print([x(i) for i in range(0, N2 + N1)])
2a5e7d076fedc19e4dc9ad03dfbcf35826a06b67
OncDocCoder/projects
/distance.py
1,529
3.859375
4
import math blue = False while blue == False: dims = input('how many dimensions (2 or 3)?') if dims == '2': value_1 = (input('first point, x and y')) x1, y1 = value_1.split(',') x1, y1 = float(x1), float(y1) value_2 = (input('second point x and y')) x2, y2 = ...
0bf1af41e1afa7b7a5ebc0a9a08663ce138b1e8b
OncDocCoder/projects
/elipses.py
2,593
3.625
4
#x2/a2 + y2/b2 = 1 import matplotlib import math # a>b # the length of the major axis is 2a # the coordinates of the vertices are (±a,0) # the length of the minor axis is 2b # the coordinates of the co-vertices are (0,±b) # the coordinates of the foci are (±c,0) # , where c2=a2−b2. #(x-h)^2/a^2 + (y-v)^2/...
527d334d8909c84b131250c70d53c402556b1d30
Manishthakur1297/Card-Game
/Card_Game.py
5,225
3.953125
4
import random class Game: # Intialize Cards and Players def __init__(self, n): self.size = n self.card_names = {1: "A", 2:"2", 3:"3", 4:"4", 5:"5", 6:"6", 7:"7", 8:"8", 9:"9", 10:"10", 11:"J", 12:"Q", 13:"K"} self.card_values = {"A": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8...
ed972573af7247640ecaafc94c09b096cce1e838
karelbondan/Intro_to_program
/1.py
226
4.0625
4
# -*- coding: utf-8 -*- """ Created on Mon Sep 21 12:37:57 2020 @author: karel """ degrees = eval(input("Enter number= ")) radians = degrees*3.14/180 print("Degrees:", degrees) print("Radians:", degrees*3.14/180)
8a8c5b36cafb18508e837b9d398c9d3516aaa5a5
mintas123/MIW
/Class04/knn.py
3,584
3.546875
4
import numpy as np # for data from matplotlib import pyplot as plt # for visualization import math # for square root from sklearn.preprocessing import LabelEncoder # for labeling data from scipy.stats import mode # for voting plt.style.use('seaborn-whitegrid') def plot_dataset(f, l): # Females x0 = f[l ...
3f30e91059cba3f37fb76224ab070c369a250611
Demondul/python_algos
/functionIntermediateII.py
1,057
3.578125
4
# PART I """ students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ] for student in students: print(str(student["first_name"]) + "...
6acb4ba5dcc6ae13f0ca0552cacee774b249218f
Demondul/python_algos
/store.py
392
3.53125
4
import product class Store: def __init__(self,products,address,owner): self.products=products self.address=address self.owner=owner def add_product(item): self.products.append(item) def remove_product(item_name): for item in range(0,len(self.pro...
c12890b5a29c284c0cd5bdc4591ea94e057ac06b
Sammyalhashe/CSC_Course_Work
/twoSum_withIceCream.py
2,466
3.59375
4
'''input "2" "4" "5" "1 4 5 3 2" "4" "4" "2 2 4 3" ''' class tuples2: def __init__(self, val1, val2): self.tupl = (val1, val2) def comparitor(self): return self.tupl[1] t = int(input().strip()) for a0 in range(t): m = int(input().strip()) n = int(input().strip()) a = list(map(i...
b92950bff370296369bee2e13b4f1e8d3cbcf79a
Sammyalhashe/CSC_Course_Work
/FindInversions.py
1,045
4.09375
4
def merge(left, right): swaps = 0 result = [] i, j = 0, 0 while (len(left) > i and len(right) > j): if left[i] <= right[j]: result.append(left[i]) i += 1 else: swaps += len(left) - i result.append(right[j]) j += 1 if i =...
7b2a85d1a6226de574ba11269572c80480f6cc9f
Sammyalhashe/CSC_Course_Work
/Merge_Sort_Pythonic.py
1,686
4
4
'''input 10 "12 4 19 3 2" "2 8 9 17 7" "2 3 15 9 4" "16 10 20 4 17" "18 11 7 20 12" "19 1 3 12 9" "13 5 7 9 6" "9 18 3 16 10" "16 18 6 3 9" "1 10 14 19 6" ''' # More pythonic implementation of merge sort def Merge_Sort_Pythonic(array): return mergesort_Pythonic(array) def mergesort_Pythonic(array): if(len(a...
c87810a69b35215a9e8590580dd19a75ccd5029e
Sammyalhashe/CSC_Course_Work
/minimizeUnfairness.py
1,589
3.890625
4
"""Greedy Algorithm minimizes unfairness of an array by choosing K values unfairness == max(x0,x1,...,xk)-min(x0,x1,...,xk) Variables: int: N -> number of elements in list int: K -> number of list elements to choose list: vals -> list to minimize unfairness Example Input: 10 (N) 4 (K) (The Re...
304d59ca7759125373f19c497c664438c7f78b14
DinaShaim/GB_Algorithms_data_structures
/Les_5_HomeWork/les_5_task_1.py
2,114
3.515625
4
# Пользователь вводит данные о количестве предприятий, их наименования и прибыль # за 4 квартал (т.е. 4 числа) для каждого предприятия. # Программа должна определить среднюю прибыль (за год для всех предприятий) и # отдельно вывести наименования предприятий, чья прибыль выше среднего и ниже среднего. from collect...
afbb4590c1e77843dc2dbdcc20f77fa75716d2dd
DinaShaim/GB_Algorithms_data_structures
/Les_1_HomeWork/les_1_task_5.py
811
3.984375
4
#Пользователь вводит две буквы. Определить, на каких местах алфавита они стоят, # и сколько между ними находится букв. import string print("Введите две строчные буквы латинского алфавита от a до z:") letter1 = str(input("первая буква = ")) letter2 = str(input("вторая буква = ")) index1 = ord(letter1) - ord(...
b2a620d6e016513b0c8eeddc1fdf4f48206c0e49
DinaShaim/GB_Algorithms_data_structures
/Les_4_HomeWork/les_4_task_1.py
8,303
4.3125
4
# Проанализировать скорость и сложность одного любого алгоритма из разработанных # в рамках домашнего задания первых трех уроков. # Задание № 2 урока № 2: # Посчитать четные и нечетные цифры введенного натурального числа. # Например, если введено число 34560, в нем 3 четные цифры (4, 6 и 0) и 2 нечетные (3 и 5)....
c676c6a3e43c95656e6643a30a91120a3e3f9e4e
openseg-group/openseg.pytorch
/lib/utils/tools/average_meter.py
626
3.59375
4
#!/usr/bin/env python #-*- coding:utf-8 -*- # Author: Donny You (youansheng@gmail.com) # Utils to store the average and current value. from __future__ import absolute_import from __future__ import division from __future__ import print_function class AverageMeter(object): """ Computes ans stores the average and ...
c9690b333c631fa91c79405707d45182ce1874f8
Doodlebug511/hello-world
/myscraper.py
2,412
3.8125
4
# basic web page scraper as final project for bootcamp... # import needed modules import requests from bs4 import BeautifulSoup import pandas as pd # bring desired webpage into python and create soup object via beautifulsoup url = 'https://pauladeen.com/recipe/mashed-potatoes-with-sautaed-mushrooms/' # url...
ec6d2983bfe00b677d39b49759406dc482e60fd0
vankhoakmt/pyHTM
/pyhtm/support/getsetstate.py
1,134
3.890625
4
def GetSomeVars(self, names): """Grab selected attributes from an object. Used during pickling. Params: names: A sequence of strings, each an attribute name strings Returns: a dictionary of member variable values """ return {i: getattr(self, i) for i in names} def CallReader(...
b3b7bab386391dab91910d4bd64a5c094da05a94
shwetasharma18/test_questions
/insert.py
359
3.859375
4
def insertion_sort(num): i = 1 while i < len(num): temp = num[i] j = i - 1 while j >= 0 and temp < num[j]: num[j+1] = num[j] j = j -1 num[j+1] = temp i = i + 1 return num l = [5,...
eba24ce1802c67d7f48289e4abd88f0084ea317b
abd124abd/algo-toolbox
/week3/1.py
356
3.671875
4
#python3 # money change import sys def get_money_change(n): count = 0 if n <= 0: return 0 denominations = [10,5,1] for i in denominations: count = count + int(n / i) n = n % i return count if __name__ == '__main__': input = sys.stdin.read() n = int(inpu...
3eb6094bde8eb1a842fd4cbcbd0049cb2fd81373
abd124abd/algo-toolbox
/week2/8.py
863
3.96875
4
#python3 # last digit of sum of squares of fib from sys import stdin # last digit sum of squares at n = ((last digit at n) * (last digit at n + 1)) % 10 def last_digit_sum_squares_fib(n): if n <= 2: return n last_digits = last_digits_fib(n+1) return (last_digits[0] * last_digits[1]) % 10 d...
91d55ae511d7b2c47a07569496d1e55d6bbc2204
chrispoch/adventofcode
/13.py
1,825
3.5625
4
import os import sys debug = False fileName = "" try: fileName = sys.argv[1] if len(fileName) < 1: fileName = "13.txt" except: fileName = "13.txt" print(fileName) with open(fileName) as file: time = int(file.readline()) note = file.readline() note2 = note.replace(",x","") buses = n...
d5dee3c68ce06e1f95046d443f68c447be0af944
korynewton/Intro-Python-II
/src/room.py
783
3.59375
4
# Implement a class to hold room information. This should have name and # description attributes. from item import Item class Room: n_to = None s_to = None e_to = None w_to = None def __init__(self, name, description): self.name = name self.description = description self.i...
3b4ffa6d1ced6ad6b7328cd686d6cd5868dd6b18
KuanHsuanTiffanyLin/stanCode-project
/stanCode Projects for GitHub/breakout_game/breakout.py
1,535
3.953125
4
""" stanCode Breakout Project Adapted from Eric Roberts's Breakout by Sonja Johnson-Yu, Kylie Jue, Nick Bowman, and Jerry Liao ----------------------------------------- SC101 - Assignment 2 File: breakout.py Name: Tiffany Lin """ from campy.gui.events.timer import pause from breakoutgraphics import BreakoutGraphics F...
69b7fe0a027b868cc731e45c263387893e9db832
Tsunamicom/Hackerrank-Solutions
/FromParagraphsToSentences.py
702
3.859375
4
# https://www.hackerrank.com/challenges/from-paragraphs-to-sentences sample = input() def processSentences(text): sentence = [] isQuote = False charCount = 0 sentenceTerminators = ['.', '?', '!'] for character in text: sentence.append(character) charCount += 1 if chara...
e425c1e23f27acc4519eea7506cbaebd75e747b1
MiaoJiawei/Python-voltage-correct
/correct.py
606
3.828125
4
import matplotlib.pyplot as plt def correct_func(voltage, current, resistance): voltage_correct = [] for i in range(len(voltage)): voltage_correct.append(voltage[i] - (current[i] * resistance)) return voltage_correct voltage = [8.19,2.72,6.39,8.71,4.7,2.66,3.78] current = [7.01,2.78,6.47,6.71,4.1,...
f9684d6cafaf0381618bd01423b4a7227427e665
brunston/goeuler
/3.py
923
3.828125
4
""" brunston 2016 Euler 3 """ from math import ceil, sqrt #make is_prime only search to square root #make main() begin with low values that % = 0, then divide n by that value to get the corresponding # big value and test *that* value for prime-ness. def is_prime(n): if n % 2 == 0: return True else: ...
d17ec96b85f652027381ee14c761ecd15758e829
sadipgiri/Sensor-DashBoard
/sensor_api.py
2,619
3.59375
4
#!/usr/bin/env python3 """ sensor_api - python3 program to return sensor readings hitting the given endpoints Author: Sadip Giri (sadipgiri@bennington.edu) Created: 15 May, 2018 """ import re import requests import json def last_hour_sensor_data(): try: req = requests.request('GET', 'http://54...
c246c6a153b6bc176ed0e279a60d32f1b2100711
ntkawasaki/complete-python-masterclass
/7: Lists, Ranges, and Tuples/tuples.py
1,799
4.5625
5
# tuples are immutable, can't be altered or appended to # parenthesis are not necessary, only to resolve ambiguity # returned in brackets # t = "a", "b", "c" # x = ("a", "b", "c") # using brackets is best practice # print(t) # print(x) # # print("a", "b", "c") # print(("a", "b", "c")) # to print a tuple explicitly i...
acf3384d648aa16c781ac82c61b8e3c275538bae
ntkawasaki/complete-python-masterclass
/10: Input and Output/shelve_example.py
1,638
4.25
4
# like a dictionary stored in a file, uses keys and values # persistent dictionary # values pickled when saved, don't use untrusted sources import shelve # open a shelf like its a file # with shelve.open("shelf_test") as fruit: # makes a shelf_test.db file # fruit["orange"] = "a sweet, orange fruit" # fruit[...
fcd60015393e712316586a32f75462eff2f4543f
ntkawasaki/complete-python-masterclass
/11: Modules and Functions/Functions/more_functions.py
2,460
4.125
4
# more functions! # function can use variables from main program # main program cannot use local variables in a function import math try: import tkinter except ImportError: # python 2 import Tkinter as tkinter def parabola(page, size): """ Returns parabola or y = x^2 from param x. :param page: ...
b9096be499b5324792acee537eb36a6cf1121c5b
ntkawasaki/complete-python-masterclass
/6: Flow Control/if_program_flow.py
1,098
4.0625
4
print() name = input("Please tell me your name: ") age = int(input("How old are you, {0}? ".format(name))) if not (age < 18): print("You are old enough to vote.") print("Please put an X in the box.") else: print("Please come back in {0} years".format(18 - age)) # print("Please guess a number between 1 an...
053003b71dcec146dcccdfcbba06c4bcd8406f54
ntkawasaki/complete-python-masterclass
/6: Flow Control/for_loops.py
862
3.59375
4
# for i in range(1, 21): # print("i is now {}".format(i)) number = "9,333,455,768,234" cleaned_number = "" # for i in range(0, len(number)): # if number[i] in "0123456789": # cleaned_number = cleaned_number + number[i] # concatenation of strings # through a sequence of values for char in number: ...
4ef8a7a07238c6930ff101f62fed0eead560b3bd
TheLoneGuy/Home-Loan-Calculator
/index.py
8,544
3.546875
4
from tkinter import * from tkinter import ttk from tkinter import font from threading import Timer import math import random from Graph import * from background import Background random.seed() TRANSPARENT = "#576890" DECIMAL_POINTS = "{:.2f}" inputs = { 'loan': 10000, 'down': 10, 'rate': 4.5...
72808324afe7943941c3ea9673bfba435561ab82
ZibingZhang/Minesweeper
/src/minesweeper.py
13,869
3.859375
4
import tkinter as tk from random import randint from itertools import product from cell import Cell class Minesweeper(object): """ The minesweeper game. The minesweeper game. It includes all the widgets for the GUI. Class Attributes: PAD_X (int): The amount of horizontal padding for the top and ...
b44f64493cd2afd91cb134580625091c4ca0aa96
dlcios/coding-py
/basic/mail_re.py
376
3.546875
4
import re #验证email的正则表达式,邮箱名可以使英文字母或数字或 -,_ 符号,后巷后缀网址名可以是英文或数字,域名可以使 com,org,edu #例: chu-tian-shu_1981@heibanke2015.com # mail = "1905790854@qq.com" mail = "chu-tian-shu_1981@heibanke2015.com" pattern = re.compile(r"^[\w\-\,]+@[a-zA-Z0-9]+\.(com|org|edu){1}$") match = pattern.match(mail) if match : print('ok') ...
42b5a11339851544418f71b3cd7e1ceb8ab46966
dlcios/coding-py
/basic/def.py
594
3.65625
4
#coding: utf-8 # to16mod = hex # n1 = to16mod(25) # print(n1) # #定义函数 # def mabs(num): # if num > 0: # return num # else: # return -num # a = -15 # b = 15 # print(mabs(a), mabs(b)) # def power(x): # return x * x # print(power(a)) # def powern(x,y = 2): # s = 1 # while y > 0: ...
50c94f0dcf4ed5abc4af1bd3a4b6fe7a190a3471
Geo-Root/code5
/code5/console_scripts.py
2,526
3.71875
4
#!/usr/bin/env python """ code5 - Convert stdin (or the first argument) to a Code5 Code. When stdout is a tty the Code5 Code is printed to the terminal and when stdout is a pipe to a file an image is written. The default image format is PNG. """ import sys import optparse import os import code5 def main(args=sys.arg...
b0bce312122d6b733dc4c63bd6f7e432e8084d78
georgebzhang/Python_LeetCode
/14_longest_common_prefix.py
854
3.703125
4
class Solution(object): def longestCommonPrefix(self, strs): if not strs: return '' lcp = '' ind = 0 while True: letters = [] for item in strs: if ind == len(item): return lcp letters.append(it...
af3a21971e6ca7593bdc88efb05563dd37892cb6
georgebzhang/Python_LeetCode
/142_linked_list_cycle_II_2.py
1,838
3.734375
4
class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def detectCycle(self, head): def hasCycle(): slow = head while fast[0] and fast[0].next: slow = slow.next fast[0] = fast[0].next....
4bc07ecb11ed78ec76815d8058ea67924109584d
georgebzhang/Python_LeetCode
/88_merge_sorted_array_2.py
670
3.78125
4
class Solution(object): def merge(self, nums1, m, nums2, n): if not n: return i, j = m-1, n-1 ind = m+n-1 while j >= 0: if i < 0 or nums2[j] > nums1[i]: nums1[ind] = nums2[j] j -= 1 else: nums1[ind] =...
b0757ed59534e19f646e054abb4ba6b001e5cc2e
georgebzhang/Python_LeetCode
/22_generate_parentheses.py
958
3.578125
4
class Solution: def generateParenthesis(self, n): def permute(perm, rem): if not rem: perms.add(perm[:]) for i in range(len(rem)): permute(perm+rem[i], rem[:i]+rem[i+1:]) def validParenthesis(s): mapping = {')': '('} st...
a3788a58c6702af9e8bd0c397f298bf6c74f979f
georgebzhang/Python_LeetCode
/690_employee_importance_2.py
1,224
3.8125
4
from collections import deque class Employee: def __init__(self, id, importance, subordinates): # It's the unique id of each node. # unique id of this employee self.id = id # the importance value of this employee self.importance = importance # the id of direct subor...
7bce04d20e4c7b828831040372bfddb25820ebd0
georgebzhang/Python_LeetCode
/62_unique_paths_2.py
509
3.640625
4
from math import factorial class Solution(object): def uniquePaths(self, m, n): def num_combinations(n, k): return int(factorial(n)/(factorial(k)*factorial(n-k))) steps = m-1 + n-1 down_steps = m-1 return num_combinations(steps, down_steps) def print_ans(self, ans...
cf66a9a5256601495187f39d1db14b329138207b
georgebzhang/Python_LeetCode
/139_word_break.py
729
3.5625
4
class Solution(object): def wordBreak(self, s, wordDict): def wordBreakRec(s): if s in wordSet: return True for i in range(len(s)): s1 = s[:i+1] if s1 in wordSet: s2 = s[i+1:] if wordBreakRec(s2):...
ff90d9c953787cbb9975ca6130b5a2cd810a3716
georgebzhang/Python_LeetCode
/973_k_closest_points_to_origin_6.py
714
3.5
4
from heapq import heapify, heappop, heappush, nsmallest class Point(object): def __init__(self, c): # c for coords self.c = c self.dist2 = c[0] ** 2 + c[1] ** 2 class Solution(object): def kClosest(self, points, K): l_points = [] for c in points: l_points.append...
07cb7d2e8c636cb9ba70afe4d555be52a9cad251
georgebzhang/Python_LeetCode
/287_find_the_duplicate_number.py
470
3.65625
4
class Solution(object): def findDuplicate(self, nums): s = set() for i in range(len(nums)): if nums[i] in s: return nums[i] else: s.add(nums[i]) return -1 def print_ans(self, ans): print(ans) def test(self): n...
cbc9d6af1d0a443eb6c9f4c2c0da318e9653a911
georgebzhang/Python_LeetCode
/102_binary_tree_level_order_traversal.py
2,149
3.765625
4
from collections import deque class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def levelOrder(self, root): if not root: return [] q = deque() q.append(root) levels_vals = [] ...
6e393d2f96a5cc60b428b5fb699079e75586280e
georgebzhang/Python_LeetCode
/python_heapq.py
1,443
3.8125
4
import heapq class Solution(object): class Person(object): def __init__(self, name, age): self.name = name self.age = age class PersonHeap(object): def __init__(self, l_init=None, key=lambda person: person.age): # -person.age for max heap on age self.key =...
22f0b2868c705c4980c2cfac39349ff93974cc80
georgebzhang/Python_LeetCode
/43_multiply_strings_2.py
857
3.609375
4
class Solution: def multiply(self, num1, num2): def str2int(s): result = 0 for k in s: result = 10*result + ord(k)-ord('0') return result def int2str(i): digits = [] while i > 0: digits.append(i % 10) ...