blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
43291a5fd5027815ebff5fa8d4474c8624329f78
LEE2020/leetcode
/coding_100/1094_carpooling.py
1,952
3.8125
4
''' 假设你是一位顺风车司机,车上最初有 capacity 个空座位可以用来载客。由于道路的限制,车 只能 向一个方向行驶(也就是说,不允许掉头或改变方向,你可以将其想象为一个向量)。 这儿有一份乘客行程计划表 trips[][],其中 trips[i] = [num_passengers, start_location, end_location] 包含了第 i 组乘客的行程信息: 必须接送的乘客数量; 乘客的上车地点; 以及乘客的下车地点。 这些给出的地点位置是从你的 初始 出发位置向前行驶到这些地点所需的距离(它们一定在你的行驶方向上)。 请你根据给出的行程计划表和车子的座位数,来判断你的车是否可以顺利完成接送所有乘客...
3c32ffa6b592dfedadb79d1157bb019e9a3ef6d9
unc0mm0n/pygame-tetris
/piece.py
4,344
3.671875
4
from utils import * from random import * UP = Vector((0, -1)) DOWN = Vector((0, 1)) LEFT = Vector((-1, 0)) RIGHT = Vector((1, 0)) class Block(object): ''' A representation of a block. Holds xy coordinates and color Supports move operation with Vector ''' def __init__(self, pos, color): self.po...
f606f1854a7969ed7ab6d2f1c365c95c9eac7d17
marcelus20/Blockchain_in_Python
/main.py
6,887
3.640625
4
""" AUTHOR: FELIPE MANTOVANI DATE: 23/5/2018 PROJECT: RUDMENTARY BLOCKCHAIN IN PYTHON """ #importation of the library import hashlib import datetime import json from typing import Any """ this function will encrypt all the arguments passed and return an a hashing of all of the parameters converted into strings and ...
16ceec7caa13b34d9c72fdbe8f97676443e47fe5
aernesto24/Python-el-practices
/Basic/Python-university/OOP/volume-calculation.py
564
4.21875
4
print("***THIS PROGRAM CALCULATE THE VOLUME OF A BOX***") print("") class VolumeCalc: def __init__(self, base, height, depth): self.base = base self.height = height self.depth = depth def volume_calculation(self): return self.base * self.height * self.depth b = i...
c2d6ffa2f3d4618e40acda7181e04a21a703f595
Zahrou/EDX
/polysum.py
403
3.703125
4
import math def polysum(n, s): """ Takes 2 arguments (number of sides 'n' and side length 's') Returns the sum of area and perimeter squared of the polygon rounded to 4 decimals """ area = (0.25*n*(s*s))/(math.tan(math.pi/n)) perimeter = n*s summation = area + perimeter**...
92c2ed8075bf7745a71ea709015d1cfd223fd9f3
amrithajayadev/misc
/palindrome_pairs.py
708
3.828125
4
# https://leetcode.com/problems/palindrome-pairs/ def check_palindrome(word): i = 0 j = len(word) - 1 while i <= j: if word[i] != word[j]: return False else: i += 1 j -= 1 return True def find_palindrome_pairs(words): n = len(words) pairs = []...
07221124b86c99de8f61d05a85cadc088e8d7563
ania4data/DSND1
/OOP_Udacity/rename_files.py
616
3.890625
4
import os def rename_files(): files=os.listdir("prank/") print(files) print(type(files)) not_to_have="0123456789" dir_="prank/" where_=os.getcwd() print(where_) for i in range(len(files)): #os.chdir("file_path") x=drop_the_letter(files[i],not_to_have) #instead can use translate ...
d1e7e8c629acd0434de2bd2d78a41c238c969b3e
dezgeg/Python-Regex
/ListTest.py
567
3.625
4
from List import * import unittest class ListTest(unittest.TestCase): def setUp(self): self.list = List() def testInsert(self): self.list.insert(42) self.list.insert(1337) self.assertEquals(list(self.list), [1337, 42]) def test__iadd__(self): self.list.insert(2) self.list.insert(1) list2 = List() l...
ca91293fb9d9629b8e2a32bcf91496ae65916344
JiangYuzhu/LearnPython
/python-qiyue/ten-re/c6.py
576
3.734375
4
# 边界匹配符(完整地匹配字符串) # ^ 开始 # $ 末尾 import re qq = '1000001' #7位 r = re.findall('\d{4,8}',qq) #易犯错误:{4,8}写成{4-8}、[4,8]、[4-8] print(r) r = re.findall('^\d{4,8}$',qq) #开始到结束至少4个数字最多8个数字 print(r) qq = '101' r = re.findall('\d{4,8}',qq) print(r) r = re.findall('^\d{4,8}$',qq) print(r) qq = '100000001' #9位 r = re.finda...
400f4ae08766fa3f1ece6210b410f4077b3926e6
vsriram1987/python-training
/src/blackjack.py
4,652
3.515625
4
''' Created on 19-May-2019 @author: vsrir ''' from deckofcards import Deck, Card, EmptyDeck import time class NoBalance(Exception): pass class Participant: def __init__(self, playertype, chips): self.playertype = playertype self.chips = chips self.cards = [] se...
c1512632e7492ac000de288e73d64a81ea1e4834
jrmullen/algo-study
/src/leetcode/stack/20.py
574
3.625
4
class Solution: def isValid(self, s: str) -> bool: stack = [] map = {')': '(', ']': '[', '}': '{', } for char in s: # If the map does not contain our character, we know it is an opening character if map.get(char) is None: stack.append(char) ...
22569d2f6e4225c3a760fbe5e284b283a63faca6
biogui/exercicios-criptografia-rsa
/capitulo_10/exercicio_10/main.py
1,142
4
4
''' Números Inteiros e Criptografia RSA - Capítulo 10. Exercício 10 - Teste de Pepin. ''' import datetime F = lambda k: 2**(2**k) + 1 def pot_mod(a, k, n): modulo = 1 while k != 0: if k % 2 == 1: modulo = (a * modulo) % n k = (k - 1) // 2 else: k = (k - 1)...
4e22233a3efd7d8bc9abf882af74add74f56ac55
GlaucoPhd/Python_Zero2Master
/Argsand__kwargs86.py
456
3.640625
4
# args ##kwargs # Accept any numbers of characters is necessary # Python Community Uses *args and **Kwargs def super_func(*args): print(args) return sum(args) # Rule of parameters: (params, **args, default parameters, **kwargs) # Rule(name, *arg, i'', **kwargs) def super_func_sum(*args, **kwargs): total = ...
0f4c6db0155e0d20ab09c351feaff1f023651c87
SilversRL-Yuan/CC150_Python
/Chapter1/1.7.py
608
4.1875
4
#1.7 Write an algorithm such that if an element in an M*N matrix is 0, its entire row and column are set to 0. def setzero(matrix): #row,column row = [False for i in range(len(matrix))] column = [False for j in range(len(matrix[0]))] #find 0 positions for i in range(0,len(matrix)): for j in range(0,len(matrix[0]...
a7b32c283aad08e10fb8f2de5a015d8726e98f17
Dwyanepeng/leetcode
/maxArea.py
1,182
3.84375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # File : maxArea.py # Author: PengLei # Date : 2019/4/2 '''给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条 垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共 同构成的容器可以容纳最多的水。 说明:你不能倾斜容器,且 n 的值至少为 2。''' class Solution: # 暴力解法 def maxArea(height): ...
42e0ee2ee493ebde7c93afaf2deefaac986dbdec
tinkle1129/Leetcode_Solution
/DynamicProgramming/97. Interleaving String.py
1,233
3.703125
4
# - * - coding:utf8 - * - - ########################################### # Author: Tinkle # E-mail: shutingnjupt@gmail.com # Name: Interleaving String.py # Creation Time: 2017/7/29 ########################################### ''' Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. For example, ...
740de558a3162d9894865b2d6bacebf4bd0052a4
boelterr/infosatc-lp-avaliativo-01
/exercicio27.py
279
3.6875
4
#Gabriel Custodio Boelter 2190 h = float(input("Digite um valor em hectares: "))#Entrada da variavel h pedindo para lhe dar um valor m = (h*10000)#Entrada da variavel m com sua equação correspondente print("O valor da conversão para m² é {}" .format(m))#Print na tela mostrando o resultado
17e721f06eef7d5109acf3a9961ca17059dab11b
Jadams29/Coding_Problems
/String Functions/Caesar_Cipher.py
2,487
4.09375
4
# -*- coding: utf-8 -*- """ Created on Sun Jun 24 16:36:04 2018 @author: joshu """ # A - Z -> 65 - 90 # a - z -> 97 - 122 # ord(yourletter) # chr(your_code) # Receive the message to encrypt and the shift amount def caesar_cipher(): message = input("Enter the message you want to be encrypted: ") shift_amoun...
96a329ea2e0b525e3581773fcf74a4f2a0fae279
harshadrai/Data-Mining
/Document_Similarity_tf_idf/DocumentSimilarity.py
7,961
4.09375
4
import sys essay = open(sys.argv[1], 'r') #open the file as a read only file under variable name essay essayread = essay.readlines() #convert essay into a list under variable name essayread #essayread[:] #check out what essayre...
ac5f33601f459f1442f7588359f1a801abee7be4
rrkas/Exercism-Python
/62_matching-brackets/matching_brackets.py
419
3.8125
4
def is_paired(input_string) -> bool: s = [] opening = ('(', '{', '[') closing = (')', '}', ']') for i in input_string: try: if i in opening: s.append(i) elif i in closing: if s.pop() != opening[closing.index(i)]: return ...
b357b806f7a9fc3168d002f6d25eb930273c5983
AndersonChristian-P/practical_python
/Flow_Control/if_elif_example.py
385
4.125
4
name = "Bob" age = 3000 if name == "Alice": print("Hi Alice!") elif age < 12: print("You are not Alice, kiddo.") elif age > 2000: print("Unlike you, Alice is not an undead, immortal vampire.") elif age > 100: print("You are not Alice, grannie.") # You can have as many elif statements as you want | when...
9ec5590df8ac55a4feb6332a573c16b343cc9a42
jgarciagarrido/Tuenti-Challenge-6
/challenge_7/tiles.py
661
3.515625
4
def generate_translation(): uppercases = [(chr(letter), letter-ord("A")+1) for letter in xrange(ord('A'), ord('Z')+1)] lowercases = [(chr(letter), -(letter-ord("a")+1)) for letter in xrange(ord('a'), ord('z')+1)] point = [('.',0)] return dict(uppercases+lowercases+point) def read_tile(): translatio...
29df63bb545c688834de7da2d4dcc413ce80a841
oo363636/test
/Leetcode/LC198.py
1,338
3.71875
4
""" 你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金, 影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入, 系统会自动报警。 给定一个代表每个房屋存放金额的非负整数数组,计算你 不触动警报装置的情况下 ,一夜之内能够偷窃到的最高金额 """ class Solution: def rob(self, nums: [int]) -> int: # 动态规划,两个选择,要么偷,要么不偷 # 偷的话,i-1不能偷,所以是i-2的state加上当前的金额 # 不偷的话,就等于i-1的state ...
2bececce907265c24e6df3a53464010f8e8aa280
apiavis/Ashford-University-CST
/Ashford University-CPT200/CPT200_Wk3Assignment.py
4,767
4.28125
4
## Author: Alicia Piavis ## Title: Employee Management System Functionality 3 ## Course: CPT 200 Fundamentals of Programming Languages ## Instructor: Amjad Alkilani ## Date: 7/22/2018 print('WELCOME TO YOUR EMPLOYEE MANAGEMENT SYSTEM') ## sets run_again variable to 'yes' to initiate loop that asks the user which fun...
b85d91904aa10b5910769ac14ab5db829199a39d
Anchal-Mittal/Machine_Learning_Tensor_Flow_With_Python
/linearAlgebra/tensor2.py
1,028
3.609375
4
# tensor algebra def fun(): from numpy import array A= array([ [[1,2,3],[4,5,6],[7,8,9]], [[11,12,13],[24,15,16],[17,18,19]], [[20,21,22],[23,24,25],[26,27,28]], ]) B= array([ [[12,23,35],[74,85,96],[73,85,93]], [[11,72,83],[22,45,36],[17,18,19]], [[90...
87871a05b91e6d3a372c96616db6ad095290bbac
snehabal1/python-projects
/shapes.py
606
4.25
4
# # Draw shapes and learn about classes # import turtle def draw_square(someturtle): for i in range (1,5): someturtle.forward(100) someturtle.right(90) def draw_art(): wn = turtle.Screen() wn.bgcolor("red") #Create a turtle where square is drawn sqr = turtle....
e8e8b2d8d10c48a1cd507edbfe1bd9d9f5083f68
i4leader/Python-Basic-Pratice-100-questions
/code/012.py
293
3.75
4
#!/usr/bin/python3 import math count = 0 leap = 1 for i in range(101,201): k = int(math.sqrt(i+1)) for j in range(2,k+1): if i%j == 0: leap = 0 break if leap == 1: print(i) count += 1 leap = 1 print("素数总计数:%d"%count)
cf1005671068a9727e275f1ba2c9eda70a8cf24d
mpanczyk/SelfStabSimulator
/utils.py
1,428
3.8125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import random import copy def random_pick(sequence): '''Choose one rule amongst the active ones. ''' return random.choice(sequence) def updated_dict(d, *args): '''Return copy of a nested dictionary d with keys args[:-1] updated with value args[-1]. For examp...
b3861ae945176e8b0b7165793a5927b4a7d05e32
cwdbutler/python-practice
/Problems/even sides of an array.py
576
4.0625
4
def find_even_index(arr): # find the point where there is an equal sum to the left and to the right for i in range(len(arr)): # i will be the index of our value where this is true if sum(arr[:i]) == sum(arr[i+1:]): # excluding i, check the sum to the left (lower index) and right (higher index) ...
c34ebf2b8b0258c0e9b0b67ba267fd6e5feec3c1
jefferytsummers/Optics_Ray_Tracer
/v_1/raydiagram.py
4,149
3.734375
4
from math import tan, pi from tkinter import * from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg from matplotlib.figure import Figure from matplotlib import * use("TkAgg") class RayDiagram(Frame): """ This class creates the actual ray diagram graph in a tkinter frame ...
3dd5d81afc9575f947d478224335f76972421089
amitpnpatel/SlamSimulation
/simulator/keyboard.py
167
3.609375
4
import sys def keyboard(key, x, y): # Allows us to quit by pressing 'Esc' or 'q' if key == chr(27): sys.exit() if key == "q": sys.exit()
6c40426b10c3b3dfb3ee1eb2889148d3e997ab79
AlexBlokhin1/mytests
/file_reader3.py
1,757
3.984375
4
#!/usr/bin/env python import re import json import argparse from pprint import pprint """ AARON Jewish, English From the given name AARON. ABBEY English Indicated a person who lived near an abbey or worked in an abbey, from Middle English abbeye. ABBOTT English """ # "Aaron ['Jewish', 'English'] exampl...
3b8fb7d7cd680d9de85f64233afc1032c0f9f5c2
weekswm/cs162p_week7_lab7
/Instructor.py
729
3.671875
4
#Instructor class from Person import Person class Instructor(Person): '''Creates an Instructor class derived from Person class attributes: officeHours ''' #initializes Instructor person object with office hours def __init__(self, firstName, lastName, age, lNumber, officeHours = ''): super()...
db133eea811e2e8bb7834986d7d8160371c5c4af
lucas234/leetcode-checkio
/LeetCode/69.Sqrt(x).py
732
3.71875
4
# @Time : 2021/7/27 9:39 # @Author : lucas # @File : 69.Sqrt(x).py # @Project : locust demo # @Software: PyCharm def my_sqrt(x: int) -> int: if x == 1: return 1 for i in range(int(x / 2) + 1): if i * i == x: return i if i * i > x: return i - 1 return i prin...
61ebc88c2112588ee84a586dec72e90278cbe206
prateksha/Source-Code-Similarity-Measurement
/Datasets/python-loops/Correct/042.py
109
3.859375
4
# Enter your code here. Read input from STDIN. Print output to STDOUT for i in range(input()):print(pow(i,2))
8b33951b786453eadae112e90ca4a4da62dce11d
12reach/PlayWithPython
/classes/decorators.py
822
3.984375
4
#!/usr/bin/python3 class Dog: name = None def __init__(self, **kwargs): self.properties = kwargs def get_properties(self): return self.properties def set_properties(self, key): self.properties.get(key, None) @property def Color(self): return self.properties...
01b1e8975563cc521d49fba35775df516164c401
HappyAnony/studynotes-of-python
/Control/generator.py
2,782
3.953125
4
#!/usr/bin/env python # -*-coding :uft-8 -*- # Author:Anony ''' 生成器一 g = ( i*2 for i in range(10) ) print(g) print(g.__next__()) # 依次取一个元素 print(g.__next__()) # python2中是next() print(g.__next__()) for i in g: # 循环取元素 print(i) print(g.__next__()) # 当生成器的元素取完后,会置空,此时无法访问生成器;此时访问会报StopIt...
2a24bfd94733627da99f1f79412cf1d392b26336
rafalacerda1530/Python
/atividades/Seção 13/atividade 2.py
654
3.890625
4
""" Receba um texto e mostre quantas letras são vogais """ with open('arq2.txt', 'w') as arquivo: text = input("digite seu texto: ") resul = 0 for letra in text: if letra == 'a': resul = resul +1 elif letra == 'e': resul = resul + 1 elif letra == 'i': ...
3e797c70e628c50c182063b617373ca01b24267c
jordanchenml/leetcode_python
/0077_Combinations.py
721
3.953125
4
''' Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. Example: Input: n = 4, k = 2 Output: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ] ''' from typing import List class Solution: def combine(self, n: int, k: int) -> List[List[int]]: res = [] ...
48936067c30657c77ac3f97333309f3e4cd940d2
fwangboulder/DataStructureAndAlgorithms
/#97InterleavingString.py
1,329
3.59375
4
""" 97. Interleaving String Add to List Description Submission Solutions Total Accepted: 64775 Total Submissions: 268978 Difficulty: Hard Contributors: Admin Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. For example, Given: s1 = "aabcc", s2 = "dbbca", When s3 = "aadbbcbcac", return t...
c37b1ccb879312047fde12b9add1aafdf617bfc0
Giovannisb/snake
/snake.py
3,602
3.625
4
import pygame, random from pygame.locals import * #função para gerar a posição da maçã nas posições corretas do grid def on_grid_random(): x = random.randint(0,590) y = random.randint(0,590) return (x // 10 * 10, y // 10 * 10) #função para detectar a colisão entre a cobra e a maça def collision(c1, c2): ...
18671dbc38ce11fe3d48093dbf753a4d57f5567d
rubivenkatesan/kanimozhi
/prog4.py
170
4.28125
4
k=str(raw_input("enter any character")) print k if(k>='a' and k<='z')or(k>='A' and k<='Z'): print("the letter is alphabet") else: print("the letter is not a alphabet")
597c2cd88170636ea6a2970386e1cfcd52df1f0f
sairajbhise98/Python-Study
/Data Structures in Python/Searching and Sorting Algorithmsn/optimisedbubblesort.py
987
4.25
4
''' ------------------------------------------------------------- Code By : Sairaj Bhise Topic : Data Structures and Algorithms (Optimised Bubble Sort Algorithm) ------------------------------------------------------------- ''' def bubble_sort(array) : ''' Algo : swapped = false for i <- 0 to indexOfLastEle...
9cda78d105193a8a51cb4a869c41dfd69108342c
kvntma/coding-practice
/codecadamy/Towers_of_Hanoi/tower_of_hanoi.py
3,014
4.09375
4
from stack import Stack print("\nLet's play Towers of Hanoi!!") # Create the Stacks - Global Scope, can be changed to reduce pollution if needed. left_stack, middle_stack, right_stack = Stack( "Left"), Stack("Middle"), Stack("Right") stacks = [left_stack, middle_stack, right_stack] # Set up the Game def initi...
32a3daf6ff1c4216cf2628f90c4fa455c019eab7
dahjinkim/python_summer2020
/HW/hw3.py
5,721
3.625
4
""" Class: Python 2020 Homework Assignment 3 Author: Jin Kim """ # import necessary packages import importlib import sys import tweepy # set directory and get API key sys.path.insert(0, '/Users/jinki/Documents/API keys') twitter = importlib.import_module('start_twitter') api = twitter.client # get wustl user info wu...
d363ba1c82892af81f6684eafe1619cde6c99f33
arty-hlr/CTF-writeups
/2018/XMAS/ultimate_game/nim_sum.py
713
3.609375
4
heaps = [] for i in range(15): print("Enter heap {}: ".format(i)) heaps.append(int(input())) while(True): xored = 0 for i in range(15): xored ^= heaps[i] print(heaps) print(xored) min = 15 for i in range(15): newXored = xored^heaps[i] if (newXored < heaps[i]): ...
0e5deb695424d172216e9221bb8cff65cdc5ae06
brianchiang-tw/leetcode
/2020_September_Leetcode_30_days_challenge/Week_3_Length of Last Word/by_token_parsing.py
1,302
3.953125
4
''' Description: Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string. If the last word does not exist, return 0. Note: A word is defined as a maximal substring con...
48c4135534c0b85116c8a2e276cc9c5ad4794389
JonathanCSantos098/programacao-orientada-a-objetos
/listas/lista-de-exercicio-03/questao02.py
115
4.03125
4
num=float(input("Informe um valor: ")) if (num>0): print("Valor Positivo!") else: print("Valor Negativo!")
17a1363c3c98f062aea5a7848fd9b44a65505cb0
aggiebck/Py
/Python/Lab4 Programs/q2.py
399
3.890625
4
s = int(input("Starting Year: ")) e = int(input("Ending Year: ")) print() while True: if s > e: print( s, "is >", e, "the starting year must be larger than the ending year, please try again") break if s <= e: print("Leap Years Between", s, "and", e) while s <= e: if s%4==0 and s%100!...
dc110cd1e8d97f50f212164d4bb17c3696539321
mayankkejriwal/GNOME-p3
/monopoly_simulator/card.py
7,336
4.0625
4
class Card(object): def __init__(self, action, card_type, name): """ :param action: A function from card_utility_actions, with the same name as specified in the game schema. Note that all such functions will have the same signature (player, card, current_gameboard). For details on these, se...
e9bb04213cf97c6ad1588c58964f629020be588f
amirkashi/AmirInsightProject
/src/readNoaaClimateDataToSparkToS3.py
3,943
3.6875
4
""" This code is responsible to get climate daily data from s3 year by year. Find data that belong to stations in lower 48 states of the US. Save them as csv format in s3. """ import sys from pyspark.sql.functions import dayofmonth, hour, dayofyear, month, year from pyspark.sql import SQLContext from pyspark import...
c853a7c6e6cb62601ad30586d9ec99f8ad898ad2
angelotc/pythonprojects
/project-2-notes/echoclient.py
2,699
3.890625
4
#echo client import socket # USER INTERFACE #functions to solve parts of the problem def read_host()->str: while True: host = input('Host: ').strip() if host == '': print('That is not valid; please try again') else: return host #keep asking until legit...
b7dd7f0f157f537e61ee9bc75e0bbd2df2f23258
Sahale/algo_and_structures_python
/Lesson_6/1.py
2,235
3.75
4
""" 1. Подсчитать, сколько было выделено памяти под переменные в ранее разработанных программах в рамках первых трех уроков. Проанализировать результат и определить программы с наиболее эффективным использованием памяти. Примечание: Для анализа возьмите любые 1-3 ваших программы или несколько вариантов кода для одной и...
1129b8d082729b07c498a7ecfb54a3333ca7727d
LongylG/python-try
/base/operator.py
635
3.625
4
a = 1 b = 4 ''' 太久没用容易混淆,mark一下 运算规则 按位或 1|1=1; 1|0=1; 0|1=1; 0|0=0 按位异或 0^0=0; 0^1=1; 1^0=1; 1^1=0; 取反 ~1=0; ~0=1; 按位与 0&0=0; 0&1=0; 1&0=0; 1&1=1; ''' #算数运算符 print(a + b) print(a - b) print(a * b) print(a / b) print(a % b) print(a // b) # 整除 #逻辑运算符 print(~-1) # 按位取反 ~x=-(x+1) print(a ^ b) # 按位异或 print(a | ...
1144ce993a927a6c7f34711c811e230fe2d6b83e
stuart727/edx
/edx600x/L11_OOP/L11_P5_hashSet.py
2,619
4.03125
4
class hashSet(object): def __init__(self, numBuckets): ''' numBuckets: int. The number of buckets this hash set will have. Raises ValueError if this value is not an integer, or if it is not greater than zero. Sets up an empty hash set with numBuckets number of buckets. ...
d5fc00e91bd5052a3cc977337218b65fd35d64ac
awsserver/awsserver
/python/production.py
1,323
3.890625
4
#!/usr/bin/python from sys import exit def prod_act(): print "There is production activity this weekend.Are you ready?" choice = raw_input("> ") if "saturday" in choice or "sunday" in choice: weekend = str(choice) else: dead ("There is no production activity this weekend.") if ...
b53a9355177c4f4ebd63ebc772eb6e39f1e1cc02
stag152766/gb_ik_python
/Lesson6/task_4.py
1,347
3.59375
4
import sys print(sys.version, sys.platform) a = 5 b = 125.54 c = 'Hello World!' print(sys.getsizeof(a)) print(sys.getsizeof(b)) print(sys.getsizeof(c)) lst = [i for i in range(10)] print(sys.getsizeof(lst)) def show_size(x, level = 0): print('\t' * level, f'type={x.__class__}, size={sys.getsizeof(x)}, object={...
f62f167f8dda49d635a3a556987a3bf8516920b8
Lamiel01/Competitive-Programming
/Codewars/FindTheParity.py
464
3.9375
4
def find_outlier(integers): odd = [] even = [] for i in range(len(integers)): if integers[i] % 2 == 0: odd.append(integers[i]) else: even.append(integers[i]) if len(odd) > 1: return even[0] else: return odd[0] # Other solution def find_out...
8b71a618222c5e1511df1e04c5fde8aaaf290be4
devaljain1998/dsaPractice
/Competitions/Mockvita/petrol_pump.py
2,436
4.03125
4
"""Question: Petrol Pump - Mockvita A big group of students, starting a long journey on different set of vehicles need to fill petrol in their vehicles. As group leader you are required to minimize the time they spend at the petrol pump to start the journey at the earliest. You will be given the quantity of petrol (in...
a75c1456acbba0bf9669d9c0f2efb278b71e547e
Brian-Musembi/ICS3U-Unit5-04-Python
/volume.py
1,479
4.34375
4
#!/usr/bin/env python3 # Created by Brian Musembi # Created on May 2021 # This program calculates the volume of a cylinder import math def cylinder_volume(radius, height): # This function calculates the volume of a cylinder # process volume = math.pi * (radius * radius) * height return volume de...
9996962975be0c0cf970627ced187354717e6a3a
angelusualle/algorithms
/cracking_the_coding_interview_qs/10.2/group_anagrams.py
425
3.875
4
# O(nslog(s)) where n is number of words and s is length of string def group_anagrams(arr): buckets = {} for word in arr: sorted_word = ''.join(sorted(word)) if sorted_word in buckets: buckets[sorted_word].append(word) else: buckets[sorted_word] = [word] ans =...
8c9cbd117be714b3dc89a01d3a1142afb06f8927
TaySabrina/python-practice
/ex081.py
501
3.859375
4
lista = [] i = 0 v = 5 while True: resp = ' ' lista.append(int(input('Digite um valor: '))) i += 1 while resp not in 'SN': resp = str(input('Quer continuar? [S/N] ')).strip().upper()[0] if resp == 'N': break print('-=' * 30) print(f'Você digitou {i} elementos.') lista.sort(reverse=Tr...
1d151db154f105fa736db04c20e8a4235cfa4e0d
csagar131/Data_Structures_And_Algo
/Math/primeFactorOptimal.py
286
3.734375
4
import math n = int(input("Enter N:")) for i in range(2,int(math.sqrt(n))): if n % i == 0: c = 0 while n % i == 0: n = n // i c+=1 print(int(math.pow(i,c))) print(i,c) if n != 1: print(math.pow(n,1)) print(n,1)
b1e99ef961ce44543bb4dcdf850011ceaf60e1a8
adrian273/tkinter_examples
/Examples/t03_position.py
840
4.1875
4
from tkinter import * root = Tk() root.title('t03_posicionamiento') ''' para dar el ancho y alto a la ventana ''' root.geometry("400x200") ''' @ se utiliza grid para pocicionar grid(row = fila, column = columna ) esta es una forma para aserlo como tabla ejemplo -> etiqueta2 = Label(root, text = '...
76002840d5cd5f2dad0ee910b79bdbfa31f121d6
AidenMarko/CP1404Practicals
/prac_05/word_ occurrences.py
479
4
4
""" CP1404/CP5632 Practical Do-from-scratch - Word Occurrences """ words = input("Input a phrase: ") words = words.split(" ") words.sort() word_to_count = {} for word in words: if word in word_to_count: word_to_count[word] += 1 else: word_to_count[word] = 1 max_length = 0 for word in words: ...
6900e51d0689c6d8d807ec17af4167768068dd7a
wparedesgt/Master-Python
/02-Variables-Tipos/variables.py
808
4.125
4
""" Una variable es un contenedor de información que dentro guardará un dato, se pueden crear muchas variables y que cada una tenga un dato distinto. """ #Crear Variables y Asignarles un valor texto = "Master en Python" texto2 = "De prueba" numero = 45 decimal = 6.7 print(texto) print(texto2) print(numero) print(d...
b0a9ddb3f4b6a383a29d96d4ac3acefd89211216
devanshkaria88/Python_Playground
/Compititve Questions/Level 1/The museum of incredible dull things.py
2,151
4.3125
4
""" The museum of incredible dull things wants to get rid of some exhibitions. Miriam, the interior architect, comes up with a plan to remove the most boring exhibitions. She gives them a rating, and then removes the one with the lowest rating. However, just as she finished rating all exhibitions, she's off to an impo...
2d02399a937b00e3aaee72afc7b8f51891e7c147
Coohx/python_work
/python_base/python_list&tuple/list_slab.py
1,467
4.09375
4
# -*- coding: utf-8 -*- # 列表部分元素——切片 players = ['a', 'b', 'c', 'd', 'e'] # 输出索引从0开始到索引为3-1=2的列表元素 print(players[0:3]) # ['a', 'b', 'c'] # 省略第一个索引,从头开始切片 print(players[:4]) # ['a', 'b', 'c', 'd'] # 省略终止索引,切片终止于列表末尾 print(players[2:]) # ['c', 'd', 'e'] # 负数索引返回列表末尾任何切片 print(players[-3:]) # ['c', 'd', 'e'] print(play...
69c6b01e7e8c3683dd3c953831dcd0f9a08c27ca
Fahmi161415/PosLists
/Lists.py
424
4.0625
4
# Program to print positive numbers in a list list1 = [12, -7, 5, 64, -14] list2 = [12, 14, -95, 3] print("Original numbers in the list : ", list1) new_list1 = list(filter(lambda x:x>0,list1)) print("Psitive numbers in the list : ",new_list1) print("Original numbers in the list : ", list2) new_list2 = list(f...
eb1f6919d01abd82d715599f4b572867a40f9365
awesome-linus/sample_code_python
/expy/generator/generator1.py
262
3.875
4
def fibonacci(): a, b = 0, 1 while True: yield b a, b = b, a + b fib = fibonacci() print(next(fib)) print(next(fib)) print(next(fib)) print("-" * 10) list_comprehensions = [next(fib) for i in range(10)] print(list_comprehensions)
0ab5c2219b196c95176d0a71e5cbf80186989bac
binsoy69/assignmentLyn2
/Problem_7.py
1,405
4.3125
4
print('A program that gives the user the choice of computing the area of any of the following: a circle, a square, a rectangle, or a triangle') loop = True while loop: print('Find the area of any of the following: ') print('Type "1" for area of circle') print('Type "2" for area of square') print('Type...
62b4b630def82ebf9100c438698e9ded5b7312fb
iamakhildabral/Python
/CommonCode/second largest.py
482
4.125
4
user_number = int(input("Enter a number of three digits:")) array = list() i= 0 while user_number >= 0: array[i] = user_number%10 user_number = user_number /10 i+= 1 array.sort(reverse=True) # Lets do some sorting to get second largest temp = array[0] array[0] = array[1] array[1] = temp # now we ar...
850077f1657f3ab19bfc50b65ac44455165c4a12
rahuldss/Python
/MatPlot1.py
1,285
3.703125
4
import matplotlib.pyplot as plt import numpy #1. Plotting X values # plt.plot([1,2,3,4,10]) # plt.show() # #2. Plotting X,Y Values with 2 ways # y_values=[1,2,3,4,10] # print([i**2 for i in y_values]) # plt.plot(y_values,[i**2 for i in y_values]) # plt.show() # plt.plot([i**2 for i in y_values],y_values) # plt.show(...
0119cfb1c862bf97a020a4713653720ab41225e0
mmoghey/Implementing-Random-Forest-Classifier
/RandomForest.py
2,736
3.90625
4
import random from math import log, ceil from DecisionTree import DecisionTree class RandomForest(object): """ Class of the Random Forest """ def __init__(self, tree_num): self.tree_num = tree_num self.forest = [] def train(self, records, attributes): """ This funct...
b83540f0bf66cd918277732aa51f05a2e2b1869f
script85/NMDL_Python_Study
/myfirstscript.py
225
3.609375
4
# Graph draw using python import math import numpy as np import matplotlib.pyplot as plt x = np.arange(-2*np.pi,2*np.pi,np.pi/100) y = np.cos(x) * np.exp(x) plt.plot(x,y) plt.show() z = np.cos(x) plt.plot(x,z) plt.show()
ac1019cd5968650ebcd3c95f11094b48e25cfba7
Akmal4163/Calculator-of-Economic-Performance
/IndexValue.py
1,142
3.609375
4
import numpy as np import math """ this is program to calculate 1. Lespeyres index 2. Paasche Index 3. Fisher's Ideal index 4. Value Index """ """ notes : pt is the current price p0 is the price in the base period qt is the quantity in the current period q0 is the quantity in the base period """ #fill the array with...
ef3067c2ac067d6054fc0ff277d7ea2e58f189c1
betalantz/CodingDojo_LearningProjects
/Python/Python OOP/classWorkThurs.py
784
3.8125
4
class Classroom(object): def __init__(self,name): self.name = name self.room = [] def add(self,kid): self.room.append(kid) return self def allSpeak(self): for i in self.room: i.speak() return self def debug(self): print self.room ...
a338333bc158da164a5c3cab09e789e1414dd34f
gus-an/algorithm
/2020/06-3/math_3613.py
795
3.75
4
import sys input = sys.stdin.readline # f(x) = x^3 # f(x) = 0 def cube_root(num): answer = num i = 0 while True: i += 1 tmp = answer # f'(x) = 3 * x^2 answer = answer - ((answer * answer * answer) - num) / (3 * (answer * answer)) # print(tmp, answer) if (...
0b2320c9fceb49771e20f0334cdaed0f43b16d30
YJL33/LeetCode
/old_session/session_1/_150/_150_evaluate_reverse_polish_notation.py
1,712
4.09375
4
""" 150. Evaluate Reverse Polish Notation Total Accepted: 74095 Total Submissions: 296662 Difficulty: Medium Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each operand may be an integer or another expression. Some examples: ["2", "1", "+", ...
a61ee2546e64d48c19beabdaaa598d2d353e62f4
ASKJR/udemy-projects
/python3-basic/cores.py
247
3.765625
4
dicionarioCores = {'vermelho': 'red', 'amarelo': 'yellow', 'verde': 'green', 'azul': 'blue'} cor = input('Digite uma cor: ').lower() print(dicionarioCores.get(cor, 'Esta cor não consta no meu dicionário')) input('Aperte enter para encerrar...')
a9cec75b619cb9d087bc35a0e7ed85777f832ac1
Ty-Allen/Allen_T_RPS_Fall2020
/game.py
3,229
3.984375
4
# import packages to extend python from random import randint from gameComponents import gameVars, winLose, gameComparison # set up our game loop while gameVars.user_choice is False: # this is the player choice print("============*/ RPS /*==============") print(" Computer Lives:", gameVars.computer_lives, "/", ga...
50132ed87714816d92fecaf68955b3b2a8852424
Zamio77/School-Projects
/LamarDougM03_Ch3Ex16.py
523
3.953125
4
year = int(input("What is the year?")) # Testing against the year 2100 as this year is not a leap year # but it is divisble by both 100 and 4, but not 400. if (year % 100 == 0): if (year % 400 == 0): print("In ", year, ", February had 29 days.", sep='') else: print("In ", year, ", Feb...
7af9e49c162878f1229b519b372ffcc156e75310
Adrian-Jablonski/python-exercises
/Turtle_Exercises/Ex4_Night_Sky.py
1,876
3.5
4
from turtle import * import random starColors = ["#9bb0ff", "#aabfff", "#cad7ff", "#f8f7ff", "#fff4ea", "#ffd2a1", "#ffcc6f"] x = -350 y = 300 i = 0 def randomVariables(): global size global x global y global color goForward = random.randint(40, 65) size = random.randint(1, 5) if size < 2...
bf1c494cb57918025814a4e76f578441d076e3a0
benbendaisy/CommunicationCodes
/python_module/examples/467_Unique_Substrings_in_Wraparound_String.py
1,571
4.03125
4
from collections import defaultdict class Solution: """ We define the string base to be the infinite wraparound string of "abcdefghijklmnopqrstuvwxyz", so base will look like this: "...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....". Given a string s, return the number of u...
0db0bb1fb7c6e3502763784402a314d1f5e56fb4
YashaswiniPython/pythoncodepractice
/2_2_PrintingStatment.py
858
4.03125
4
# Python file Created By Bibhuti """ Internal syntax of print() method """ # print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False) """ print in same line """ # print("Hello",end=""); # print("Hi"); # print("hi","ghjg") # print(1,2,3,sep="*"); # print(1,2,3,sep="*",end="Hi"); # print("Hello") # print("...
c9c580cae58ba610b1d25b393b4174869489c25d
kRituraj/python-programming
/print-square-of-even-and-cube-of-odd.py
320
3.828125
4
from array import * MyArray = array("i",[1,2,3,4,5,6,7,8,9,10]) i = 0 even = 1 odd = 1 while (i < len(MyArray)): if (MyArray[i] %2 == 0): even = MyArray[i] * MyArray[i] print(even , end = " ") else: odd = MyArray[i] * MyArray[i] * MyArray[i] print(odd , end = " ") i = i + 1
22ae1e4a69c8917dc691fa49d9196a2f8ed59704
abrahambtz/Python-basic
/funciones.py
1,098
3.90625
4
menu = """ Bienvenido al conversor de monedas. ------------------------------------ * Opcion 1 : Convertir de pesos mexicanos a colombianos * Opcion 2 : Convertir de pesos mexicanos a dolares. * Opcion 3 : Convertir de dolares a pesos mexicanos. Selecciona una opcion: """ def convertidor(tipo_moneda, moneda_a_conve...
0b710e7f6c09b9238d8a18325cb3f4d0786a04b2
shafiqul-islam/URI_solve
/uri1038.py
275
3.546875
4
a,b=input().split() a,b=int(a),int(b) r1=b*4.00 r2=b*4.50 r3=b*5.00 r4=b*2.00 r5=b*1.50 if a==1: print("Total: R$ %.2f"%r1) elif a==2: print("Total: R$ %.2f"%r2) elif a==3: print("Total: R$ %.2f"%r3) elif a==4: print("Total: R$ %.2f"%r4) else: print("Total: R$ %.2f"%r5)
4a38b9cf5ac95cf2f544e02f250bf334c0c7bf8b
wangbo-android/python
/Python3高级编程/chapter3/senior_level_class2.py
724
3.515625
4
class RealAccess: def __init__(self, name, age): self.name = name self.age = age def __get__(self, obj, owner): print('get func') return self.name, self.age def __set__(self, obj, value): self.name = value print('set func') @property def user_name(...
45e36c4cd57248ab08165fd76de646c6ce1e1442
yakovitskiyv/algoritms
/unlike_deal_test.py
1,044
3.984375
4
class Node: def __init__(self, value=None, next=None): self.value = value self.next = next def print_linked_list(vertex): while vertex: print(vertex.value, end=" -> ") vertex = vertex.next print("None") def get_node_by_index(node, index): while index: node = n...
6d09cc3ba592300b4922b986b0be44916c513ddd
roger6blog/LeetCode
/SourceCode/Python/Problem/00003.Longest_Substring Without Repeating Characters.py
2,780
4.03125
4
''' Level: Medium Given a string, find the length of the longest substring without repeating characters. Examples: Given "abcabcbb", the answer is "abc", which the length is 3. Given "bbbbb", the answer is "b", with the length of 1. Given "pwwkew", the answer is "wke", with the length of 3. Explanation: The answer...
3f297e3fd937cfdae0ee08a0d35bb5425e86e4f8
Amrutha-M/Online-Coding
/Day 20(08-06-2020)/Program 1.py
334
3.984375
4
#Python Program to Copy the Contents of One File into Another with open("test.txt") as f: with open("out.txt", "w") as f1: for line in f: f1.write(line) print("successful done") output new.txt: hello,how r you this is a python program out.txt: hello,how r you this is a py...
cb98be9b79ebdbf5b99a8659b5d52db7234591a9
kyrin28/sort_method
/main/selectSort.py
382
3.640625
4
#coding=utf-8 def selectSort(alist): for index in range(len(alist)-1,0,-1): positiomMax = 0 for location in range(1,index+1): if alist[location] > alist[positiomMax]: positiomMax = location tmp = alist[index] alist[index] = alist[positiomMax] alist[positiomMax] = tmp alist = [54,26,93,17,77,31,44,5...
f75a7f5a33dbb159e06c2709fc1a207491564e0f
Spectrum3847/BRNCL
/network_tables_deep_development/utils.py
1,357
4.03125
4
#!/usr/bin/env python class SequenceNumber(object): """ Sequence numbers are a form of comparable wrapping numbers. See http://tools.ietf.org/html/rfc1982 """ SERIAL_BITS = 16 def __init__(self, val=0): self.val = val def increment(self): "Increment the value by one with w...
ac420603cb43ca96afb7dbcfbfcad04dfd04d517
janakiraam/Python_Basic_Advance
/set2/linear_search.py
603
3.75
4
# -*- coding: utf-8 -*- """ Created on Tue Sep 11 17:32:54 2018 @author: I340968 """ def linear_search(n,x): elemnet = [] for i in range(1,n): elemnet.append(i) count=0 flag=0 for i in elemnet: count+=1 if(i==x): print("The number is found at p...
40cf1717819571c86bfe8aedb29f02fb094794ff
kandarpkakkad/Machine-Learning-A-to-Z
/002Simple_Linear_Regression.py
1,005
4.03125
4
import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression import math as m #Data Preprocessing dataset = pd.read_csv("Salary_Data.csv") #print(dataset) x = dataset.iloc[:, :-1].values y = dataset.iloc[:...
4354e248994189ab611eb21c2910181a8ef70a44
agapow/py-konval
/konval/base/types.py
1,756
3.5
4
from . import Konvalidator, KonversionError, ValidationError class ToType(Konvalidator): ''' Convert a value to a given type. Will actually accept any callable as an argument, but is intended for use with class constructors. You could use raw types and classes, but this throws much nicer error messages. Conve...
8794fd8c457f516ddffc4811214ebc904d0ac71b
vamshigvk/Stripe_Django_challenge
/compression.py
930
4.1875
4
#String Compression def compress(string): #compress function which accepts an input string and returns a compressed string. #compressed string result = "" #counter to count continous occurances of character count = 1 #Adding the first character result = result + string[0] #Iterate through...
a4936ef93e2f03d5df3c7dd828e4e2ce4de43558
arsummers/python-data-structures-and-algorithms
/challenges/tree_intersection/tree.py
2,788
4.09375
4
class Node: def __init__(self, value): self.value = value self.left = None self.right = None class BinaryTree: def __init__(self): self.root = None def in_order(self): results = [] def visit(node): # visits left node if node.left: ...
7dc81b14b19fb42be3b709954b41818698af6bc7
bitsimplify-com/coding-interview
/Microsoft/11/11.py
1,915
4.0625
4
class newNode: def __init__(self, key): self.key = key self.left = self.right = None # This function prints all nodes that # are distance k from a leaf node # path[] -. Store ancestors of a node # visited[] -. Stores true if a node is # printed as output. A node may be k distance # away...