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
5502f5991c780b5c296736545176769148a1b7cd
TheDivic/Gilmore-algorithm
/gilmore/syntax_tree.py
35,426
3.8125
4
"""A module that contains the syntax tree for first order logic.""" from sys import stdout import copy import pdb class OperandTypes(object): """An enum for all the operand types in first order logic.""" T_ATOM = 0 T_NOT = 1 T_AND = 2 T_OR = 3 T_IMP = 4 T_IFF = 5 T_FORALL...
24ed2d9125c33b2105cd12fc24fbe2a1da5a2df1
Goggot/Automne2012
/Python/Projet1/f1.py
710
3.5625
4
#if __name__=="__main__" : TableDeJeu=[] Dalek=[5] class Lecture(): def lis(self): f=open(self,"r") class Docteur(x,y,choix): def coordonnee(self): x=(self.x) y=(self.y) if choix == 1: Deplacer(x,y) if choix == 2: Attaque(x,y) if choix == 3: ...
1459877e583981da5f6012053c34474e6dc59d03
Wendellmga/teste
/Exercicios.py
3,370
4.09375
4
#Quest 1 """" print("Wendel") """ #Quest 2 """ nome = input("Digite seu nome nome:") #print("Digite o seu nome: ", nome) print("O seu nome é: %s, volte sempre" %nome) """ #Quest 3 """" nome = input("Informe seu nome: ") idade = input("Informe sua idade: ") print() print("O seu nome é %s, e a sua idade é " %nome + str...
3cb2fb3f11fc0c341112ec63fd99258de95eb313
aniquetahir/DailyCodingProblem
/Day8/solution.py
1,346
3.796875
4
import copy class Tree(): def __init__(self, value, left=None, right=None): self.value = value self.isunival = None self.left = left self.right = right def isUnival(tree): ''' We use memoization to solve our problem. The status about the unival is stored with each node ...
ef92085d28b0df0fba35ae3d3c3ad6f569994193
Daylanq10/Early_Python_Projects
/SnakeGame.py
3,876
4.03125
4
import random #RUNS A SNAKE GAME IN THE SHELL. MUST HIT ENTER BETWEEN EACH INPUT class board: """Class for implimenting the grid that the snake game is played on""" def __init__(self): self.grid = [] self.food_spot = [] def create(self): """Creates a blank grid for the game to s...
de096945ea44907ec1f3d394f193f5962ba06222
Agnar22/AIProg
/ActorCritic/Board/Hexagonal.py
1,541
3.53125
4
import numpy as np import json class Hexagonal: def __init__(self, board_type, board_size, cell_types): self.neighbours = [(-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0)] self.board = self._create_board(board_type, board_size, cell_types) @staticmethod def _create_board(board_type, di...
81364853e7c2cd12725dcee062b679eb061880bd
bililioo/LearnPython
/myStuff/regular_expression.py
857
3.59375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import re print(re.match(r'^\d{3}\-\d{3,8}$', '010-12345')) print(re.match(r'^\d{3}\-\d{3,8}$', '010 12345')) test = '用户输入的字符串' if re.match(r'正则表达式', test): print('ok') else: print('failed') test_str = 'a, b, ;; c d' t = test_str.split(' ') print(t) t = re....
598815868af40aa07254b78b20fe37cca64f5cb3
bililioo/LearnPython
/myStuff/ex06.py
4,055
3.75
4
# -- coding: utf-8 -- from collections import Iterable # 迭代器 # Iterable 可迭代对象 print(isinstance([], Iterable)) print([x for x in range(10)]) print(isinstance({}, Iterable)) print(abs) # 结论:函数本身也可以赋值给变量,即:变量可以指向函数。 # 那么函数名是什么呢?函数名其实就是指向函数的变量! # 对于abs()这个函数,完全可以把函数名abs看成变量,它指向一个可以计算绝对值的函数! f = abs print(f(-999)) # ...
3f6082162921df1f9f1060f042d6ce97c6c50236
bililioo/LearnPython
/myStuff/ex04.py
2,706
3.90625
4
# -- coding: utf-8 -- L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack'] # 切片 print(L[0:3]) print(L[:3]) L2 = list(range(100)) print(L2[:10:3]) print(L2[::3]) print(L2[9:-2]) def trim(s): print('输入的内容(%s)' %s) if s == '': print('最终结果:%s' %s) return s if s[0] == ' ': s = s[1:] print('前空格', s) return tr...
fced1db823943ecbfe545d75d9ed3ec467edffa5
IDTitanium/Data-Structures-and-Algorithms
/searching/linear_search.py
227
3.875
4
from typing import Iterable def linear_search(arr: Iterable[int], target: int) -> int: """Linear search """ for index, value in enumerate(arr): if value == target: return index return -1
cdca2c668690bb9fccaf16347eb5c6d7bdfe646d
IDTitanium/Data-Structures-and-Algorithms
/sorting/selection_sort.py
406
3.84375
4
from typing import List def selection_sort(arr: List[int]) -> List[int]: for i in range(0, len(arr) - 1): current_index = i smallest_index = i for j in range(current_index + 1, len(arr)): if arr[smallest_index] > arr[j]: smallest_index = j arr[current_...
037a7417d36630bff296eff4878a2785580d2697
tdarcher/pace_interview
/prediction.py
1,312
3.859375
4
#!/usr/bin/env python # The function predict() takes a pandas vector containing dates and # the historical avarage as arguments. # a numpy vector contining probability for each date is returned ############## usage example ############################### #mindate = datetime.datetime(2017, 3, 6) #maxdate = mindate +...
80157ef174a750be481f836fee11e898b9a74ca9
jmpitt822/PyHangman
/Gameboard.py
1,335
3.5
4
def printGameBoard(triesRemaining): if triesRemaining == 10: gameboard = "---------\n |\n |\n |\n |\n |\n_________" elif triesRemaining == 9: gameboard = "---------\n | |\n |\n |\n |\n |\n_________" elif triesRemaining == 8: gameboard =...
3aa3292bad982d13aa181250c738804b14af68ca
ssenthil-nathan/DSA
/linkedlistdelwithkey.py
1,628
4.21875
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def Delete(se...
c0404913e36a5395ce4bee6fda5038d0aecae5ac
jsalfity/bear_atm
/bear_atm/ATM.py
6,135
3.734375
4
''' J. Salfity, October 2020 ATM API implemented considerations for this example: - No encryption between ATM and Bank, including initilization, transactions, requests - Transactions do not have uniqueID's - ATM has only one Bank / Bank has single ATM - cash bin is not implemented, assume ATM user enters proper amou...
5e137da87cb14ebcae462477f2059c332d6a59ba
GodspeedyJulian/3.1
/4.py
303
3.890625
4
def weight(Weight): if Weight == 3: Weight=1 else: Weight=3 return Weight Weight=1 total=0 for i in range(12): digit=int(input('digit: ')) value=digit*Weight total+=value Weight=weight(Weight) r=total%10 c=10-r print('校验码为: ' +str(c))
efa9a0970b3f123d00265ef25f4b84a1c9032a36
JameyCalbreze/AdventOfCode2020
/day06/problem2.py
672
3.796875
4
import io def solve(rows): count = 0 cur_set = set() first = True for row in rows: if row == "": count += len(cur_set) first = True else: cur_letters = set() for letter in row: cur_letters.add(letter) if first: cur_set = cur_letters first = False ...
52a676b3e517e87deeab2ad330c3aaffe9749598
fahadsaeed57/firstpythonproject
/oddeven.py
109
3.984375
4
numb = input("enter a num"); if int(numb) % 2 == 0: print("Even number"); else: print("Odd number");
c7699ed05d976057a0517c0fee56fa0f2c82d4cf
amolife/IBM-Pythonlearn
/fibonacci2.py
155
3.578125
4
#! /usr/bin/env python3 # _*_ coding: UTF-8 _*_ print("output 50 fibs:") fibs = [1, 1] for i in range(50): fibs.append(fibs[i]+fibs[i+1]) print(fibs)
b5c0f8d436139dbe29cce9381d9e188fa014f442
hartikainen/euler
/031_coin_sums.py
338
3.546875
4
COINS = [1,2,5,10,20,50,100,200] TARGET = 200 def coin_sums(coins, target): print( "called coins_sums with coins {} and target {}".format(coins, target) ) if len(coins) == 1: return 1 subproblems = [ coin_sums(coins[0:-1], x) for x in xrange(target, -1, -coins[-1]) ] return sum(subproblems) print(coin_sum...
f0dd04ab74a1692d9f892c86b99001040458f05c
csse120/csse120-public
/PythonProjects/12-SequencesAndMutation/src/m3e2_objects_are_mutable.py
3,026
4.15625
4
""" This module demonstrates MUTATION of an OBJECT in two ways: -- From an assignment in main. -- From within a function call. Authors: David Mutchler, Vibha Alangar, Matt Boutell, Dave Fisher, Mark Hays, Amanda Stouder, Derek Whitley, and their colleagues. """ # --------------------------------------...
a4968e6feb2cbf5d227009dfe272ebc84ca6ebbc
csse120/csse120-public
/PythonProjects/16-Input_WaitUntilEvent_WhileLoops/src/m3r_v1_wait_for_event_examples.py
11,951
4.0625
4
""" This module demonstrates the WAIT-FOR-EVENT pattern using the WHILE TRUE pattern: while True: ... if <event has occurred>: break ... See the module that is the COMPANION to this one for the same examples, but using the ITCH pattern for WHILE loops. Authors: David Mutchler, Vibh...
bb1149d0cbdc4f3333215e083452d034507aae87
iancross/projects
/Playground/python/remove_duplicates.py
257
3.71875
4
word = "Today is the day" word = list(word) i = 0 size = len(word) while i < size: testing = word[i].lower() temp = i + 1 while temp < size: if testing == word[temp].lower(): word.pop(temp) size -= 1 else: temp += 1 i+=1 print ''.join(word)
eef3249f86e247d377e5a7d7ccec531df6e878f1
iancross/projects
/Playground/python/Max_sum_subsequence.py
415
3.515625
4
numbers = [-2,13,5,2,10] max_so_far = numbers[0] max_here = max_so_far begin = 0 begin_temp = 0 end = 0 size = len(numbers) for i in range(0,size): if max_here < 0: max_here = numbers[i] begin_temp = i else: max_here += numbers[i] if max_here >= max_so_far: max_so_far = max_here begin = begin_temp en...
4b9da9a953a5032f9708b15cfd4e10fd4759b07c
Kirperepolov/python_practics
/chapter4/ospathutils.py
1,000
3.546875
4
import os from os import path import datetime from datetime import time, datetime, timedelta import time def main(): # print the name of the OS print(os.name) # check for an item existence and type print("Item exists: " + str(path.exists("textfile.txt"))) print("Item is a directory: " + str(path....
2cfd8bf29061bbdd0f32bb351a5e27236948832a
sarthaksr19/Chapter-12
/03_try_else_clause.py
201
3.78125
4
try: a = int(input("enter the number ")) b = 1/a print(b) except Exception as e: print(e) else: print("this else block only exceutes when try method is true otherwise it dosen't")
0c3870477cdccef0662d34a514463983410be2c6
sarthaksr19/Chapter-12
/01_try.py
334
4.0625
4
while(True): print("press q to quit") a = input("Enter the number\n") if a == 'q': break try: a = int(a) if a>10: print("you entered a number greater than 10") except Exception as e: print(f"your input result throws an error: {e}") print("Thanks for playi...
9395758b820c067941a102e2dab41aa8ecb9db9c
ss-won/ps_study
/ss-won/programmers/42839.py
758
3.5
4
import math def solution(numbers): answer = 0 arr, checked, size = list(numbers), [], len(numbers) def ckDecimal(num): if num == 1 or num == 0: return False for i in range(2, int(math.sqrt(num))+1): if num % i == 0: return False return True ...
e8eb98cfa0e97570bbaaf16863893387d6ecef5e
ss-won/ps_study
/ss-won/programmers/17679.py
904
3.5
4
import re def solution(m, n, board): answer = 0 ck = [[False for _ in range(m)] for _ in range(n)] boardq = [[board[j][i] for j in range(m)] for i in range(n)] for i in range(n-1): for j in range(m-1): cur = boardq[i][j] if re.match('[A-Z]', cur) != None and cur == boar...
9f72f47da67b932651229c8927250be8017be011
LIFA-0808/my_exercises
/file_to_reed_py.py
337
3.671875
4
file_name = 'text.txt' linelist = [] with open(file_name) as file_object: # for line in file_object: # print(line.rstrip()) # print(file_object.read()) # for line in file_object: # linelist.append(line.rstrip()) #print(linelist) for line in file_object: print(line.replace('python'...
2494d474fb7a80196bd34a7119c7bd24e00510af
arturops/AlgosRefresher
/greedy_algorithms/5_maximum_number_of_prizes/different_summands.py
609
3.734375
4
# Uses python3 import sys def optimal_summands(n): """ Finds the maximum number of different numbers that added together give n """ summands = [] i = 1 while(n != 0): #print('n-i:{}-{} = {}'.format(n,i,n-i)) if(n-i > i or n-i == 0): summands.append(i) n -= i i += 1 ...
61739837cf983d73229378376144c6465d798813
sevresbabylone/python-practice
/quicksort.py
744
4.34375
4
"""Quicksort""" def quicksort(array, left, right): """A method to perform quicksort on an array""" if left < right: pivot = partition(array, left, right) quicksort(array, left, pivot-1) quicksort(array, pivot+1, right) def partition(array, left, right): """Returns new pivot after ...
c4529e52c8bc4ce430413c04a9d1d339d8b9ad44
mclavan/Work-Maya-Folder
/2014-x64/prefs/1402/functions_02b.py
1,769
3.734375
4
''' Lesson - Functions This exercise will introduce functions. How to Run: import functions_01 reload(functions_01) ''' import pymel.core as pm print 'Lesson - Function practice.' ''' # Think of a function as a chapter of a book. # Functions allow the user to run any part of a script on demand. def funct...
c832e855070a8b2af1a5e76460e15578b6ba559e
mclavan/Work-Maya-Folder
/2014-x64/prefs/1311/snapping2.py
1,326
3.546875
4
''' Exercise - Snapping Tool Create a tool that will snap one object to another. Objectives: - Plan out and document each step. - Get Selected Objects - Use constraints to move objects. - Delete unused components. - Output what your tool has done to the scene. How To Run: import snapping reload(snapping) ''' i...
f853cecddcac4e12ec8d8d2f60e01e80ad840f98
mclavan/Work-Maya-Folder
/2014-x64/prefs/1402/if_01_notes.py
1,239
4.5625
5
''' Lesson - if statements ''' ''' Basic if statement if condition: print 'The condition is True.' ''' if True: print 'The condition is True.' if False: print 'The condition is True' ''' What is the condition? 2 == 2 2 == 3 ''' ''' Operators == Equals != Not Equals > Greater Than >= Greater Than or equal...
43692b7dfe2f49f99b2220666903b48c7c0047f3
mclavan/Work-Maya-Folder
/2014-x64/prefs/1405/creating_icons.py
956
3.9375
4
''' Exercise - Creating Padded Controls creating_icons.py Creating a padded control icon. ''' import pymel.core as pm print 'Creating Icons Example' ''' - Target - Create three controls are parent them to each other. - WATCH OUT - Controls return more then just a transform node. ''' # Create a control icon and s...
e2bb492d4461530ee4d5eae09ac586fa67f3e7a6
shuai93/drf-demo
/others/func_rate_decorator.py
984
3.546875
4
from functools import wraps TOTAL_RATE = 2 FUNC_SCOPE = ['test', 'test1'] def rate_count(func): func_num = { # 需要注意函数名不能重复 func.__name__: 0 } @wraps(func) def wrapper(): if func.__name__ in FUNC_SCOPE: if func_num[func.__name__] >= TOTAL_RATE: rai...
8992fea2a47dbb335f70260889767e3a7507f872
richnakasato/lc
/22.generate-parentheses.0.python3.py
1,418
3.765625
4
# # [22] Generate Parentheses # # https://leetcode.com/problems/generate-parentheses/description/ # # algorithms # Medium (51.33%) # Total Accepted: 268.1K # Total Submissions: 522.1K # Testcase Example: '3' # # # Given n pairs of parentheses, write a function to generate all combinations # of well-formed parenthes...
ed3da342d81815c68bca7b5f5a81d9076cac5751
richnakasato/lc
/670.maximum-swap.python3.py
737
3.8125
4
# # [670] Maximum Swap # # https://leetcode.com/problems/maximum-swap/description/ # # algorithms # Medium (39.01%) # Total Accepted: 30.5K # Total Submissions: 78.2K # Testcase Example: '2736' # # # Given a non-negative integer, you could swap two digits at most once to get # the maximum valued number. Return the...
f4814a8ac8d830375f1d66f3df32dc0e330c0df2
richnakasato/lc
/48.rotate-image.0.python3.py
994
3.625
4
class Solution: def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ top = left = 0 bot = right = len(matrix) - 1 while top < bot and left < right: sz = bot - top ...
4e353c2390128a2018f4c01c814a1a87cbfcf035
joebg10/connect4
/connect4Game.py
4,713
3.625
4
# # ps9pr3.py (Problem Set 9, Problem 3) # # Playing the game # from connect4Board import Board from connect4Player import Player import random def connect_four(p1, p2): """ Plays a game of Connect Four between the two specified players, and returns the Board object as it looks at th...
11b6fd0538c083c5ad8200d6627495f992a6e747
Courage-GL/FileCode
/Python/month02/day16/exercise/exercise01.py
909
3.5625
4
""" 基于select 的io多路复用 """ from socket import * from select import select ADDR = ("0.0.0.0", 23456) r_list = [] w_list = [] x_list = [] sock = socket(AF_INET, SOCK_STREAM) sock.bind(ADDR) sock.listen(5) sock.setblocking(False) r_list.append(sock) while True: # 在这里阻塞 rs, ws, xs = select(r_list...
763c98537e82cf41af148b99f89e489460ce047a
Courage-GL/FileCode
/Python/month01/day15/exercise01.py
450
4.03125
4
""" 定义函数,根据年月日,计算星期. 结果:星期一  星期二  星期三   """ import time def get_week(year, month, day): tuple_time = time.strptime("%d-%d-%d" % (year, month, day), "%Y-%m-%d") index_week = tuple_time[6] tuple_weeks = ("星期一","星期二","星期三","星期四","星期五","星期六","星期日") return tuple_weeks[index_week] print(get_week(2...
a79efd8338b2d0d27c4af520743cd75bd0cb3ac8
Courage-GL/FileCode
/Python/month02/day09/exercise01.py
888
3.6875
4
""" 练习: input输入一个学生的姓名 ,将该学生的成绩改为100分 """ import pymysql input_name = input("输入姓名:\n") db = pymysql.connect(host='192.168.196.128', port=3306, user='root', password='123456', database='stu', charset='utf8') cur = d...
3efc08f2e3bc5f399fc0a97602af4dd3470680b1
Courage-GL/FileCode
/Python/month02/day14/thread01.py
345
3.5625
4
from threading import Thread from time import sleep def fun01(): for i in range(3): sleep(1) print("播放:粉红色的回忆") t = Thread(target=fun01) t.setName("new_thread") t.start() print(t.is_alive()) print(t.getName()) for i in range(4): sleep(1) print("播放:葫芦娃") t.join() print(t.is_alive())
f993c3fb623b5c03acede47ab04539d840e763ba
Courage-GL/FileCode
/Python/month01/day04/exercise07.py
433
3.90625
4
""" 练习2: 循环录入编码值打印文字,直到输入空字符串停止。 效果: 请输入数字:113 q 请输入数字:116 t 请输入数字: Process finished with exit code 0 """ while True: str_input = input("请输入数字:") if str_input == "": break # 跳出循环 number = int(str_input) print(chr(number))
c297bfde92c1cfdd5e1784ff548374a9f17e6aa5
Courage-GL/FileCode
/Python/month01/day08/demo03.py
557
4.21875
4
""" 局部变量:小范围(一个函数)内使用的变量 全局变量:大范围(多个函数)内使用的变量 """ b = 20 def func01(): # 局部作用域不能修改全局变量 # 如果必须修改,就使用global关键字声明全局变量 global b b = 30 func01() print(b) # ? c = [30] def func02(): # 修改全局变量c还是修改列表第一个元素?? # 答:读取全局变量中数据,修改列表第一个元素 # 此时不用声明全局变量 c[0] = 300 func02() print(c) ...
d97a612322b589841ac1914cbb6442305fa7faa5
Courage-GL/FileCode
/Python/month01/day06/demo01.py
679
4.03125
4
""" 列表推导式 列表 = [对变量操作 for 变量 in 可迭代对象 if 对变量的判断] 适用性:根据可迭代对象构建列表 练习:exercise01 """ # 需求1:将list01中大于10的数字,存入另外一个空列表中 list01 = [4, 54, 56, 67, 8] # list_result = [] # for item in list01: # if item > 10: # list_result.append(item) list_result = [item for item in list01 if item > 10] pri...
77e65d7242d0273e5b86b155fb45a63bd8cb5deb
Courage-GL/FileCode
/Python/month01/day16/demo06.py
602
3.6875
4
""" MyRange 3.0 生成器函数 """ """ class Generator: # 生成器 = 可迭代对象 + 迭代器 def __iter__(self): # 可迭代对象 return self def __next__(self): # 迭代器 准备数据 return 数据 """ def my_range(stop): number = 0 while number < stop: yield number number += 1 # for number in my_rang...
a6d5f3680095ecef00f0c71dda3a16a3d545c64d
Courage-GL/FileCode
/Python/month01/day07/demo06.py
605
4.09375
4
""" 函数 - 返回值 制作函数时 给 使用函数时 传递的信息 def 函数名(参数): ... return 数据 变量 = 函数名(参数) 练习:exercise11 """ # 定义函数,两个数字相加. # number_one = int(input("请输入数字:")) # number_two = int(input("请输入数字:")) # result = number_one + number_two # print(result) def add(number_one,number_two)...
5fce175166e70faffa9eae9e9313c3b8c4de23cc
Courage-GL/FileCode
/Python/month01/day19/demo06.py
462
3.859375
4
""" 装饰器语法细节 - 参数 """ def new_func(func): def wrapper(*args, **kwargs): # 多个实参 合为 一个形参(元组/字典) print("new_func执行了") result = func(*args, **kwargs) # 一个实参 拆 多个形参 return result return wrapper @new_func def func01(p1): print("func01执行了", p1) @new_func def func02(p1, p2): ...
c08d154cc14216d2b067450bedd5cb4512c2cb54
Courage-GL/FileCode
/Python/month02/day11/tcp_server.py
962
3.890625
4
""" tcp 服务端代码示例 """ import socket ADDRESS = ('0.0.0.0', 8888) # 参数如果不写 也是TCP tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 绑定地址 tcp_socket.bind(ADDRESS) # 设置监听 为连接做准备 tcp_socket.listen(1024) while True: print('<-----WAITING FOR CONNECTION----->') # 等待客户端连接 ...
3580a2af2a21f9f5d08bbb3115b7c3f7daf70f44
Courage-GL/FileCode
/Python/month01/day13/student_info_system.py
1,531
4.40625
4
""" 学生信息管理系统 """ class StudentModel: """ 学生信息模型 """ def __init__(self, name="", score=0, age=0, sid=0): self.name = name self.score = score self.age = age # 全球唯一标识符:系统为数据赋予的编号 self.sid = sid class StudentView: """ 学生信息视图:负责处理界面逻辑 """ ...
05af8dcf85f104912c05a377b29537a0111be969
Courage-GL/FileCode
/Python/month01/day06/exercise03.py
532
4.0625
4
""" 练习2: 根据月日,计算是这一年的第几天. 公式:前几个月总天数 + 当月天数 例如:5月10日 计算:31 29 31 30 + 10 """ month = int(input("请输入月份:")) day = int(input("请输入月份:")) day_of_month = (31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) # 累加前几个月 # total_days = 0 # for i in range(month - 1): # total_days += day_of_month...
259a2f1710323a6aa1a905996af1563143528424
Courage-GL/FileCode
/Python/month01/day09/exercise02.py
491
4.1875
4
# 练习:定义数值累乘的函数 # list01 = [4,54,5,65,6] # result = 1 # for item in list01: # result *= item # print(result) def multiplicative(*args): # 合 result = 1 for item in args: result *= item return result print(multiplicative(43, 4, 5, 6, 7, 8)) print(multiplicative(43, 4)) print(multiplicative(43, 4...
ce35fe30a63e8485c201d734f4fa3539d8051ef1
Courage-GL/FileCode
/Python/month01/day03/exercise12.py
359
3.875
4
""" 在终端中循环录入5个成绩, 最后打印平均成绩(总成绩除以人数) """ count = 0 # 循环前 -- 创建变量 total_score = 0 while count < 5: score = int(input("请输入成绩:")) # 循环中 -- 累加 total_score += score count += 1 # 循环后 -- 结果 print("平均成绩是:"+str(total_score / count))
b6d39d5c2f062fcf2dbafbf739f0c03f1c7ce3f4
Courage-GL/FileCode
/Python/month01/day10/exercise02.py
983
4.40625
4
""" 练习:对象计数器 统计构造函数执行的次数 使用类变量实现 画出内存图 class Wife: pass w01 = Wife("双儿") w02 = Wife("阿珂") w03 = Wife("苏荃") w04 = Wife("丽丽") w05 = Wife("芳芳") print(w05.count) # 5 Wife.print_count()# 总共娶了5个老婆 """ cl...
f0bb994dcb9fdc3bc96177da99f96a928a9e6ebf
Courage-GL/FileCode
/Python/month01/day04/demo03.py
547
4.375
4
""" for + range函数 预定次数的循环 使用 for 根据条件的循环 使用 while 练习:exercise04 """ # 写法1: # for 变量 in range(开始,结束,间隔): # 注意:不包含结束值 for number in range(1, 5, 1): # 1 2 3 4 print(number) # 写法2: # for 变量 in range(开始,结束): # 注意:间隔默认为1 for number in range(1, 5): # 1 2 3 4 print(number) # 写法3: # for 变量 in...
f5d1d3d359f76588728efa9477bd304f7613dc47
Courage-GL/FileCode
/Python/month01/day03/exercise09.py
625
3.96875
4
""" 练习:在终端中输入一个年份,如果是闰年为变量day赋值29,否则赋值28。 闰年条件:年份能被4整除但是不能被100整除 年份能被400整除 效果: 请输入年份:2020 2020年的2月有29天 """ year = int(input("请输入年份:")) # if (year % 4 == 0 and year % 100 != 0 or # year % 400 == 0): # day = 29 # else: # day = 28 if (year % 4 == 0 and ye...
157ae64facfa681773430adaade655b44c8464ca
Courage-GL/FileCode
/Python/month02/day16/epoll_io_server.py
1,342
3.515625
4
""" 基于EPOLL的 IO网络并发模型 IO 多路复用与非阻塞搭配 重点代码!!! """ from socket import socket from select import * map = {} HOST = "0.0.0.0" PORT = 12346 ADDR = (HOST, PORT) sock = socket() sock.bind(ADDR) sock.listen(5) # 设置非阻塞 sock.setblocking(False) p = epoll() p.register(sock, EPOLLIN | EPOLLERR) map[sock.fileno()] = soc...
90a6cae3473a8caff999344e283ead22b0351ffe
Courage-GL/FileCode
/Python/month01/day17/demo01.py
712
3.96875
4
""" 生成器表达式 复习:列表推导式 """ # 需求1:将list01中大于10的数字,存入另外一个空列表中 list01 = [4, 54, 56, 67, 8] # list_result = [] # for item in list01: # if item > 10: # list_result.append(item) list_result = [item for item in list01 if item > 10] print(list_result) # def find01(): # for item in list01: # if ite...
18d5e864ab8ee5e60327f89e21a5689860c71ad8
Courage-GL/FileCode
/Python/month01/day03/demo03.py
928
4.0625
4
""" 逻辑运算符 判断两个命题(bool值)之间的关系 短路运算 一但结果确定,后面的语句将不再执行。 and 有false or 有true 练习:copy_dir.py """ # True True # False True # True False # False False # 与 and 都得满足 结果才满足 print(True and True) # True print(False and True) # False print(True and False)...
c6d89bcaeb162b59041dd05b4acbef04f09c38fe
Courage-GL/FileCode
/Python/month01/day18/demo02.py
587
4.15625
4
""" 排列组合 全排列(笛卡尔积) 语法: 生成器 = itertools.product(多个可迭代对象) 价值: 需要全排列的数据可以未知 """ import itertools list_datas = [ ["香蕉", "苹果", "哈密瓜"], ["牛奶", "可乐", "雪碧", "咖啡"] ] # 两个列表全排列需要两层循环嵌套 # n n list_result = [] for r in list_datas[0]: for c in list_datas[...
7399f5423967989527c30c25c0d35285b65ed186
Courage-GL/FileCode
/Python/month01/day05/demo08.py
639
3.96875
4
""" 1. 列表转换为字符串: result = "连接符".join(列表) 练习:exercise08 """ # list01 = ["a", "b", "c"] # result = "*".join(list01) # print(result) # 需求:频繁修改不可变数据 # (根据某些逻辑,拼接字符串) # 0 1 2 3 4 5 6 7 8 9 # 缺点:循环一次 产生一个新字符串 之前的数据成为垃圾 # result = "" # for number in range(10): # # result = result + str(number) # res...
ae58da8b5b001fdc9c5059c8c177ea9979276c2b
Courage-GL/FileCode
/Python/month01/day06/demo04.py
718
3.859375
4
""" 字典dict 练习:exercise04 """ # 1. 创建 # 语法1:字典名 = {键1: 值1, 键2: 值2} dict_lsw = {"name": "李世伟", "age": 26, "sex": "男"} dict_yjm = {"name": "杨建蒙", "age": 23, "sex": "女"} # 语法2:字典名 = dict(可迭代对象) # 注意:可迭代对象内的元素必须能够一分为二 #    [( , ) , ( , )] list01 = ["唐僧", ("猪", "八戒"), ["悟", "空"]] dict01 = dict(list01) print(dict0...
183771055132c4d3d282046ab1740975e37dc336
Courage-GL/FileCode
/Python/month01/day10/demo03.py
697
3.984375
4
""" 小结 - 实例成员 与 类成员 class 类名: 变量名1 = 数据 # 创建类变量 def __init__(self): self.变量名2 = 数据 # 创建实例变量 @classmethod # 类方法:操作类变量 def 方法名1(cls): 通过cls操作类变量 不能操作实例成员 def 方法名2(self): # 实例方法:操作实例变量 通过self操作实例变量 ...
7a1a526eb7b610c36c8baf332aa27e5b2299a342
yanaadi/AllPythonProjects
/passwordmanager.py
9,020
3.59375
4
import sqlite3 import base64 import time from sqlite3 import Error class StoreManager: def __init__(self, username, website, password): self.username = username self.website = website self.password = password def store(self): try: conn = sqlite3.connect('p...
172a6bae6d58688537493e477879a70abec69a51
akshaygithub12/flask123
/23jan24jan/bhu.py
128
3.65625
4
def ran(x): x=input("enter the no") if x in range(1,10): print x ,"is in the range" else: print "invalid value", x ran(x)
4560ae75b9c66bbb4cf36973f48db46b620e10a8
pedronora/exercism-python
/prime-factors/prime_factors.py
458
4.125
4
def factors(value): factors_list = [] # Divisible by 2: while value % 2 == 0: factors_list.append(2) value = value / 2 # Divisible by other primes numbers: sqrt = int(value**0.5) for i in range(3, sqrt + 1, 2): while value % i == 0: factors_list.appen...
b97086abe8afb10732701523cfca278e5802fc03
pedronora/exercism-python
/phone-number/phone_number.py
568
3.65625
4
class PhoneNumber: def __init__(self, number): numbers = ''.join((filter(str.isdigit, number))) if numbers[0] == '1': numbers = numbers[1:] if len(numbers) != 10: raise ValueError('Invalid phone number format') if numbers[0] in ['0', '1'] or numbers...
4bfd1d4a03b12f1c69e23119e23b04dc2c4dc425
pedronora/exercism-python
/secret-handshake/secret_handshake.py
674
3.640625
4
handshakes = {1000: 'jump', 100: 'close your eyes', 10: 'double blink', 1: 'wink'} def convert_to_binary(number): if number == 0: return 0 binary = '' while number / 2 > 0: binary += str(number % 2) number = number // 2 return i...
60fd84767631b780099d4d7872312906ff02808f
KaterinaMutafova/Udemy-courses
/Beginner_to_Advanced_course/Project_1_calculator/main_calc.py
382
3.953125
4
import re previous = 0 run = True print("Magical calculator") print("Type 'Quit' to exit\n") a = 6 while run: equation = input("Enter equation:") if equation == "Quit": run = False else: equation = re.sub("[a-zA-Z,.()" "]", "", equation) equation = eval(equation) + ...
563089d2d3019d416e37fb402916d7f2068392e2
Kavin1701/PythonTutorial
/Ordering0and1.py
778
3.90625
4
# ordering of 0's and 1's (Optimised) import array as arr str = input("\nEnter the sequence (containing 0's and 1's) : ") # getting input as string myArray = arr.array("i", [int(s) for s in list(str)]) # converting string to array print(" Array before ordering : {}".format(myArray)) i, j = 0, len(str)-1 # to p...
b08441f5fa3cd922f63e7a8adf6560954e3e2a68
eighteenthousandonehundredandsixtyfive/Project---JevaanIrwin
/WindowTest1.py
2,473
3.90625
4
#Python hello #https://realpython.com/python-gui-tkinter/ #for mplotting data #%% from tkinter import * import time class data(): def __init__(self, parent): self.main_page = Frame(parent, width=750, height=350) self.main_page.pack() intro = Label( ...
5784e2b19102935882e34a758823f4dfa08b3ea4
mcnnowak/advent_of_code_2018
/p1/p1.py
904
3.53125
4
# AOC -- https://adventofcode.com/2018/day/1 # Frequency Changes # Sum the frequency changes. import os AOC_DIR = 'C:\\Users\\mnowak6\\Desktop\\advent_of_code_2018' PUZZLE_NAME = 'p1' INPUT_FILENAME = 'input.txt' INPUT_FILE = os.path.join(AOC_DIR, PUZZLE_NAME, INPUT_FILENAME) def read_input(filename): ...
7da2a693b787cf3da8fdebeb50bac672f6dcd5cf
autumnalkitty/python_work
/Hello/test/Step15_Random.py
731
3.609375
4
# -*- coding:utf-8 -*- ''' [random package 사용하기] ''' import random as ran ranNum=ran.random() # 0이상 1미만의 무작위 실수 ranNum2=int(ran.random()*10) # 0이상 10미만의 무작위 정수 ranNum3=int(ran.random()*10)+10 # 10이상 20미만의 무작위 정수 ranNum4=int(ran.random()*45)+1 # 1이상 45 미만의 무작위 정수 ranNum5=ran.randint(1, 45) #1 이상 45미만의 무작위 정...
a7b5bb2eb57175959b779fd773d76dd836d17060
autumnalkitty/python_work
/Hello/test/Step14_Math.py
419
3.640625
4
# -*- coding:utf-8 -*- ''' [math] ''' import math # 수학에 관련된 module 을 제공하는 package # 원의 면적 구하기 r=input(u"원의 반지름 입력: ") area=3.14*r*r area2=math.pi*r**2 area3=math.pi*math.pow(r, 2) print area, area2, area3 num=1234.5678 result1=math.floor(num) # 내림 result2=math.ceil(num) # 올림 result3=round(num) # 반올림...
128f6aab6b3962ccb3c473a778ffceee76d4913b
autumnalkitty/python_work
/Hello/test/Step05_Tuple.py
720
3.890625
4
# -*- coding:utf-8 -*- ''' [tuple type] 1. list type 의 read only 버전 2. 수정, 삭제 불가 3. list type 보다 빠른 처리 속도 ''' tuple1=(10, 20, 30, 40, 50) for tmp in tuple1: print "tmp:", tmp # tuple[0]=999 수정 불가 # del tuple1[0] 삭제 불가 # 방 1개짜리 tuple 만들 때 result=(1+1) #int type 2 result2=(1+1,) #tuple type ...
30fc0b6c790967d6c50233d894bae3a2a9f35bc6
odagora/variance-calculation
/reto-logico.py
505
3.75
4
def userInput(): n = int(input("Enter number of elements: ")) a = list(map(int,input("Enter the numbers in '' and space separated: ").strip().split()))[:n] return a def varianceCal(b): sum = 0.0 sumC = 0.0 i = 0 b = userInput() while i < len(b): sum += b[i] ...
11b6d2e56cbac88c5a017acfa1da0ed6af8a6804
gangaramana/leetcode-python
/problem_102.py
1,530
3.5625
4
from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: if(root is not None): result=[[]] if(root is not None): ...
03e34355098b0957cf5a19571bfc64e5a3cc209e
gangaramana/leetcode-python
/868_binary_gap.py
572
3.59375
4
from math import log class Solution: def binaryGap(self, N: int) -> int: li=[] x=N while(x>0): no=int(log(x,2)) li.append(no) x=x-2** no # if(x==0): # return 0 # else: # return no-int(log(x,2)) ...
b1e63d24b9773c87ed3efec0e7fc9cdf4fd32138
mehrzadch/RTP
/AlgoTrader/event.py
2,741
3.78125
4
# -*- coding: utf-8 -*- class Event: """ Event is base class providing an interface for all subsequent (inherited) events, that will trigger further events in the trading infrastructure. """ pass class MarketEvent(Event): """ Handles the event of receiving a new market update with ...
ad1166ee04f3c788817578e691826993e36d5486
sys3948/problem_solving_in_python
/same_number.py
957
3.65625
4
''' 앞 뒤가 같은 수 앞 뒤가 같은 수는 바로 쓴 값고 거꾸로 쓴 값이 같은 수이다. 다음과 같은 예를 들 수 있다. 입력 : 1 출력 : 0 입력 : 4 출력 : 3 입력 : 30 출력 : 202 ''' n = input('몇 번째의 같은 수를 찾으시겠습니까? > ') n = int(n) value = 0 count = 1 while True: check = True if len(str(value)) > 1: if str(value)[0] == str(value)[-1]: ...
f2158950b866d2f4fe0c0d40103b57c6572dc6f9
sys3948/problem_solving_in_python
/threetimessum.py
531
3.546875
4
''' 디지털 시계에 하루동안(00:00~23:59) 3이 표시되는 시간을 초로 환산하면 총 몇 초(second) 일까요? 디지털 시계는 하루동안 다음과 같이 시:분(00:00~23:59)으로 표시됩니다. 00:00 (60초간 표시됨) 00:01 00:02 ... 23:59 00:00 ~ 23:59까지의 3이라고 입력된 시간의 유지시간(60초)의 총 합을 구하시오. ''' total_sec = 0 for i in range(24): for j in range(60): if "3" in str(i) or "3" in str(j): ...
6e5f418420de0efa2d0d9a05cf12b1a9e87a7bfa
asegura4488/Cplusplus
/Applications/Kepler/plot.py
387
3.671875
4
import numpy as np import matplotlib.pyplot as plt data = np.loadtxt('datos.dat') x = 2*data[:,1] y = 2*data[:,5]#/3600. #print(x,y/3600.) from sklearn.linear_model import LinearRegression regresion_lineal = LinearRegression() regresion_lineal.fit(x.reshape(-1,1), y) print(regresion_lineal.coef_*100.*3600.) # ...
a746a97ae7250749238526c552ba896cf5a122f5
weijiang1994/Learning-note-of-Fluent-Python
/character02/11生成井字板.py
342
3.890625
4
""" @Time : 2020/6/12 16:50 @Author : weijiang @Site : @File : 11生成井字板.py @Software: PyCharm """ # 采用列表推导生成正确的井字板 board = [['_']*3 for i in range(3)] print(board) board[1][2] = 'X' print(board) # 采用*生成错误的井字板 board = [['_']*3]*3 print(board) board[1][2] = 'X' print(board)
e991e53d24b80d8d91fabdf7696faefcfa3a61d3
weijiang1994/Learning-note-of-Fluent-Python
/character01/sample1-2.py
872
4.28125
4
""" @Time : 2020/6/11 9:59 @Author : weijiang @Site : @File : sample1-2.py @Software: PyCharm """ from math import hypot class Vector: def __init__(self, x=0, y=0): self.x = x self.y = y # print类实例不在以<class object --- at --->的形式输出,而已字符串进行输出,称作为'字符串表示形式' def __repr__(self): ...
9c7d0650c6067047b2a8a2b29cc6a416d471d9a3
weijiang1994/Learning-note-of-Fluent-Python
/character05/1.高阶函数示例.py
338
4.03125
4
""" # coding:utf-8 @Time : 2020/8/18 @Author : jiangwei @mail : jiangwei1@kylinos.cn @File : 1.高阶函数示例 @Software: PyCharm """ fruits = ['strawberry', 'fig', 'apple', 'cherry', 'raspberry', 'banana'] res = sorted(fruits, key=len) print(res) def reverse(word): return word[::-1] res = sorted(fruits, key=r...
b5fdf0bc89390f586effabb317d9e3c6b236df93
goelpriyanshu99/Hacktoberfest20
/liststack.py
654
3.921875
4
class Stack: def __init__(self): self.list_items = list() self.length = 0 def push(self,d): print(str(d)+" is pushed.") self.list_items.append(d) self.length+=1 def pop(self): if self.length<1: return None k = self.list_items.pop() ...
7bc42ee43b4e31b257cb2527e00d019d91c3665d
HernanFranco96/Python
/Curso de Python/Intro-python/Python/13_Objetos.py
451
3.640625
4
class Usuario: # El primer argumento, hace referencia a la instancia. def __init__(self, nombre, apellido): self.nombre = nombre self.apellido = apellido def saludo(self): print('Hola, mi nombre es ',self.nombre, self.apellido) usuario = Usuario('Hernan','Franco') usuario.saludo() usuario....
62b0c62e5d1f93a770ffc64b37b522b41c979b4b
HernanFranco96/Python
/Curso de Python/Intro-python/Python/7_controlflujo.py
941
4.3125
4
#if 2 < 5: # print('2 es menor a 5') # a == b # a < b # a > b # a != b # a >= b # a <= b #if 2 == 2: # print('2 es igual a 2') #if(2 > 1): # print('2 es mayor a 1') #if(2 < 1): # print('1 no es mayor a 2') #if(2 != 3): # print('2 es distinto que 3') #f(3 >= 2): # print('3 es mayor o igual a 2') #i...
3eaac78ad1200d0c7b3c7ca3de33732553fcca9e
eafox/ldProject_Code
/SandBox/Curve_Fitting/05_lmfitFreehand_Gamma.py
1,306
3.546875
4
#!/usr/bin/python """Practicing minimize from lmfit with a gamma function. Modelled after 03_lmfitFreehand_Exponential Decay, http://www.intmath.com/blog/mathematics/factorials-and-the-gamma-function-4350, and https://en.wikipedia.org/wiki/Gamma_distribution""" ___author__ = "Emma Fox (e.fox16@imperial.ac.uk)" __vers...
aa0d7c5af5fb12475f991079378d7c71f11f81c4
j94wittwer/Assessment
/Informatik/E7/task_2.py
6,764
3.5625
4
import random # ========= Your classes ========== class Settings: def __init__(self, shuffle, repeat): self.shuffle = shuffle self.repeat = repeat class Song: def __init__(self, title, artist, duration): self.title = title self.artist = artist self.duration = durati...
0e683de62caac0fb76b798be744fb31d2ac1512b
j94wittwer/Assessment
/Informatik/E4/task_3.py
1,104
3.9375
4
# Please do not modify this part of the code! def tokenize(text): return text.split() # ======== You can define the search_text function here. Do not write any code other than your solution here! ========== def search_text(filename, query): content = "" num_of_occurences = 0 with open(filename, 'r') a...
c3e7978d6873c8c8bf1b44b5ef1bec9cd20cbddd
j94wittwer/Assessment
/Informatik/Algo/turtle_random_movement.py
702
3.625
4
import random import time import turtle def roll_dices(): dice_one = random.randint(1, 6) dice_two = random.randint(1, 6) return dice_one + dice_two def createTurtle(): kröte = turtle.Turtle() kröte.penup() kröte.shape("turtle") return kröte if __name__ == "__main__": x_index = -7...
f52568ec7ea273dbb1f45b4415ce35f462783ef1
j94wittwer/Assessment
/Informatik/E3/task_4.py
460
4.1875
4
is_prime = False n = int(input("Please enter a number, to check if it's prime: ")) factors = [1] if n <= 1: is_prime = False elif n == 2: is_prime = True elif n % 2 == 0: is_prime = False else: for i in range(2, n): if n % i == 0: factors.append(i) if len(factors) > 2: ...
ef70270ce45521d46f3cd4c362cb461280421c4f
shobhit-nigam/onsemi_one
/day1/data_structs/6.py
543
3.609375
4
# lists # mutable # deleting functions num_a = [8, 9, 3, 4, 6, 10, 20] num_b = [33.4, 77.8, 99.0, 12.3] south_america = ['lima', 'bogota', 'brasillia', 'buenos aires', 'santiago', 'caracas'] lista = [23, 88.9, 'hello', 'hi', 10] listb = [22, 'tt', lista, 'yy'] print(south_america) print("-----") south_america.remove...
54ecab2a1ba5e638b14ab8260bcec2e540a606bb
shobhit-nigam/onsemi_one
/day2/data_structs_2/13.py
399
3.765625
4
# sets # operations fruits = {'apples', 'oranges', 'straberries', 'apples', 'bananas', 'oranges', 'watermelons'} basket = {'mangoes', 'avocados', 'apples', 'bananas', 'tomatoes', 'plums'} print("fruits =", fruits) print("basket =", basket) print("union =", fruits | basket) print("intersection =", fruits & basket) pri...
96f27ed1c0c8caf766c94e9dd77b9890c248677b
shobhit-nigam/onsemi_one
/day1/strings/11.py
210
3.578125
4
# replace # functions company = "onsemi" place = 'manila' team = "philadelphia 76ers" spot = "san agustin church" print("spot =", spot) print(spot.replace("san agustin", "quiapo")) print("spot =", spot)
472b0a4790fcb16b9b70be11e4c549617a119287
shobhit-nigam/onsemi_one
/day5/exception_handling/5.py
475
3.5
4
# try except # multiple except blocks # fails if we enter a string # generic except block (catch all) # name error varx = 10 vary = 5 varz = 20 lista = [37, 28, 11, 13, 55, 16] try: vara = varx/varz print(vara) i = int(input("enter the index:\n")) print(listb[i]) except ZeroDivisionError: print(...