blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
baa949c6168222dda0cf63624ca31138942b4e1a
dfeusse/codeWarsPython
/06_june/08_dieRolling.py
520
4.0625
4
''' Hello! Today your task is to build a basic die feature, where you will get a range in the form (min, max) - both included - and return a random number in the inclusive range. Props if you don't use your language's random library! dice(2, 7) # returns a value that can be 2, 3, 4, 5, 6, 7 Good luck! ''' from rando...
11a0d32519e918d1181b79c8385b0a4e2ef76399
ibogorad/CodeWars
/Thinkful - Object Drills.py
179
3.546875
4
class Vector(object): def __init__(self, x, y, ): self.x = x self.y = y def add(self, other): return Vector(self.x + other.x,self.y + other.y)
63af1268a161465ab368d8b59dc438b15a925ce4
vietthanh179980123/VoVietThanh_58474_CA20B1
/page_100_project_08.py
1,073
4.125
4
""" Author: Võ Viết Thanh Date: 18/09/2021 Program: The greatest common divisor of two positive integers, A and B, is the largest number that can be evenly divided into both of them. Euclid’s algorithm can be used to find the greatest common divisor (GCD) of two positive integers. You can use this algorithm in th...
fa9a72623ca46f790c45f84aa46b9cba9a10c287
hsycamp/algorithm
/leetcode/valid_anagram.py
789
3.671875
4
''' LeetCode 242. Valid Anagram https://leetcode.com/problems/valid-anagram/ Description: Given two strings s and t , write a function to determine if t is an anagram of s. Example 1: Input: s = "anagram", t = "nagaram" Output: true Example 2: Input: s = "rat", t = "car" Output: false Note: You may assume the str...
45758db3365fc9dc51dd1960173a144a206bc7ce
Passionatecricketer/100-days-code-challenge
/day100/delete linklist.py
2,026
4.28125
4
#class to create structure of the node class node: def __init__(self,data): self.data=data self.next=None #class to perform the operation in linked list class linklist: def __init__(self): self.head=None #Function to insert data in beginning of the list def begin(self,newdata)...
b81a0d3baefd3482c68a0957b82050cf3dd9826c
goaguilar/GoAguilar_CS50_Projects
/goaguilar-cs50-2017-fall-sentimental-caesar/caesar.py
784
3.765625
4
from cs50 import get_string from cs50 import get_int def main(): print("plaintext: ") plaintext = get_string() ciphertext = list(plaintext) print("code: ") code = get_int() for i,plainchar in enumerate(ciphertext): ##for lowercase if (plainchar >= 'a' and plainchar <= 'z'): ...
468f2592da5ddd36c19a0637378310f6618d2b8f
Zadigo/my_python_codes
/automation/pdf.py
1,686
3.984375
4
import PyPDF2 from PyPDF2 import PdfFileWriter def decrypt_pdf(path, page=0, password=None): """A simple program that takes a PDF file in order to return the text """ with open(path, 'rb', encoding='utf-8') as f: source_file = PyPDF2.PdfFileReader(f) # The file might require a password....
6ccc78ca167a52059e9a731bccc5e29629ba1306
LuizVinicius38/03-Quiz
/Desafio_Quiz 3.py
753
4
4
print("Qual é minha comida preferida") resposta = input("").lower() print("Qual a minha cor favorita") respostas = input("").lower() print("Eu prefiro frio ou calor") respost = input("").lower() print("Qual animal que eu mas amo?(escreva em inglês)") res = input("").lower() print("Qual time de futebol eu torço?...
b405ed976fe440b549fc714ace4a5a1c72ab6421
minjung0/scaffold
/hello.py
75
3.5625
4
def add(x, y): return x+y print(f"This is the sum : 5, 1, {add(5,1)}")
c61da17cf06a737e870ea38da5cf21a375a41c7f
jzdmdxww66666/myedu-1902-
/day03/assert_demo.py
854
3.796875
4
if __name__ == '__main__': ##断言为ture 不会有报错 #assert 4>2 ##断言为false会报错 AssertionError #assert 1>2 ##断言字符串 astr = '的经费和大家回复大家更好地' ##判断astr字符内 是有包含 你 这个字 #assert '你 'in astr ##判断 astr字符内 是否不包含 你 这个字 #assert '你 'not in astr #a=0 ##while语法 : while(当)条件:--> 条件为true 进入循环, 知道 条...
1f8a376082760571e7062e67b3ad3e1c30d8e54f
angnicolas/cs50_ai
/tictactoe/tictactoe.py
4,953
4.0625
4
""" Tic Tac Toe Player """ import math X = "X" O = "O" ALPHA = -math.inf BETA = math.inf EMPTY = None def initial_state(): """ Returns starting state of the board. """ return [[EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY]] def player(board): """ ...
d35407718a5792ccbfa6e607885dc90d0c7bb3cd
ComSciCtr/vroom
/vroom/utils/generators.py
1,691
4.28125
4
# System imports from random import random, randrange def random_vertex(start, stop): ''' Return a random [x,y,z] value in the range (start, stop).''' return [randrange(start, stop, _int=float) for i in range(3)] def random_color(): ''' Return a random [r,g,b] value in the range (0, 1).''' return [ran...
299db2665fb0cf5c09d84c19e21de62db7a6c7bb
chongjing001/Python-Basis
/python project/Day3-Python基础语法2/tj_00_test.py
1,901
3.609375
4
# # x = 51561456156 # x = str(x) # x = list(x) # print(x) # # a = "1231556" # print(a[::-1]) def reverse_num(): x = input("请输入要反转的数字") if x == "0": return x elif int(x) > 0: return x[::-1] else: x = -int(x) x = str(x) x = x[::-1] return -int(x) # new_x ...
dfa1074cf4bc0665c39a7fb81be2cd8fdfc02cd9
qkrwldnjs89/dojang_python
/UNIT_11_시퀀스 자료형 활용하기/143p_인덱스 생략하기.py
96
3.59375
4
# 인덱스 생략하기 a = list(range(0, 100, 10)) print(a[:7]) print(a[7:]) print(a[:])
4cbe8d449c71a82b4676266d1058f7c7eda9aacd
Slidem/coding-problems
/permutations/permutations.py
459
3.953125
4
def permute(nums): if not nums: return [] permutations = [] for x in nums: remaining = nums.copy() remaining.remove(x) remaining_permutations = permute(remaining) if not remaining_permutations: permutations.append([x]) continue for p ...
6419b19b713a29c89f908b95d63ed26a6d0a90bd
coblan/py2
/try/scin/pad.py
513
3.84375
4
from pandas import Series, DataFrame import pandas as pd obj = Series([4, 7, -5, 3]) sdata = {'Ohio': 35000, 'Texas': 71000, 'Oregon': 16000, 'Utah': 5000} obj3 = Series(sdata) states = ['California', 'Ohio', 'Oregon', 'Texas'] obj4 = Series(sdata, index=states) print(obj4) data = {'state': ['Ohio', 'Ohio', ...
8d90d444764b2abe5bf1ae714c37b23ded050e2e
aidanrfraser/CompSci106
/reverse.py
383
3.90625
4
from cisc106 import assertEqual #working with Ben def reverse(alist): """ Reverses a list """ if not alist: return alist else: return reverse(alist[1:]) + [alist[0]] assertEqual(reverse([1, 2, 3]), [3, 2, 1]) assertEqual(reverse([0, 1, 0]), [0, 1, 0]) assertEqual(reverse([1,...
0f51f948f0b9596accbfd72abfe95609aa24dba2
qzwj/learnPython
/learn/基础部分/多线程.py
5,663
4
4
#!/usr/bin/env python3 # -*- coding:utf-8 -*- #多任务可以由多进程完成, 也可以由一个进程内的多个线程完成, 线程是程序的最基本的执行单元 #python提供了: 低级模块_thread, 和高级模块 _threading #启动一个线程就是把一个函数传入并创建Thread实例, 然后调用start()开始执行 import time, threading #默认有一个主线程, 这个函数很清晰 def loop(): print('thread %s is running...' % threading.current_thread().name) n = 0 while ...
3d4941e60802680aa19b7795f82e0969b67811d9
brainiacpimp/mystuff
/encryption/utils.py
997
4.125
4
#!/usr/bin/env python3 # utils.py """ Module that holds helper functions. """ import math import string SYMBOLS = string.printable def findModInverse(a, m): """ Returns the modular inverse of a % m, the number x such that a*x % m = 1 This is a function from InventWithPython. :param a: int to find m...
737990eb61fe6f18eebdcd4bab902216cc0576ec
filipo18/-uwcisak-filip-unit3
/numberorder.py
826
4.15625
4
# This program will put numbers defined in array in order # Define the array num = [3, 4, 1, 100, 34, 17, 21, 16] # Set the variable that will check if program is complete or not check = 0 # measure length of the array n = len(num) # looping through the program until numbers are in order while check < 8: # set to...
6e8a9f22a955ff00875a0629a7f88205aa52136b
LindseyAnneHello/New-Project2
/wordjumble_Caldwell.py
1,161
4.53125
5
#Lindsey Caldwell #3/27/17 #Word Jumble #the computer picks a random word and then "jumbles" it #the player has to guess the original word import random #create a sentence of words to choose from WORDS = ("oyster", "river", "high", "school", "is", "cool") #pick one word randomly from the sequence w...
4abc5b9f5088458a0684f561a511630833a289ad
Jreamz/100DaysOfCode
/day-3-love-calculator.py
2,062
4.03125
4
## JREAMZ VERSION ## #################### print("Welcome to the Love Calculator!") name1 = input("What is your name? \n") name2 = input("What is their name? \n") lower_name1 = name1.lower() lower_name2 = name2.lower() t_counter = lower_name1.count("t") + lower_name2.count("t") r_counter = lower_name1.count("r") + lo...
049a568b08c1275221379affff010b2f0598130b
willianflasky/growup
/python/day02/字典.py
666
3.671875
4
#!/usr/bin/env python # coding:utf8 __author__ = "willian" names = { "stu1101": {"name": 'alex', 'age': 22, 'hobbie': 'girl'}, "stu1102": "jack", "stu1103": "rain", } """ # search print(names["stu1101"]['hobbie']) print(names.get('stu1108', 'nobody')) # add names['stu1104'] = ['yy', 32, 'DBA'] # update ...
8c9207a393423a904b286cc881ea6289dbac99ec
vishwanathj/python_learning
/python_hackerrank/BuiltIns/input.py
969
4.15625
4
''' This challenge is only forPython 2. input() In Python 2, the expression input() is equivalent to eval(raw _input(prompt)). Code >>> input() 1+2 3 >>> company = 'HackerRank' >>> website = 'www.hackerrank.com' >>> input() 'The company name: '+company+' and website: '+website 'The company name: HackerRank and webs...
1244aa3a7cc809f92334f35bdc35a55c79065a9e
jdleo/130
/Project4/Solution1/solution1.py
440
4.03125
4
#!/bin/python3 import sys def introTutorial(V, arr): #enumerate array and iterate through for (index, element) in enumerate(arr): #if current element == V, then return the index if element == V: return index if __name__ == "__main__": V = int(input().strip()) n = int(inp...
73383aac59d48f325127ec0b83604f7861d9ada6
girishteli/firstrepository
/date time.py
134
3.765625
4
import datetime current=datetime.datetime.now() print("current date & time is ::") print(current.strftime("%Y-%m-%d %H:%M:%S"))
ef4b1f9b167c368dbd47e7bd9c270db6326bc7af
Dervun/Python-at-Stepik
/1/11.5/11.5.py
754
4.3125
4
''' Напишите программу, которая получает на вход три целых числа, по одному числу в строке, и выводит на консоль в три строки сначала максимальное, потом минимальное, после чего оставшееся число. На ввод могут подаваться и повторяющиеся числа. ''' arr = sorted([int(input()) for i in range(3)]) print(arr[2], arr[0], ar...
514c79089b0b910f251629a8a27ea1fa783df09b
MattR-GitHub/Python-1
/L6 Input Counter.py
700
3.96875
4
#!/usr/lo#!/usr/local/bin/python3 mywordset2 = set() mydict = {} while True: text = input("Please enter a sentence or type nothing and select Enter to end: ") # intitalize set if not text: # no data entry exit break for punc in ",?;.": ...
5b714b49c4622abe411a299b44e2f1cbfd9b52ee
rajlath/rkl_codes
/BB_PythonDS/backtracking.py
527
3.859375
4
# -*- coding: utf-8 -*- # @Date : 2018-09-06 10:20:42 # @Author : raj lath (oorja.halt@gmail.com) # @Link : Benjamin Baka PythonDSandAlgo Examples # @Version : 1.0.0 def main(): print(bit_str("abc", 3)) def bit_str(s, l): ''' returns a set of permutation ( of a length ) of a string @param str...
fcc0d90c7df9d10dae79e8c464afb8fa88ab809a
Rodrigodebarros17/Livropython
/CAP5/5-22.py
1,205
4.125
4
operacao = input("Digite a operação (+ para soma, - para subtração, * para multiplicação, / para divisão, ^ para potenciação, 0 para sair): ") while operacao != "0": base = int(input("Digite o valor da tabuada: ")) operando = 1 if operacao == "+": while operando <= 10: print(f"{base} + ...
c8ce10b1c1c9875bd48d0e0e80e520537b52717b
wghreg/pystudy
/height/heigher-order-function.py
1,282
4.1875
4
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # 高阶函数-小结 # 把函数作为参数传入,这样的函数称为高阶函数,函数式编程就是指这种高度抽象的编程范式。 print(abs(-1)) print(abs) f = abs print("f =", f) print("f(-10) =", f(-10)) # 由于abs函数实际上是定义在import builtins模块中的,所以要让修改abs变量的指向在其它模块也生效,要用import builtins; builtins.abs = 10。 # 既然变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数...
23abf2cab0794c82f3f26e182502f80b55464f31
daigo0927/ctci-6th
/chap8/Q13_alt2.py
1,247
3.5625
4
class Box: def __init__(self, width, height, depth): self.width = width self.height = width self.depth = depth def is_smaller(self, box_tar): if self.width < box_tar.width and self.height < box_tar.height and self.depth < box_tar.depth: return True else: ...
70e3660177db87442a91019a14b235e496862af5
Dallas98/Applet
/Experiment/OrderingSystem/Customer.py
937
3.84375
4
from Experiment.OrderingSystem.Employee import Employee class Customer(object): def __init__(self, customer_name, name_list, number_list): self.__name = customer_name self.__name_list = name_list self.__number_list = number_list def get_customer_name(self): return self.__name ...
ea9cb32bf762363ee4887e39125319b56b7cbad3
zxy-zhang/python
/返回值.py
1,819
4.03125
4
def get_formatted_name(first_name,last_name): full_name=first_name+' '+last_name return full_name.title() muician=get_formatted_name('jimi','hendrix') #提供一个变量,用于存储返回的值(这里返回值存储在muicain中) print(muician) def get_formatted_name(first_name,middle_name,last_name): full_name=first_name+' '+middle_name+' '+last_...
95a7b82043cff001db70cf433bf16d3db12b46c0
afarizap/holbertonschool-machine_learning
/supervised_learning/0x08-deep_cnns/2-identity_block.py
1,665
3.6875
4
#!/usr/bin/env python3 """ 2-identity_block task """ import tensorflow.keras as K def identity_block(A_prev, filters): '''Builds an identity block as described in Deep Residual Learning for Image Recognition (2015) Args: A_prev is the output from the previous layer filters is a tuple or li...
287721a8ffaf70c408bbe4d34665ccfee9e76b93
Prasanth-G/HackerRank
/Python/Regex_and_Parsing.py
9,467
3.984375
4
######1.Introduction to Regex Module ''' Sample input : 5 1.414 +.5486468 0.5.0 1+1.0 0 Sample output : True True False False False ''' import re for i in range(int(input())): print(bool(re.match("^[\+\-]?\d*\.\d+$",input()))) ######2.re.split() ''' Sample input : .172..16.52.207,172.16.52.117 Sample Output : 172 ...
01624ccf508809a693ca50892692b90cd78126d1
siddhism/leetcode
/array/hash-table/insert-delete-getrandom-o1.py
1,646
4
4
# import time class RandomizedSet(object): def __init__(self): """ Initialize your data structure here. """ self.pos = {} # store index of each value self.nums = [] self.idx = 0 def insert(self, val): """ Inserts a value to the set. Returns true...
a96e5553ace1fa48eb07deeec10f99827d053ae8
Gam1999/Practice-Python
/RightTriangleDown.py
127
3.734375
4
Input = int(input("Enter the number of rows: ")) i = 0 for i in range(Input): print(' '*((i-1)+1) + "*"*(Input-(i+1)+1))
5666ed93a786969da407cd866814109cd7d41972
TheDycik/algPy
/les1/les_1_task_3.py
1,467
4.25
4
# 3. Написать программу, которая генерирует в указанных пользователем границах: # a. случайное целое число, # b. случайное вещественное число, # c. случайный символ. # Для каждого из трех случаев пользователь задает свои границы диапазона. # Например, если надо получить случайный символ # от 'a' до 'f', то вводятся эти...
8ddf50c6c620ba96d175825171669405ad79eca2
wzxedu/Recurrent-Autoencoder
/utils/metrics.py
571
3.53125
4
class AverageMeter: """ Class to be an average meter for any average metric like loss, accuracy, etc.. """ def __init__(self): self.value = 0 self.avg = 0 self.sum = 0 self.count = 0 self.reset() def reset(self): self.value = 0 self.avg = 0 ...
3450baf922e78831110470ef18175d6ea85b0d00
KWMalik/py-coursera
/ML/mlclass-ex1/ex1.py
4,132
3.875
4
## Machine Learning Online Class - Exercise 1: Linear Regression # Instructions # ------------ # # This file contains code that helps you get started on the # linear exercise. You will need to complete the following functions # in this exericse: # # warmUpExercise.py # plotData.py # gradientDescent....
d6d68bbee298e379f45c5a2fdb02af2d9bd0b64a
VasuShashi/Practice-Python
/linkedlist.py
2,350
3.765625
4
from node import Node class UnorderedList: def __init__(self): self.head = None self.tail = None def isEmpty(self): return self.head == None def add(self, val): n = Node(val) n.setNext(self.head) self.tail = self.head self.head = n def size(se...
288445aa9c0e70bc6980cc69fd3ea8458d632ddc
Aasthaengg/IBMdataset
/Python_codes/p02730/s113613633.py
269
3.5625
4
def main(): S = input() L = len(S) def check(s): return s == s[::-1] cond = check(S) cond = cond and check(S[:L // 2]) cond = cond and check(S[(L + 1) // 2:]) print('Yes' if cond else 'No') if __name__ == '__main__': main()
036fc7bc5ec55f5f5042da1c4c67f09e3845fa36
spencergoles/Blackjack
/blackjack.py
4,284
3.5625
4
# Blackjack # By: Spencer Goles @2019 import sys from random import shuffle from time import sleep # 4 suites in a deck is 52 - 4*13 = 52 # In blackjack suite is irrelevant only facevalue is needed deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] * 4 # Function shuffles the deck and deals two cards to the hand de...
8228c6ab3569ab9d47bac1e6723a85f26434fefd
1rjun/pythonbasics
/functions.py
178
3.6875
4
def currency(oldnotes): if oldnotes==500 or oldnotes==1000: print("You need to change your currency") else: print("yes currency is valid") currency(1000)
e35352f5cb33f6b721c0b6b7148450586e514412
hari819/python_related_courses
/00.FullSpeedPython/07.Iterators/01.range.py
451
3.796875
4
class MyRange: def __init__(self, a, b): self.a = a self.b = b def __iter__(self):# returns the iterator object itself return self def next(self): if self.a < self.b:# returns the next item in the sequence value = self.a self.a += 1 return value else: raise StopIterat...
0169aa865b823ce172ae752f7ad7624c91f83f67
albertsunn/working
/letters_count.py
223
3.671875
4
sentence = list(input("Enter a string: ")) collected = {} for i in range(len(sentence)): if sentence[i] not in collected: collected[sentence[i]] = 1 else: collected[sentence[i]] +=1 print(collected)
4bc2c95438437843f1be7f6f963ebdec8c471430
pruthu-vi/CV-Project2
/circle_shape_detect.py
1,221
3.6875
4
import numpy as np import matplotlib.pyplot as plt import cv2 print('Loaded') # read the image #img = cv2.imread('Resources/test_image.jpg') img = cv2.imread('resources/file-shapes-for-kids-1592568510.jpg') # convert BGR to RGB to be suitable for showing using matplotlib library img = cv2.cvtColor(img, cv2.COLOR_BGR2...
e41f9757704c33857ad00544d3f2c02a8aa9ec96
PrabuddhaBanerjee/Python
/Chapter3/Ch3P8.py
266
3.9375
4
import math def main(): print("This program is used to figure out the date of Easter") year = eval(input("Please enter an year:")) c = year // 100 epact= (8 + (C // 4) - C + ((80+13) // 25) + 11( year % 19)) % 30 print("Value of epact is ", epact) main()
2f72df61ca0be03efd876f43b4254038bceabf96
Cindylopes17/Premier-TP
/TP/TPEX4.py
1,095
3.90625
4
#Compagnie d'assurance age: int = int(input("Quel age avez-vous?")) permis: int = int(input("Nombre d'années de permis?")) accidents: int = int(input("Nombre d'accidents ?")) annéesAssurance: int = int(input("Nombre d'années d'assurance ?")) Vert: str = "vert" Bleu: str = "bleu" Rouge: str = "rouge" Orange:...
4614cb138f8c4bf5a88ff9e7d91ced3e2b98ee0a
JDGC2002/programacion
/Talleres/TallerCondicionalesPunto1.py
631
3.859375
4
#---------CONSTANTES-----# PREGUNTA_A = "¿Cuál es el número A?: " PREGUNTA_B = "¿Cuál es el número B?: " MENSAJE_A_MAYOR = "El número A es mayor al número B" MENSAJE_B_MAYOR = "El número B es mayor al número A" MENSAJE_IGUALES = "Los números son iguales" #---------ENTRADA AL CÓDIGO-----# NumeroA = int(input(PREGUNTA_A...
083b5ece7d805493daad91fe98b8c163509b6a42
AliBeec/TheServer2
/Beec/Checking.py
2,245
3.921875
4
import re EnglishLitters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ArabicLitters = "اأإبتثجحخدذرزسشصضطظعغفقكلمنهويةلآآلإئءؤ" ArabicNumbers = "1234567890" EnglishLitters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" def RemoveUnwantedChar(inputText:str): result = "" for oneChar in inp...
249bb04ad159c1a07013dba8b8864343f53ba25d
mido1003/atcorder
/152/B.py
101
3.5
4
a,b = (int(x) for x in input().split()) if a > b: print(str(b)*a) else: print(str(a)*b)
bdb583c54c547d8ebf8a0b48f8ceeb26a30b05d5
thiago5171/python.
/exercicios/ex024.py
825
4.15625
4
"""Faça um programa que leia o ano de nascimento de um jovem e informe, de acordo com a sua idade, se ele ainda vai se alistar ao serviço militar, se é a hora exata de se alistar ou se já passou do tempo do alistamento. Seu programa também deverá mostrar o tempo que falta ou que passou do prazo. """ ano = int(input(...
cffc9be0bb56436c2168bf6c40c908faa29aad3b
WallysonGalvao/Python
/CursoEmVideo/1 - OneToTen/Challenge008.py
527
4.3125
4
""""Measurement converter""" # Challenge 008 # Write a program that reads a value in meters and displays it converted to centimeters and millimeters. print("Challenge 008") print("Write a program that reads a value in meters and displays it converted to centimeters and millimeters.") distanceInMeters = float(input("A ...
b3cf7b4d2573db99cb9ada6127106b1c58e100c3
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/222/users/4067/codes/1643_1055.py
416
3.625
4
# Teste seu código aos poucos. # Não teste tudo no final, pois fica mais difícil de identificar erros. # Use as mensagens de erro para corrigir seu código. from math import* v0 = float(input("velocidade inicial: ")) a = radians(float(input("angulo: "))) d = float(input("distancia: ")) g = 9.8 r = (v0**2 * sin(2*a))/g ...
ab17f5530a005e6a478c246b644420c7e69b6e43
leognon/2048Bots
/2048/simulation.py
4,129
3.859375
4
import random DOWN = 0 RIGHT = 1 UP = 2 LEFT = 3 def made_2d(w, h, val): arr = [] for i in range(w): tempArr = [] for j in range(h): tempArr.append(val) arr.append(tempArr) return arr def flip_arr(arr): new_arr = [] for i in range(len(arr)-1, -1, -1): ...
8d3ddada32a53f405dc4b94c286dc705c43eed6e
lim-jonguk/ICE_HW3
/임종욱_2.py
249
3.609375
4
# C111152 임종욱 from random import randint a = randint(0,100) b = randint(0,100) c = a + b print(a,' + ', b,'의 값은? ',end=" ") d = int(input()) if c == d: print('맞았습니다.') else : print('틀렸습니다')
7f52d8ae37ef58e61e0e37d0d714a028025ef2cd
johngaitho05/CohMat
/data_structures/LinkedLists/SingleLinkedList.py
12,310
3.78125
4
class InvalidOperationException(Exception): pass class Node: def __init__(self, value): self.info = value self.link = None def _merge(p1, p2): if p1.info <= p2.info: startM = Node(p1.info) p1 = p1.link else: startM = Node(p2.info) p2 = p2.link pM =...
bda46b97aa3735b8c31a7040479e86bf542cc7c8
mateusleiteaalmeida/trybe-projects
/Computer-Science/sd-07-project-ting/ting_file_management/queue.py
553
3.578125
4
class Queue: def __init__(self): self.files = list() def __len__(self): return len(self.files) def enqueue(self, value): self.files.append(value) def dequeue(self): if self.files.__len__() == 0: raise IndexError("list index out of range") return sel...
e3b8e077337692eead00f504ab92f00d7adac482
ivoryli/myproject
/class/phase1/day09/code02.py
309
3.78125
4
class Wife: def __init__(self,name,age): self.name = name #缺点:缺乏对象数据的封装,外界可以随意赋值 self.age = age class Wife: def __init__(self,name,age): self.name = name self.__age = age w01 = Wife("芳芳",26) w01 = Wife("铁锤",74)
abe9f3bdb1f8d872f1c96b705bb1e7e89d61e575
chaimleib/intervaltree
/test/intervals.py
3,929
3.515625
4
""" intervaltree: A mutable, self-balancing interval tree for Python 2 and 3. Queries may be by point, by range overlap, or by range envelopment. Test module: utilities to generate intervals Copyright 2013-2018 Chaim Leib Halbert Licensed under the Apache License, Version 2.0 (the "License"); you may not use this fi...
442b818222e83aedb1c899f8b301c224dcb626d8
ICC3103-202110/laboratorio-01-MariM-16
/LABORATORIO_1_MARIN_MARIA.py
3,535
3.921875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 25 00:33:02 2021 @author: mariamarin """ from numpy import * from numpy import random from random import shuffle from tabulate import tabulate import random print ("BIENVENIDO A MEMORICE \n") print('Ingrese el numero de cartas a jugar: ') num_card...
1b8abf77b9e61e5e72263f409a452bb11b0bb5b6
harbm17/snakeGame
/snake.py
4,223
3.8125
4
#snake game tutorial from TokyoEdtech import turtle import time import random delay = 0.1 #score score = 0 highscore = 0 # screen window = turtle.Screen() window.title("Snake Game") window.bgcolor("black") window.setup(width=1250, height=700) window.tracer(0) # snake head snakeHead = turtle.Turtle() snakeHead.spee...
26838ed325263a93b7c48b911ccac8e0e098a7cf
brij2020/Ds-pythonic
/Quiz-Linked-List/Remove_first_elem_add_at_end.py
545
3.6875
4
import Singly_linked_list # Linked List function lis = Singly_linked_list.List() def remove_first(): node = lis.head prev = None while node : prev = node node = node.next pass xnode = lis.head lis.head = xnode.next prev.next = xnode xnode.next = None pass ...
801887630567cedcb3cbeb8260590f948726f019
wuqunfei/algopycode
/leetcode/editor/en/[155]Min Stack.py
2,026
4
4
# Design a stack that supports push, pop, top, and retrieving the minimum # element in constant time. # # Implement the MinStack class: # # # MinStack() initializes the stack object. # void push(int val) pushes the element val onto the stack. # void pop() removes the element on the top of the stack. # in...
da55eb650fa3ecff2ca63bd0e78c1262bbd2903d
sethmsk88/Bioinformatics
/Week1/find_reverseDNA.py
172
3.828125
4
#Read text file file1 = open("myfile.txt","r") print file1.read() trans = str.maketrans('ATGC', 'TACG') y=file1.translate(trans) y_reversed = y[-1::-1] print(y_reversed)
d8bb120f994e5ced0ac6e01e3f3bb4d629daf9f6
trwhitcomb/euler
/prob104.py
587
3.59375
4
""" Solve Project Euler Problem 104 Pandigital numbers in Fibonacci numbers """ is_pandigital = lambda s: ''.join(sorted(s)) == '123456789' def fib_stream(): a, b = 1L, 1L while True: yield a a, b = b, a+b def solve(): fibs = fib_stream() for i, f in enumerate(fibs): if i % ...
b90c33817576430ce31c85b7a60eff39695e14ad
quangngoc/CodinGame
/Python/mars-lander-episode-1.py
433
3.625
4
# https://www.codingame.com/training/easy/mars-lander-episode-1 def solution(): surface_n = int(input()) for i in range(surface_n): land_x, land_y = map(int, input().split()) while True: x, y, h_speed, v_speed, fuel, rotate, power = list(map(int, input().split())) if abs(v_speed) ...
6771e00b4a95ff832d819e558594d406971b5c39
15751064254/pythonDemo
/threading/3_join.py
468
3.5625
4
import threading import time def T1_job(): print('T1 start \n') for i in range(10): time.sleep(0.1) print('T1 finish \n') def T2_job(): print('T2 start \n') print('T2 finish \n') def main(): thread_1 = threading.Thread(target = T1_job, name = 'T1') thread_1.start() thread_2 = threading.Thread(...
dd4031a552f1dd301cf755f8d3bcaa9b5e7a43bd
wanchai-saetang/meme-generator
/src/MemeEngine/MemeEngine.py
1,840
3.515625
4
"""Represent meme engine to create meme with quote.""" from PIL import Image, ImageDraw, ImageFont import random import os import textwrap import pathlib class MemeEngine(): """A MemeEngine class for auto generate meme with quote base on directory that is given.""" def __init__(self, directory) -> None: ...
f76e1270fa3273653d92fccb16319e7b1000a766
ian0011/PythonStudy
/estruturas_de_controle/for_2.py
515
3.828125
4
# percorrendo lista, tupla e set palavra = 'paralelepípedo' for letra in palavra: print(letra, end=',') print('Fim') aprovados = ['Rafaela', 'Pedro', 'Renato', 'Maria'] for nome in aprovados: print(nome) for posicao, nome in enumerate(aprovados): print(posicao + 1, nome) dias_semana = ('Domi...
ce973afbcdb428927001672e0ebc67453a2cfedd
AkashC96/python_training
/T6.py
750
3.9375
4
# Q1 print('Q1: uppercase using list comprehension ') input_Str= str(input()) print([x for x in input_Str if x.isupper()]) # Q2 print('Q2: Use Zip function') alist=['Smit', 'Jaya', 'Rayyan'] blist=['CSE', 'Networking', 'Operating System'] mydict=dict(zip(alist,blist)) print(mydict) # Q3 print('Q3:') pri...
c8f5a59148832b12a56f3008b75f256e4ceaf523
kirihar2/coding-competition
/find_parallel.py
1,559
3.96875
4
##Method 1: Create all rectangles and filter out ones that are not parallel to x ##Method 2: Find all lines parallel to x, then try to find the lines that have the same start and end x values ##Method 3: Find all y values with the same x. Like a bucket for each x value and their counts. set of 2 lines that have same ...
0a138af8b492b06275978151558178d9d8860262
yogeshkhola/python1
/Datastructure/cinema.py
899
3.90625
4
# first elemment is age and 2nd is seats films={ "Finding Dory":[3,5], "Tarzen":[18,5], "Bhaubali":[20,2], "Krish 3":[18,6] } # to maintain the infinite loop while True: choice=input("Which movie would you like to watch? :").strip().title() if choice in films: # pass # chk us...
0c07e96fa0f943caaff4b9e85b608d276a621a70
spicy-crispy/python
/py4e/exercises/exercise6_5/fileread.py
155
3.734375
4
# Prints each line of a file count = 0 samplefile = open('sample.txt') for i in samplefile: count = count + 1 print(i) print('Line Count:', count)
103db8e8c5eca497360a576b5fa12262e06d63a8
macrdona/UserLogin
/Completed Login App/Hash.py
530
3.765625
4
import hashlib #creating class hash class Hash: #contructor to initialize password def __init__(self, password): self.password = password #return the hash value of the given password '''After the password has been hashed, it is then converted into hexadecimal form. It returns a...
a2fc3ac9e21355322be38cea46e0d77ad1c7b050
AnDsergey13/Bot
/example/ex10_json.py
457
3.796875
4
import json #не использовать модуль pickle!!! data = [ {'a' : 10,'b' : 20,'c' : 30}, {'a' : 100,'b' : 200,'c' : 300}, {'a' : 1000,'b' : 2000,'c' : 3000} ] print(type(data),data) with open('data.json', 'w') as file: data = json.dumps(data) file.write(data) print(type(data),data) with open('data.json') as fil...
0471ebe82c65e3e89281423bfd48b385c1bf47eb
Saigurram235/Mastering-Python
/Ass4.py
1,184
4.375
4
class Box: def area(self): return self.width * self.height def __init__(self, width, height): self.width = width self.height = height # Create an instance of Box. x = Box(10, 2) # Print area. print(x.area()) ''' Write a program to calculate distance so that it takes two Points (x1, ...
f6acd601f877f1e50d2c75843a975b9609403864
daniel-reich/turbo-robot
/BeCSQjqycsY8JadFT_10.py
2,035
4
4
""" Create a **recursive** function that identifies the very first item that has recurred in the string argument passed. It returns the identified item with the index where it **first appeared** and the very next index where it **resurfaced** \- entirely as an object; or an empty object if the passed argument is eit...
13e8ecf4cbd5a978513025bc55891198df20e1b6
tabletenniser/leetcode
/5921_max_path_quality.py
3,882
3.515625
4
''' There is an undirected graph with n nodes numbered from 0 to n - 1 (inclusive). You are given a 0-indexed integer array values where values[i] is the value of the ith node. You are also given a 0-indexed 2D integer array edges, where each edges[j] = [uj, vj, timej] indicates that there is an undirected edge between...
a890e2b834b074b48b470dadc91f02238e898add
nbro/ands
/ands/algorithms/sorting/comparison/heap_sort.py
3,112
4.09375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ # Meta-info Author: Nelson Brochado Created: 09/09/2015 Updated: 19/09/2017 # Description Heap-sort is one of the best sorting methods being in-place and with no quadratic worst-case scenarios. Heap-sort algorithm is divided into two basic parts: 1. Creating...
7b41ad2fad49bb6759dcf61d501224bc51f1f3b3
TimothyRBinding/UniPortfolioV3
/UniPortfolio/ComputerNetworks/CW2/State.py
757
3.515625
4
class State: state = None #abstract class CurrentContext = None def __init__(self, Context): self.CurrentContext = Context class StateContext: stateIndex = 0; CurrentState = None availableStates =[] #availableStates = ["CLOSED", "LISTEN", "SYNSENT", "SYNRECVD", "ESTABLISHED", "FINWA...
9f899133c88e5b284d13f2b286365315132822ca
laferna/python
/Fun_with_Functions.py
1,415
4.8125
5
#Fernandez_Python_Assignment: Fun with Functions #Create a series of functions based on the below descriptions. Odd/Even: #Create a function called odd_even that counts from 1 to 2000. #As your loop executes, print the number of that iteration and specify whether it's an odd or even number. #Your program output shou...
364fc390558435ae387555cf009ff5ad89192da4
pangyouzhen/data-structure
/contest/reverseList.py
655
3.78125
4
from typing import List class Solution: def permute(self, nums: List[int]) -> List[List[int]]: all_ans = [] one_ans = [] def permute_memo(nums, one_ans): if len(one_ans) == len(nums): all_ans.append(one_ans[:]) for i in nums: ...
f82835be88165ccdcbfdb4f8facaab05a83bea4f
zhengxiang1994/JIANZHI-offer
/test1/demo24.py
1,172
3.78125
4
# -*- coding:utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def __init__(self): self.result = [] self.temp = [] # 返回二维列表,内部每个列表表示找到的路径 def FindPath(self, root, expectNumber): # write code...
0b93e8f102c95fae9189001148325937dcb520f9
davide990/IRSW-lab
/PythonApplication1/nltk_ex1.py
3,791
3.8125
4
'''from nltk.book import *''' import nltk import math import numpy def main(): print("hi") ''' Open a text file, tokenize and return an nltk.Text object ''' def open_textfile(fname): f = open(fname, 'r') raw_text = f.read() tokens = nltk.word_tokenize(raw_text) text = nltk.Text(tokens) re...
cc6a6626b17e99079ed2af78acd6d3360be2d84d
JimYin88/ProjectEuler
/Problem036.py
561
3.6875
4
# Created on Jun 2, 2022 # # @author: Jim Yin import time def palin(n): """ :param n: an integer number you are checking whether it is palindrome :return: True if number is palindrome, False otherwise """ return str(n) == str(n)[::-1] def main(): print(sum(i for i in range(1, 10**6) if pal...
6c3b3ec7b02ac86e7fb389ffb3d86d29c4f06742
KickItAndCode/Algorithms
/LeetCode/FindTheDifference.py
675
3.6875
4
# 389. Find the Difference # Given two strings s and t which consist of only lowercase letters. # String t is generated by random shuffling string s and then add one more letter at a random position. # Find the letter that was added in t. # Example: # Input: # s = "abcd" # t = "abcde" # Output: # e # Explanation:...
f8989478af137f6833fb830fe3c4e91b3f9142d6
0010abhi/Python201
/assignment10/assign10_1scrapFromUrl.py
619
3.6875
4
from bs4 import BeautifulSoup import urllib2 ## get url from the user print "We will give you 10 href present in the url." url = raw_input("Please enter the url to scrap data:") ## Read Html Data from Url using urllib2 # url = "https://www.reddit.com" print "Url Accepted:", url.strip() url_to_scrap = urllib2.urlopen(u...
fc374af7587643a9e9edc4d5ac4b12287c3bb535
jiahenglu/VeblenWedderburn
/NumberSystem.py
1,535
3.734375
4
listoflists = [] list = [] for i in range(0,10): list.append(i) if len(list)>3: list.remove(list[0]) listoflists.append((list, list[0])) def numeric_compare(alist1, alist2): list1 = alist1[0] list2 = alist2[0] for i in range(0,len(list1)): if list1[i] != list2[i]: ...
6690e06f240abe5ccd227f41148814bc5d63dfa9
farihanoor/Codecademy
/Data Science/Python Fundamentals/Python Loops/LIST COMPREHENSION - CODE CHALLENGE/Greater Than Two.py
223
3.75
4
""" Create a new list called greater_than_two, in which an entry at position i is True if the entry in nums at position i is greater than 2. """ nums = [5, -10, 40, 20, 0] greater_than_two = [ item > 2 for item in nums]
be1dc507b17ffb8484ca6077a048841e97781300
Ngwind/PycharmProjects
/practise_20180719/if.py
258
3.703125
4
print("hello world!".center(50, "=")) user_id = input("inter the id,please!\n") user_pwd = input("inter the password,please!\n") if user_id == "xiaoming" and user_pwd == "123456": print("welcome! {}\n".format(user_id)) else: print("error!\n")
d47a13ae0fe6c8de5c90852efe91435be06dafca
redoctoberbluechristmas/100DaysOfCodePython
/Day14 - Higher Lower Game/Day14Exercise1_HigherLowerGame.py
1,390
3.9375
4
import random import art from os import system from game_data import data # Need to select two celebrities def choose_accounts(): return random.choice(data) def format_entry(choice): return f'{choice["name"]}, a {choice["description"]}, from {choice["country"]}' def compare_accounts(player_choice, not_choic...
67312b3a6300a8ad00d2ec393655b8ec6f8f9c4d
AdamZhouSE/pythonHomework
/Code/CodeRecords/2163/60677/287625.py
455
3.6875
4
answerlist=[] def recursion(degree,list,answer): if answer.__len__()==degree: answerlist.append(answer[:]) return for i in list: answer.append(i) index=list.index(i) list.remove(i) recursion(degree,list,answer) list.insert(index,answer[-1]) answer....
e6159d10ef6fab6b94d0e1eb6ef39d0e27decaaa
slingam00/Introduction_to_Python
/Collection Data Types/Tuple.py
168
4.03125
4
myTuple1 = (1, 2, 3, 4, 5) myTuple2 = ('a', 1, 'b', 2, 'c', 3') # Indexing print(myTuple1[2]) # Result is 3 # Range Indexing print(myTuple1[2:4]) # Result is (3, 4)
26e995195e3a5dba4c138d9742a9c0fb2038ff00
9998546789/firstpart
/python/lesson1/first/Task4.py
274
3.796875
4
value = int(input("Введите число: ")) remainder = value % 10 last_part = value // 10 while last_part > 0: if remainder == 9: break if last_part % 10 > remainder: remainder = last_part % 10 last_part = last_part // 10 print(remainder)
74fd3c26c2f171e2371e9f05998a03d82dd8f014
apoorva9s14/pythonbasics
/CompetetiveProblems/hash_table.py
1,261
4.03125
4
import pprint class Hashtable: def __init__(self, elements): self.bucket_size = 2 self.buckets = [[] for i in range(self.bucket_size)] self._assign_buckets(elements) def _assign_buckets(self, elements): for key, value in elements: hashed_value = hash(key) ...
c79786b93479280b8b1d1357da5e84893143223d
osdmaria/Hacktoberfest-2k20
/projects/Text Adventure Fantasy Game/adventure.py
5,168
3.8125
4
import random # playables class wizard (object): hp = 100 stregth = 12 defence = 12 magic = 30 class warrior (object): hp = 100 stregth = 30 defence = 18 magic = 10 class elf (object): hp = 100 stregth = 20 defence = 18 magic = 18 # enemies class goblin (object): name = "Goblin" hp = 6...
19aed679c934a30610e1b4f69d818b37e4125559
uamhforever/pyraytrace
/pyraytrace/pyraytrace.py
12,616
3.609375
4
# pylint: disable=invalid-name """ Basic routines for ray tracing To do: * Add lenses and mirrors * Properly document Scott Prahl May 2018 """ import numpy as np import matplotlib.pyplot as plt __all__ = ['Plane', 'Ray', 'Sphere', 'Prism', 'Lens', 'Thin...