blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
4a88cf718ed3acc7a0eb35567a01d7cba892b68d | inwk6312winter2019/week4labsubmissions-yaoruohan | /lab[5]Task[8].py | 391 | 3.796875 | 4 |
class Point:
def __init__(self,x=0,y=0):
self.x=x
self.y=y
def __str__(self):
return "The Points are ({},{})".format(self.x,self.y)
def __add__(self,ob):
print (self.x+ob.x,self.y+ob.y)
def add(self,ob):
if isinstance(ob,tuple):
print(self.x+ob[0],self.y+ob[1])
else:
print(self+ob)
o1=Point(15... |
0889cd702882e6ed1fea4853d1589b06861a5394 | Greesha1337/python_basic_11.05.2020 | /les4_hw/task2.py | 1,276 | 4.03125 | 4 | # Lesson 4 HomeWork - Task 2
"""
Представлен список чисел.
Необходимо вывести элементы исходного списка, значения которых больше предыдущего элемента.
Подсказка: элементы, удовлетворяющие условию, оформить в виде списка.
Для формирования списка использовать генератор.
Пример исходного списка: [300, 2, 12, 44, 1, 1, 4,... |
9281712cd7e51aaf61586d09ffa27f40a9b1c57b | Greesha1337/python_basic_11.05.2020 | /les3_hw/task1.py | 2,205 | 4.5 | 4 | # Lesson 3 HomeWork - Task 1
"""
Реализовать функцию, принимающую два числа (позиционные аргументы)
и выполняющую их деление. Числа запрашивать у пользователя,
предусмотреть обработку ситуации деления на ноль.
"""
def degree_func(a, b):
"""Возвращает частное от деления
a, b - позиционные аргументы, запрашив... |
93655ca1e0923060d17c2f314348725c3cc12567 | Greesha1337/python_basic_11.05.2020 | /les3_hw/task5.py | 1,579 | 4.0625 | 4 | # Lesson 3 HomeWork - Task 5
"""
Программа запрашивает у пользователя строку чисел, разделенных пробелом.
При нажатии Enter должна выводиться сумма чисел.
Пользователь может продолжить ввод чисел, разделенных пробелом и снова нажать Enter.
Сумма вновь введенных чисел будет добавляться к уже подсчитанной сумме.
Но если... |
8b5d4fee5aeb15a62865e378a419eae5d9b05251 | Greesha1337/python_basic_11.05.2020 | /hw5/hw5_task2/task2.py | 835 | 4.34375 | 4 | # Lesson 5 HomeWork - Task 2
"""
Создать текстовый файл (не программно), сохранить в нем несколько строк,
выполнить подсчет количества строк, количества слов в каждой строке.
"""
with open('my_file.txt', encoding='UTF-8') as user_file:
content = user_file.read()
print(f'В файле записаны следующие данные: \n\n... |
c14e648a5176a66eaae5d7d09213d8bb2c8de637 | Greesha1337/python_basic_11.05.2020 | /les6_hw/task2.py | 1,459 | 4.5625 | 5 | # Lesson 6 HomeWork - Task 2
"""
Реализовать класс Road (дорога), в котором определить атрибуты:
length (длина), width (ширина).
Значения данных атрибутов должны передаваться при создании экземпляра класса.
Атрибуты сделать защищенными.
Определить метод расчета массы асфальта, необходимого для покрытия всего дорожного... |
381c0db40bc9315e96f589e36c8a14335cecd72c | ohikhatemenG/Sentimental-Analysis-Model | /Sentimental model.py.py | 3,830 | 3.84375 | 4 | #!/usr/bin/env python
# coding: utf-8
#
# THE APPLICATION OF TEXT DATA FOR SENTIMENTAL ANALYSIS
Text Data is one of the type of data,and can be use for sentimental analysis. The dataset used for
this project contains label for the emotional content(such as happiness, sadiness and anger) of texts. The dataset contai... |
e07ea976343e4de62cdf0078e3952f08f3405cf1 | ashokanumandla100/python-utils | /command_pattern.py | 774 | 3.78125 | 4 | # Command Pattern: Controlling the sequence of operations
from abc import abstractmethod,ABC
class Command(ABC):
@abstractmethod
def execute(self):
pass
class Copy(Command):
def execute(self):
print('Copying...')
class Paste(Command):
def execute(self):
print('Pasting...')
cl... |
2366a1c52e8057dac14a920040f48f99d2de3b92 | kajal1122/python_practice | /listValues.py | 228 | 3.875 | 4 | """ Make a list of all even num b/w 1-10 and print it """
list = []
for i in range(1,11):
if(i % 2 == 0):
list.append(i)
print(list)
list2 = [x for x in range(1, 11) if x % 2 == 0]
print(list2)
# packing unpacking
|
65eac02bcd1df830f03f9e5743548043fc97b987 | jydoskey/Data-Visualization | /cube_plot.py | 523 | 3.796875 | 4 | import matplotlib.pyplot as plt
#Define the values to be used
x_cube = [1, 2, 3, 4, 5]
y_cube = [1, 8, 27, 64, 125]
#Make the plot
plt.scatter(x_cube, y_cube, c=y_cube, cmap=plt.cm.Oranges, edgecolor='none', s=40)
#Labelling of the axis
plt.title('Cube Plot of first 5 Numbers', fontsize='14')
plt.xlabel('First 5 Num... |
6fc9121818424a3f8a347d4a7769d31b06d81df0 | Coriaa/Mision_04 | /Reloj.py | 1,052 | 3.96875 | 4 | #Mariana Coria Rodríguez, A01374765
# Leer la hora en formato de 24 y trasnformarlo a formato de 12
#Convertir las horas de 24 a 12
def calcularHora (Formato24):
if Formato24 > 12:
return Formato24-12
else:
return Formato24
#Definir main y preguntas para el usuario
def main():
Formato24 ... |
1d0d5e61268a5264e7ffd8578fe7fdfd4f3d5a41 | bdrummo6/Sprint-Challenge--Data-Structures-Python | /names/names.py | 1,819 | 3.65625 | 4 | import time
from binary_search_tree import BSTNode
start_time = time.time()
f = open('names_1.txt', 'r')
names_1 = f.read().split("\n") # List containing 10000 names
f.close()
f = open('names_2.txt', 'r')
names_2 = f.read().split("\n") # List containing 10000 names
f.close()
duplicates = [] # Return the list of ... |
7c96d2af4ddd63fedc53aa2529fe0371bf177794 | Borwe/python-crash_course | /alien_invasion/ship.py | 1,330 | 3.65625 | 4 | import pygame
class Ship():
def __init__(self,a1_settings,screen):
"""Initialize the ship and set its starting position"""
self.screen=screen
self.a1_settings=a1_settings
# load the ship image and get its rect
self.image=pygame.image.load('images/ship.bmp')
self.r... |
90bc67d882b13a8a0e07037cada9a59f65f1aa5b | un-simp/utilman | /applauncher.py | 1,148 | 3.515625 | 4 | from tkinter import *
import os
import sys
import subprocess
# import filedialog module
from tkinter import filedialog
# Function for opening the
# file explorer window
def browseFiles():
filename = filedialog.askopenfilename(initialdir = "/",title = "Select a File",)
# Change label contents
label_f... |
3ba831d1fec898d0c9f9c83197854e7a5f96cca4 | kawabangaa/xyz_mb | /Game.py | 9,396 | 3.765625 | 4 | import numpy as np
from random import randint
from constants import BLACK_VALUE, RED_VALUE, DRAW_VALUE, VERBOSE,POSSIBLE_PLAYER_VALUES
from rounds import invoke_beast, validate_board
RAND_TACTIC = "random"
DRAW_TACTIC = "draw"
class Game:
"""
Game class implements a full game minus the beasts logic.
A ga... |
bc4a52479ac3e26e58c55edb8e0975045b3e9393 | stefanpostolache/pythonHandsOnExamples | /complete/example-4/main.py | 2,677 | 3.515625 | 4 | import qrcode
import re
import numpy as np
"""
This module creates a QR code
"""
class URLError(Exception):
"""
Exception to be raised when the string presented is not a url
"""
def __init__(self, message="The provided URL is not valid"):
self.message = message
super().__init__(self.me... |
f4fb93abdfd4a0b7c0d8cbb5c0e8021928f70f04 | gustavogattino/Curso-em-Video-Python | /Mundo 1 - Fundamentos/Aula06/aula06_desafio02.py | 477 | 4.28125 | 4 | """Aula 06 - Desafio 02."""
algo = input('Digite alguma coisa: ')
print('{} é numero? {}'.format(algo, algo.isnumeric()))
print('{} é letra? {}'.format(algo, algo.isalpha()))
print('{} é numeros e/ou letras? {}'.format(algo, algo.isalnum()))
print('{} está apenas com letras minúsculas? {}'.format(algo, algo.islower())... |
c9c360f7aa6ff3e096b4e0153079984c5d8b9587 | gustavogattino/Curso-em-Video-Python | /Mundo 1 - Fundamentos/Aula09/aula09_desafio02.py | 185 | 3.625 | 4 | """Aula 09 - Desafio 02."""
n = input('Digite um número de 0000 à 9999: ').zfill(4)
print('Unidade: {}\nDezena : {}\nCentena: {}\nMilhar : {}'
.format(n[3], n[2], n[1], n[0]))
|
0b0d3924b01477aa60644e66664c0b9c0377f3b1 | gustavogattino/Curso-em-Video-Python | /Mundo 1 - Fundamentos/Aula10/aula10_desafio06.py | 415 | 4.15625 | 4 | """Aula 10 - Desafio 06."""
n1 = int(input('Digite um número: '))
n2 = int(input('Digite outro número: '))
n3 = int(input('Digite mais outro número: '))
if n1 > n2:
maior = n1
else:
maior = n2
if maior < n3:
maior = n3
print('O maior número é {}.'.format(maior))
if n1 < n2:
menor = n1
else:
menor =... |
a40fbe0b6861520d6de8602e2e86e8c6a23b3923 | gustavogattino/Curso-em-Video-Python | /Exercicios/ex033.py | 508 | 4.03125 | 4 | """
Exercício Python 033.
Faça um programa que leia três números e mostre qual é o maior e qual é o
menor.
"""
n1 = int(input('Primeiro valor: '))
n2 = int(input('Segundo valor : '))
n3 = int(input('Terceiro valor: '))
menor = n3
maior = n3
if n1 < n2 and n1 < n2:
menor = n1
if n2 < n1 and n2 < n3:
menor = n... |
60b3cfd658fed7e359941787bc3a70f7004c988b | gustavogattino/Curso-em-Video-Python | /Mundo 1 - Fundamentos/Aula07/aula07_desafio09.py | 195 | 3.6875 | 4 | """Aula 07 - Desafio 09."""
salario = float(input('Qual o salário atual do funcionário? R$'))
print('O salário do funcionário com reajuste de 15% é de R%{}.'
.format(salario * 1.15))
|
76f9543a1a77736295b8e15659efdcc4e7a0f3cb | gustavogattino/Curso-em-Video-Python | /Mundo 1 - Fundamentos/Aula08/aula08_desafio05.py | 247 | 3.671875 | 4 | """Aula 08 - Desafio 05."""
from random import sample
al1 = input('Aluno 1: ')
al2 = input('Aluno 2: ')
al3 = input('Aluno 3: ')
al4 = input('Aluno 4: ')
print('A ordem de apresentação será {}!'
.format(sample([al1, al2, al3, al4], 4)))
|
55869b8dfcdc6bbe71e1eb2e05d62fdedeaf0fb1 | gustavogattino/Curso-em-Video-Python | /Mundo 1 - Fundamentos/Aula09/aula09_desafio06.py | 206 | 4.0625 | 4 | """Aula 09 - Desafio 06."""
nome = input('Qual o seu nome completo? ')
print('O seu primeiro nome é {} e o seu último sobrenome é {}.'
.format(nome.split()[0], nome.split()[len(nome.split())-1]))
|
203d2087798d34ad3da554787ad175cbacfaeb05 | gustavogattino/Curso-em-Video-Python | /Mundo 1 - Fundamentos/Aula09/aula09_desafio05.py | 345 | 4.0625 | 4 | """Aula 09 - Desafio 05."""
frase = input('Digite uma frase: ')
print('Na frase inserida, a palavra "A" aparece {} vezes.\n'
'Ela apareceu pela primeira vez na posição {}.\n'
'Ela apareceu pela última vez na posição {}.'
.format(frase.upper().count('A'), frase.upper().find('A'),
frase.u... |
4b99c42f3dd2cf236c5cbdfc0bfd4ca44484aad0 | joshua-paragoso/PythonTutorials | /4_BasicOperators.py | 1,756 | 4.59375 | 5 | #---Arithmetic operators-----#
# Just as any other programming languages, the addition,
# subtraction, multiplication,
# and division operators can be used with numbers.
number = 1 + 2 * 3 / 4.0
print(number)
# using two multiplication symbols makes a power
# relationship
squared = 7 ** 2
cubed = 2 ** 3
print(squar... |
9d346795798abb2f2d5350d7036ea1d32b0f1850 | jorzel/introduction_to_algorithms | /code/ch2/bubble_sort.py | 248 | 3.796875 | 4 |
def bubble_sort(A):
len_ = len(A)
for i in range(len_ - 1):
for j in reversed(xrange(i + 1, len_)):
if A[j] < A[j - 1]:
A[j], A[j - 1] = A[j - 1], A[j]
return A
A = [31, 41, 59, 26, 41, 58, 4, 2]
|
84a510c0f8f52b2bf95612f5109d1c47f1c900fd | AnkitaTandon/NTPEL | /python_lab/fibonacci.py | 267 | 3.734375 | 4 | '''
Q4: Write a program to get the fibonacci's series b/w 0 to 50
'''
a=0
b=1
print("The fibonacci series is here:\n",a,b,end=" ")
while( (a+b) <= 50):
c=a+b
a=b
b=c
print(c,end=" ")
print(" ......and it goes on")
|
c6aeda9fc798e0a61c7bfd338c30dccd95e2196e | AnkitaTandon/NTPEL | /src/merge.py | 956 | 3.921875 | 4 | def mergeSort(nlist):
print("Splitting ",nlist)
if len(nlist)>1:
mid =len(nlist)//2
lefthalf=nlist[:mid]
righthalf=nlist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
merge(nlist,lefthalf,righthalf)
def merge(nlist,lefthalf,righthalf):
i=j=k=0
... |
3c069ff1a13ca27ae4698a44afa1fa225b4da15e | AnkitaTandon/NTPEL | /python_lab/continue().py | 158 | 4.09375 | 4 | '''
Q3: Write a program to print all the numbers from 0 to 6 except 3 and 6
'''
for i in range(0,7):
if i==3 or i==6:
continue
else:
print(i)
|
cac864ecc718490cee6323127c27b50f502c40fc | AnkitaTandon/NTPEL | /python_lab/rem.py | 331 | 4.1875 | 4 | '''
1.Write a program that prompts the user for two integers,
and then prints them out in a sentence like
The quotient of 13 and 3 is 4 with a remainder of 1
'''
print("Enter 2 integers:")
a=int(input())
b=int(input())
rem=a%b
q=a/b
print("The quotient of",a," and " ,b, " is " ,int(q), "with a reminder of... |
f2d6f2b7d6ce2c1358b05c5a7a163a56d6b98dc3 | AnkitaTandon/NTPEL | /python_lab/median.py | 569 | 4.25 | 4 | #Q: Write a Python program to find the median among three given numbers.
num=[]
for i in range(3):
num.append(int(input("Enter a number: ")))
print("The median of three given number: ",end='')
if num[0]>num[1] and num[0]>num[2]:
if num[1]>num[2]:
print(num[1])
else:
print(num[2]... |
bbf8be78f02cc9826b4928055f3b6196327848db | yadifuentes/EjercicioPrueba | /VelocidadPromedio.py | 245 | 3.984375 | 4 | #Autor: Yadi Fuentes
#Calcula la velocidad promedio en un viaje
time = int(input("Teclea el tiempo del viaje: "))
distance = int(input("Teclea la distancia del viaje :"))
velocity = distance/time
print ("La velocidad promedio es: ", velocity) |
2bbd72d92aa1922e9a7232cbf086a9fa64da1113 | zou23cn/Python | /MOOC/turtle_04.py | 5,106 | 3.75 | 4 | #小猪佩奇
import turtle
turtle.screensize(400, 300)
turtle.pensize(4) # 设置画笔的大小
turtle.colormode(255) # 设置GBK颜色范围为0-255
turtle.color((255,155,192),"pink") # 设置画笔颜色和填充颜色(pink)
turtle.setup(840,500) # 设置主窗口的大小为840*500
turtle.speed(10) # 设置画笔速度为10
#鼻子
turtle.pu() # 提笔
turtle.goto(-100,100) # 画笔前往坐标(-100,100)
turtle.pd() # 下... |
0c5e9fd0278a69b9397d4900a350568dff0835a2 | zou23cn/Python | /MOOC/ex_Week1.py | 158 | 3.90625 | 4 | #
n =eval(input())
str = "Hello World"
if n==0:
print(str)
elif n >0:
print("He\nll\no \nWo\nrl\nd")
else:
for i in str:
print(i)
|
337adb1ae14d70bb97848c5042c7c2a0e4052d41 | Serio-Programming/ROT13Encryptor | /ROT13Encryptor.py | 5,103 | 3.71875 | 4 | # ROT13 Encryptor
# This program takes text files as input and encrypts them using an ROT13 algorithm
# Programming began circa June 2021
# A program by Tyler Serio
# Python > 3.7
import os
import sys
alphkey = {
"A": "N",
"a": "n",
"B": "O",
"b": "o",
"C": "P",
"c": "p",
"... |
1213b90404cf761fd2beb5c0fabd5e0bc43447b9 | JDer-liuodngkai/LeetCode | /leetcode/1 两数之和.py | 2,109 | 3.6875 | 4 | """1.两数之和
https://leetcode-cn.com/problems/two-sum/
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
题目假设只有一组答案,暗示了 key 的单一性
哈希表
- 保持数组中的 每个元素与其索引相互对应的最好方法.
- Python dict 类型就是哈希表,key 不会相同,不用担心 hash 函数设计
- 通过以空间换取速度的方式,可以将查找时间从 O(n) 降低到 O(1)
哈希表支持以 “近似” 恒定的时间进行快速查找。
... |
f02e5c0b65d47740e7691b96df4a8ca5e8438bc9 | JDer-liuodngkai/LeetCode | /labuladong/3_算法思维/回溯/46 全排列.py | 2,906 | 3.859375 | 4 | """
给定一个 没有重复 数字的序列,返回其所有可能的全排列。
"""
from typing import List
class Solution:
# dfs 回溯: 回到之前状态的意思
def permute(self, nums: List[int]) -> List[List[int]]:
n = len(nums)
ans = []
# 回溯过程 就是保存 决策树的搜索路径
used = [False] * n
path = []
def dfs(d): # 当前树的深度,也即全排列第i个位置可选的... |
36337b624ae4f6f1c31d8687e9102b592c04ca41 | JDer-liuodngkai/LeetCode | /labuladong/3_算法思维/回溯/77 组合.py | 1,722 | 3.5 | 4 | """
https://leetcode-cn.com/problems/combinations/
给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
"""
from typing import List
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
ans = []
path = []
# cur ~ [1, n]
def dfs(cur): # 当前位置
pl = len(path)
... |
bdad3a104ed6a757278a0551f3879a38a3ff795e | JDer-liuodngkai/LeetCode | /base/prime.py | 2,236 | 3.765625 | 4 | # 试除法
def is_prime(x):
for i in range(2, int(x ** 0.5) + 1): # 平方根更小
if x % i == 0:
return False
return True
# 试除法浪费了很多时间 在 明显就是合数的数上面
def generate_primes(n=20):
return [x for x in range(2, n + 1) if is_prime(x)]
# 埃拉托色尼筛
def eratosthenes_primes(n=100):
"""
1.创建连续数表 [2,..,n]... |
342bfe2259a109aeb8fa6ad114c0c32b525924ef | JDer-liuodngkai/LeetCode | /offer/20-表示数值的字符串.py | 634 | 3.859375 | 4 | """
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。
例如,
字符串"+100"、"5e2"、"-123"、"3.1416"、"0123"都表示数值,
但"12e"、"1a3.14"、"1.2.3"、"+-5"、"-1E-16"及"12e+5.4"都不是。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/biao-shi-shu-zhi-de-zi-fu-chuan-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class Solution:
def isNumber(self, s: str) -> bo... |
7adeef2561e9dbc424d2eeb93f76c54e8fd26c7f | JDer-liuodngkai/LeetCode | /offer/4-从尾到头打印链表.py | 2,163 | 3.84375 | 4 | from typing import List
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
res = []
while head:
res.append(head.val)
head = head... |
a720749f0cff19ebb480f74da0728b668a147c1e | JDer-liuodngkai/LeetCode | /company/meituan/1.py | 973 | 3.71875 | 4 | """
每天最多 n 个,各有1个正整数重量
已做好 m 个
买 最重 最轻 a,b; 保证 a/b 大小关系
剩余 n - m 在烤
"""
# 不保证 a/b 大小关系
# 1 ≤ n,m,a,b ≤ 1000 , m≤n , 蛋糕重量不会超过1000
def cake():
vmax, vmin = max(arr), min(arr)
tmax, tmin = max(a, b), min(a, b)
# 已做出的蛋糕 不满足要求
if vmax > tmax or vmin < tmin:
return 'NO'
# 仍在区间内
remain = ... |
11903d5130ca08acdf0856066776e6a292a6a92c | JDer-liuodngkai/LeetCode | /offer/7-斐波那契数列.py | 593 | 3.5625 | 4 | def f(n):
"""
严重超时, 200 就要算很久
大量重复的递归计算,例如 f(n) 和 f(n - 1) 两者向下递归需要 各自计算 f(n−2) 的值。
"""
if n == 0 or n == 1:
return n
else:
val = f(n - 2) + f(n - 1)
return val % 1000000007
class Solution:
"""
f(n) = f(n-1) + f(n-2)
"""
def fib(self, n: int) -> int:
... |
6e9dc4512b304cabb45cbe46de974fd6743cfb07 | JDer-liuodngkai/LeetCode | /offer/46-数字翻译成字符串.py | 2,632 | 3.5625 | 4 | """
给定一个数字,我们按照如下规则把它翻译为字符串:
26个英文字母 与 数字对应
0 翻译成 “a” ,1 翻译成 “b”,……,11 翻译成 “l”,……,25 翻译成 “z”。
一个数字可能有多个翻译。
请编程实现一个函数,用来计算一个数字有多少种不同的翻译方法。
有点 信号解码 感觉
链接:https://leetcode-cn.com/problems/ba-shu-zi-fan-yi-cheng-zi-fu-chuan-lcof
"""
class Solution:
def translateNum(self, num: int) -> int:
# DP 往往从 最后的情况 考... |
2815f03c77c0eb5396d4b065e6b67bf816a67d3d | JDer-liuodngkai/LeetCode | /offer/29-顺时针打印矩阵.py | 1,194 | 3.71875 | 4 | """
从外向里以顺时针 打印矩阵
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
"""
from typing import List
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
res = []
if len(matrix) > 0 and len(matrix[0]) > 0:
l, r, t, b = 0, len(matrix[0]) - 1, 0, len(matri... |
5c3c302df84344e3fa48a765c1490c1b74fdf009 | JDer-liuodngkai/LeetCode | /leetcode/3 无重复字符的最长子串.py | 1,952 | 3.5625 | 4 | # 错误解,想 1 次遍历完
def lengthOfLongestSubstring_error(s):
ll = 0 # 初始化 ll 可能长度,may have empty str
ll_str = ''
i = 0
while i < len(s): # 用 for 里面更新 i 这里不会更新
sub_str = s[i]
while i + 1 < len(s) and s[i + 1] not in sub_str:
sub_str += s[i + 1]
i += 1
# find a l... |
eff1342a654af28d57ce54c380220da1dd120aab | newtonfulcrum/first | /GuessNumberGame.py | 976 | 4 | 4 | import random
lie=["Dont give up","It's cold","It's near","You've gone too far mate!!","Please try harder next time","Don't you have a brain","Almost near dude"]
print "You wanna play a game..."
name=raw_input("What is your name?\n")
print "Thank you %s"%(name)
print "You only have five tries %s"%(name)
num=random.rand... |
cb8135443d3a9ba14d370f3f9fffb18022a5d48c | dormir12021/python-1 | /Random Code.py | 6,849 | 4.21875 | 4 | from matplotlib import pyplot as plt
from math import * # More Math functions (Module)
# ("Hello World!") # Prints into console whatever is in the string.
name_input = "Ramon" # Variable, can be changed in the ""
# Seperate the "" from the variable and put spaces so it can be spaced out.
# print("There was an old m... |
b9718f0b9a3938ac42f6cdb2066659de2151eeb3 | mjtribble/Python | /list_comprehension.py | 657 | 3.9375 | 4 | double_my_range = [2*i for i in range(10)]
print double_my_range
#-----------------------------------------------------
# Using a function
def double_my_val(x):
return 2*x
my_range = range(10)
double_my_range2 = [double_my_val(my_range)]
print double_my_range2
#-----------------------------------------------------
... |
8cd6201ce019c9a97bb6737ff50d69922e19d2cc | mjtribble/Python | /curried_functions.py | 389 | 3.578125 | 4 | def curry (f, x):
return lambda y: f(x, y)
#General curry function
def general_curry(f, x):
return lambda *args, **kwargs: f(x, *args, **kwargs)
def times123(x, xx, yy, y=1, z=2):
return x * y * z * xx * yy
def mult(x, y):
return x * y
mult4 = curry(mult, 4)
print mult4(6)
print times123( 1, 2, 3, y = 4, z = 5... |
eb5210d1dfaf5630806758728acd28a13907b368 | Bhavyakala/Python_scripts | /noOfIslands.py | 2,015 | 3.90625 | 4 | # QUESTION
# Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is
# surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You
# may assume all four edges of the grid are all surrounded by water.
# Example input
# Input: grid = [
# [ "... |
2fca18861c9ced341992870c3f932103aada7de4 | yuhan1212/image_cartoonifier | /image_cartoonifier.py | 4,992 | 3.734375 | 4 | '''
Image Cartoonifier
Using Tkinter and OpenCV to build a Cartoonifier
that can transform image into cartoon style.
'''
''' import requred modules'''
import cv2 #for image processing
import numpy as np #to store image and deal with numbers (image taken as arrays)
import imageio #to read image stored... |
1b201533a619e9eb4080b07105059567535e153e | UCSB-CMPTGCS20-S16/CS20-S16-Lecture-04-14-Koc | /p1.py | 659 | 3.890625 | 4 | def func(n):
sum = 0
for i in range(1,n+1):
sum = sum + i**2
return(sum)
def func2(n):
sum = 0
for i in range(1,n+1):
sum = sum + 1/i
return(sum)
#-------------------------
def func3(n):
prod = 1
for i in range(2,n+1):
prod = prod*i
print(... |
907e89a951f400aec496b1d4e2177393738f627c | strogera/AoC2020 | /template.py | 263 | 3.53125 | 4 | def partOne():
with open("input.txt", "r") as inputFile:
for line in inputFile:
#elems=line.strip().split()
def partTwo():
return 'unknown'
print("Answer for part 1: ")
print(partOne())
print("Answer for part 2: ")
print(partTwo())
|
5e0d88e4bcc3bacce6d9a82ba0e53f184dec6c00 | YUNSERA/welcome | /9장 공부.py | 643 | 3.5625 | 4 | from tkinter import *
class ProcessButtonEvent:
def __init__(self):
window = Tk()
label = Label(window,text = "welcome to python.")
button_OK = Button(window, fg ="red", bg = "white",text ="OK",command = self.processOK)
button_Cancle = Button(window,text ="Cancle",command = s... |
4fdf71495ffe7cd45f19ccc2f78697d703f06da1 | Mamata720/Function | /speed.py | 152 | 3.625 | 4 | def num(speed):
if speed<70:
print("ok")
elif speed >70:
print("points:2")
else:
print("license suspended")
num(50) |
4917cade056e6eab9ba5c877b9e14036b1b8ec7f | Mamata720/Function | /prime number.py | 457 | 3.9375 | 4 | def prime_not(num):
if num==1:
return False
elif num==2:
return True
else:
for x in range(2,num):
if (num%x==0):
return False
return True
print(prime_not(10))
# i=1
# a=0
# while num>=i:
# if num%i==0:
# print(i)
#... |
4d92fdb4346cb756c333cd5014e0f1aed1023b1f | E-nuri/Hello_Coding | /chapter4/4_1.py | 450 | 3.953125 | 4 | # 재귀함수 연습...
# TODO: 재귀함수 예제를 찾아보고 그것을 직접 '노트에 손으로 풀어본 뒤' 코드로 옮겨보기
sum_value = [0]
def sum_list(list):
def add_value(list):
if(len(list) == 0):
return sum_value
else:
sum_value[0] = int(sum_value[0]) + int(list[0])
list.pop(0)
sum_list(list)
a... |
186ec3ad0a34a6299adb5d08415bc29f8670d4aa | JonathanChavezTamales/Fundamentos-Programacion | /Laboratorio_1/L1_E2_A01636160_A01251000.py | 483 | 4 | 4 | #Santiago Yeomans
#A01251000
print("Ingresa 3 numeros que quieras")
a = float(input("Escribe el primer numero: "))
b = float(input("Escribe el segundo numero: "))
c = float(input("Escribe el tercer numero: "))
if a == b and b == c:
print("\nLos 3 numeros son iguales")
elif a == b or b == c or a == c:
pr... |
a2a030e7794b30ab909a86b8f97ff24079c8faa9 | JonathanChavezTamales/Fundamentos-Programacion | /Tarea_1/Ej6_A01636160.py | 386 | 3.53125 | 4 | #Autor: Jonathan de Jesús Chávez Tabares A01636160
nacimientos_segundo = 1/7
muertes_segundo = 1/13
tiempo = int(input("Ingrese tiempo en años: "))
tiempo *= 365*24*3600 #Paso los años a segundos
nacimientos_totales = int(nacimientos_segundo*tiempo)
muertes_totales = int(muertes_segundo*tiempo)
print("En ese tiempo n... |
c247a4613a4273fdccac39c44fe0fcc964f6e6fd | JonathanChavezTamales/Fundamentos-Programacion | /Laboratorio_3/Ej_grupal_4.py | 276 | 3.953125 | 4 | n = int(input("Ingrese n: "))
if n>0:
#Método 1
print(sum(list(range(1,n+1))))
#Método 2 Ciclo
sum = 0
for i in range(1, n+1):
sum += i
print(sum)
#Método 3 Matemático
print(int(n*(n+1)/2))
else:
print("Número no valido")
|
81903ebdaf240b31f500a1ac17442196b325e18b | JonathanChavezTamales/Fundamentos-Programacion | /Laboratorio_1/L1_E3_A01636160_A01251000.py | 197 | 3.734375 | 4 | #Autor: Jonathan Chávez A01636160
year = int(input("Ingrese el año: "))
if (year%4==0 and year%100!=0) or year%400==0:
print(f"{year} Año bisiesto.")
'''
Usé operadores lógicos con paréntesis
'''
|
d28c44a3ee86e0453bb158967f58dbf23d8a89da | JonathanChavezTamales/Fundamentos-Programacion | /Tarea_1/Ej1_A01636160.py | 214 | 3.71875 | 4 | #Autor: Jonathan de Jesús Chávez Tabares A01636160
celcius = float(input("Escriba grados Celcius: "))
fahrenheit = celcius*(9/5)+32
kelvin = celcius+273
print("En fahrenheit: " , fahrenheit)
'''
Aprendí a hacer comentarios multilinea
'''
|
e03f5a3826fdd7aac2a0ab42d3e60c764fb00b43 | shubhankar994/adventure-game-1 | /adventure(3).py | 4,257 | 4.0625 | 4 | import time
import random
def print_pause(message):
print(message)
time.sleep(0)
def valid_input(prompt, option1, option2):
while True:
response = input(prompt).lower()
if response == option1:
break
elif response == option2:
break
else:... |
4e1b5a464974e373a2a3578cc6fbeb140ba0491f | nc-yc/MachineLearningZJU | /assignment3/hw3/ml2020fall_hw3/neural_network/fc_net.py | 10,595 | 3.84375 | 4 | import numpy as np
from layers import *
from layer_utils import *
class TwoLayerNet(object):
"""
A two-layer fully-connected neural network with ReLU nonlinearity and
softmax loss that uses a modular layer design. We assume an input dimension
of D, a hidden dimension of H, and perform classific... |
e13944719a43a7e8be274debb1032476beb9d6c1 | frappefries/Python | /Assignment/ex1/prg15.py | 1,146 | 4.59375 | 5 | #!/usr/bin/env python3
"""Program to create a list and check if a name exists in the list
a) use membership operator to check the presence of the element
b) perform above task without using the membership operator
c) print the elements of the list in reverse direction
usage: python3 prg15.py
"""
def init():
"""F... |
b29dbc63bb8000b2c2812e23662accbb14a014b2 | frappefries/Python | /Assignment/ex1/prg12.py | 2,278 | 4.40625 | 4 | #!/usr/bin/env python3
"""Program to read 10 numbers from user and find the average
Also perform the below operations
a) Use comparison operator to check how many numbers are less than average and
print them
b) Check how many numbers are more than average
c) Check how many are equal to average
"""
import decimal
de... |
57c6629a115b2ec2323edcaf0ab45453f17c837a | frappefries/Python | /Assignment/ex1/prg13.py | 1,045 | 4.21875 | 4 | #!/usr/bin/env python3
"""Program to find the biggest of 4 numbers
a) read 4 numbers using input statment
b) Extend the program to find the biggest of 5 numbers
(use if, if else, elif and nested if statements)
"""
def init():
"""Fetch inputs and display the biggest of the numbers"""
num = []
f... |
92dd46ee8f2c62a22f185e024f5f3a227e1b0812 | Abhulimen/Paula | /WK 5 Assignment for Paulina.py | 1,893 | 3.734375 | 4 | print('Assignment number 1')
print('...........\
.............')
cities = ('Lagos', 'Kano', 'Abuja', 'Warri')
empty_list = []
for city in cities:
empty_list.append(city)
print(empty_list)
print('Assignment number 2 and 3')
print('............\
............')
States = {'Lagos' : 'Ikeja', 'Imo' : 'Owerri', 'Delt... |
a407143ea0034550876d14c41da42a153bc01fb3 | WesleySorrentino/theadventuresofleathren | /chapter_1.py | 5,328 | 3.578125 | 4 | import time
import random
def act_1(Character,Enemy):
'''
Intro to the Game
'''
intro = f"""
Chapter 1 - Through the woods:
You awaken in the middle of the woods with your memory in pieces and only one thought....
"How did I get here?"
You start to get up and find that your... |
8a5f278144017ec98db517282225e39f7b2a5d94 | jenniferjqiai/Python-for-Everybody | /Chapter 8/Test.py | 870 | 3.890625 | 4 | # To compute the average
numlist=list()
while (True):
inp= input("Enter a number :")
if inp=='done':
break
try:
value= float(inp)
numlist.append(value)
average = sum(numlist) / len(numlist)
print(average)
except:
average=0
print('devide by zero')
# delim... |
91ff380570630279625c6eade947c7c40915f993 | jenniferjqiai/Python-for-Everybody | /Chapter 6/Exercise 4.py | 152 | 3.859375 | 4 | # Write an invocation that counts the number of times the letter a occurs in "banana"
word ='banana'
print (word.count('a'))
print('banana'.count('a')) |
88d2b4604bc4dac6b26e3ac3b302743b1cc08df6 | jenniferjqiai/Python-for-Everybody | /Chapter 9/Exercise 3.py | 591 | 4 | 4 | # Write a program to read through a mail log,
# build a his- togram using a dictionary to count how many messages have come from each email address,
# and print the dictionary.
fname=input('Please enter a file name: ')
try:
fhand=open(fname)
except:
print('Cannot open file'+fname)
exit()
count=dict()
emai... |
f5a4241ae4606fa0f39cb5d6e68e87fba6b4b611 | jenniferjqiai/Python-for-Everybody | /Chapter 10/Exercise 1.py | 835 | 3.859375 | 4 | # Revise a previous program as follows: Read and parse the “From” lines and pull out the addresses from the line.
# Count the num- ber of messages from each person using a dictionary.
# After all the data has been read,
# print the person with the most commits by creating a list of (count, email) tuples from the dictio... |
db081630f0a99945f828d8b5754edf205f5c11b7 | zmmille2/aoc | /2016/advent7.py | 1,348 | 3.828125 | 4 | def is_reversible(segment):
for index in xrange(len(segment) - 3):
if segment[index] != segment[index + 1] and segment[index:index + 4] == ''.join(reversed(segment[index:index + 4])):
return True
return False
def has_reversible(segments):
for segment in segments:
if is_reversibl... |
e0b123b88af485e1347583780f9d273a96942965 | yuliasimanenko/Python | /lab4/test.py | 759 | 3.578125 | 4 | import unittest
import file
class TestFile(unittest.TestCase):
"""------------------OPEN-FILE------------------"""
def test_open_file_not_found(self):
incorrect_names_list = ['', 'AAAAA', 'name', 'nafile', 'name2000.html']
for name in incorrect_names_list:
self.assertRaises(FileNot... |
4bc72138f9311ca9c6cdde6cf590150753474f2f | yuliasimanenko/Python | /lab2/string2.py | 538 | 3.75 | 4 | import re
# 1.
# Вх: строка. Если длина > 3, добавить в конец "ing",
# если в конце нет уже "ing", иначе добавить "ly".
def v(s):
if len(s) > 3 :
s = s + 'ly' if s[-3:] == 'ing' else s + 'ing'
return s
# 2.
# Вх: строка. Заменить подстроку от 'not' до 'bad'. ('bad' после 'not')
# на 'good'.
# Пример: So 'T... |
07257877a9ec210a03aed1d675f7a0d6682d0f64 | tasfia-makeschool/spaceman | /spaceman.py | 9,427 | 4.21875 | 4 | import random
import math
def load_word():
'''
# A function that reads a text file of words and randomly selects one to use as the secret word from the list.
# Returns:
# string: The secret word to be used in the spaceman guessing game
'''
f = open('words.txt', 'r')
words_list = f.re... |
1421c222a4d349814a3db663b0bcab92a3a43769 | atmilich/DaltonPython | /function.py | 598 | 4.1875 | 4 | #prints multiples of 3 starting at 1 thru
def print_multiples(n):
i = 1
output = ""
while i <= 6:
output += str(n*i) + "\t"
i+=1
print(output)
print_multiples(3)
#print_squares is a function that prints the squares of a range from (0,10)
def print_squares():
return[n**2 for n in range(10)]
print(print_sq... |
edeff5de25c4bb6905cb0a7beb2a4d2dea024ca6 | devilcn/hackerrank-Python | /Python/11. Built-Ins/02. Input().py | 342 | 3.640625 | 4 | """
Problem: https://www.hackerrank.com/challenges/input/problem
Max Score: 20
Difficulty: Easy
Author: Ric
Date: Nov 14, 2019
"""
# Enter your code here. Read input from STDIN. Print output to STDOUT
x, k = map(int, input().split())
command = eval(input())
# print(type(command))
Flag = False
if command == k:
F... |
875031599499f51f979991a63d9f94abfcb7a24d | devilcn/hackerrank-Python | /Python/10-Days-of-Statistics/Day-0-Weighted-Mean.py | 844 | 3.6875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
from decimal import Decimal
#
# Complete the 'weightedMean' function below.
#
# The function accepts following parameters:
# 1. INTEGER_ARRAY X
# 2. INTEGER_ARRAY W
#
def output_custimization(x): # output custimization
x_out = Decimal(x).q... |
c56e885bd390f1601e165f44571b80ae1ff02d78 | devilcn/hackerrank-Python | /Python/10-Days-of-Statistics/Day-1-Quartiles.py | 1,386 | 4 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'quartiles' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts INTEGER_ARRAY arr as parameter.
#
def median_cal(array_input): # median cal
if len(array_input)%2 == 1:
if l... |
ebd7e363b1522ea17365d8558c9724e07b4fbe59 | UofA-EEE-LAUS/Artificial-Intelligence-vs-Human-Who-Wins-the-Board-Game | /Ex_Files_AI_Algorithms_Gaming_ cat_trap/Exercise Files/hexutil.py | 11,448 | 3.859375 | 4 | """
Classes and functions to deal with hexagonal grids.
This module assumes that the hexagonal grid is aligned with the x-axis.
If you need it to be aligned with the y-axis instead, you will have to
swap x and y coordinates everywhere.
"""
from collections import namedtuple
from heapq import heappush, heappo... |
ef518385a2a3a4c15b301046b7cfeb449e7e8957 | EarthenSky/Python-Practice | /misc&projects/py_game_tiles.py | 658 | 3.703125 | 4 | import pygame # Import the pygame library.
# Init pygame
def init():
pygame.init() # Init pygame
pygame.display.set_caption("Mai Windou")
# Init pygame
init()
# Create a game window
display_surface = pygame.display.set_mode( (300, 300) )
# Exit flag
f_done = False
while not f_done:
# Draw things -w-
... |
5772f36b81aec611b37869e825e457ca97be2877 | EarthenSky/Python-Practice | /Lesson2Folder-Pygame/Template.py | 2,730 | 3.59375 | 4 | # This template is built to make the user no longer need to work with the
# "while loop" that runs pygame when building something simple.
# This template is also made to include a frame independent movement constant,
# as well as some other useful prebuilt code.
import pygame
# This is a 2d vector that holds the size... |
2b4eaa19df1d002511832a2347e641fb5a53d5e7 | EarthenSky/Python-Practice | /misc&projects/ex(1-1).py | 220 | 3.71875 | 4 | # global variable parameters
name = "Gabe Stang"
grade = 11
class_period = 5
# str() casts the integer variables into strings
print name + " is in grade " + str(grade) + " and has programming in block " + str(class_period)
|
b583794c80ded1b8ade6d14601a30dffb840b88e | EarthenSky/Python-Practice | /Lesson2Folder-Pygame/Ex1.py | 3,721 | 3.828125 | 4 | import pygame
import random
# This is a 2d vector that holds the size of the screen.
SCREEN_SIZE = [1024, 768]
# Sets the prefered fps. Mostly affects the speed of the main gameloop,
# although complex calculations may cause the fps to drop.
FPS = 60 #FUN FACT, if you run this at > 5000 fps it stops hurting your ey... |
23bd7fdc875ff0f31ecfad510e3c4520245e94a9 | iamsohel/play-with-python | /loop.py | 463 | 4 | 4 | for number in range(1, 10):
print("attempt", number, (number) * ".")
for number in range(1, 10, 2): # every time increment by 2
print("attempt", number, (number) * ".")
successful = False
for number in range(3):
print("attempted", number)
if successful:
print("successful")
break
els... |
8e5382015249bccc197dced9b5b2698c61f02b5f | zopiro00/m02_boot_0 | /01_funciones_nivel/04b_reduce.py | 493 | 3.625 | 4 | from functools import reduce
lista = [1,2,3,4]
# Este código da 19 y DEBERÍA dar 20
sumatorioDobles = reduce(lambda x, y: x+y*2, lista)
print(sumatorioDobles)
def SumatorioDobleClasico (l):
resultado = 0
for i in l:
resultado += i*2
return resultado
print(SumatorioDobleClasico(lista))
# Este p... |
e1c59324815318f89776be0905551059b20feb85 | RobbieL22/Rlopez22 | /files/RobertLopezproject.py | 18,408 | 3.734375 | 4 | import itertools #imports the tools used in the programming so that the program understands certain functions used
import random
suits = ['s', 'c', 'd', 'h'] #possible suits
faces = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'] #possible faces
'''deck = set(itertools.product(faces , suits))''' ... |
085cdae5ffaff74fc942be4af745d28658f5ee2a | BigBigHulk/PythonSpace | /test/exercise.py | 661 | 3.53125 | 4 | # 列出1,2,3,4四个数字组成的互不相同的3位数,并进行倒序排序
listSort = []
for a in range(1,5):
for b in range(1,5):
for c in range(1,5):
if (a !=b) and (a !=c ) and (b !=c):
listSort.append(a*100+b*10+c)
print(listSort[::-1])
# 平方根
import math
a = 3 **2
print(f'开平方为:{math.sqrt(a)}')
# 生成一个随机数
import ra... |
cf086f86e62c2031980dff61898ddb554052eca8 | gavmcnamara/algorithms | /python/class_practice/cars.py | 322 | 3.59375 | 4 | class Vehicle(object):
wheels = 4
def __init__(self, make, model):
self.make = make
self.model = model
@staticmethod
def make_car_sound():
print 'VRooooom!'
car = Vehicle('Ford', 'Mustang')
print car.wheels
print car.make
print Vehicle.wheels
print Vehicle.make_car_sound(... |
c78684c4624ca6ee9c3917ae8d50c993af9d8a81 | pgaetan/Projet_Annuel | /V1.0/bras.py | 1,704 | 3.75 | 4 | import random
class Bras:
"""Représente une machine à sous avec ses propriétés"""
def __init__(self, *args):
#args[0] = proba
#args[1] = gain
if len(args) == 2:
self.proba = args[0]
self.gain = args[1]
else:
# proba et gain definis entre 0 et... |
cae3241b1545fcf5f735e78460ea1dcf4bf0c9c0 | HaoboChen1887/leetcode | /tree/117_populating_next_right_pointers_in_each_node_ii/117.py | 1,853 | 3.953125 | 4 | """
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution:
def connect(self, root: 'Node') -> 'Node'... |
1ab1d2976fde2f974ddac48390cde1a10ea4e7a8 | HaoboChen1887/leetcode | /linked_list/92_reverse_linked_list_ii/92.py | 560 | 3.78125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
dummy = ListNode(next=head)
pre = dummy
for _ ... |
e1ebaa29e55aa860f9e43e80f9dbd0cfd9aa5441 | HaoboChen1887/leetcode | /tree/100_same_tree/100.py | 1,422 | 3.71875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
# def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
# stack1, stack2 = [p], [q]
# ... |
de3bc5bcc7fd0dc28f58a1880b24133da6ec259c | HaoboChen1887/leetcode | /string/294_flip_game_ii/294.py | 561 | 3.609375 | 4 | class Solution:
# the problem asks if the starting player can guarantee a win
# which is equal to asking whehter there is at least one way player one can win
# this is equal to asking is it possible to guarantee that player 2 can not win no matter what
# by following this logic, we construct the rec... |
f554a9e4eb243b342c11ddad1a537d3f7ceb1fd8 | HaoboChen1887/leetcode | /string/383_ransom_note/383.py | 486 | 3.5 | 4 | from collections import defaultdict
class Solution:
# hashmap record letter count of magazine
# decrement count when iterating through ransomNote
# if a letter is depleted, return false
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
m = defaultdict(int)
for ch in ... |
79892ead9e029c05e4d889a0c9bfc647acc546bb | HaoboChen1887/leetcode | /design/346_moving_avergae_from_data_stream/346.py | 598 | 3.78125 | 4 | from collections import deque
class MovingAverage:
# add the new val to sum, if nums size exceeds given size, pop and decrement by the first item
def __init__(self, size: int):
"""
Initialize your data structure here.
"""
self.size = size
self.nums = deque()
... |
85392cb799bdd713ebf1017b69eed6fd9cf9e641 | HaoboChen1887/leetcode | /linked_list/23_merge_k_sorted_lists/23.py | 1,914 | 4.0625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
# use a min heap to maintain the order, add one item at a time
# NOTE: python heapq maintains a minheap. if we want to specify a priority,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.