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
f9ddd6a203df229fe3036d80b222cf2472ba7956
mounarajan/NLP
/16_Chinking.py
1,630
3.96875
4
# -*- coding: utf-8 -*- """ Created on Sat Sep 1 00:00:00 2018 @author: Nikhil """ """ Chinking : Chinking means removing a chunk for chunk. The chunk which you want remove from a chunk is called chink. Why to do : In chunking you have seen that, there are lot of words which you do...
2f0aebe310530d9540a8cff71661f3a548d2efa5
kobeding/python
/lxfpy/class/err_raise.py
520
3.71875
4
class FooError(ValueError): pass #抛出错误,捕捉到一个错误就是捕获到该class的一个实例 #自己编写函数也可以抛出错误 def foo(s): n = int(s) if n == 0: raise FooError('invalid value:%s' % s) return 10 / n foo('0') main() print('END') #产生错误,END不能输出 """ Traceback (most recent call last): File "err_raise.py", line 11, in <module> foo('0') File "e...
01347fe0b4c86632b1cc24c578e074d8f3f9af68
kobeding/python
/2016/use_itertools.py
1,010
3.890625
4
#!/usr/bin/env python3 import itertools #itertools提供了很多非常有用的用于操作迭代对象的函数 #返回值不是list,而是iterator,只有通过for迭代生成 #count()创建一个无限迭代器 natuals = itertools.count(1) #takewhile()根据条件判断来截取一个有限的序列 ns = itertools.takewhile(lambda x:x <= 10,natuals) print(list(ns)) #[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for n in natuals: print(n,end=',') ...
e9840375c81c4bc383698ab2fd105ddabfd0f27f
kobeding/python
/lxfpy/class/special_getattr.py
811
4.15625
4
#!/usr/bin/python3.5 #__getattr()__:动态的返回一个属性 class Student(object): def __init__ (self): self.name = 'kobe' def __getattr__ (self,attr): #调用不存在,会试图调用这个来尝试获取属性 if attr == 'score': return 99 if attr == 'age': return lambda:25 #返回函数也是完全可以的 raise AttributeError(" Student() object has no attribute '%s' "...
5089c21f68c69902d083c928a0bda7d42597c21e
kobeding/python
/lxfpy/the_list.py
356
3.953125
4
#!/usr/bin/python3.4 classmate = ('Michael','Bob','Tracy') print('classmate=',classmate) print('LEN=',len(classmate)) print('classmate[0]=',classmate[0]) print('classmate[1]=',classmate[1]) print('classmate[2]=',classmate[2]) print('classmate[-1]=',classmate[-1]) #cannot modify tuple; #classmate.pop() #print('classmate...
3e8876136e71147e7a4ffa745a7a15e3e04de87c
kobeding/python
/2015/generator_fib.py
203
3.859375
4
#!/usr/bin/python3.4 # Filename: generator_fix.py def fib(max): n,a,b = 0,0,1 while n < max: print(b) a,b = b,a+b n = n+1 x = int(input('please input a number:')) fib(x)
0eaf6a07089c9123ed5c9852633eb26423ad88b2
kobeding/python
/2015/if.py
212
3.796875
4
#!/usr/local/bin/python3.5 #Fliename if.py number = 23 guess = int(input('Enter an integer:')) if guess == number: print('1.') print('2.') elif guess < number: print('3.') else: print('4.') print('Done')
8e1c060de8064804efc2a2e7d7255967ade6f435
kobeding/python
/2015/return_func.py
792
3.6875
4
#!/usr/bin/python3.4 # 关于返回函数: #看的不是很明白 def lazy_sum(*args): def sum(): ax = 0 for n in args: ax = ax + n return ax return sum f = lazy_sum(1,2,3,4,5,6,7,8,9) print(f) print("----") print(f()) def count(): fs = [] for i in range(1,4): def f(): re...
727284a93eceba81fa9304142df50c5ec28fc808
kobeding/python
/2016/do_queue.py
1,451
3.734375
4
#!/usr/bin/python3.5 #进程间通信通过Queue,Pipes等多种方法来交换数据 #multiprocessing(跨平台多进程)需要模拟出fork()的效果 #父进程所有python对象都必须通过pickle序列化再传到子进程 #在window下调试失败,是不是考虑pickle失败了 #进程接收的参数都是序列化后传过来的,如果参数无法序列化,就无法传送 #建议使用int str 等基本类型做参数 from multiprocessing import Process,Queue import os,time,random #写数据进程的执行代码 def write(q): print('Process to...
47ee26a88c5ceb608109d9eed51d5856d1aaf037
kobeding/python
/2016/do_subprocess.py
1,607
3.546875
4
#!/usr/bin/python3.5 #很多时候,子进程并不是自身,而是外部进程,需要控制子进程的输入输出 #在python代码中运行命令 $ nslookup www.python.org import subprocess #subprocess模块可以非常方便的启动一个子进程,然后控制其输入输出 print('$ nslookup www.python.org') r = subprocess.call(['nslookup','www.python.org']) print('Exit code:',r) print('$ nslookup') p = subprocess.Popen(['nslookup'],stdi...
3e6208cbd7e14ee93e40e7561a469df84ba5e8d8
omkarfirame/Coursera-Machine-Learning
/Linear Regression/Regularized_linear_regression.py
5,486
3.609375
4
import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.io import loadmat data = loadmat("ex5data1.mat") X = data["X"] Xval = data["Xval"] y = data["y"] yval = data["yval"] Xtest = data["Xtest"] ytest = data["ytest"] theta = np.ones((X.shape[1]+1,1)) ""...
9bb10940ebbb628067c7cf9056cb6ba9ec87e72b
Zelandini/Calculator-python-script-by-ZBG
/Calculator.py
4,505
4.15625
4
# <===========================================># # This program made by Zelandini Borromeu Guterres # If there's any question ask me via: # zelandiniduarte@gmail.com # Thank for downloading # hastag i don't win money from this # Novince programmer #PEACE!!! from colorama import Fore # Not necessary can be deleted ...
567adfaa1820360595371c8b2da8cef1a5650424
nehajain803/sessions
/control stat.py
1,086
4.09375
4
# if else a=20 b=55 if(a>b): print("a is less than b") else: print("b is greater") # User input n=int(input("Enter first number")) m=int(input("Enter second number")) if n>m: print(n,"is greater") else: print(m,"is greater") # elif a=int(input("Enter first value")) b=int(input("E...
bb697b4af9b5656d44395725087c0908dd4ee2ab
nehajain803/sessions
/exp.py
1,517
3.84375
4
# Ass1 try: a=10/0 print (x) except NameError: print("Variable x is not defined") except: print("Something else went wrong") else: print("no exception") # Ass2 try: a=int(input("Enter a:")) b=int(input("Enter b:")) c=a/b print("a/b = %d"%c) except Exception: print(...
6d5b012250a4f93f41d076b89db26dc8dd1160fb
MortalHappiness/LA2019Fall
/HW1/p1.py
1,441
3.953125
4
import numpy as np def p1_has_cycle(sets): # TODO # return True if the graph has cycle; return False if not ''' HINT: You can `print(sets)` to show what the matrix looks like If we have a directed graph with 2->3 4->1 3->5 5->2 0->1 0 1 2 3 4 5 0 0 0 -1 1 0...
3f89ff24fa8ee3fc44d9f3abc6820c4faedc595d
kushal-manohar/KUSHAL532
/KUSHAL532/packages/module.py
673
3.96875
4
def add(num1,num2): return num1+num2 def isprime(n): count=0 for i in range(1,n+1): if n%i==0: count=count+1 print("number of factors for",n,"is",count) if count==2: print(n,"is a prime") else: print(n,"is not prime") def evod(s,e): for i in...
ba9a0648bc145bae5e2d58c5e69e6b70abe0be33
kdongxie/TIL
/python/Read_txt.py
273
3.515625
4
# Read files # 1. open() (구)방식 # f = open("mulcam3.txt", 'r') # all_text = f.read() # print(all_text) # f.close() # 2. with open() # with open("mulcam3.txt", 'r') as f: # lines = f.readlines() # list # for line in lines: # print(line) # print(lines)
7a4f798722f83258e2a8b686894d543858d12db0
FrankieSanzica/Python
/test.py
788
4.03125
4
#!/usr/bin/env python import sys ## Sort list with 0's at the end test = [0, 5, 3, 1, 2, 4, 0] test = sorted(test) for number in test: if number == 0: test.append(test.pop(0)) print test ### Creating classes class Zombie: def __init__(self, size, color, speed): self.size = size self.co...
24711ce83542ada2844be4d5b1795f7dfb4a517c
nikhsharma/codewars_katas
/6_kyu/your_order_please_python/yop_solution.py
172
3.5
4
def order(sentence): res = [] for i in range(1, 10): for word in sentence.split(): if str(i) in word: res.append(word) return " ".join(res)
d898d1161a3b6f21ca5ca6dc57bd05a6380b2e06
lau1512/LunarLanderAI
/AI_LunarLander.py
2,520
3.75
4
# Lunar Lander: AI-controlled play # Instructions: # Land the rocket on the platform within a distance of plus/minus 20, # with a horizontal and vertical speed less than 20 # # Controlling the rocket: # arrows : Turn booster rockets on and off # r : Restart game # q / ESC : Quit from LunarLander ...
5d33a1676ee7291f0ccb7ac207f7d9af3ceb8d06
ngm01/Python_OOP
/hospital.py
1,261
3.546875
4
class Hospital(object): def __init__(self, name, capacity): self.name = name self.capacity = capacity self.patients = [] * self.capacity self.beds = ["Empty"] * self.capacity def admit(self, *args): for p in args: if "Empty" not in self.beds: print "Sorry, {}. The hospital is full.".format(p.name) ...
a8432c453782426f19ccd621ebe253c5e68248b3
JC6/coursera-py4e-assignments
/chapter_10/assignment_10_2.py
447
3.6875
4
name = input("Enter file:") if len(name) < 1: name = "mbox-short.txt" handle = open(name) words = list() word_dict = dict() for line in handle: if line.startswith("From") and len(line.split()) > 2: pos = line.find(":") word = line[pos - 2:pos] if word not in words: words.appe...
a6aa1d72d50415db9784715a29b8251dbc8a7178
deepshikha-hub/C170
/Gradewise_percentage_calculation.py
2,337
3.90625
4
from tkinter import * root = Tk() root.geometry("600x600") percentage_grade_3_label = Label(root) percentage_grade_5_label = Label(root) percentage_grade_10_label = Label(root) class grade_3(): def __init__(self, language_arts, mathematics): self.language_arts = language_arts self.math...
ce3b74634ec47e5842ee5fe4215654bdd1b8fe1e
modevops/python_practice
/hackerrank/clarketm/built-ins/zipped.py
384
3.84375
4
#!/usr/bin/env python3 # Zipped! # https://www.hackerrank.com/challenges/zipped/problem if __name__ == "__main__": N, X = map(int, input().spit()) grades_by_subject = [] for _ in range[x]: grades_by_subject.append(map(float, input().split())) for grades_by_student in zip(*grades_by_subject)...
51a7575474cea040d9f858861dce516ac1175b62
modevops/python_practice
/hackerrank/clarketm/built-ins/any_or_all.py
460
3.84375
4
#!/usr/bin/env python3 # Any or All # https://www.hackerrank.com/challenges/any-or-all/problem if __name__ == "__main__": N = int(input()) array = list(map(int, input().split)) is_postive = all(n > 0 for n in array) # Using `reversed` # is_palindrome = any(str(n) == ''.join(reversed(str(n))) fo...
54e9e7aa74488673a51e19806a01dbab5648587e
RescueDiver/test3
/MOD.py
1,592
3.796875
4
def truncate(number: float, digits: int) -> float: pow10 = 10 ** digits return number * pow10 // 1 / pow10 def yes_or_no(question): # used to start and end loop reply = str(input(question + ' (y/n): ')).lower().strip() if reply[0] == 'y': return if reply[0] == 'n': retur...
58d9efb609ca6d45094c284ed3586c05da867e46
Rimesh/Python-LPTHW
/ex19.py
849
3.9375
4
# Title: Exercise 19 - Functions and Variables # from Learn Python the hard way # Date: 2nd March 2017 # by Rimesh Jotaniya # Description: passing parameters to a function def cheese_and_crackers(cheese_count, boxes_of_crackers): print "you have %d cheeses!" % cheese_count print "you have %d boxes of crackers!...
b564685c9f5f899cd3562a8cdbe89415b006244c
Rimesh/Python-LPTHW
/ex13.py
390
3.703125
4
# Title: Exercise 13 - Parameters, Unpacking, Variables # from Learn Python the hard way # Date: 1st March 2017 # by Rimesh Jotaniya # Description: taking command line arguments from sys import argv script, first, second, third = argv print "The script is called: ", script print "Your first variable is: ", first pri...
359b0e6beff760031984f66a6ba8728c2f9c9409
m-sterling/Project-Euler-Py
/p014.py
356
3.6875
4
if __name__ == "__main__": longest = 0 for i in range(13, 1000000): n = i chain = 1 while not n == 1: if n % 2 == 0: n /= 2 else: n = 3*n + 1 chain += 1 if chain > longest: longest = chain ...
01751fc68c652475aee8f2d7afe62912b5372826
FrozenLemonTee/DSAA
/data_structure/myStack.py
1,880
3.625
4
from DSAA.data_structure.basic.node import Node from DSAA.data_structure.basic.LinkedList import LinkedList import random from time import sleep class myStack(LinkedList): def push(self, node): if not self.is_empty(): self.last_node.modifyNextNode(node) self.last_node = node ...
25472eeee2c6403975bc1c974a764d24f1859f06
FrozenLemonTee/DSAA
/algorithm/Quick_sort_ok.py
1,940
3.53125
4
import time from DSAA.data_structure.basic.init_structure import initializeLinkedList from DSAA.data_structure.basic.node import Node from DSAA.algorithm.Nodes_changing import changeNode def quickSort(my_linked_list, index_left, index_right): if index_left >= index_right: return node_pointer = my_lin...
a39930276b3c78aa998260e9c3759c096645399b
SalihErenYuceturk/DSA-Python
/algorithms/search/sequential_search.py
185
3.609375
4
def sequential_search(list_in, item_in): index = 0 while index < len(list_in): if list_in[index] == item_in: return True index += 1 return False
bafa2907e3618fc5307edf6776b6a1a1dcd12d26
SalihErenYuceturk/DSA-Python
/algorithms/sort/quick_sort.py
1,028
3.828125
4
def quick_sort(list_in): quick_sort_helper(list_in, 0, len(list_in) - 1) def quick_sort_helper(list_in, first, last): if first < last: split_point = partition(list_in, first, last) quick_sort_helper(list_in, first, split_point - 1) quick_sort_helper(list_in, split_point + 1, last) d...
daeebad2c0e0677d61328b5aaf292d2b252d915e
SalihErenYuceturk/DSA-Python
/data_structures/trees/binary_tree_nodes.py
1,080
3.84375
4
class BinaryTree: def __init__(self, root): self.key = root self.left_child = None self.right_child = None def insert_left(self, new_node): if self.left_child is None: self.left_child = BinaryTree(new_node) else: tree = BinaryTree(new_node) ...
edf82e172ea6fd3f28d6dd447723b2efe7d39dca
SalihErenYuceturk/DSA-Python
/exercises/3_basic_data_structures/general_balanced_brackets.py
577
3.671875
4
from data_structures.linear.stack import * def check_balance(string_in): balance = Stack() open_brackets = "([{" close_brackets = ")]}" for element in string_in: if element in ")]}" and balance.is_empty(): return False if element in "([{": balance.push(element) ...
4c374a38d319f02def009c01dd57f401d3aa9d33
sviridchik/prep_for_isp
/isp/32.py
961
3.640625
4
class unflat_iter: def __init__(self, iterable): self.iters_stack = [iterable.__iter__()] def __iter__(self): return self def __next__(self): while True: if len(self.iters_stack) == 0: raise StopIteration try: e = self.iters_...
56d8fc9a6cd0b1e533bb50b69bf0d6698f74acd8
Draygo22/First-Website
/Task 7/example.py
3,958
4.03125
4
#************* HELP ***************** #REMEMBER THAT IF YOU NEED SUPPORT ON ANY ASPECT OF YOUR COURSE SIMPLY LOG IN TO www.hyperiondev.com/support TO: #START A CHAT WITH YOUR MENTOR, SCHEDULE A CALL OR GET SUPPORT OVER EMAIL. #************************************ # PLEASE ENSURE YOU OPEN THIS FILE IN IDLE othe...
6ec3cb3b65eb836d64d79208fb86f8f466522783
timoangerer/cs50-ai
/0-tic-tac-toe/tictactoe.py
3,880
3.9375
4
""" Tic Tac Toe Player """ import math import copy X = "X" O = "O" EMPTY = None def initial_state(): """ Returns starting state of the board. """ return [[EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY]] def player(board): """ Returns player who h...
d1b1cad4b92e715045cb74b09120c632dc199601
combat1818/SmallestEnclosingCircle
/GameState.py
1,022
3.609375
4
class GameState(): def __init__(self): self.points=[] self.currentCircle=((0,0),0) self.tripleToCheck=(0,0,0) self.order=0 self.simulating=False def addPoint(self,point, color): self.points.append((point,color)) #print(self.points) def getPoints...
009d07375b64985b79e9b91615222838b1b4a8c9
mikedelgaudio/CS-555-GEDCOM
/src/modules/gender_check.py
191
3.5625
4
# Husband in family should be male and wife in family should be female def husb_wife_gender(husb,wife): if husb == "M" and wife == "F": return True else: return False
3fcbb64c8d94a49fa4a89c7cb26ab6d60e2595d1
ktanan/PythonForBeginners
/basiccsv.py
774
3.609375
4
# basiccsv.py import csv from datetime import datetime def WriteCSV(data): # 'a' is append , 'w' is replace dt = datetime.now().strftime('%Y-%m-%d %H:%M:%S') #strftime.org data.insert(0,dt) #ใส่วันที่ลงไปหน้าข้อความทุกครั้งที่บันทึก with open('data.csv','a',newline='',encoding='utf-8') as file: fw = c...
2d28d65037daf0b673b2ff0868a5bc867e3840d9
vanshika1104/learning-python-codes
/printing all subsets of a list.py
302
3.953125
4
import itertools l=[] choice='yes' while (choice in ('yes','y','1','YES','Y')): element=input("Enter the element of list: ") l.append(element) choice=input("Do you want to enter more elements?\n") for i in range(len(l)+1): for a in itertools.combinations(l, i): print(a)
7c46d453e8cc017101c8e96a9cb192baea562d71
VilmaLago/Estudos_iniciais_Python
/testes_iniciais/teste_funções.py
641
4.125
4
# Testes iniciais para aprender sobre funções. # Defina a função para formatar nomes. def nome_formatado(primeiro_nome, sobrenome): '''Formate o nome da pessoa''' nome_completo = primeiro_nome + ' ' + sobrenome return nome_completo.title() # Receba os inputs de nome e sobrenome. print("Digite seu nome comp...
20ef3d59c8d2b75569e2fbe8a419dc8a6461a38e
VilmaLago/Estudos_iniciais_Python
/testes_iniciais/teste_exceptions.py
577
4.15625
4
# Testes iniciais para aprender sobre exceções. print("Dê-me dois números e eu irei dividí-los: ") print("Digite 'sair' sempre que quiser fechar o programa.") while True: primeiro_numero = input("Digite o primeiro número: ") if primeiro_numero.lower() == 'sair': break segundo_numero = input("Digit...
c5a56e960daf6a6e9d9fdf993a3b0e88cdf685ff
pras306/capstone_projects
/Numbers/pi_to_n_digit.py
385
4.0625
4
import math def roundoff(num, limit): strlist = str(num)[0:limit + 2] return strlist digit = int(input("Enter how many digits of pi you wish to see? ")) if digit > 15: print("Program has an upper limit to print till 15 digits only") digit = 15 num = math.pi result = roundoff(num,digit) print("The ...
5e19471a2cb61785a3ae7a4a8bd02d489837eced
pras306/capstone_projects
/Numbers/fibonacci.py
2,093
4.09375
4
from tkinter import Tk, Frame, Entry, Label, Button, END, OptionMenu, StringVar ############################################################## #######################Generate Fibonacci##################### ############################################################## root = Tk() root.title('Fibonacci Generator') ro...
820ca49f045891c200489faa2db67e34fb7e0aa0
priya510/Python-codes
/29.10.20/python important questions set 1/New folder/python9.py
258
3.65625
4
data=50 try: data=data/0 except ZeroDivisionError: print("cannot divide by 0",end="") else: print("Division successful",end="") try: data=data/5 except: print("inside except block",end="") else: print("abc",end="")
fc97ae87303d27eb0a3ba68d180f7ca1ea9400e0
priya510/Python-codes
/python important questions/python1.py
250
3.5625
4
import pandas as pd df=pd.DataFrame({"A":[2,4,8,0], "B":[2,0,0,0], "C":[10,2,1,8], "D":[4,6,1,0]}, index=["W","X","Y","Z"]) df["A"].sample(n=3,random_state=1) print(df)
4b76be8696a21192f6d5927d7a4891f2f21375f2
priya510/Python-codes
/python important questions/python questions/python22.py
94
3.53125
4
import pandas as pd s=pd.Series(["Tom","Willium Rick","John","Alber@t"]) print(s.str.swapcase())
14e0fa9c2a493870a09bd9be0818e2c0d0766ca2
priya510/Python-codes
/01.10.2020 python/min.py
419
4.125
4
num1=int(input("Enter the first number: ")); num2=int(input("Enter the second number: ")); num3=int(input("Enter the Third number: ")); def find_Min(): if(num1<=num2) and (num1<=num2): smallest=num1 elif(num2<=num1) and (num2<=num3): smallest=num2 elif(num3<=num1) and (n...
5824fc172c567584a4a54931423f2ef233851fb2
priya510/Python-codes
/19.09.2020 python/while_demo5.py
182
4.0625
4
''' WAP in python to accept a number from user and display table of that number. ''' n=int(input("Enter a number")) i=1 while(i<=10): print(n*i) i=i+1
e44ffabf326c597f15927b14690b1e9048a3cf94
priya510/Python-codes
/5.11.2020/numpy python/numpydemo1.py
466
3.96875
4
# Python program for # Creation of Arrays import numpy as np # Creating a rank 1 Array arr = np.array([1, 2, 3]) print("Array with Rank 1: \n",arr) # Creating a rank 2 Array arr = np.array( [ [1, 2, 3], [4, 5, 6] ] ) print("Array wit...
f2b8db8dec3cd4276f48ac3f249d33311300560f
priya510/Python-codes
/03.10.2020 Python/main_file.py
694
3.71875
4
#Modularization import insert_product from select_products import select import delete_product import update_product def menu(): print("========MENU========") print("1. Insert Product") print("2. Delete Product") print("3. Update Product") print("4. Select Products") ch=int(input("S...
a920ca059a9c1a7e69da45b28cb60191660feac0
priya510/Python-codes
/19.09.2020 python/for_demo.py
603
4.0625
4
''' WAP to print first 10 natural numbers. ''' #1st parameter - start value #2nd parameter - stop value #3rd parameter - stride value/step value (bydefault it is +1) for i in range(1,11): print(i) print() for i in range(1,11,1): print(i) print() for i in range(1,11,2): print(i) ...
132de0f31993771139ac40ddcf64459d7bb0f6cd
priya510/Python-codes
/03.10.2020 Python/insert_product.py
402
4.0625
4
''' Insert data ''' def insert(): import sqlite3 productid=int(input("Enter product id")) productnm=input("Enter product name") productpr=float(input("Enter product price")) con=sqlite3.connect("mydb.db") con.execute("insert into products values(?,?,?)",(productid,productn...
a5a490cd2bcf23d4e7a38c6cffe71c7c47dbd3b1
priya510/Python-codes
/01.10.2020 python/light_signal.py
652
4.03125
4
''' Traffic light example ''' #Internal Package/Library import time def countdown(x): for i in range(x,0,-1): print(i) time.sleep(1) def lightsignal(): color="red" if(color=="red"): print("Color is red. Please stop!!!") color="gr...
2a3bd6574c12c5e12431b59ba43b9fed569f6e17
komalnagpal/BFS-1
/rightSideView.py
1,270
3.96875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None from collections import deque class Solution: def rightSideView(self, root: TreeNode) -> List[int]: # Idea: In order to traverse tree level by l...
515b08380eb65e3d66d98faf23c58670c258868a
KFranciszek/pylove-training
/1.1/Excersise_1_9.py
920
3.65625
4
# char() ord() >>> ord("a") 97 >>> chr(98) "b" f # zaimplementuj szyfr cezara, który jako drugi parametr będzie brał przesunięcie. # Przykłady szyfr cezaraz o parametrze 3 podmieni każd literka alfabetu na trzecią z kolei np A na D a Z na C. # >>> cezar("abc", 2) "cde" >>> cezar("abc", -2) "yza" # Pamiętaj żeby znaki i...
a611278c125bcf5ef3b370eb9bb5784cc01274c1
KFranciszek/pylove-training
/1.5/Excersise.py
3,412
3.5625
4
class Human: def __init__(self, name, height, weight, hobby, beloved_food): self.name = name self.height = height self.weight = weight self.bmi = self.count_bmi() self.hobby = hobby self.beloved_food = beloved_food def speak(self): print("I'm telling the...
365ae6345e581af5ba2acecf933e8529717d6c81
KFranciszek/pylove-training
/1.0/Lists.py
590
3.671875
4
list_persons = [[],[],[]] list_persons[0].append(input('Podaj imię 1 osoby: ')) list_persons[0].append(int(input('Podaj wiek 1 osoby: '))) list_persons[1].append(input('Podaj imię 2 osoby: ')) list_persons[1].append(int(input('Podaj wiek 2 osoby: '))) list_persons[2].append(input('Podaj imię 3 osoby: ')) list_persons[...
3118b680dacbf3b9fc094b8975d49e832c8389a7
KFranciszek/pylove-training
/1.0/largest_word.py
3,046
3.859375
4
def longest_word(tekst): longest = [] tekst = tekst.replace(',','') tekst = tekst.replace('.', '') tekst = tekst.replace('?', '') tekst = tekst.replace('!', '') tekst = tekst.replace('#', '') lista = tekst.split() lista.sort() lista.sort(key=len) longest.append(lista[-1]) wh...
bfc9ceab8907d7d57c5e23901c543bef4cb1c44f
Darckoxe/cryptographie
/src/functions_misc.py
927
3.84375
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- import os import string def compterLettres(nomFichier): fichier = open("a_analyser/"+nomFichier, 'r') contenu = fichier.read() cpt=0 for i in contenu: if i=="u": cpt=cpt+1 else: pass print cpt def analyseFreq(): ...
3fdacd65a711d6db08138cf226747055b55f7a38
nguyenmthien/VGUServer_archive
/Raspberry Pi/TCP/socket_server.py
4,951
3.625
4
#!/usr/bin/env python3 # *_* coding: utf-8 *_* """TCP Server library""" import socket import select import time import getmac class new_connection(Exception): """TCP: New connection detected""" pass class address_does_not_exist(Exception): """TCP: Address does exist in dictionary""" def __init__(sel...
f81211de1766cb76da9fe3dbc3b1f2ff80f11165
nathnim/smooth_location_trajectory
/util/__init__.py
1,121
3.53125
4
from math import sin, cos, sqrt, atan2, radians def latlon_distance_all(args): # approximate radius of earth in km distances = [latlon_distance(args[i][0], args[i][1], args[i + 1][0], args[i + 1][1]) for i in range(0, len(args) - 1)] return distances def latlon_distance(location1_lat, l...
0861441b326f86ff40e2037a80ae92573c6fa4e3
jesusdavidgomezrobles/tarea4
/problema03.py
1,323
4.09375
4
# creamos la clase banco class Banco: # inicializamos def _init_(self): self.cliente1=Cliente("") self.cliente2=Cliente("") self.cliente3=Cliente("") # función para operar def operacion(self): self.cliente1.depositar(0) self.cliente2.depositar(0) self.cliente3.depositar(0) self.cliente1.extraer(0) ...
ad293e14f6981a0e23f6815be20d49a999a2de51
thanhvn184/truongcongthanh-fundamental-c4e29
/Fundamental/Session3/HW3/Serious2.py
744
3.65625
4
size0 = [10, 23, 69, 184, 207, 430, 300] print('Hello my name is Thanh and these are my sheep sizes: ') print(size0) print("Now my biggest ship has size", max(size0), "let's shear it") size0[size0.index(max(size0))] = 8 print("After shearing, here is my flock: ") print(size0) for j in range(4): print("MONTH", j+1) ...
7157d5f9002f973151701acfdbe9e7cda4bed76c
thanhvn184/truongcongthanh-fundamental-c4e29
/Fundamental/Session3/list.py
291
4.0625
4
# fav = ["dota2", "watch movies", "badminton"] # print(*fav, sep=",") # add=input("anything else?") # fav.append(add) # print(fav) fav = ["games", "watch movies", "badminton"] for index, item in enumerate(fav): print(index+1, item, sep=".") print("{}. {}".format(index+1, item))
7482d8301cac1d8dae8bca30dad16bb1efc3d6b1
thanhvn184/truongcongthanh-fundamental-c4e29
/Fundamental/Session3/Nhapso.py
276
3.90625
4
# so = int(input("Enter your number")) # count = 0 # while so>0: # so = so // 10 # count += 1 # print (count) x = int(input("enter your number")) count = 0 loop = True while loop: x = x // 10 count += 1 if x == 0 : loop = False print(count)
7fbbf42c0b1d5a929031f3a3bd4f966679e53840
thanhvn184/truongcongthanh-fundamental-c4e29
/Fundamental/Session1/conrua.py
168
3.90625
4
from turtle import * shape("turtle") color("green") speed(0) for i in range(30): for i in range(360): back(1) left(1) left(15) mainloop()
e597a2da01d4a7b240c292e4cbfb44474400d3d5
thanhvn184/truongcongthanh-fundamental-c4e29
/Fundamental/Session4/HW4/Serious4.py
1,176
4.03125
4
answer = [{ "If x = 8, then what is the value of 4(x + 3) ?": [35, 36, 40, 44] }, { "Jack scored these marks in 5 math tests: 49, 81, 72, 66 and 52.What is the mean? ": ["About 55","About 65","About 75","About 85"] }] print("Answer the following algebra question: ") x = 0 for index, item in enumerate...
593155b4e913d86e1486614d6e511c811389284f
thanhvn184/truongcongthanh-fundamental-c4e29
/Fundamental/Session5/nhap.py
384
3.84375
4
# x = int(input("Nhap x? ")) # y = int(input("Nhap y? ")) # a = x + y # print("x + y =",a) x = int(input("Nhap x? ")) y = int(input("Nhap y? ")) op = input("Nhap phep tinh? ") result = 0 if op == "+": result = x + y elif op == "-": result = x + y elif op == "*": result = x + y elif op == "/": result =...
a6018f57fd1e2e944bf75d75f0615e6ee0554ad6
AshleyAlpha/pets
/control/user_Test.py
3,295
3.953125
4
import unittest # Importing the unittest module from users import Users # Importing the contact class class TestUsers(unittest.TestCase): ''' Test class that defines test cases for the Users class behaviours. Args: unittest.TestCase: TestCase class that helps in creating test cases ''' def...
4ddcecdbb97a17c6537ad2d9360cba1f9f2dc54e
CUCEI20B/zodiaco-AndresSanchez-A
/main.py
2,047
4.21875
4
print("Simbolo del Zodiaco") dia = int(input("Numero de dia de nacimiento: ")) mes = int(input("Numero de mes de nacimiento: ")) if mes == 12: if dia >= 1 and dia <= 21: print("Tu simbolo es sagitario") if dia >= 22 and dia <= 31: print("Tu simbolo es capricornio") elif mes == 1: if dia >=...
2445c8d39ac8f5cfecd63f174d78fc18cdbdd7e0
dariavoblikova/uw-csse
/css340-python/Lab2-TimeSpan/time340.py
4,753
3.703125
4
import math class TimeSpan: SECONDS_IN_MINUTE = 60 MINUTES_IN_HOUR = 60 def __init__(self, seconds = 0, minutes = None, hours = None): self.__seconds = round(seconds) if minutes is not None: self.__minutes = minutes else: self.__minutes = 0 if hours...
d71f97c81b541236f310f3800166e636bb820a68
dariavoblikova/uw-csse
/css340-python/Lab5-Sort/sort.py
7,755
4.0625
4
import random from random import randint import timeit import copy def BubbleSort(inList):#n^2 for i in range(len(inList)): for j in range(len(inList) - i - 1): if inList[j] > inList[j+1]: inList[j], inList[j+1] = inList[j+1], inList[j] def InsertionSort(inList):#n^2 for pla...
404311bbb1f7a157bb5801fa98f71f77cabe0b9b
IordanisSidiropoulos/Week-4
/pkg/copy_deepcopy_demo.py
753
3.5625
4
""" # # File : copy_deepcopy_demo.py # Created : 23/10/2021 7:17 p.m. # Author : R.G. Lennon # Version : v1.0.0 # Licencing : (C) 2021 Ruth G. Lennon, LYIT # Availaable under GNU Public License (GPL) # Description : # """ from copy import deepcopy if __n...
d8ba2c1d7ee91b2313b2dd1dac760af8da771411
ms2020bgd/cyounes
/String1.py
1,774
3.75
4
import string def donuts(count): if count >= 10: return "Number of donuts: many" else: return "Number of donuts: " + str(count) def both_ends(s): if len(s) < 2: return "" else: return s[:2] + s[len(s)-2:] x = 'Vincent' both_ends(x) def fix_start(s): first_char...
12c2fc5c5a2f4661f095e48d0fe48bb94f1bc4a6
aaronbassett/Reading-time
/reading_time.py
796
3.734375
4
from datetime import timedelta import math class ReadingTime: def __init__(self, text, wpm=180): self.words = text.split(" ") self.wpm = wpm def duration(self): minutes = math.floor(len(self.words) / self.wpm) return timedelta(minutes=minutes) def humani...
374c977da102b96509c4240713704a47c04c208c
gannaramu/Coursera-The-Raspberry-Pi-Platform-and-Python-Programming-for-the-Raspberry-Pi
/Week3.py
130
3.546875
4
a=input("Enter first Number: ") b=input("Enter Second Number: ") c=input("Enter Third Number: ") out=[a,b,c] out.sort() print(out)
22ea2a998f7905713d4a220fa145896740f31def
kunal12kaushik/calculator
/short hand if else.py
128
3.984375
4
a = int(input("enter a\n")) b = int(input("enter b\n")) if a>b: print("a b se bada hai bhai") else: print("b bada hai bhai")
56ea1fa1d8eacf5286485717b0a570fd4ae31fe1
kunal12kaushik/calculator
/break and countinue.py
113
3.765625
4
# x = int(input("how much candies you want?")) # # # # i = 1 # # while i<=x: # # print("candy") # # i+=1
3684666d9334ea45dadbf01d9bb7d5e7af0b1c01
alexmochu/BrightEventsAPI
/tests/test_useraccounts.py
3,176
3.75
4
""" File to handle testing of user accounts """ import unittest from app.useraccounts import UserClass class AccountTestCases(unittest.TestCase): """ Test for duplicate accounts(user already exists) Test for short passwords Test for correct output/account creation Test login with no accoun...
c8503897bb274bac5cb7d4ed0762db5316501b9c
MythicalCuddles/Learning-Python
/simple calculator.py
350
4.1875
4
# int only allows whole numbers num1 = input("Please enter a number: ") num2 = input("Please enter another number: ") result = int(num1) + int(num2) print(result) # float allows for decimals num1 = input("Please enter a number: ") num2 = input("Please enter another number: ") result = float(num1) + ...
2277d79ab6036d80b8f2dbc0070859fce4d00e16
xiadx/InterviewAlgorithm
/offer/16_Merge.py
1,151
4
4
# -*- coding:utf-8 -*- class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # 返回合并后列表 def Merge(self, pHead1, pHead2): # write code here if pHead1 is None: return pHead2 if pHead2 is None: return pHead1 i...
f255723b1d9022b59464352e394f41ad0e022ec2
xiadx/InterviewAlgorithm
/offer/17_HasSubtree.py
1,095
3.96875
4
# -*- coding:utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def HasSubtree(self, pRoot1, pRoot2): # write code here def Root1HasRoot2(pRoot1, pRoot2): if pRoot1 is None and pRoot2 is not None: ...
ef480d1c4ee341756bbd3d4ad6cb664a0154867b
xiadx/InterviewAlgorithm
/offer/24_FindPath.py
826
4
4
# -*- coding:utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # 返回二维列表,内部每个列表表示找到的路径 def FindPath(self, root, expectNumber): # write code here if not root: return [] if root and not ro...
357f589a501f2fbab11b47bb59dc63fbbdf94641
xiadx/InterviewAlgorithm
/offer/28_MoreThanHalfNum.py
791
3.609375
4
# -*- coding:utf-8 -*- class Solution: def MoreThanHalfNum_Solution(self, numbers): # write code here n = sorted(numbers) l = 0 index = 0 for i in range(len(n)): if n[i] == n[index]: i += 1 if i - index > len(n) / 2: ...
6f2732f0d16f18edc1dc40bcd0c7064c596ba2c9
xiadx/InterviewAlgorithm
/exam/15_.py
2,159
3.6875
4
# -*- coding:utf-8 -*- """ 题目描述 考拉有n个字符串字符串,任意两个字符串长度都是不同的。考拉最近学习到有两种字符串的排序方法: 1.根据字符串的字典序排序。例如: "car" < "carriage" < "cats" < "doggies < "koala" 2.根据字符串的长度排序。例如: "car" < "cats" < "koala" < "doggies" < "carriage" 考拉想知道自己的这些字符串排列顺序是否满足这两种排序方法,考拉要忙着吃树叶,所以需要你来帮忙验证。 输入描述: 输入第一行为字符串个数n(n ≤ 100) 接下来的n行,每行一个字符串,字符串长度均小于100,均...
6b2e3eb016fd6462704cfae770406603db06c205
xiadx/InterviewAlgorithm
/offer/53_multiply.py
420
3.921875
4
# -*- coding:utf-8 -*- class Solution: def multiply(self, A): # write code here def product(array): mul = 1 for a in array: mul *= a return mul B = [0] * len(A) for i in range(len(A)): B[i] = product(A[:i]) * product(A[i...
bd4a8d749e2bb5aa6bc3251cf6e6294083bf0364
cothidalgo/proyects
/Python/List.py
1,381
3.59375
4
__author__ = 'MariaJose' class Node: def __init__(self, ide=None): self.next = None self.ide = ide class List: def __init__(self): self.tail = None self.head = None def add(self, ide): if not self.head: self.head = Node(ide) self.tail = se...
9443c06c87e46e127b6edd91730cc03801b3efd8
RobinAxelsson/ChalmersLab1
/wordfreq.py
2,643
3.640625
4
class strType(): Alpha = 0 Digit = 1 Symbol = 2 White = 3 def checkType(char: str): if char.isspace(): return strType.White if char.isdigit(): return strType.Digit if char.isalpha(): return strType.Alpha else: retur...
40c1d5dc47f8b5cfa1e53812ac2d7458d9cb9d0b
muhammadahmadazhar/my-whole-programing
/PycharmProjects/pythonProject/8_Variables_Datatypes_and_Typecasting.py
306
3.8125
4
var1="hello" var2=5 var3=36.7 print(var1) print(var2+var3) var4="66" var5="3.333" #type casting function str() int() float() print(int(var4)+float(var5)) print(str(var3)) print(5*"world ") print("enter first no=") n1=input() print("enter second no") n2=input() n3=int(n1)+int(n2) print("sum of two no=",n3)
2c76439fb30473a1ac307d76610d96c329bf6126
mlesfield/coordinator_data_tasks
/coordinator_data_tasks/utils/recoders.py
328
3.671875
4
"""Provide functions to recode a dataframe column. Each function should be in a form that can be handed to df[column_name].apply(func). """ import pandas as pd def recode_dates(x): """Return `x` recast as datetime[ns], or `NaT`.""" try: return pd.to_datetime(x) except ValueError: return...
b6de4bd1f23daba6a2cee75f17ec0a19d32a9256
BogdanSorbun/Date_Finder
/what_day_is_it.py
614
4.25
4
days = ['saturday', 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday'] days_in_month = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # day 1 started on a saturday def num_of_leap(year): leap_years = int(year/4)-(int(year/100) - int(year/400)) return leap_years def date(y...
0302f356d7f4f292e8ac2d2350f11d19d01d5db0
YILINQ/ACM-prep
/Heap/MedianOfTwoArray.py
1,053
3.5625
4
# leetcode 4 from heapq import * class Solution: def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float if total number is odd, then find the middle one if total number is even, then find the middle two and aver...
7c7cf216003f44bd5a5b31a6049f7e18d40d32be
kaczmm/BooleanParser
/Boolean Parser.py
11,006
3.75
4
# Boolean Parser # Matthew Kaczmarek # Program can be run as python2 or python3 from __future__ import print_function # Tokens (defined using regular expressions) # VAR = \$[0-9a-zA-Z]* # BOOL = True | False # OP = and | or # NOT = not # LP = \( # RP = \) # EQ = \= # Tokens EOF = 0 VAR = 1 BOOL = 2...
d2a02053b6beeaf81c3bbb4c306a2c0524504d7a
yashhjaggi1998/Python3
/Python3_Homework02/test_coconuts.py
2,616
3.578125
4
''' Created on May 17, 2013 @author: tnguyen7 Corrected on May 21, 2013 x This tries to get an attribute of the Inventory.add_count method called "South Asian", which that method does not have: self.assertRaises(AttributeError, getattr, Inventory.add_coconut, "South Asian") o Create an instance (ex: inv = Inventory()...
886ab87338fe873257b61abdb90971044bfb1db1
jdn8608/Analysis_of_Algo_hw_2
/src/sphere.py
2,341
4.1875
4
import math ''' Name: Joseph Nied Date: 2/12/20 Class: CSC-261 Question: 3 Description: Algorithm to see if given a points, if any would lie on a sphere together ''' def main() -> None: SIZE = int(input()) #Create an empty array with size SIZE Magnitude = [None] * SIZE #Get the input coordinates ...
f3710b081ea0d751fa53a7114137187db17c5a20
Khalid-Sultan/Section-2
/average, min, max and average.py
377
4.03125
4
n=int(input("How many numbers do you want?")) m=int(input("enter a number:")) s=0 j=m k=m for i in range(0,n-1): m=int(input("enter a number:")) s=s+m if j<m: j=m if j>m: k=m a=s/n print("the max value of the numbers is",j) print("the min value of the numbers is",k) print("the sum of the...
f3c093a0eb4458dfe15f3204629f6784f8ba63d2
Khalid-Sultan/Section-2
/sum function.py
429
3.671875
4
s=0 def sum_range(start,stop,step): sum=0 for i in range(start,stop,step): sum+=i return sum print('9 + 10 + ... + 21 =',sum_range(9,22,1)s) print('first summation done') print('37 + 38 + ... + 50 =',sum_range(37,51,1)) print('second summation done') print('45 + 46 + ... + 66 =',sum_range(45,67,1))...