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
29092df41091483a72f9bfb8e047c98eaf9d748a
igekaratas/python
/A03.py
719
4.1875
4
# # Name: Mehmet Karatas # SSID: 1640957 # Assignment #: 3 # Submission Date: # Description of program: # Convert upper case to lower case and lower case to upper case # user_input_sentence = input("Enter sentence to convert opposite cases: ") for i in user_input_sentence: if i.isupper(): make_lower = user_input...
382e3bc261316de2e335dbf79e32660468745a73
ProgFuncionalReactivaoct19-feb20/clase06-vysery98
/ejercicio6.py
1,311
4.125
4
""" @vysery98 Programación Funcional: Funciones Puras Efectos Secundarios """ import csv def lineasDiccionario(archivo): return csv.DictReader(archivo, delimiter = ";") with open("data/data-estudiantes.csv") as midata: """ # EN VARIAS LINEAS DE CODIGO # Conversion de la informacion del archivo a lista li...
e14123e2c7099c36677a01b3baf3db1659c43e41
simi1079/host-info
/hostinfo/lib.py
3,785
4.28125
4
from .exceptions import InvalidIP, InvalidHostname def usage(): """ Displays a usage message parameters: none """ how_to_use = """ Usage: hostfile [-args] arguments: # -h: To display help # -r <search_string>: display a list of hosts matching the search_string or all hosts otherwise ...
eb7fb78113f606e27235fb008952bc7d1690ee23
galya-study/ji
/py/7. lists/ex 7 lineup.py
1,255
3.875
4
# Шеренга # Петя перешёл в другую школу. На уроке физкультуры # ему понадобилось определить своё место в строю. # Помогите ему это сделать. # Программа получает на вход невозрастающую # последовательность натуральных чисел, означающих # рост каждого человека в строю. После этого вводится # число X – рост Пети. Все...
b8049dfd432d56d8d4386d274b933034b472c629
cornelialiu/F_CK
/2/P2_check.py
5,118
3.734375
4
##################Assign variables#################### move = [1,1,1] face = 1 #the face panel for print ##################Assign variables#################### n = 3 cube = [[[ k for i in range(n)] for j in range(n)] for k in range(6)] surface = {0:{"top":4,"bottom":5,"left":3,"right":1}, 1:{"top":4,"bo...
c3f60378fb7b2ff8463eabdd0972560dd2285b6e
sajinamatya/ping-pong
/sajin.py
3,971
4.0625
4
import turtle as t # importing the turtle module of python then aliasing it as "t" import os # importing the os module # Score varibales ...
65142d535a6242083c6d1c514b7d4f2210f91dc2
lkrych/get_some_exercise
/util/generate_ex_sol_test.py
1,631
3.71875
4
#easily generate exercise, test and solution files def get_file_suffix(lang): if lang == "python": return ".py" elif lang == "go": return ".go" elif lang == "c": return ".c" elif lang == "cpp": return ".cpp" elif lang == "elixir": return ".ex" elif lang == "ocaml": return ".ml" el...
e05a38ebf1f4485603a1f2885413dba2c9a36275
kongkongo/LeetCode
/strStr.py
761
4.03125
4
# 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回  -1。 # 示例 1: # 输入: haystack = "hello", needle = "ll" # 输出: 2 # 示例 2: # 输入: haystack = "aaaaa", needle = "bba" # 输出: -1 class Solution: def strStr(self,haystack:str,needle:str): """ :type haystack:str :...
bb6805a83ac2cbab1fa733f13c253943d392d4c9
RogerHuba/math-series
/test_series.py
1,089
3.625
4
from series import fibonacci from series import lucas def test_single_number_fib(): """test fibonacci function by bringing in a single number """ actual = 4 expected = 3 assert fibonacci(actual) == expected def test_zero_number_fib(): """test fibonacci function by bringing in a zero number ...
7dbc48457130389295b4390661ba95a6008270c9
kingl4166/CTI-110
/P2HW2_TipTaxTotal_King Lafayette.py
463
3.984375
4
3# CTI-110 # P2HW2 - Tip Tax Total # Lafayette King # 2/3/2018 # TipAmount = 0.18 # salesTax = 0.07 foodcost = float(input('Enter the foodcost')) totalcost = foodcost * 0.07 print('The salestax is $', format (totalcost ,'.2f')) print('totalcost:', foodcost + totalcost ) print('TipAmount:', foodcost * 0...
483aecd558d9407c3cd4cecad53ca6a9650c8d4d
thehanemperor/LeetCode
/LeetCode/Sliding Window/30. Substring with Concatenation of All Words.py
1,110
3.59375
4
# HARD # since we want to find the combined length of [words], means => loop through s[0:len(s)-len(words)] # two loops. # 1. first loop is to check an element as a start of a potential result # 2. second loop is to check if s[i:i+len(words)] a correct substring # Time O(N^2) Space O(N) class Solution: ...
90499d045e890ed155c6247e0727bcbc8a2c1ff0
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4161/codes/1747_3096.py
266
3.6875
4
n = int(input("posicao: ")) s = 0 while n!=0: if n < 0: a = 0 elif n > 0: if n == 1: a = 20 elif n == 2: a = 15 elif n == 3: a = 10 elif (4<=n) and (n<=10): a = 11 - n elif n>10: a = 0 s = s + a n = int(input("posicao: ")) print(s)
3b2e1a8b900f99234cacd464b312e26ba1b738a0
macarro/imputena
/test/simple_imputation/test_knn.py
3,423
3.5625
4
import unittest from imputena import knn from test.example_data import * class TestKNN(unittest.TestCase): # Positive tests ---------------------------------------------------------- def test_KNN_returning(self): """ Positive test data: Correct data frame (example_df) The...
29f0376f513add4449ccb9cf065a3c4e97c82fcf
dimkh/GeekBrains
/course06/hw01/task04.py
962
4.15625
4
import random as rnd # Проверку введённых значений на корректность не провожу # (примеры проверок в начальных заданиях) print('Список генераторов:') print('1 - Случайное целое число') print('2 - Случайное вещественное число') print('3 - Случайный символ') choice = int(input('Выберите генератор: ')) start = input('Вв...
af86337fad6521a77bb678dc49101f509fb06ca6
MisterMomito/Learning
/Algorithms and Data Structures/Data Structures/Trees/Trie.py
1,277
4.46875
4
# time complexity to check if word exists: # O(nm) where n is words in list and m is length of word searched for # time complexity to insert word: O(m) m - length of word added class Trie: def __init__(self): self.root = {'*': '*'} def add_word(self, word): curr_node = self.root for l...
6b61dfcd5c476b603f10679c37b8834757bec0a8
bombpersons/RPGlibs
/tilez/tileset.py
2,371
3.5
4
# Class to contain information about a tileset # Contains: # The data of the actual tileset # The size of the tileset # The size of the individual tiles # # Functions for getting a specific tile (returning a tile structure) # # # # from base import Base from tile import Tile class Tileset (Base): def __init__(self...
58498b99ee95b8c3db802666854e4de0be77f368
TayChak/HackerRank
/Practice/30 Days of Code/Day 0 Hello, World/Day 0 Hello, World.py
318
3.953125
4
# Read a full line of input from stdin and save it to our dynamically typed variable, input_string. input_string = input() # Print a string literal saying Hello, World. to stdout. print('Hello, World.') # TODO Write a line of code here that prints the contents of input_string to stdout. print(input_string)
a80b04f04f3a33390d0b4c46c82ac23b1a373bbf
srikanthpragada/PYTHON_06_MAY_2021
/demo/dbapi/db_to_json.py
464
3.703125
4
# Convert Employees table to JSON import sqlite3 import json import dbutil employees = [] con = sqlite3.connect(dbutil.DBNAME) cur = con.cursor() cur.execute("select * from employees") # SQL Command for id, name, job, salary in cur.fetchall(): employees.append({"id": id, "name": name, "job": job, "salary": sala...
b7f6c945f6e6a214acc50e8104e63a7ed64c02f1
mechanicalamit/learning_python
/project_euler/problem_048.py
125
3.828125
4
print ('this program prints the sum of self powers upto 1000') i=1 a=0 while i<=1000: a=a+pow(i,i) i=i+1 print (a)
413c341139713cebd50ba95f341532ead1bc7590
LevenWin/Algorithm
/Python/Code/Tree/1-17.py
1,048
3.53125
4
# -*- coding: UTF-8 -*- # 给定一个整数N,如果N<1,代表空树结构,否则代表中序遍历的结果为{1,2,3,…,N}。 # 请返回可能的二叉树结构有多少。 # [1...5] # 依次已 j = 1...5为root节点,则左边为 j - 1,右边 n - j个节点 # 如果知道 1个,2个,3个节点能组成多少个二叉树,则n个节点我们都可知。 # i 代表共几个节点 # j 代表当前节点作为root节点 # 如果要求出n个节点能够组成多少种搜索二叉树,则需要知道n-1个节点能组成多少个搜索二叉树 # 依次类推,已知 1个节点能组成一个搜索二叉树,则2个点能组成2个搜索二叉树 # 3个节点能组成 1*2 ...
94ac7b8301ed19dfd454eb4261a257393d5a3b96
zackeua/Kattis
/Completed/synchronizinglists.py
520
3.515625
4
n = int(input()) while n != 0: i = 0 L1 = [] L2 = [] d = {} while i < n: L1.append(int(input())) i += 1 i = 0 L1Sorted = L1.copy() L1Sorted.sort() while i < n: L2.append(int(input())) ...
320b9b21c06b4ac967d5b3717b401dfb2ac6ee84
markanson25/python-fundamentals
/08_file_io/08_00_long_words.py
444
3.9375
4
''' Write a program that reads words.txt and prints only the words with more than 20 characters (not counting whitespace). ''' word_list = [] with open("words.txt", "r") as words: for word in words.readlines(): word = word.rstrip() word = word.lstrip() sep = ' - ' word = word.split(...
b4eee08c445497424f558c9876d100245eb38d0d
Yxav/URI-python
/1020.py
834
3.953125
4
'''Leia um valor inteiro correspondente à idade de uma pessoa em dias e informe-a em anos, meses e dias Obs.: apenas para facilitar o cálculo, considere todo ano com 365 dias e todo mês com 30 dias. Nos casos de teste nunca haverá uma situação que permite 12 meses e alguns dias, como 360, 363 ou 364. Este é apenas u...
c2615f138df326f6febfb907913826ceaf6a9b11
ODCenteno/python_100days
/day_4/rock_paper_scissors.py
3,405
4.09375
4
""" Develop a Rock, Paper, Scissors game """ import random def rules(): print("""\n ________ ________ ____ `MMMMMMMb. `MMMMMMMb. 6MMMMb\ MM `Mb MM `Mb 6M' ` MM ...
cc6b3953d02595791583f02d4c8f565c2a58f60d
lixiang2017/leetcode
/leetcode-cn/0058.0_Length_of_Last_Word.py
764
3.890625
4
''' two while from the end 执行用时:40 ms, 在所有 Python3 提交中击败了22.53% 的用户 内存消耗:15 MB, 在所有 Python3 提交中击败了46.13% 的用户 通过测试用例:58 / 58 ''' class Solution: def lengthOfLastWord(self, s: str) -> int: r = len(s) - 1 while r >= 0 and s[r] == ' ': r -= 1 last = 0 while r >= 0 and s[r] !...
020ebacb9babe487828771e9dc2eb8669d495df5
jpang330/Game
/MASH.py
7,038
3.859375
4
print """ \n\t\t\t\t\t\tWelcome to M.A.S.H This is the abbreviation for Mansion, Apartment, Shack, House. This will make more sense as the game progresses. Have you ever wondered about your future? What car you will drive, your spouse, children and your living situation? Well you are in luck! This game has all the ans...
6e7e20137c2627fc34743f1de6efe10c443aebea
shabbir22/Learn-to-Code
/ch4/pg-131/retrieving_last_item.py
394
4.5
4
###Obtaining the last item of a List breakfast=['Bread','Butter','Banana','Water','Tea'] breakfast[len(breakfast)-1] #We can directly call the last item of that list like this #Conventional way: length=len(breakfast) last=breakfast[length-1] #Since the indexing of the list starts at 0 print(last) #Using Negative In...
8eff68f921e4eb7afe53417daee122120f9cf8ba
jamiegowing/jamiesprojects
/don'tpressthebutton.py
634
4
4
import tkinter window = tkinter.Tk() button = tkinter.Button(window, text="Do not press this button", width=40) button.pack(padx=10, pady=10) clickCount = 0 def onClick(event): global clickCount clickCount = clickCount + 1 if clickCount == 1: button.configure(text=f"this is the {clickCount}st time y...
e93bce7ec2920d83e7f4a1db002325aac254d01d
jmery24/python
/ippython/file_cuenta_caracteres_451.py
550
3.59375
4
# -*- coding: utf-8 -*- """ Created on Sun Jun 30 07:44:00 2013 @author: daniel """ # programa: file_cuenta_caracteres_451 # el programa abre un <file> y cuenta la cantidad de caracteres # ejercicio 451 # abre el fichero y comprueba su existencia try: nombre = raw_input('Nombre del file: ') print fichero...
a539e736b880f3537b7e19f1384602dabf489ab6
EgoSay/show--me-the-code
/004/004.py
652
3.5625
4
# @Author : adair_chan # @Email : adairchan.dream@gmail.com # @Date : 2019/3/1 下午5:45 # @IDE : PyCharm import re from collections import Counter from functools import reduce def create_list(filename): word_list = list() with open(filename, 'r') as f: # 利用正则表达式,‘\b’匹配一个单词边界,即字与空格间的位置,‘+’等价于匹配...
bca469622cdc333211ec50bfb952f698aee7ec69
paulolemus/leetcode
/Python/ransom_note.py
946
3.84375
4
# Source: https://leetcode.com/problems/ransom-note/description/ # Author: Paulo Lemus # Date : 2017-11-09 # Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, ...
39bfcde8d3c971e7dd825461f18602d2c3b3f0d0
mynk-rjpt/Practice
/main.py
227
3.625
4
# print("hello world!") # import math as m # print(m.sin(1)) a = input("Enter Your Name :\n") movies_list = ["Fight Club","Se7en","Inglourious Bastards","Snatch","Twelve Monkeys"] print(movies_list) print(f"Your name is : {a}")
daded0c3cd34fafd63d9e348e2935e33dcd08bc0
Jorge505/Compiladores-y-Traductore
/E3-EjerciciosdePython/fuction.py
286
4.15625
4
'''26-Diseñar una funcion que calcule x^n para x variable real y para n variable entera ''' def calculando(): x = float(input("Ingrese la base de x= ")) n = int(input("Ingrese el valor exponecial de n= ")) return x**n print(f"El resultado de su potencia es de: {calculando()}")
6bbc1dd7e36e2c5ecec8b459c0281c23469a694f
Adrianozk/exercicios_python
/resolucoes/ex059.py
945
4.125
4
# leia 2 valores e mostre um menu na tela # 1 somar # 2 multiplicar # 3 maior # 4 novos numeros # 5 sair do programa # seu programa deverá realizar a operação solicitada em cada caso from time import sleep opcao = 0 while opcao != 5: valor1 = float(input('1º Valor: ')) valor2 = float(input('2º Va...
1088dc673d2065d4447e87ee145ad557f80e0808
noscetemet13/pp2_2021
/TSIS1/conditionals/a.py
91
3.875
4
a=int(input()) b=int(input()) if(a>b): print(a) elif(a<b): print(b) elif(a==b): print(a)
5282edc67e38085fb06976cbd9a1c55238b63b56
RishabhGoswami/Algo.py
/Vertical ttraversal .py
959
3.703125
4
class Node: def __init__(self,data): self.left=None self.right=None self.nextRight=None self.data=data def vertical(root): l=[] l.append(root) m={} hd={} hd[root]=0 m[0]=[root.data] while(len(l)>0): a=l.pop(0) if(a.left): l...
67e363f491fbec26648890baa95f2fcea4db7799
DemonZhou/leetcode
/minStack.py
1,274
3.984375
4
class MinStack(object): def __init__(self): """ initialize your data structure here. """ self.stack = [] self.minstack = [] def push(self, x): """ :type x: int :rtype: None """ self.stack.append(x) if len(self.minstack) =...
8ad97112489397fe689d6e40833e4d860787ec67
Mitterdini/Learning-The-Hard-Way
/Python/Scripts/write_files.py
1,866
4.03125
4
from sys import argv #Import the argument module import os #Allows for terminal commands script, filename = argv #Set script name and gets the target file name from the terminal command print(f"""\nThis script will er...
ad2f6648b4306ac0436f87746bef147dfb923663
Hoshizx/CryptographyPython1
/cryptography.py
261
3.671875
4
while True: msg = input("メッセージ: ") result_cryptography = " " i = len(msg) - 1 while i>=0: result_cryptography = result_cryptography + msg[i] i = i-1 print("コード結果: "+ result_cryptography)
7e1b616c60bd3e8c8bd2c13ba738725ab123f775
pooya-shams/computer-vision-course
/lessons/opencv 2nd session/bitwise_operation.py
534
3.5625
4
import cv2 circle = cv2.imread("circle.png") rectangle = cv2.imread("rectangle.png") And = cv2.bitwise_and(circle, rectangle) # -> (image 1, image 2, mask which means part(optional)) --> returns bitwise gate of any pixel in two images(they should be the same size) Or = cv2.bitwise_or(circle, rectangle) Xor = c...
4ebae15572a09028708b73d793619d880a88d2b1
elshadow11/Prog
/ejercicios terminados/Python/estructuras alternativas/act1.py
667
4.03125
4
#Programa: act1.py #Propósito: Algoritmo que pida dos números e indique si el primero es mayor que el segundo o no. #Autor: Jose Manuel Serrano Palomo. #Fecha: 17/10/2019 # #Variables a usar: # n1 y n2 serán los número que vamos a pedir al usuario # #Algoritmo: # LEER n1,n2 # Comparar n1 y n2 # Escribir si n1 es mayor...
3a412acd11e5acb5819b5fa09c6aeb798a148698
Renqianbei/python_study
/pythonBase/text_16_类对象的.py
985
3.875
4
#! /usr/bin/env python # -*- coding: utf-8 -*- #类的专有方法: #__init__ : 构造函数,在生成对象时调用 #__del__ : 析构函数,释放对象时使用 #__repr__ : 打印,转换 #__str__ #__setitem__ : 按照索引赋值 #__getitem__: 按照索引获取值 #__len__: 获得长度 #__cmp__: 比较运算 #__call__: 函数调用 #__add__: 加运算 #__sub__: 减运算 #__mul__: 乘运算 #__div__: 除运算 #__mod__: 求余运算 #__pow__: 乘方 #运算符重载 cl...
57b28d54a7f0a77330795b85120cbbe6d68127c6
grosa1/bankAccountExample
/BankAccount.py
919
3.53125
4
from CustomerAccount import CustomerAccount class BankAccount(CustomerAccount): __balance = 0 def __init__(self, owner, accountNumber, balance): super().__init__(owner, accountNumber) self.__balance = balance @property def balance(self): return self.__balance @balance...
b4a1d9992332e4e26862229606655fab1ffd82ab
pingting420/LeetCode_Algorithms
/Tree/LC144. Binary Tree Preorder Traversal.py
614
3.71875
4
#recursive def preorderTraversal(root): def preorder(root): if not root:#结束的条件 return res.append(root.val) preorder(root.left) preorder(root.right) res = list() preorder(root) return res #Time Complixity: O(N) #Iterative def preorderTraversal2(root): res...
f3cfedd285ceb131de6fc411fffad2601817a319
OZ1LQO/NTC_Class
/NTC_py2.py
7,136
3.609375
4
#Class to work with NTC Thermistors in Python 2 #Fell free to modify, improve, hack! #Note! Temperature range is limited to a range between 1 and 98C #OZ1LQO 2014.05.29 import math from scipy import interpolate class Ntc(object): """A class to work with NTC Thermistors. Input, is B, Rn (resistance at Tn), ...
42e920ad1a6494a41e604e007ae9253a85b6f6cc
alexlikova/Python-Basics-SoftUni
/3. Conditional Statements Advanced - Lab/08. On Time for the Exam.py
3,794
4.03125
4
""" hour_exam = int(input()) # 0...23 min_exam = int(input()) # 0...59 hour_arrival = int(input()) min_arrival = int(input()) total_min_exam = (hour_exam * 60) + min_exam # 9:30 exam --> 570 min total_min_arrival = (hour_arrival * 60) + min_arrival # 9.00 arrival --> 540 min // 8.30 arrival --> 510 min difference = t...
8f296632488fde9b6a9e149adb5a604ed27e0304
ritumehra/trainings
/basics_python/operators.py
1,757
4.4375
4
# Operators print("=========== Arithmetic Operators =============") x = 5 y = 2 # Output: x + y = 7 print('x + y =', x + y) # Output: x - y = 3 print('x - y =', x - y) # Output: x * y = 10 print('x * y =', x * y) # Division Returns Exact Quotient # Output: x / y = 2.5 print('x / y =', x / y) # Floor Division : R...
535bf60da7ee456a43758101f71283572004f222
alonglob/AtBS
/Chapter_15/time_demo_2.py
1,535
4.21875
4
#! /usr/bin/python3.7 # The Datetime Module import time import datetime # Create a datetime object: dt = datetime.datetime.now() # the datetime methods: print('year: ' + str(dt.year)) print('day: ' + str(dt.day)) print('time: ' + str(dt.hour) + ':' + str(dt.minute) + ':' + str(dt.second)) # Convert Unix epoch timest...
e1b4fac4aec6d337ac63619b93cc0096a566c3d8
SimeonTsvetanov/Coding-Lessons
/SoftUni Lessons/Python Development/Python Fundamentals September 2019/Problems And Files/23 DICTIONARIES - Дата 6-ти ноември, 1830 - 2130/02. Stock.py
1,365
3.890625
4
""" Dictionaries - Lab Check your code: https://judge.softuni.bg/Contests/Practice/Index/1736#1 SUPyF2 Dictionaries-Lab - 02. Stock Problem: After you have successfully completed your first task, your boss decides to give you another one right away. Now not only you have to keep track of the stock, but also y...
d3beab3e0c9a6c84566179647d75504ac4bdb056
KoeusIss/holbertonschool-machine_learning
/supervised_learning/0x0D-RNNs/0-rnn_cell.py
1,365
3.625
4
#!/usr/bin/env python3 """RNN module""" import numpy as np class RNNCell: """RNNCell class """ def __init__(self, i, h, o): """Initializer Arguments: i {int} -- Is dimensionality of the data h {int} -- Is dimensionality of hidden state o {int} -- Is dim...
4e7cfd913464be0d7b16a6031cf086f6bc2a8d83
chrom/python_advanced
/lesson_5/thread_decorator.py
1,027
3.609375
4
# 1) Создать декоратор, который будет запускать функцию в отдельном потоке. # Декоратор должен принимать следующие аргументы: # название потока, является ли поток демоном. import functools from threading import Thread import time def decorator(name: str, id_demon: bool): def actual_decorator(func): @funct...
ea396e64ca3b1bf76952c1be36cd521a92a0a354
GitZW/LeetCode
/leetcode/editor/cn/[1518]换酒问题.py
1,457
3.609375
4
# 小区便利店正在促销,用 numExchange 个空酒瓶可以兑换一瓶新酒。你购入了 numBottles 瓶酒。 # # 如果喝掉了酒瓶中的酒,那么酒瓶就会变成空的。 # # 请你计算 最多 能喝到多少瓶酒。 # # # # 示例 1: # # # # 输入:numBottles = 9, numExchange = 3 # 输出:13 # 解释:你可以用 3 个空酒瓶兑换 1 瓶酒。 # 所以最多能喝到 9 + 3 + 1 = 13 瓶酒。 # # # 示例 2: # # # # 输入:numBottles = 15, numExchange = 4 # 输出:19 # ...
a046edba7d567d011c82ea9cac67bb2ec45e9c93
SqrtiZhang/2019.Python-DL_ASS1
/Lab1/weather.py
1,900
3.5
4
import json from urllib import parse from urllib import request from urllib.request import urlopen #天气api接口 class weather(): def __init__(self): self.__appkey="4a1e38a63ef132cfd0de382d4b4b9338" def RequestCitySupp(self,m="GET"):#获得支持城市,但这个没有用到 url = "http://v.juhe.cn/weather/citys...
2e4d5a2609e787f31dcc9d4bb145256316ac2e80
ihuei801/leetcode
/MyLeetCode/python/Max Chunks To Make Sorted.py
959
3.640625
4
### # Array # The basic idea is to use max[] array to keep track of the max value until the current position, # and compare it to the sorted array (indexes from 0 to arr.length - 1). # If the max[i] equals the element at index i in the sorted array, then the final count++. # For example, # original: 0, 2, 1, 4, 3, 5...
6e4ceea957e9fc42858560b323a9647e0de16232
tjvick/advent-of-code
/2019_python/solutions/day1/part1.py
183
3.578125
4
import math sum = 0 with open('input.txt', 'r') as f: for line in f: mass = int(line.strip('\n')) fuel = math.floor(mass / 3) - 2 sum += fuel print(sum)
d183c61473855a28d3455c0bea125b4cacaf56dd
mmpoko/PIC_EpochDataAnalysis
/bincount2d.py
397
3.734375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np def bincount2d(arr, bins=None): if bins is None: bins = np.max(arr) + 1 count = np.zeros(shape=[len(arr), bins], dtype=np.int64) indexing = np.arange(len(arr)) for col in arr.T: count[indexing, col] += 1 return count ...
3bf5d04cc8b39d4becb36d1b3a8badc84e510314
huffmp2/python
/parrot2.py
247
3.96875
4
prompt = input("Tell me something, and I will repeat it back to you: ") prompt+= "\nEnter 'quit' to end the program. " active= True while active: message = input(prompt) if message == 'quit': active = False else: print(message)
ca2fcd087a31b1f25161293d1b7aa1713dfb83da
MacoChave/Compi2-JOLC
/ts.py
1,121
3.578125
4
class Simbolo() : id = '' valor = None data_type = None def __init__(self, id, valor = None, data_type = None) -> None: self.id = id self.valor = valor self.data_type = data_type def __str__(self) -> str: return f'id: {self.id}, valor: {self.valor}, data_type: {...
1d9c6b740c40d6389185e3edd2f1587095f1bb15
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_136/3530.py
1,127
3.515625
4
#B: Cookie clicker alpha ''' count time to get to n farms. if time to get to n-1 farms then to the end is less, this time is the answer increase values of n from 0 until this occurs ''' prob_file = open('B-small-attempt0.in', 'r')#open the file containing the problems out_file = open('out_b.txt', 'w') ...
ecbd16b4257fcb9a1838e6ebca72a9307b673488
linshaoyong/leetcode
/python/array/0985_sum_of_even_numbers_after_queries.py
858
3.5625
4
class Solution(object): def sumEvenAfterQueries(self, A, queries): """ :type A: List[int] :type queries: List[List[int]] :rtype: List[int] """ v = sum([a for a in A if a % 2 == 0]) res = [] for query in queries: before_even = A[query[1]] % ...
731a82c0fd1a4ef6b34bfbee9484a3849c2778f1
Captain02/LearningNotes
/python/code/lesson_07/01.异常.py
398
3.71875
4
print('hello') try: #try中放置的是由可能出现错误的代码 print(10/0) except: # except中放置的是出错以后的处理防暑 print("出错了") else: print("程序正常执行没有错误") print('你好') def fn(): print("Hello fn") # print(a) print(10/0) def fn2(): print("hello fn2") fn() def fn3(): print("hello fn3") fn2() fn3()
c0ceae8b805f4dc652c418772064c6c014035f5c
Guan-Ling/20210125
/6-6.py
265
4
4
# Given a sequence of non-negative integers, where each number is written in a separate line. # The sequence ends with 0. Print the sum of the sequence. # 1 7 9 0 # 17 # 輸入直到0 印出總和 n=int(input()) m=0 while n!=0: n=int(input()) m=m+n print(m)
90bba051c94e23db5242d5dc24f18785e1865f16
johnibarra/8-weekof10-7
/thisweek.py
2,864
4.21875
4
# more strings and text X = "there are %d types of people." % 10 binary = "binary" doNot = "don't" y = "Those who know %s and those who %s" % (binary, doNot) print(X) print(y) print("I said: %r.:" % X) print("I also said : '%s' ") hilarious = True jokeEvaluation = "isn't that joke so funny?! %r" print(jokeEvaluati...
e200e7c4134316036322852f6ea722ac95a107a9
bssrdf/pyleet
/D/DigitCountinRange.py
1,861
3.796875
4
''' -Hard- Given an integer d between 0 and 9, and two positive integers low and high as lower and upper bounds, respectively. Return the number of times that d occurs as a digit in all integers between low and high, including the bounds low and high. Example 1: Input: d = 1, low = 1, high = 13 Output: 6 Expla...
5da3dfab50685e04ba5e435a7bf09a42765a9265
kurijlj/IPython-Environment
/environment.py
4,056
3.609375
4
from os import listdir from os.path import isdir, exists class OsDirectory(object): """Wrapper for common os module directory functions. Attributes: _path (str): string representing path to directory. If not provided on instantiation '.' is used as default value. ""...
cf49fa793bd69e05e3b92ffe6cd96c09342ef6cd
SzczotkaKamil/pp1
/02-ControlStructures/After Class/zad44.py
625
3.5
4
try: podanyLimitPredkosci = int(input("Podaj limit prędkości: ")) podanaPredkosc = int(input("Podaj prędkość pojazdu: ")) if podanaPredkosc-podanyLimitPredkosci<=0: mandat=0 print("Mandat (zł):",mandat) elif podanaPredkosc-podanyLimitPredkosci>0 and podanaPredkosc-podanyLimitPredkosci<=1...
d6f0116394d93a2408b4a40d9b07c0e930dd30bd
ggerod/Code
/PY/quicksort.py
755
4.09375
4
#!/usr/bin/python3 def swap(arr,n1,n2): temp=arr[n1] arr[n1]=arr[n2] arr[n2]=temp def partition(arr,p,r): #print("in partition") q=p for j in range(p,r): if(arr[j] <= arr[r]): swap(arr,j,q) q+=1 swap(arr,r,q) return(q) def quicksort(arr,p,r): #prin...
f33f17a90649db9b20eb24afe0c1e9aafc247c49
HaydenInEdinburgh/LintCode
/167_add_two_numbers.py
951
3.859375
4
""" Definition of ListNode """ class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next class Solution: """ @param l1: the first list @param l2: the second list @return: the sum list of l1 and l2 """ def addLists(self, l1, l2): # w...
1d2b5993d112bcf4b8a499073a4d199f8a0a0253
UweZiegenhagen/Py3-Kurzanleitung
/Codes/inout.py
238
3.75
4
print('Hallo Welt!') print('Hallo', 'Welt') name = input('Geben Sie Ihren Namen ein: ') alter = input('Geben Sie Ihr Alter ein: ') print('Hallo, ' + name) print('In einem Jahr sind Sie ' + str(int(alter)+1) + ' Jahre alt' )
d73c64f48ac1da3a188dabd4e44d150e40ef2148
GeorgeS1995/education
/test_rec(infinite).py
214
3.5625
4
import time def countdown(i): print(i) if i > 0: time.sleep(0.25) i -= 1 countdown(i) else: return print('STOP') countdown(int(input('Залупим?')))
61771dab1f6d7b42ccbdd50d3325382a43946b22
Tiburso/Trabalhos-IST
/FP/Treino Exame/ex 4.py
523
3.515625
4
from random import random def euromilhoes(): def insere_ordenado(lista,n): if n < lista[0]: return [n] + lista[0] else: numeros = [] estrelas = [] while len(numeros) != 5: num = round(random()*100)+1 if not(num > 50 or num in numeros): ...
eb2d3f27236ab936a72a589d36f91bd8c7ba6fab
HuggyHugMe/tunacell
/tunacell/simu/main.py
11,110
3.75
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ The purpose of numerical simulations is to simulate growing and dividing cells: a process must be defined to sample instantaneous, single cell growth rate, to relate the instantaneous growth rate (in units of time) to cell size, and then to sample size regulation throug...
a27ad868cd5b92cee52270ae537478d2cedee289
KETULPADARIYA/Data-Structure-and-Algorithem-in-Python
/src/Chapter6Trees/BinaryTreeNode.py
1,233
3.875
4
class BinaryTreeNode: def __init__(self,data,left =None,right = None): self.data = data # root data self.left = None self.right = None def setData(self,data): self.data = data def getData(self): return self.data def setLeft(self,object): self.left = obj...
d3ccaee3467e936a869eeef426d63c93002a936a
pengzhang-cd/jia-yi
/BeautifulSoup/bs_bookstore_classification.py
731
3.578125
4
# 调用requests库 import requests # 调用BeautifulSoup库 from bs4 import BeautifulSoup # 返回一个response对象,赋值给res res = requests.get('http://books.toscrape.com/') # 把res解析为字符串 html = res.text # 把网页解析为BeautifulSoup对象 soup = BeautifulSoup( html,'html.parser') # 通过匹配属性class='books'提取出我们想要的元素 # items = soup.find_all('div',class_='s...
39f30c24c985a8a23e3566ee3090e3d99d18a2f4
X9X/leetcode_python
/solutions/reverseInteger.py
261
3.6875
4
def reverse : digits = ('' + x).split(''); isPositive = True; if digits[0] === '-' : isPositive = False; digits = digits.splice(1) # number = parseInt(digits.reverse().join(''),10); # return isPositive ? number : 0 - number;
b8e686e0b4943f7362872e22687c4e6801df578f
SourabhMohite/Python-programs
/Assignment2_10.py
400
3.921875
4
"""Write a program which accept number from user and return addition of digits in that number. Input : 5187934 Output : 37 """ def Sumdigit(num): sum=0 digit=0 while num!=0: digit=num%10 sum=sum+digit num=num//10 return sum def main(): value=int(input("Enter the number:")) add=Sumdigit(value...
a973a9f6b133f5d71ce133823cb023261e1dda33
misrab/bioinformatics-1-ucsd
/week1/Complement.py
345
3.765625
4
INPUT = 'foo.txt' with open(INPUT, 'r') as myfile: data=myfile.read() result = [] for letter in data: if letter == 'G': result.append('C') if letter == 'A': result.append('T') if letter == 'T': result.append('A') if letter == 'C': result.append('G') result.reverse() ...
2ad6986a2efdbe98d40a962ad44309510860d3f9
dbanerjee/ctci-5th-ed
/chp02_linked_lists/2_4.py
1,399
3.96875
4
# Solution to Exercise 2.4 from Cracking the Coding Interview, 5th Edition # Nitin Punjabi # nptoronto@yahoo.com # https://github.com/nitinpunjabi # # Assumptions: # - Singly linked list has a tail pointer import linked_list as lst import doubly_linked_list as dublst def partition_singly(x, singlst): be...
afe9f0ae4f63ecf90d7337ddcbf116626b00bce6
vikkastiwari/The-Joy-Of-Computing-Using-Python
/week4/birthdayparadox.py
1,858
3.921875
4
# -*- coding: utf-8 -*- """ Created on Sun Mar 22 18:40:16 2020 @author: user """ import random import datetime birthday=[] i=0 while(i<50): year = random.randint(1895,2019) # print(year) if(year%4==0 and year%100!=0 or year%400==0): leap=1 else: leap=0 month=rando...
e6744ab3e4cc6764b9501c6d88aa5c410c942269
MaxwellVale/Homeworks
/AI Python/Normie/TicTacToe/TicTacToe-AllBoards.py
4,158
3.859375
4
#! usr/bin/python3 import sys # Counting the total number of possible games and resulting game boards in the Tic-Tac-Toe solution set # Layout positions: # 0 1 2 # 3 4 5 # 6 7 8 # Counter for the total number of possible games of Tic-Tac-Toe # Games end when one side wins or when the board is filled (after 9 moves)...
2f16d69d33ae2c55e0d4082c113569a710311f11
masoodch/DataloaderJSON
/Dataloader_User_JSON.py
851
3.546875
4
import csv domain = input("Please enter the customer primary email domain: ") root = input("Enter the Root Path: ") newRoot = str(root.replace("\\", "\\\\")) with open('famcs.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 for row in csv_reader: if li...
2fea8ca2e7d7c52aee82bb986db00ac6d6198c6a
nagybalint/advent-of-code-2020
/day_10/task2.py
1,388
3.84375
4
import os from typing import List from task1 import parse_input ways_of_finishing_from_index = {} def calculate_answer(in_list: List[int]) -> int: in_list.sort() in_list = [0] + in_list + [in_list[-1] + 3] return get_ways_to_finish_from(0, in_list) def get_ways_to_finish_from(index: int, in_list: List[in...
0a0d7544453850fd688796ab3003f23a49e8b7a0
vlad-bezden/py.checkio
/scientific_expedition/seven_segments.py
2,914
4.03125
4
"""Seven Segments. https://py.checkio.org/en/mission/seven-segment/ You have a device that uses a Seven-segment display to display 2 digit numbers. However, some of the segments aren't working and can't be displayed. You will be given information on the lit and broken segments. You won't know whether the broken segme...
4dd3e0ec919c080de2e4a09c2ddec5ac762541ef
ronaldsimamora/kode-python
/string.py
431
3.671875
4
def main(): #membuat string str1 = 'Ini string menggunakan petik tunggal' str2 = "Ini string menggunakan petik ganda" str3 = """Ini adalah string panjang yang ditulis menggunakan tanda petik sebanyak tiga kali. Jenis string ini digunakan untuk teks yang terdiri dari beberapa teks""" ...
f367fd83e424a2768805bc518551c52a122c3cde
NahHyun-Kim/PythonProject
/CodeitPython/파이썬_1/practice/토픽2_리스트_활용.py
2,757
3.9375
4
# 실습과제(learn92) greeting의 원소를 모두 출력하는 프로그램 작성 greetings = ["안녕", "니하오", "곤니찌와", "올라", "싸와디캅", "헬로", "봉주르"] i = 0 while i < len(greetings): # greetings 배열의 길이만큼 출력(while 반복문 실행) print(greetings[i]) i = i + 1 # 실습과제(learn96) 화씨 온도를 섭씨 온도로 바꿔주는 프로그램 # 섭씨와 화씨의 관계씩 섭씨 = (화씨 - 32) * 5 / 9 def fahrenheit_to_celsiu...
bd079e73306cf6c930d1918c0fbf97c20d3d9646
kobi-ed/file_finder
/file_finder.py
591
3.796875
4
# /usr/bin/env python 3 # Implementation of the file_finder.py program # Locates a file in the current directory # Based on the os.walk() function # Copied from Python Projects by Laura Cassel and Alan Gauld import os, re import os.path as path def find_file(pattern, base='.'): """Find the file in base based on t...
6f4caf812cdaaa5f583b7501c6b1d8cf3bd109db
NeenaBenny1995/Luminaronlineclassneenabeny
/collections/set/difference.py
185
3.71875
4
st1={1,2,3,4,5,6,7,8,9,10} st2={5,6,7,8,9,10,11,12,13,14,15} st=st1.difference(st2) print(st)#elemet in set1 not in set2 std=st2.difference(st1) print(std)#elements in set2 not in set1
71db57c6f5cc231e059d85a8fc99680b258e249e
0TonyAnt0/Apuntes
/04 Escuela de Machine Learning/01 Curso de Introducción al Pensamiento Computacional con Python/programas/practica2_ciclos.py
351
3.625
4
contador_externo =0 contador_interno =0 while contador_externo < 5: while contador_interno < 6: print(contador_externo, contador_interno) contador_interno += 1 contador_externo += 1 contador_interno = 0 contador2 =0 x = 0.0 for i in range(10): x += 0.1 if x == 1.0: print(f'x = {x}...
c8965645a9f9938c5a2f1f7b0d25bdc57c06be43
Nikolay-spec/MyWorks
/Laboratory2/lab2.2.0.py
788
3.859375
4
""" Використовуючи алгоритм Евкліда, знайти НСД двох чисел. """ flag = "" while flag == "": def T(): while True: try: x = int(input()) y = int(input()) if x <= 0 or y <= 0: print("Not real") else: ...
be561fa6dfce23f524d69e73f90cbc4afa963d0c
DenBlacky808/Python-Developer
/generators finding pair in two lists.py
204
4
4
fruits_1 = ['apples', 'pears', 'bananas', 'orange', 'lime'] fruits_2 = ['pears', 'tangerines', 'dragonfruit', 'pomelo', 'lime'] result = [fruit for fruit in fruits_1 if fruit in fruits_2] print(result)
f24886a3b54bffeea3d906247723ecc4647d1727
Cuboxylate/PairwiseAlignment
/NeedlemanWunsch.py
4,368
3.65625
4
from platform import python_version print("python", python_version()) import numpy as np print("numpy", np.version.version) import pandas print("pandas", pandas.__version__) import numpy as np # F matrix, sequence A in row, B in col def get_F_matrix(A, B, match=1.0, mismatch=-1.0, gap=-2.0): # The dimension of ...
01547cbe3e2945d6f62c517ef80600606d65d8a5
skhortiuk/python_course
/lab_7/main_5.py
207
3.90625
4
#! /usr/bin/python3 # -*- coding: utf-8 -*-S letters = ['a', 'o', 'u', 'i', 'e', 'y'] def num_of_letter(line: str) -> int: return sum([line.count(i) for i in letters]) print(num_of_letter(input()))
6a72924aa9b5ceeb2a287e74596c97d87fe986d0
schafer14/Complexity
/DLList.py
556
3.5625
4
class DLList(object): def __init__(self, nl=[]): self.nl = nl self.last = None self.first = None def __str__(self): return str(self.nl) def __len__(self): return len(self.nl) def append(self, node): if(len(self) > 0): try: node.prev = self.last self.last.next = node self.last = node ...
b2e0532fd31b35c23b88ab672c37efca3893dc16
dorond/zomato-eda
/region_scraper.py
1,282
3.640625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue May 29 10:52:14 2018 @author: dorondusheiko """ import requests from bs4 import BeautifulSoup import pandas as pd response = requests.get('https://en.wikipedia.org/wiki/List_of_Cape_Town_suburbs') content = response.content parser = BeautifulSoup(cont...
3268726a1f3303ae937b2ff35ae4bf8e1d77ac5b
LoganHentschel/csp_python
/CSP_Sem1/Living_Code_Final/color_turtle.py
679
3.96875
4
#change colors of a turtle turlte based on key press #turtle must be turtle shape #r is red, b is blue, g is green, c is black import turtle screen = turtle.Screen() # # # # # # # def change_red(): color_turtle.color('red') def change_blue(): color_turtle.color('blue') def change_green(): color_turtle.col...
bd49458006542ad8b6742a9517a127f90e8b5b27
TheNoumanDev/Python-Small-Functions
/Insertion_Sort_Algorithm.py
1,191
4.21875
4
# Program = Insertion Sort Algorithm. # Muhammad Nouman Butt # (Github : https://github.com/Nouman0x45) (Linkedin : https://www.linkedin.com/in/nouman0x45/) # Necessary Variable L = [] # input Function to take Integer Input def int_input_function(arr): size = int(input("Enter the Array Size: ")) j =...
af75c195e5c3f56e5b7b5fdab7405c1ea4bc5f12
tuongviatruong/hangman.py
/hangman.py
4,814
3.9375
4
from random import choice def choose_word(): """randomizes a list of words""" secret_words = ["postcard", "icecream", "pencil", "hike", "almond", "laptop", "travel", "picture", "island", "adventure", "balloon", "elephant", "computer", "water", "paper", "backpack"] secret_word = choice(secret_words) sec...
99bf1913dfcf394ebd754709175a2fed8bf2ac32
linminhtoo/algorithms
/DP/medium/longestPalindrome.py
2,416
3.578125
4
# https://leetcode.com/problems/longest-palindromic-substring/submissions/ # nice DP solution # https://leetcode.com/problems/longest-palindromic-substring/discuss/151144/Bottom-up-DP-Logical-Thinking class Solution: # mine but not the fastest, since I have to loop twice. time O(N^2) def longestPalindrome(self, S...
380ca299eba6dcdb7a5d3611d3aa2d05b754b6f0
kjspgd/aoc2020
/6/aoc6.py
812
3.5
4
#!/usr/local/bin/python3 with open("input.txt", "a") as file: file.write("\n") file.close() sum=0 cumulline='' commonanswers=[] newsetindicator = True for line in open("input.txt"): #print(str(len(line))) if len(line) != 1: #print("not yet") cumulline += line.rstrip() currentline = [] ...
2ec0328dfa2c15420b622cceade99b34155120d1
silpaps/mypython
/Test2/6thproblem.py
677
3.578125
4
class Student: def __init__(self,name,rlno,dept,mark): self.n=name self.r=rlno self.d=dept self.m=mark def pval(self): print("name is ",self.n) print("rolno is",self.r) print("dept is",self.d) print("mark is",self.m) def __str__(self): ...