blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
4032ada25ecdc533a0af38696881bb74f533de6b
M0use7/python
/python基础语法/day16-正则表达式和作业/04-歌词解析.py
2,197
3.609375
4
"""__author__ = 余婷""" class Lyric: def __init__(self, time, word): self.time = time self.word = word def __str__(self): return '%.2f %s' % (self.time, self.word) def __gt__(self, other): return self.time > other.time class LyricAnalysis: """歌词解析类""" # 创建解析器对象的时候...
93d7915141d7620f940a7da82a28b481968ca942
M0use7/python
/day15-类和对象/05-属性的setter和getter.py
2,923
4.4375
4
"""__author__ = 唐宏进 """ """ 1.保护类型的属性: a.就是在声明对象属性的时候在属性名前加一个下划线来代表这个属性是受保护的属性。 那么以后访问这个属性的时候就不要直接访问,要通过getter来获取这个属性的值,setter来给这个属性赋值 b.如果一个属性已经声明成保护性的属性,那么我们就需要给这个属性添加getter,也可以添加setter 2.添加getter 添加getter其实就是声明一个没有参数有一个返回值的函数 a.格式: @property def 去掉下划线的属性名(self): 函数体 将属性相关的值返回 b.使用场景 场景一:如果想要获取对象的某个属性的值之前,...
5d18bc0fb3c365aac5cafb55be411d0b8bcbd7d2
M0use7/python
/python基础语法/day9-函数/05-模块和包的使用.py
2,167
4.34375
4
"""__author__ = 余婷""" """ 封装: 1.函数:对实现某一特定功能的代码段的封装 2.模块:对变量、函数、类进行封装 模块:一个py文件就是一个模块 """ def multiply(*numbers): sum1 = 1 for item in numbers: sum1 *= item return sum1 print(multiply(1,2,5)) """ 1.怎么使用其他模块中的内容? a.import 模块 通过模块.内容的形式去使用模块中的内容(能够使用是全局变量、函数、类) b.from 模块 import 模块中的内容 可以直接使用模块中的内容...
fa4941d78f6ee86dde8c6efef38dde33bddc7b00
M0use7/python
/day18-网络基础/01-socket套接字.py
2,479
4.0625
4
"""__author__ = 唐宏进 """ """ socket又叫套接字,就是进行数据通信两端。分为服务端套接字和客户端套接字 套接字编程:自己写服务器和客户端,进行数据传输 python对socket编程的支持:提供一个socket的库(内置) """ import socket def create_server(): """写一个服务器""" # 1.创建套接字对象 """ socket(family, type) a.family:确认IP协议类型 AF_INET:ipv4(默认) AF_INET6:ipv6 b.type:传输协议类型 S...
9b53fb54060edae03e612b3ebefcef27056276b5
M0use7/python
/day2-基础语法/03-变量.py
1,427
4.40625
4
# 声明变量就是在内存中开辟空间存储数据。(变量就是用来存储数据的) # python是动态语言 # 1.怎么声明变量 # 格式:变量名=值 # 说明: """ 类型:python声明变量的时候不需要确定类型 变量名:标识符,不能是关键字;见名知义,PEP8命名规范(所有的字母都小写,多个单词之间用_隔开) =:赋值符号,将右边的值赋给左边的变量 值:表达式(就是有结果的,例如:字面量,运算表达式(10+20),其他的变量) """ # 声明了一个变量name,赋值为'路飞'。使用name的时候,就相当于使用'路飞' name = '路飞' print(name) # 声明一个变量class_name,保存'python1806'...
d9637c2315e52d5dabb5d298eae2b1bca1b4b409
M0use7/python
/python基础语法/day2-python基础/03-变量.py
1,473
4.375
4
# 声明变量就是在内存中开辟空间存储数据。(变量就是用来存储数据的) # python是动态语言 # 1.怎么声明变量 # 格式: 变量名 = 值 # 说明: """ 类型:python声明变量的时候不需要确定类型 变量名:标识符,不能是关键字;见名知义,PEP8命名规范(所有的字母都小写,多个单词之间用_隔开) =:赋值符号,将右边的值赋给左边的变量 值:表达式(就是有结果的,例如:字面量,运算表达式(10+20),其他的变量) """ # 声明了一个变量name,赋值为'路飞'。使用name的时候,就相当于在使用'路飞' name = '路飞' print(name) # 声明一个变量class_name,保存'python...
03657ab590440aa3ad00fbe7d3b85c4c8ef497de
M0use7/python
/day7-字典和集合/02,-字典.py
2,223
4.09375
4
"""__author__ = 唐宏进 """ # 字典(dict) """ 1.字典是容器类型(序列)、以键值对作为元素(字典里面存的数据全是以键值对的形式出现) {key1:value1,key2:value2...} 2.键值对:键:值(key:value) 键(key):要唯一,不可变的(数字、布尔、字符串和元祖,推荐使用字符串) 值(value):可以不唯一,可以是任何类型的数据 3.字典是可变(增删改) --- 可变指的是字典中的键值对的值和个数可变 """ # 1.声明字典 dict1 = {10:100, 'a':97, True:100, (10,10):'start', 'a':'A'} print(dict1...
c8cde2f63d33263327da07a67139e0009353da06
M0use7/python
/day6-容器类型/01-recode.py
1,476
3.5
4
"""__author__ = 唐宏进 """ # python基础语法: """ 1.注释 2.标识符:a.有字母数字下划线组成,python可以是中文。 b.数字不能开头。c.大小写敏感。 3.行与缩进:python中对缩进有严格的要求 4.多行显示:加反斜杠\ 5.python中的基本数据类型:整型(int)、浮点型(float)、布尔(bool)、字符串(str) """ # 变量的声明 """ 1.变量名 = 值 2.变量名:标识符,不能是关键字;PEP8(字母全部小写,字母之间用下划线隔开),见名知义 3.变量的写法 4. """ # 运算符 """ 数字运算符:+,-,*,/,//,** 比较运算...
594a29735cc633381402428d4592c079ae5dfaed
M0use7/python
/python基础语法/day15-类和对象/06-继承.py
1,585
4.28125
4
"""__author__ = 余婷""" """ python中类可以继承,并且支持多继承。 程序中的继承:就是让子类直接拥有父类的属性和方法(继承后父类中的内容不会因为被继承而减少) 1.继承的语法 class 子类(父类): 类的内容 注意:如果声明类的时候没有写继承,那么这个类会自动继承python的基类,object;相当于class 类名(object): python中所有类都是直接或者间接的继承自object 2.能继承哪些东西 a.所有的属性和方法都能继承 b.__slots__的值不会继承,但是会影响子类对象的__dict__属性。不能获取到父类继承下来的属性 """ clas...
f397bf0e5874894166a1bace276766aa2ba52d4f
M0use7/python
/python基础语法/day9-函数/my_list.py
370
3.78125
4
"""__author__ = 余婷""" empty = [] def count(list1, item): """ 统计指定列表中指定元素的个数 :param list1: 指定的列表 :param item: 指定的元素 :return: 个数 """ num = 0 for x in list1: if x == item: num += 1 return num print('abc') print(empty) print(count(['a', 12, 'b', 'a'], 'a'))
322890af660feeb97739ba2214810f3f44c819c2
M0use7/python
/day19-多线程/01-多线程技术.py
1,489
3.765625
4
"""__author__ = 唐宏进 """ """ 1.主线程 每个进程默认都会有一个线程,这个线程我 们一般叫它主线程。 默认情况下,所有的代码都是在主线程中执行。 2.子线程 一个线程中可以有多个线程。除了主线程以外,其他的线程需要手动的添加 3.threading是python中的一个内置模块,用来支持多线程 a.Thread类的对象就是线程对象,需要线程的时候,就创建这个类或者这个类的子类对象 b.threading.currentThread() --> 用来获取当前线程对象 """ import threading import datetime import time # 下载两个电影 def downlo...
b2cc07905720f1504f755bc219e29466f4fdeedf
M0use7/python
/day7-字典和集合/zuoye.py
2,824
4.03125
4
"""__author__ = 唐宏进 """ def menu(): print('=================') print('****学生管理系统****') print('1.添加学生') print('2.查看学生') print('3.修改学生') print('4.删除学生') print('5.退出') print('=================') students = [ {'name':'stu1', 'age':16, 'tel':'110'}, {'name':'stu2', 'age':18, 'tel':...
d5e721e3e419b3067438a56f5a5a92e9b52dbd66
M0use7/python
/day3-字符串/zuoye.py
936
4.03125
4
# 题目1 ''' name = 'ZhangSan' print('Hello %s, would you like to learn some Python today?'%(name)) ''' # 题目2 ''' name = 'zHaNgsAn' print(name.lower()) print(name.upper()) print(name.capitalize()) ''' # 题目3 # name = 'Ralph Waldo Emerson' # word = 'Don’t be pushed by your problems. Be led by your dreams.' # print('%s sa...
1e50a0a662a8f6b35cf79e597f9ec1a19c717208
M0use7/python
/python基础语法/day6-容器类型/01-recode.py
1,643
3.71875
4
"""__author__ = 余婷""" # python基础语法: """ 1.注释 2.标识符:a.由字母数字下划线组成,python3中可以是中文。b.数字不能开头。c.大小敏感 3.行与缩进:python中对缩进有严格的要求 4.多行显示:加反斜杠 5.python中的基本数据类型:整型(int)、浮点型(float)、布尔(bool)、字符串(str)等 """ abc = 10 b = 20 'name' sum1 = 100 + 23333333 + abc\ + 82973940712982738 + 90 # 变量的声明 """ 1.变量名 = 值 2.变量名:标识符,不能是关键字;PEP8:(字...
cde7d87c864d76a7003ba05cd0b8e7c21f67ae7c
SIVATHANU0708/diffevenodd
/diffoddeven.py
97
3.765625
4
a=int(raw_input()) b=int(raw_input()) c=a-b if(c%2==0): print("even no") else: print("odd no")
13947fb8fedb8eb3e89c99f7f5848f0e651b73ac
hi101000/mathhelp
/mathhelp/__init__.py
2,644
3.765625
4
import math import numpy, scipy import matplotlib.pyplot as plt import constants def TR(n): '''function to gve you triangular number n''' tr=n*(n-1) return tr def tn(n, t1, d): tn=t1+d*(n-1) return tn #define some constants PI=3.14159265358979323846264338327950 E=2.7182818284590452353602874713527 def sqrtofn(...
b835288ee7b2380ddeabbfee4601006007b789a5
ya-demo/Algorithms
/Sort/QuickSort.py
1,454
3.515625
4
from random import randint # 原始資料 count = randint(1, 10) nums = [randint(1, 100) for i in range(count)] print('\n原始資料:', nums, '\n') # Quick Sort Start def switch(nums, index, target): tmp = nums[index] nums[index] = nums[target] nums[target] = tmp def quick_sort(nums, root, left_idx, right_idx): if l...
21b999441e12e99e48f3e0e4e527da5f84581fc0
taufiqlibrary/Learn-Python
/default_values_sample2.py
273
4.21875
4
# -*- coding: utf-8 -*- """ Created on Tue Aug 10 16:47:24 2021 @author: taufiqlibrary """ # For example, the following function accumulates the arguments passed to it on subsequent calls: def f(a, L=[]): L.append(a) return L print(f(1)) print(f(2)) print(f(3))
e9a86b81878281e3730553fa460730f823e91899
veldm/IO_Labs_2020
/IO_Lab_1/module3.py
1,657
3.765625
4
# Задание 3 - Операции со списками def Mas(): N = int(input("Введите размер массива: ")) A = [] for i in range(N): A.append(int(input("Введите число {0} из {1}: ".format(i + 1, N)))) list.sort(A); Max = A[N - 1] print("Максимальное число в массиве -", Max) Min = A[0] print("Мин...
63e38255e8afbb4c1d786e6fcd8559b5b1bf419c
zn-jba/Python-TicTacToe
/Problems/Lucky 7/main.py
108
3.625
4
n = int(input()) for _ in range(n): temp = int(input()) if temp % 7 == 0: print(temp ** 2)
4df6c77ab756969c4d3bbdbe4be8f6cb690821e2
zn-jba/Python-TicTacToe
/Problems/Vowels/main.py
132
4.09375
4
vowels = 'aeiou' # create your list here string = input() string_vowels = [x for x in string if x in vowels] print(string_vowels)
09c4f07d6e5622041ea4d68f562361df129c639b
zn-jba/Python-TicTacToe
/Problems/A list of words/main.py
117
3.8125
4
# work with the preset variable `words` new_list = [x for x in words if x[0] == "a" or x[0] == "A"] print(new_list)
afafb638d127ea209e5cb7fb6644846522757109
zn-jba/Python-TicTacToe
/Problems/Running average/main.py
112
3.734375
4
digits = [int(x) for x in input()] average = [(x + (x + 1)) / 2 for x in range(1, len(digits))] print(average)
8933f623bddeaa4d8043304e7de9d489c3a7de3e
zn-jba/Python-TicTacToe
/Problems/Grade/main.py
300
4.125
4
grade = float(input()) maximum = float(input()) percentage = int((grade / maximum) * 100) if 90 <= percentage <= 100: print("A") elif 80 <= percentage < 90: print("B") elif 70 <= percentage < 80: print("C") elif 60 <= percentage < 70: print("D") elif percentage < 60: print("F")
5cb5919e7220b4439b43dfc1a265525db8a041fd
RoshiniVarada/Python
/ICP3/Scripts/Employee.py
1,001
3.875
4
class Employee: employeeCnt = 0 totalsal = 0 average = 0 def __init__(self, name, surname,salary, department): self.name = name self.surname = surname self.salary = salary self.department = department Employee.averageSal(salary) def averageSal(salary): ...
825279255332901d249ae818a116db5ee4b04ce3
Kavipriya98/Guvi
/nearest_even_no.py
100
3.65625
4
def fnc(N): if(N%2==0): print(N,end="") else: print(N-1,end="") N=int(input("")) fnc(N)
0ad27a81dfed9edf8121d5d915faefa2dfa5d37c
Kavipriya98/Guvi
/reverse.py
66
3.578125
4
N=int(input("")) while(N!=0): temp=N%10 print(temp) N=N//10
f22ed96727aa6e96024861223513af8f4eb97234
Kavipriya98/Guvi
/sum_of_num.py
108
3.703125
4
def fnc(N): sum=0 while(N>0): x=N%10 sum=sum+x N=N//10 print(sum) N=int(input("")) fnc(N)
3467b6c26e77e3078a527d5941e426a9f1dae196
Kavipriya98/Guvi
/nearest_multiple_of_10.py
110
3.640625
4
def mul(N): M=N//10 if(N<10): print("10") else: M=(M+1)*10 print(M) N=int(input("")) mul(N)
48eff069bc05df042e0da95e88abd02fd1621ae9
msclio/hello-world
/3.3_variables_review_1.py
2,958
4.53125
5
'''~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Initializing variables - establishing their type''' # integers are whole numbers variable_integer = 1 ## float is a number with a decimal. If you divide two integers Python will ## return a float even if the answer is a whole number variabl...
4123ad33ae397298f9eccd46963e180ec129eabd
eldimko/credit_calculator
/stage3_annuity.py
3,245
4.125
4
import math def credit_calculator(): operation = input("""What do you want to calculate? type "n" - for count of months, type "a" - for annuity monthly payment, type "p" - for credit principal: """) if operation == 'n': input_principal = float(input("Enter credit principal: ")) i...
1ae29cdcaccc1a476b3ae807732f76cf98529c9b
Adib234/Leetcode
/maximum_level_sum_of_a_binary_tree.py
971
3.703125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def maxLevelSum(self, root: TreeNode) -> int: if not root.right and not root.left: ...
dfd01b2d601ceef7972e00f3f78ef584048ebf8c
rwisecar/trigrams
/src/trigrams.py
1,548
4.125
4
"""A program that takes a txt file input and creates new similar new file.""" import io from random import choice, randint def open_file(text_file): """Open and read source text file.""" source_file = io.open(text_file, 'r+') story = source_file.read().split(' ') source_file.close() return story ...
93ecf0bac93524656ce2849d29042ddf3552ed4a
fenago/deep-learning-time-series-forecasting
/chapter_16/05_plots_of_daily_power_consumption.py
862
3.625
4
# daily line plots for power usage dataset from pandas import read_csv import warnings warnings.simplefilter("ignore") %matplotlib inline from matplotlib import pyplot # load the new file dataset = read_csv('household_power_consumption.csv', header=0, infer_datetime_format=True, parse_dates=['datetime'], index_col=['da...
bbe79b0ba66957cac2ecf52c9786e5a40d0c5c48
lucianap/lua-code-examples
/comparisions/fib.py
723
3.96875
4
import time #Naive recursivo def fib(n): if n == 0: return 0 elif n == 1: return 1 else: return fib(n-1)+fib(n-2) #Iterativo def fibI(n): a, b = 0, 1 for i in range(0, n): a, b = b, a + b return a #Tail recursion def fibRT(n): def fib_help(a, b, n): return fib_help(b, a+b, n-1) if n > 0 ...
5b85b32186b9f61a0abc356be96a49c050de6c2b
manchivarusanthosh/PythonProjects
/SimpleCalculator/SimpleCalculator.py
391
3.921875
4
input_str = input().split() first_int = int(input_str[0]) sec_int = int(input_str[-1]) operator = input_str[1] #print(input_str) if operator == "+": print(first_int +sec_int) elif operator == "-": print(first_int - sec_int) elif operator == "*": print(first_int * sec_int) elif operator == "/": print(fi...
c1fdc731fdede58c4efa02a8d3c71db551449b46
peipei1109/P_07_leetcode
/H-Index.py
986
3.625
4
# -*- encoding: utf-8 -*- __author__ = 'luopei' class Solution(object): def hIndex(self, citations): """ :type citations: List[int] :rtype: int """ citations=sorted(citations) length=len(citations) mid=length/2 current_h=0 if ci...
ac78fd8fb3d8e534cd931576bead0aa67065bb87
peipei1109/P_07_leetcode
/CountofSmallerNumbersAfterSelf.py
600
3.578125
4
# -*- encoding: utf-8 -*- __author__ = 'luopei' # Time Limit Exceeded。。。。。。。 class Solution(object): def countSmaller(self, nums): """ :type nums: List[int] :rtype: List[int] """ results=[] for i, num in enumerate(nums): coun...
8b6f01914441b429951873adbeb3625e338ce9bf
josejose02/recap_exercises
/max_4_random_numbers.py
1,221
3.90625
4
import random print("This program generates 4 random numbers than prints the biggest one") a = random.random() * 100 b = random.random() * 100 c = random.random() * 100 d = random.random() * 100 print("I have generated these numbers: %.2f %.2f %.2f %.2f" % (a, b, c, d)) if a >= b and a >= c and a >= d: print("The...
f2df18c157315ba31a1be85c626cf2859d6ff379
ITU-DB-MANAGEMENT-HM/itunder-backend-rest
/utils.py
475
3.546875
4
from datetime import datetime def int_to_datetime(time): """ :param data: timestamp to parse time object. parse integer timestamp to Date instance. """ return datetime.fromtimestamp(time) def time_to_json(data): """ :param data: time data to parse. formats the time fields in orde...
39de7d2a0c548e73d65523a8a90aeee42befc874
peace710/AJLife
/LeetCode/2.两数相加/Solution.py
892
3.71875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: node = ListNode() p = node cf = 0 while l1...
9b0ab2c74886d2a1cc67ff0c534765dc8935d8f2
narveer-rathore/python-basics
/oops/Fraction.py
652
3.703125
4
# -*- coding: utf-8 -*- """ Created on Tue Aug 29 00:05:03 2017 @author: narveer-rathore """ def gcd(m,n): while m%n != 0: oldm = m oldn = n m = oldn n = oldm%oldn return n class Fraction: def __init__(self, top, bottom): self.num = top self.den = bottom ...
9e49600e434b213ccd272c121ee3cd71a33a1ad7
dklounge/codeEval
/32trailingString.py
475
3.953125
4
# You are given two strings 'A' and 'B'. Print out a 1 if string 'B' occurs at the end of string 'A'. Else a zero. # sample input - San Francisco,San Jose # sample output - 0 # import sys # data = open(sys.argv[1], 'r') data = open("file") for line in data: line = line.rstrip().split(',') a = line[0] b = line[...
ce7bf2f5863367599145e523f9e06724b0a57bfb
HHHlaing/pythonhomework
/31.newhour.py
183
4.09375
4
x=int(input ("Enter hour: ")) y=int(input ("How many hours ahead? ")) z=x+y; if (z>12): print ("New hour: ",(z-12), "o'clock") else: print ("New hour: ", z, "o'clock")
703f213b54c13d961e13b4d6637d2f08e35c93e4
HHHlaing/pythonhomework
/8.mealandtip.py
285
3.9375
4
mealAmount = float(input("How much is your original bill? \t")) whatTip = float (input("What percentage would you like to tip? \t")) tipAmount = mealAmount * (whatTip/100) print("Your tip amount is: \t", tipAmount) print("Your total bill amount is: \t", mealAmount+tipAmount)
7a6c58406a9df6cf25d2af0a0da6df98fd62d2d6
HHHlaing/pythonhomework
/33.factiorial.py
112
4.03125
4
import math num=int(input ("Enter a number: ")) print ("Factorial of this number is: ", math.factorial(num))
8ed4f3c4cc2291f1de4ccad5718414cf8ecb7c97
HHHlaing/pythonhomework
/37.temp.py
297
4.375
4
temperature=int (input ("Enter temperature: ")) user_input = input("From what do you want to convert?: C or F? ") if user_input== "C": print ("Celsius to Fahrenheit is: ", temperature* 9 / 5 + 32) elif user_input== "F": print ("Fahrenheit to Celsius is: ", temperature* 5 / 9 - 32)
bbe2794e1da55583a485eaf440c02fef1cfcf824
justsangsue/LT-Code-Problems
/28 Balanced Binery Tree/Solution.py
1,017
4.09375
4
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class ResultType: def __init__(self, isBalanced, maxDepth): self.isBalanced = isBalanced self.maxDepth = maxDepth class Solution: """ ...
11ef633e96aaf347faff4acddf8bce0d53347bd7
justsangsue/LT-Code-Problems
/A6 MST/Solution.py
1,759
3.640625
4
import functools class Solution: """ @param graph: list of edges with weight [(node1, node2, weight)...] @return MST: list of edge in MST """ def kruskalMST(self, graph): if not graph: return [] k = Kruskal(graph) return k.mst() class Kruskal: def __init__(self, graph): nodes = set() for edge in gr...
dfaa51faaa84d1e949af73d3f829aa60f0de1813
justsangsue/LT-Code-Problems
/26 Binary Tree Paths/Solution.py
813
3.96875
4
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: the root of the binary tree @return: all root-to-leaf paths """ def binaryTreePaths(self, root): # write your code ...
23aae3cd78e32df17166add9fd38f5d0249634f6
Ajaymanoj/Python
/Pythonbasics.py
7,345
3.640625
4
# lucky_numbers = [4, 8, "fifteen", 16, 23, 42.0] # lucky_numbers[0] = 90 # print(lucky_numbers[0]) # print(lucky_numbers[1]) # print(lucky_numbers[-1]) # print(lucky_numbers[2:]) # print(lucky_numbers[2:4]) # print(len(lucky_numbers)) # 2 Dimension list # # numberGrid = [[3,6],[5,7]] # numberGrid[0][1] = 9...
2b327a5800d47b69e8595ca17bc8f98eadbb5bad
MehrdadJannesar/Python-tutorial
/SqliteDB/SQLite_Insert_Data.py
1,327
3.734375
4
import sqlite3 from sqlite3 import Error def create_connection(db_file): conn = None try: conn = sqlite3.connect(db_file) return conn except Error as e: print(e) return conn def insert_projects_tb(conn,projects): sql = """ INSERT INTO projects(name, begin_d...
3fa8bc80b42471d1504a3fe4c7a1f2695ed4bf24
MehrdadJannesar/Python-tutorial
/Metaclass.py
834
3.796875
4
# Dynamic Object # def choose_class(name): # if name == 'foo': # class Foo(): # pass # return Foo # else: # class Bar(): # pass # return Bar # # Myclass = choose_class('foo') # print(Myclass) # print(Myclass()) # # print(type(2)) # print(type(int)) # cla...
1a7da614e53829d730e9cdae77e2d0d687fa3e37
MehrdadJannesar/Python-tutorial
/Output.py
855
3.875
4
# x = 5 # print("x is ", x) # # print("Python", end='@') # print("Tutorial") # # print("Python", end='\n') # print("Tutorial") # # print('G','M','H', sep='-') # # print('09','05','2020', sep='-') # 4.51% print("Apple : %2d, Orange: %5.2f" %(1,05.333)) print("%7.3o" %(25)) print("%10.3E" %...
a3479fafd2c2072d09300ebe2be2a1dcc2e97844
MehrdadJannesar/Python-tutorial
/Functions.py
2,364
3.9375
4
# def name(args): # Statements def evenOdd(x): if (x % 2 == 0): print("Even") else: print("Odd") evenOdd(13) def myFun(x): x[0] = 10 lst = [1,20,30,40,50,60] myFun(lst) print(lst) def myFun_2(x): x = [20,30,40] # x.append() lst_2 = [10,50,70] myFun_2(lst_2) print(lst_2) d...
285d12e50ebdbdfcf96b2349c1e44d3828a76c27
MehrdadJannesar/Python-tutorial
/Test_Python_gui_builder.py
847
4.125
4
import tkinter as tk from tkinter import ttk from tkinter import * # this is the function called when the button is clicked def btnClickFunction(): print('clicked') # this is a function which returns the selected spin box value def getSelectedSpinBoxValue(): return spinBoxOne.get() root = Tk() # This is the se...
f74a0055c85284b56ea689551bda0d458d882656
kozhonberdieva12345/quiz_30
/main.py
1,365
3.765625
4
import csv score = 0 with open('sfs.csv', newline='') as sfs: reader = csv.reader(sfs, delimiter=";") for row in reader: print(row[0]) print(row[1], row[2], row[3]) us = input("Выберите вариант ответа(a, b, c): ") if us == 'a': if row[1] == row[4]: score += 5 print("Правильн...
1bbfee4f8972636df6b94d0ad807cc87dad039c7
ZheyuLi/geek_solutions_2017
/binary_search.py.py
1,348
4.0625
4
''' Binary Search Given a sorted array arr[] of n elements, write a function to search a given element x in arr[]. A simple approach is to do linear search.The time complexity of above algorithm is O(n). Another approach to perform the same task is using Binary Search. Binary Search: Search a sorted array by repea...
4d1bd79213af1d8ecdecd7072008fdb187217b50
tusvhar01/python.project
/add two nos..py
46
3.5
4
a=43 b=67 print("The sum of a and b is :",a+b)
11af3d2c63d1d7b68211c63b12a1ff3bc91d823a
cbond29/FinalProject
/soapsuds.py
6,325
3.890625
4
#Importing tkinter module from os import write from tkinter import * from tkinter.ttk import * #Initializing window master = Tk() #Defines all windows main and selections class Frames(object): #Defines soap window def soapWindow(): #Defines pop-up description text for rose de...
b1d60439139f8db342503e8b0775e36ce08e6c39
dradamski/win_shares
/win_shares.py
5,350
3.65625
4
# Purpose of this is to scrape winshare data from basketball-reference.com from bs4 import BeautifulSoup import matplotlib.pyplot as plt import pandas as pd import sqlite3 import urllib.request # Determine whether urllib, urllib2, or requests is best option # Access Basketball Reference to get league leaders i...
d6a7aaa5defa5fbd3576b85351db9bbc6fcabf98
joshkainth/ALLSESSIONS
/venv/cyclic rotation.py
286
4.0625
4
# list1 = [3,8,9,7,6] list2 = map(int, input("Enter elements in list : ").split()) rotation = int(input("Enter how many times you want to rotate :")) list2 = list(list2) for i in range(int(rotation)): list2 = list2[-1:] + list2[:-1] print(f"after {i+1} rotation : ",list2)
d179b3e2f2b67fe42ebed62c32f3fcad9605dbdb
Paezaker2021/My_First_Python_notebook
/7-2. 단순 조건문 2.py
381
3.625
4
kor=int(input("국어: ")) eng=int(input("영어: ")) math=int(input("수학: ")) total=kor+eng+math print('='*15) print('총점=',total) score=round(total/3.0) print('평균=',score) print('='*15) if score>=70: print('PASS') if score==100: print('PERFECT') elif score>=50: print('SUB PASS') else: print('FAIL') ...
e1ec1a5bb7ff8d02726d3fd9fa321f18ee788609
kx-chen/GrocerCheck
/grocercheck/scripts/populatecity/gencoords.py
4,535
3.53125
4
#!/usr/bin/python import numpy as np import sys from math import radians, cos, sin, asin, sqrt def haversine(lat1, lon1, lat2, lon2): lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) # haversine formula dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat/2)**2 + cos(lat1) * cos(la...
f3922dff4de32bb2a4ed1c3eb073431865e32f18
MichaelTangSB/Robin
/6-9.py
333
3.609375
4
favorite_places = { 'Alice': ['qwerq', 'qwertt', 'rweywfgds'], 'Steven': ['wertadf', 'ewtygw'], 'Joy': ['qwretggqwrg', 'khfggdsfg', 'imtfghndf'] } for name, places in favorite_places.items(): print("\n" + name.title() + " likes the following places:") for place in places: print("- " + p...
3bba003c1070c3378cf58c0662797c171473444b
kullu03/geeksforgeeks
/array/duplicate.py
279
3.6875
4
from sets import Set def isDuplicate(arr,k): s = set() for i in range(0,len(arr)): if arr[i] in s: return 1 else: s.add(arr[i]) if(i>=k): #s.remove(arr[i-k]) s.clear() return 0 if(isDuplicate([1, 2, 3,4,1, 2, 3, 4],3)): print "yes" else: print "NO"
8eeaa7123ee8dee5bcb4d75688e05257be0b0188
jy8474np/week02_lab02
/author_class.py
936
3.8125
4
def main(): # Create class and define its componenets class Author: def __init__(self, name): self.name = name self.books = [] def publish(self, title): self.books.append(title) # Displayed information format def __str__(self): ...
457be5f15e89f46e16bbefef397f1a64a9cafb94
wusui/toybox
/Euler/Done/problem156.py
5,013
3.84375
4
#!/usr/bin/python """ Copyright (C) 2016 Warren Usui (warrenusui@eartlink.net) Licensed under the GPL 3 license. Counting Digits -- Project Euler Problem 156 """ from datetime import datetime def checkout(numbr, digit): """ Solve f(n,d) as defined in the problem definition """ dval = 1 ans = 0 ...
ea31ef20d24388e97f264d065c8ddca05b2a764b
wusui/toybox
/Euler/Done/problem329.py
5,075
3.9375
4
#!/usr/bin/python """ Copyright (C) 2016 Warren Usui (warrenusui@eartlink.net) Licensed under the GPL 3 license. Prime Frog -- Project Euler Problem 329 """ from datetime import datetime from array import array def bigsieve(size): """ Prime number sieve -- from a common library Input: size of table (pr...
d1368a2c2ef1af7eaa2c7c2196d5c8c1df0aabe2
nyccowgirl/count_palindrome
/count_palindrome.py
574
3.515625
4
# Option 1: # To test locally: # print(sum(1 for word in open('english.txt').read().splitlines() if word == word.lower()[::-1])) # To test in hills: # print(sum(1 for word in open('/users/abrick/resources/english').read().splitlines() if word == word.lower()[::-1])) # Option 2: # To test locally: # print(sum(1...
b3394403121527e9328f94090a0609a44c8e2db7
Iamsdt/Problem-Solving
/pandas/p1873.py
702
3.640625
4
import pandas as pd def calculate_special_bonus(employees: pd.DataFrame) -> pd.DataFrame: def apply_bonus(row): if row.employee_id % 2 != 0 and str(row['name'])[0] != 'M': return row.salary return 0 employees['bonus'] = employees.apply(apply_bonus, axis=1) employees.sort_value...
cdf93b5b242eb22aba8ebe3514d68fae38484822
Iamsdt/Problem-Solving
/problems/LeetCode/p744.py
1,445
3.5625
4
from typing import List # working but hard way class Solution: def nextGreatestLetter(self, letters: List[str], target: str) -> str: if not letters: return letters p, q = 0, len(letters) - 1 lowest = "" while p <= q: m = (p + q) ...
7a68c3d8c8e92d457f31caf79d3c714aa02ac344
Iamsdt/Problem-Solving
/ds_algo/sorting/quick.py
1,400
4.0625
4
""" Like Merge Sort, QuickSort is a Divide and Conquer algorithm. It picks an element as a pivot and partitions the given array around the picked pivot. There are many different versions of quickSort that pick pivot in different ways. Always pick the first element as a pivot. Always pick the last element as a pivot (...
6539c63926e0fd8e995c3ebc5338b2415210c2a9
Iamsdt/Problem-Solving
/problems/LeetCode/p572.py
2,606
3.90625
4
# Definition for a binary tree node. from typing import Optional class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right # Solution: # 1. dfs and compare each node with second root node # if value is same then compare tree (sam...
ff7c7a63d6b0da1f94e4ed0f41ffae839982aec8
Iamsdt/Problem-Solving
/problems/LeetCode/p1448.py
614
3.625
4
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def goodNodes(self, root: TreeNode) -> int: if not root: return 0 def dfs(node, curMax)...
012b036b3a7e194a74dd54a03c0d049ca44cdd43
Iamsdt/Problem-Solving
/problems/LeetCode/p334.py
471
3.5625
4
from typing import List class Solution: def increasingTriplet(self, nums: List[int]) -> bool: l, r = float('inf'), float('inf') for n in nums: if n == l or n == r: continue if n < l: l = n elif n < r: ...
c1099c6999df89f4abaf930f4c9c7fec6291953e
Iamsdt/Problem-Solving
/problems/LeetCode/blind150/array&hash/p36.py
1,275
3.609375
4
from collections import Counter from typing import List class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: def check(values): di = Counter(values) for j in di: # not filled if j == ".": continue ...
be4b80a1466751194174fc38d4f6802cb24ffe54
Iamsdt/Problem-Solving
/problems/LeetCode/p124.py
950
3.890625
4
# Definition for a binary tree node. from typing import Optional class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right # Solution: # 1. use dfs # 2. take max from left and right value, if negative then make it zero # 3. now t...
8eda5f741b859dcddebe794f2fa37c999ad993c7
Iamsdt/Problem-Solving
/problems/LeetCode/p344.py
400
3.84375
4
from typing import List class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ p,q = 0, len(s)-1 while p < q: s[p], s[q] = s[q], s[p] p, q = p + 1, q -1 return s if __name...
e37a71d68dbb579ce6440af44b1e21418324c58d
Iamsdt/Problem-Solving
/ds_algo/graph.py
1,793
3.90625
4
class GraphTheory(object): def __init__(self, edegas): self.edegas = edegas self.graph_dict = {} for start, end in self.edegas: if start in self.graph_dict: self.graph_dict[start].append(end) else: self.graph_dict[start] = [end]...
6baec25ccd4450d9bc259d5bfcc4410af2bdbf11
Iamsdt/Problem-Solving
/ds_algo/sorting/selection.py
1,203
4.3125
4
import random """ The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. Ways (simplified): # keep two part sorted and unsorted # in every iteration take a fixed position and swap with rest of the values v...
489e5c140ee17aa171a47970a91a4845b1add30a
Iamsdt/Problem-Solving
/problems/algoe/easy/sorted_squared_array.py
374
3.5
4
# what a fucking question # # Write a function that takes in a non-empty array of integers that are sorted # in ascending order and returns a new array of the same length with the squares # of the original integers also sorted in ascending order. # if you square a sequence (ascending order), it will be sorted in asc...
1d960beef57557e8e26f57dbb07486bf4c1fbd09
Iamsdt/Problem-Solving
/problems/LeetCode/p108.py
645
3.6875
4
# Definition for a binary tree node. from typing import List, Optional class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]: # put...
680fdc0bb93e641e01302564e694eb826b518bc7
Iamsdt/Problem-Solving
/problems/LeetCode/p451.py
350
3.6875
4
from collections import Counter class Solution: def frequencySort(self, s: str) -> str: ctr = Counter(s) items = list(ctr.items()) items.sort(key = lambda x: (-x[1], x[0])) words = [ch*n for ch, n in items] return ''.join(words) if __name__ == '__main__': print(Sol...
ad6fdc8a8919026864f1b119a5de5f7de8155d57
Iamsdt/Problem-Solving
/problems/LeetCode/p230.py
822
3.71875
4
# Definition for a binary tree node. from typing import Optional class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right # Solution: # 1. start with root, and move to left until null and put all nodes in stack # 2. when we are do...
c7335fb920df33d871acc8f42f6a2957aa5ba5b0
Iamsdt/Problem-Solving
/problems/LeetCode/p206.py
554
3.65625
4
# Copyright (c) 2022 Shudipto Trafder # # This software is released under the MIT License. # https://opensource.org/licenses/MIT from typing import Optional class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def reverseList(self, head: Opti...
5a47332992e970f6ba8953fab598f0b8006eedc1
Iamsdt/Problem-Solving
/problems/LeetCode/p2095.py
897
3.796875
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, val=0, next=None): self.val = val self.next = next class Solution(object): def deleteMiddle(self, head): """ :type head: Optional[ListNode] :rtype: Optional[ListNode] """ if ...
391533a8089d9c5deb4878f6fd215b7381de3480
Iamsdt/Problem-Solving
/problems/LeetCode/p143.py
2,345
4.21875
4
from typing import Optional # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next # class Solution: # def reorderList(self, head: Optional[ListNode]) -> None: # """ # Do not return anything, modify head in-p...
137eac7291259db75ca1497e7b2a10e1325dd150
Iamsdt/Problem-Solving
/pandas/p177.py
291
3.671875
4
import pandas as pd def nth_highest_salary(employee: pd.DataFrame, N: int) -> pd.DataFrame: employee = employee.sort_values(by='salary', ascending=False) employee.drop_duplicates(subset=['salary'], inplace=True) employee = employee.iloc[N - 1:N] return employee[['salary']]
fc46c7f2ccfdae4cc61b437029d942286c33bbaa
zmbslyr/holbertonschool-higher_level_programming
/0x0B-python-input_output/5-to_json_string.py
293
3.9375
4
#!/usr/bin/python3 """Module to return JSON""" import json def to_json_string(my_obj): """Function to return JSON representation of my_obj Args: my_obj: Object to represent in JSON Returns: JSON representation of my_obj """ return json.dumps(my_obj)
2332cb4c3d7272e4e640c2fdb748c895fca52c0f
zmbslyr/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/models/base.py
2,725
4.0625
4
#!/usr/bin/python3 """Module containing Base class""" import json import os.path import turtle class Base: """Base class for other classes""" __nb_objects = 0 def __init__(self, id=None): """Init method for Base class Args: id (int): ID of the created object """ ...
dc4c5aa229bbbcfc57b74b68cd5b471cb0a4229e
zmbslyr/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/1-last_digit.py
386
3.921875
4
#!/usr/bin/python3 import random number = random.randint(-10000, 10000) n1 = number n = number % 10 if number < 0: n = (abs(number) % 10) * -1 if n > 5: print("Last digit of {} is {} and is greater than 5".format(n1, n)) elif n == 0: print("Last digit of {} is {} and is 0".format(n1, n)) else: print("La...
852b1540fe0e974957ba7e3a7cc24eba6788ce79
CHRISTOFORIDIS-CH/Python_projects
/ασκηση_2.py
795
3.609375
4
file = input("Enter the pathway of the file") #δεν χρειαζεται ελεγχο εγκυροτητας για το φακελο with open(file) as f: flat_list=[word for line in f for word in line.split()] with open(file) as f: for line in f: for flat_list in line.split(): c_word = 0 g_word = 0 ...
f4c5bae7f090b22f02dac479dbffb38465a3c61c
Nikikapralov/Codewars
/Python/Duplicate_Encoder.py
290
3.671875
4
def duplicate_encode(word): new_word = '' for letter in word: word = word.lower() letter = letter.lower() if word.count(letter) > 1: new_word += ')' else: new_word += '(' return new_word print(duplicate_encode('recede'))
e9c56aeea10522d2475a0278f6ca512c9433e7d2
sruj01/Coursera-Python-Data-Structures
/ass8.5.py
265
3.84375
4
fn=input('Enter file name: ') fh=open(fn) count=0 for l in fh: l=l.rstrip() if not l.startswith('From '): continue count+=1 w=l.split() print(w[1]) print('There were',count,'lines in the file with From as the first word')
994ab41c578a0bc2b641daa4bb1f0adf0ac13993
sruj01/Coursera-Python-Data-Structures
/ass7.2.py
254
3.53125
4
fn=input('Enter file name: ') fh=open(fn) count=0 total=0 for line in fh: if line.startswith('X-DSPAM-Confidence:'): count+=1 num = float(line[21:]) total = num + total print('Average spam confidence: ',total/count)
512ba49b2eaf170030f1b51de362dd1f07473ac0
optimus1810/crackingTheCodingIntPython
/interview questions/remove_duplicate_from_llist.py
3,087
3.5
4
__author__ = 'Gaurav' from LinkedList import CustomLinkedList, Node def remove_duplicates_from_linkedL(linkedlist): hash_map = {} current = linkedlist.head while current is not None: if current.content not in hash_map: hash_map[current.content] = 1 else: linkedlist....
3fc32ccaa59aeb87187d4913764c1236b8d07501
optimus1810/crackingTheCodingIntPython
/interview questions/duplicate.py
553
3.859375
4
__author__ = 'Gaurav' def remove_duplicate(input_str): if len(input_str) == 0: return new_string = [] for char in input_str: if char not in new_string: new_string.append(char) return (''.join(new_string)) def main(): new_string = remove_duplicate("aabb") print new_s...
600ce765418b0d90b600ea837774dbbd4f5d0a8e
optimus1810/crackingTheCodingIntPython
/interview questions/three_stack_with_array.py
1,480
3.96875
4
__author__ = 'Gaurav' class three_stack_array(object): def __init__(self, stack_size, number_of_stacks): self.stack_size = stack_size self.holding_array = [0 for x in range(self.stack_size*number_of_stacks)] self.top_pointers = [0 for x in range(number_of_stacks)] def push(self, stack_num...
fad1734838585d4c520948c69416a1b0cdca6ca2
alanz4196/linked_lists
/linked_lists.py
15,335
3.734375
4
class Linked_List: class Node: def __init__(self, val): self.val = val self.__next = None self.__prev = None def __init__(self): self.__header = Linked_List.Node(None) self.__trailer = Linked_List.Node(None) self.__header.__next = self.__trai...