blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
19016a0f53ebbf1274bee155fe0d997e3bd28a29 | Kawser-nerd/CLCDSA | /Source Codes/AtCoder/abc085/B/4935543.py | 176 | 3.515625 | 4 | import sys
unique_list = []
input_list = sys.stdin.readlines()[1:]
for i in input_list:
if i not in unique_list:
unique_list.append(i)
print(len(unique_list)) |
d2bb820b4e8d0c0bafa56838ce95c4d61a283fa9 | leonardostsouza/lambda-py | /interpreter.py | 1,219 | 3.921875 | 4 | # lambda-py
# A simple didactic lambda calculus interpreter written in python
# interpreter.py
import sys
LAMBDA = '/'
RESERVED = [LAMBDA, '.', '(', ')', ' ']
# convert string into tokens
def tokenize(raw_expression):
expression = []
token = ''
for char in raw_expression:
if char in RESERVED:
... |
bdf0fc9ad9956019d37619e8cf7a028449ccf393 | amsharma3/edison | /math51.py | 892 | 4.21875 | 4 | def even_odd_number(number,base):
even = []
while number >= base:
val = number % base
if val == 0:
even.append(number)
number -= 1
return even
def prime_number(number):
temp = 0
count = 2
val = number // 2
while count <= val:
temp = number % count
if temp == 0:
return 0
else:
count += 1
i... |
e6885db945888a9bddaff76b9c1ee24c7891ca88 | jphouminh71/csci1200_ArtOfComputationalThinking | /homework_final/<Jonathan>_<Phouminh>_FortuneTeller.py | 4,715 | 4.28125 | 4 | # Jonathan Phouminh
# Rajarshi Basak
# Section 301
# FortuneTeller
# This program will give 'fortunes' to the user depending on their input
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 3 20:42:22 2017
@author: jonathanphouminh
"""
def greeting_the_user ():
'''This function wi... |
615dfe61fcc834b90212a00e11a96f32f0e5a56f | YuriCat/test | /python/with_syntax.py | 448 | 3.96875 | 4 | # Python with構文の勉強
class Hoge:
def __init__(self):
print('init!')
def __enter__(self):
print('enter!')
return self # asによってこの返り値を受ける
def __exit__(self, *args):
print('exit!')
def __del__(self):
print('del!')
def fuga(self):
print('fuga!')
with Hoge()... |
cb63d76837aa9b16ca20b62eff6b0f60101ba627 | mohammedEshtayah/simulation | /lab1.py | 493 | 4 | 4 |
#from matplotlib import pyplot as plt
import matplotlib.pyplot as plt
if __name__ == "__main__":
t=[]
pt=[]
p=100 # عدد السكان
r=0.1 #نسبة التغير عدد السكان
dt=0.01 #انسبة التغير بالسنة
#t=0 # الزمن
n=5/dt # الفترة الزمنية
g=0.0
for i in range(int(n)):
g=r*p
... |
a9775c2b07ef093b3b8d16ed913305d511895639 | n1vera/D4E-NguyenTheCuong | /session2/xeploaihs.py | 218 | 3.84375 | 4 | grade = float(input('moi nhap diem '))
if grade > 8.0:
print('hoc sinh gioi')
elif grade > 6.5:
print('hoc sinh kha')
elif grade > 5.0:
print('hoc sinh trung binh')
else:
print('hoc sinh yeu')
|
6a0f9013285a690e09cf251da3ca9a5143e26bcc | jcarter62/euler | /problems/p6.py | 1,407 | 4.1875 | 4 | import json
class P6:
"""
Problem 6
The sum of the squares of the first ten natural numbers is,
1^2+2^2+...+10^2=385
The square of the sum of the first ten natural numbers is,
(1+2+...+10)^2=55^2=3025
Hence the difference between the sum of the squares of the first ten natural numbers
... |
7025c13c96692116e60c4326f7b72d004d0b0abd | Sposigor/Caminho_do_Python | /exercicios_curso_em_video/Exercicio 100.py | 498 | 3.546875 | 4 | from random import randint
from time import sleep
def gerador(lista):
print('Sorteando 5 valores da lista', end=' ')
for cont in range(0, 10):
n = randint(1, 10)
lista.append(n)
print(f'{n} ', end=' ', flush=True)
sleep(0.30)
print('PRONTO!')
def somaPar(lista):
soma = ... |
367d3c25983cd2edb62cf274faa55796a342a6ed | yiming1012/MyLeetCode | /LeetCode/深度优先搜索(dfs)/岛屿问题/417. 太平洋大西洋水流问题.py | 3,937 | 4.25 | 4 | """
417. 太平洋大西洋水流问题
给定一个 m x n 的非负整数矩阵来表示一片大陆上各个单元格的高度。“太平洋”处于大陆的左边界和上边界,而“大西洋”处于大陆的右边界和下边界。
规定水流只能按照上、下、左、右四个方向流动,且只能从高到低或者在同等高度上流动。
请找出那些水流既可以流动到“太平洋”,又能流动到“大西洋”的陆地单元的坐标。
提示:
输出坐标的顺序不重要
m 和 n 都小于150
示例:
给定下面的 5x5 矩阵:
太平洋 ~ ~ ~ ~ ~
~ 1 2 2 3 (5) *
~ 3 2 3 (4) (4) *
... |
d09db24ea95d223c955a2a02d61b4e4e799ebde1 | cli402/Algorithm | /HW4.py | 5,284 | 3.5 | 4 | """ Connected components and graph resilience"""
__author__ = 'Amras'
def build_scoring_matrix(alphabet, diag_score, off_diag_score, dash_score):
"""Takes as input a set of characters alphabet and three scores diag_score, off_diag_score"""
score_matrix_out={}
ele_count_one=0;
for ele_one in alphabet:
... |
edcffcab7b09029b33d902cc2f1b5831a5056280 | yagueto/code-jam-2021 | /src/utils/image_to_ascii.py | 919 | 4.03125 | 4 | from typing import Optional
from PIL import Image
def get_ascii(image_path: str, size: Optional[tuple] = None) -> str:
"""Converts the image at the given path to ascii art (str)
Parameters
----------
image_path: str
path of the image user is trying to convert to ascii.
size: ... |
3df26d1d65aea90222fb551e76a5fe55ec623b74 | luisteam/lm-asir | /python/boletin5.2.py | 1,190 | 3.703125 | 4 | import re
lista=[]
mayores=[]
vocales=[]
espacios=[]
cadena=(str(input("Dime una palabra: ")))
lista.append(cadena)
while cadena!= "*":
cadena=(str(input("Dime una palabra: ")))
lista.append(cadena)
vocales.append(cadena)
espacios.append(cadena)
lista.remove("*")
#OrdenAlfabetico
alf=sorted(lista, key = str.lowe... |
d9394b8c2cc662f5de888c40473e1b11b74b3e4f | agentproton/Python-data-structure | /week3.py | 778 | 4.3125 | 4 | #7.2 Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:
#X-DSPAM-Confidence: 0.8475
#Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. ... |
08b37c91d09648bdaa50a1fc112d66f6fe318279 | abmpinoy/test2 | /python2.7/classes/inheritance.py | 375 | 3.8125 | 4 |
#!/usr/bin/env python
class vehicle(object):
def __init__(self, color,make,model):
self.color = color
self.make = make
self.model = model
def blah(self):
print "test test test"
class car(vehicle):
def test(self):
print self.color
print self.make
print self... |
e87e9e47f825fe8b0b8f6b85d8cecb9395151104 | Abhinaay/Python-Challenges-Adhoc | /Problem4.py | 648 | 4.21875 | 4 | #Problem : take all input from user .
# i) check that all character are string
# ii) if all char are string then create user in your linux based OS
# iii) also create password for same use,
# password will be ===>> hello{username}
#!/usr/bin/python3
import os
username=input("Enter the name of user y... |
e782ac2ee34fe74613ebdba9a92a8885fcf639ad | artheadsweden/python_adv_dec18 | /day1/Closures.py | 316 | 3.671875 | 4 | def outer(x):
def inner(y):
print(x, y)
return inner
def func_fact(e):
def inner(b):
return b**e
return inner
def main():
f = outer(10)
f(20)
square = func_fact(2)
cube = func_fact(3)
print(square(3))
print(cube(3))
if __name__ == '__main__':
main()
|
0a327effda1f5351bef94039fce2985ca5a39a3a | Amelie02/oc20 | /editor/editor_ilaame.py | 3,303 | 3.875 | 4 | """Place multiple rectangles with the mouse."""
import pygame
from pygame.locals import *
BLACK = (0, 0, 0)
GRAY = (127, 127, 127)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
GRAY = (127, 127, 127)
YELLOW = (255, 255, 0)
CYAN = (0, 255, 255)
MAGENTA = (255, 0, 255)
pygame.init()... |
0a0fb0692fe2652bdd94c474fbc9ea30aa5d17a7 | mihirsam/CS1465-ALGORITHM-LAB | /18.01.18/Fibonacci_while.py | 256 | 4.03125 | 4 | # Fibonacci series using while loop
num = int(input("Enter a number here : "))
result = 1
in1 = 0
in2 = 1
while (result <= num):
result = in1 + in2
in1 = in2
in2 = result
if(result <= num):
print (result)
else:
break
|
12a07d0144c004969ae430fcbeeeddf229732945 | coderlzy/python- | /比赛训练7天/day1字符串/回文字符串.py | 176 | 3.734375 | 4 | #给出一个长度不超过1000的字符串,判断它是不是回文
str1=input("请输入一个字符串:")
if str1[::-1]==str1:
print("Yes!")
else:
print("No!") |
9863a2dfde0f19ac950ba503895b232b00ebe683 | psungu/Algorithms | /camelCase.py | 772 | 4.25 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
"""
There is a sequence of words in CamelCase as a string of letters, , having the following properties:
It is a concatenation of one or more words consisting of English letters.
All letters in the first word are lowercase.
For ea... |
923fa8962865cb7c202a4f8b224760631834f193 | fidler32/schoolWork | /Avocado.py | 7,942 | 3.734375 | 4 | # William Fidler
# 02/15/20
# Avocado
# "I have not given or received any unauthorized assistance on the assignment
# Link here:
import statistics
def getLinesOfFile():
filepath = "resources/avocado.csv"
file = open(filepath, "r")
lines = file.readlines()
file.close()
return lines
def readAndComp... |
720768650cc99f57af7f643570dcd1b5e421758b | Prasang-Biyani/Data-Science | /Programming Terms/first_class_and_high_order.py | 841 | 3.921875 | 4 | # First class function: A function which is treated like any other variable.
# A function can be passed as an argument, can be assigned to a variable, and can be returned like any other variable.
def square(x):
return x * x
def cube(x):
return x * x * x
# f = square
# print(square)
# print(f(5))
# ... |
9d9b286066de3e5202a8ce59f60f2185b1465f62 | lgaan/pseudocode-compiler | /compiler/interpreter.py | 5,084 | 3.9375 | 4 | """Interpret a file"""
import re
class Interpreter:
"""Main interpreter"""
def __init__(self, file):
self.content = self.read(file)
self.in_if = False
self._last_condition = None
self.variables = {}
def read(self, file):
"""Read a file"""
with open(file, ... |
04513a9245c0914eff768ddacecc04c798ddeb47 | Mineru98/Algorithm | /competition/step14/7785.py | 316 | 3.625 | 4 | # -*- coding:utf-8 -*-
import sys
input = sys.stdin.readline
N = int(input())
arr = {}
for _ in range(N):
people, action = input().split()
if action == "enter":
arr[people] = None
elif action == "leave":
del arr[people]
for people in sorted(arr.keys(), reverse=True):
print(people)
|
ffa8d97c0b0a886129b3931dd2c48a2d20279922 | RajGohire/Minesweeper-Python | /CLI/Minesweeper.py | 2,679 | 3.625 | 4 | from Board import *
from Moves import *
from os import system, name
from tkinter import *
class Game():
def __init__(self, size):
self.root = Tk()
self.gameOver = False
self.firstClick = True
self.size = size
self.gameBoard = GameBoard(self.root)
self.btns = []
... |
5bf1500a7a49d61d3bb18a1affb27b88bcb2ce40 | nbrahman/HackerRank | /04 Cracking the Coding Interview/Recursion-Fibonacci-Numbers.py | 435 | 4.03125 | 4 | # def fibonacci(n):
# if n == 0:
# return 0
# elif n == 1:
# return 1
# else:
# return fibonacci(n - 1) + fibonacci(n - 2)
# #return ((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5))
mem = {}
def fibonacci(n):
if n < 2:
return n
try:
return mem[n]
except... |
53735812314ed89e44558d4747fff76727909a5f | frederico-prog/python | /cursoemvideo/Atividades/exercicios/ex010.py | 596 | 4.125 | 4 | # Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos dólares ele pode comprar.
# Considere US$1,00 = R$3,27 - US$ = 5,10 - € = 5,70
print('******** DESAFIO - AULA 07 - CALCULADORA 3 *********')
n1 = float(input('Quanto você quer investir na compra dos dólares? R$ '))
cotacao = float(i... |
5a21f18a39ff0c0dda0b64a7e34fc7fc468fd600 | bkrishna2006/system | /mylab/coursera/timeofday.py | 541 | 3.53125 | 4 | filename = raw_input("Enter your file name: ")
try:
fd = open(filename)
except:
print "File not found: %s" % filename
quit()
theDict = dict()
for line in fd:
words = line.split()
if len(words) < 1 or words[0] != "From" or words[0][-1] == ":" or len(words) < 6: continue
time = words[5]
time... |
7249e290eb0b7b1ca35629038c1dacc3762a16df | sthapliyal37/my_Programs | /optimalpath.py | 275 | 3.84375 | 4 |
def Dijkstra(matrix,n,m):
length=[0]*n*m
parent=[]
for i in range(n):
lst=[]
for j in range(m):
lst.append
n,m=map(int,raw_input().split())
matrix=[]
for i in range(n):
lst=[]
lst=map(int,raw_input().split())
matrix.append(lst)
print(Dijkstra(matrix,n,m))
|
a8c167c26d5535585c626d3a0bb8ced24773aae7 | sachin0186/python_programs | /average.py | 96 | 3.703125 | 4 | a=0
y=0
while a<10:
x=int(input("enter "))
y=y+x
a=a+1
print("the average is ",y/10) |
5bcab2cd8a01cafb7d6cbeeb03e194c04f12f253 | chdharm/LearningPython | /vimeo/first_round/third.py | 773 | 3.875 | 4 | def first_approach_3(arr,):
pass
def first_approach_4(arr,):
pass
def is_adjacent(dic, num1, num2):
if num1 == num2:
#See if we have the two index no adjacent
dic_val1 = dic[num1]
dic_val2 = dic[num1]
#Check if these two arrays have atleat one combination where difference is zero
def... |
48686f39b2a6ab64befde86de16a54198b877f06 | dbychkar/python_lessons | /python_coursera/6_week/79_Сортировка подсчетом.py | 819 | 3.875 | 4 | """
Дан список из N (N≤2*10⁵) элементов, которые
принимают целые значения от 0 до 100.
Отсортируйте этот список в порядке неубывания
элементов. Выведите полученный список.
Решение оформите в виде функции CountSort(A),
которая модифицирует передаваемый ей список.
Использовать встроенные функции сортировки нельзя... |
3505d71465320dd3332c9d39ab541336e180121e | AmberJBlue/aima-python | /submissions/Fritz/mygames.py | 6,465 | 3.75 | 4 | from collections import namedtuple
from games import (Game)
class GameState:
def __init__(self, to_move, board, label=None, maxDepth=5):
self.to_move = to_move
self.board = board
self.label = label
self.maxDepth = maxDepth
def __str__(self):
if self.label == None:
... |
7e994870ad288a4d72ba8857c58a4a2427be3944 | antonkrupin/algorithms | /unittest/checkSubString.py | 460 | 3.78125 | 4 | def checkSubString(string, subString):
if len(subString) == 0:
return True
for i in range(len(string)):
counter = 0
if string[i] == subString[0]:
counter += 1
for j in range(1,len(subString)):
if i + j < len(string):
if string[... |
fa26586b782975166dbb3b64f84477cbf3b8946b | candilek/Python-Projeler | /beden Kitle Endeksi.py | 168 | 3.5625 | 4 | boy=float(input("Lütfen boyunuzu giriniz: "))
kilo=int(input("Lütfen kilonuzu giriniz: "))
BKE=kilo/ (boy* boy)
print("Beden Kitle Endeksiniz:{} ".format((BKE))) |
64e7e7f7ffa09f78bb2992c11f9b9e10b4d4e433 | Cukerman/repos | /1/60полиндром.py | 431 | 3.546875 | 4 | #a=input('Введите строку ')
a='а роза упала на лапу азора'
found=False
i=0
c=len(a)-1
k=0
while 0<(c-i) :
while a[i]==' ':
i+=1
while a[c]==" ":
c-=1
if a[i]!=a[c]:
found=True
break
i+=1
c-=1
if f... |
357909b16a759eb01daef8194e561d0b6df3dc3e | salcedogeiner/ngxGenerator | /gen_filters.py | 680 | 3.515625 | 4 |
class filters:
def space_case(self,n):
x=n.split("_")
temp = ""
for t in x :
temp += t.capitalize()+" "
return temp[0:-1]
def upper_camel_case(self,n):
x=n.split("_")
temp = ""
for t in x :
temp += t.capitalize()
return t... |
1d58a1a446e0d96c94121c9d6040142e1b3b5203 | ramya-muniraj/Read-file | /readeg.py | 508 | 3.9375 | 4 | count=0
char=input("Enter Character of the string to be fetched:\n")
file_object=open('sample.txt','r')
file_list=file_object.read()
num_words=file_list.split()
for letter in range(len(num_words)):
if num_words[letter][0]== char:
count=count+1
print("The corresponding string is:",num_words... |
f578180adf8b01edc66737e82beca8bcf9638b30 | Esala-Senarathna/Python-Ex | /DSA Labs/DSA Practice/merge sort practice.py | 423 | 4.03125 | 4 | #merge sort function
def mergeSort(array):
mid = len(array)//2
left = array[:mid]
right = array[mid:]
mergeSort(left)
mergeSort(right)
i = j = k = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
array[k] = left[i]
else:
array[k] = ... |
aa3862f185d7c3b2052eae3869a0b242c13b3eef | MalgorzataBala/repo_python | /week2/day3/proba.py | 450 | 3.5625 | 4 |
input_liczba = input("Podaj liczbę do sprawdzenia podzielności ")
s = str(input_liczba)
print(s)
list_of_string = list(s)
print(list_of_string)
konwert_to_int = [int(i) for i in list_of_string]
print(konwert_to_int)
summ = sum(konwert_to_int)
print(summ)
if summ in(3,6,9):
print(input_liczba, "- jest podzielna p... |
1bc4db27f042520dfd441dda186eca549c553f52 | subramaniam-kamaraj/codekata_beginner | /set1_prob2_odd_even.py | 123 | 3.90625 | 4 | N=input()
if N.isdigit()==True:
N=int(N)
if N%2 == 0:
print("even")
else:
print("odd")
else:
print("invalid")
|
f8a7bf81a16a5c1fcd8da6e5848f3077ab91c9d0 | vinceajcs/all-things-python | /algorithms/other/randomized_set.py | 1,241 | 3.796875 | 4 | """Design a data structure that supports all following operations in average O(1) time.
insert(val): Inserts an item val to the set if not already present.
remove(val): Removes an item val from the set if present.
getRandom: Returns a random element from current set of elements. Each element must have the same probabi... |
004e89386e94f0772f33106b5039b2367dc40bfc | ronaldo1618/petting_zoo | /animals/monkey.py | 454 | 3.59375 | 4 | from .animal import Animal
from movements import Walking
class Monkey(Animal):
def __init__(self, name, species, shift, food, chip_num):
Animal.__init__(self, name, species, food, chip_num)
Walking.__init__(self)
self.shift = shift
def feed(self):
return (f'Will still basket of... |
17347be27d96e36556e6f0dbdd96f9aabe3b1566 | AdvaithKumar412/grokking-algorithms | /3-recursion/3-recursion.py | 425 | 4.03125 | 4 | def countdown(i):
print i
if i <= 0: # base case
return
else:
countdown(i-1) # recursive case
# countdown(3)
def factorial(x):
if x == 1: # base case
return 1
else:
return x * factorial(x-1) # recursive case
# print factorial(3)
# factorial(3) -> factorial(3-1) -> factorial(2-1)
# factorial(2-1) = 1
# ... |
0faf617293f55238b10df80864cbcb686cd537b3 | nvv11/algorithms_and_data_structures_in_python | /Lesson_7/bubble_sort.py | 891 | 4.125 | 4 | # Отсортируйте по убыванию методом пузырька одномерный целочисленный массив,
# заданный случайными числами на промежутке [-100; 100). Выведите на экран
# исходный и отсортированный массивы.
import random
def bubble_sort(array, reverse=False):
sing = int(reverse) * 2 - 1
pos = 1
while pos < len(array):
... |
646d4978c18fefaab4897ac1ba89d4f016ca516a | junbyungchan/python | /scratch04/ex04.py | 1,204 | 3.734375 | 4 | """
numpy의 행렬 관련 함수
"""
import numpy as np
A = np.array([
[1,2,3],
[4,5,6]
])
B = np.array([
[1,2],
[3,4],
[5,6]
])
print(A)
print(B)
print(A.shape) # (2, 3) : 2 x 3 행렬 --> 행렬의 모양을 알수있다.
print(B.shape) # (3, 2) : 3 x 2 행렬
nrows, ncols = B.shape
print(nrows,'x',ncols)
# sclicing: 원하는 행, 열의 원... |
8c4db1d20bbd44685cb029e10ad28e72667913ab | Adub17030/CSE-2050 | /LABS/Lab 06/Starter Code/sortedlist.py | 3,025 | 3.78125 | 4 | class SortedList:
def __init__(self, L = [], cmpIn = None):
self._L = L
self._cmp = cmpIn
self.ctComparisons = 0
self.selectionSort()
# Selection sort provided to you
def selectionSort(self):
self.ctComparisons = 0
for i in range(len(self._L)):
min_idx = i
for j in range(i+1, len(self._L)):
... |
10a44200d90ce960a1780980bdd0d0788614420a | juliushaertl/uni-cg | /graphictools/models.py | 1,700 | 3.875 | 4 | from math import *
import copy
class Point:
def __init__(self,x,y):
self.x = x
self.y = y
def rotate_deg(self, deg, origin):
angle = radians(deg)
new_x = (self.x-origin.x) * cos(angle) - (self.y - origin.y) * sin(angle);
new_y = (self.x-origin.x) * sin(angle) + (self.y... |
e2d58d52ad9058abf9e62047e0b921aee7f90c68 | AJsenpai/codewars | /sumOfTwoPositiveIntegers.py | 137 | 3.65625 | 4 | # Kyu 7
def sum_two_smallest_numbers(numbers):
return sum(sorted(numbers)[:2])
print(sum_two_smallest_numbers([5, 8, 12, 18, 22]))
|
7e2018cbb8913cb1559bd95a0114a7e988811d16 | Bulka148/Bulka148 | /HomeWork_5/Authors.py | 1,528 | 3.515625 | 4 | class Author:
def __init__(self, n1, n2, coun, yearB, nick=None, yearD=None):
self.name1, self.name2 = n1, n2
self.yearB, self.yearD = yearB, yearD
self.nick, self.country = nick, coun
self.works = []
def addWork(self, work):
self.works.append(work)
class Work:
def ... |
28f0345b4f2ca26af66004508cb3afad5c226331 | kiyoxi2020/leetcode | /code/leetcode-769.py | 977 | 3.703125 | 4 | '''
leetcode 769. 最多能完成排序的块
数组arr是[0, 1, ..., arr.length - 1]的一种排列,我们将这个数组分割成几个“块”,并将这些块分别进行排序。之后再连接起来,使得连接的结果和按升序排序后的原数组相同。
我们最多能将数组分成多少块?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/max-chunks-to-make-sorted
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
class Solution(object):
def maxChunksToSorte... |
6f1e3f976462312c061a649e7fdff880209ab41b | oscarhscc/algorithm-with-python | /剑指offer/二叉搜索树与双向链表.py | 1,240 | 3.796875 | 4 | '''
题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
'''
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def Convert(self, pRootOfTree):
# write code here
... |
9a29f9d0dbcc9e77b0a6e08789f3586adb70754e | ayushxx7/learning_sockets | /server.py | 915 | 3.53125 | 4 | import socket, time, pickle
### What is a socket?
# It is an endpoint that receives data. socket sends and receives data.
# socket itself is not the communication, it's just an endpoint that receives that communication.
# the endpoint sits at an IP & and a PORT.
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)... |
2a38253a064b420415011e31a81905bb6b2330b3 | Rushabh-Runwal/python-turtle | /snake_game/scoreboard.py | 1,027 | 3.828125 | 4 | from turtle import Turtle
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.high_score = self.get_high_score()
self.score = 0
self.hideturtle()
self.goto(0, 280)
self.color('#fff')
self.update()
def get_high_score(self):
wit... |
ec3a30fc5c371fdea41eff8903e900bbe61059c8 | raindroid/ece241_helper | /logic/logicElements.py | 2,357 | 3.734375 | 4 | class LogicSignal(object):
"""
default signal is 0
>>> t = LogicSignal()
>>> t.get_signal()
0
"""
def __init__(self, sig: int = 0):
if sig != 1 and sig != 0:
raise Exception("Error Signal!")
self.__sig = sig
def __str__(self):
return... |
7652c616c2ad631c8026c04d6253ace3440c8231 | mohdsameer7408/python_codes | /test.py | 135 | 4.34375 | 4 | # My first python program!!!
name = input("What is your name? ")
col = input('whats your favourite colour? ')
print(name+' likes '+col) |
cb6ab99ab973c1f0d7be04e8c54cc717466236a1 | Dansmith-rgb/pw-manager | /db.py | 2,611 | 3.90625 | 4 | import sqlite3
# table name = pwmanager
# Can have a look at what is in the table.
def look_at_table():
# Connecting to the DB.
conn = sqlite3.connect('passwords.db')
# Create cursor
c = conn.cursor()
try:
# Getting the first 50 lines with the limit use.
c.execute("... |
01bc44271b4c34d1703e201c27fc8d39e262f046 | fathimashibila/pythonluminar | /luminarpythonprograms/flowcontrol/agebydob.py | 498 | 4.21875 | 4 | dob_date=int(input("enter the dob date="))
dob_month=int(input("enter the dob month="))
dob_year=int(input("enter the dob year="))
current_date=int(input("enter the current date="))
current_month=int(input("enter the current month="))
current_year=int(input("enter the current year="))
year=current_year-dob_year
month=... |
633bdf3aa1e70becad99839189210cc52e29a9e8 | OrenMustaki/SlurmToBash | /SlurmToBash.py | 751 | 3.875 | 4 | #!/usr/bin/env python3
#
import sys
import re
delim = ","
def convert(string):
nodes = []
string = re.split(r',\,*(?![^[]*\])', string)
for i in string:
if not "[" in i:
nodes.append(i)
continue
j = i.split('[')[1].replace(']', '')
h = i.split('[')[0]
... |
49d4d0aa5322ceae6d6431982e14bd07be7e38a9 | SfietKonstantin/iaproject | /IA.py | 1,064 | 3.578125 | 4 | import math
# We will do an algorithm based on auction.
# The fact is that the number of agents is
# different over time, and that one agent
# (a stack of wolves) can be splitted into
# two other wolves.
#
# Our cost function is proportional to
# - ratio of creature / human
# - distance to a house
# - number of hum... |
899bac960e60d3a0f07bd4b810823281eed8f375 | MonikaBarget/DigitalHistory | /TXT_replaceWORDwithREGEX.py | 1,038 | 3.78125 | 4 | # Script to replace keywords in TXT following a regex pattern
import re
infile="C:\\###\\students.txt"
outfile="C:\\###\\students_hashtags.txt"
exclude_list=["III", "VII", "VIII", "XVI", "XII" "XIII", "XIV", "NDB", "HDM", "ADB", "NDB"]
delimiter_list=[]
delimiter_dict={}
person_list=[]
count=-1
with open(infile, 'r'... |
8a0030ffa2117758c3cfc37bea08877fffdf1caf | JerickLiu/Point-of-Sale-POS-System | /Item.py | 14,796 | 3.671875 | 4 | from Menu import Menu
from Functions import Functions
from FindProduct import FindProduct
TAXRATE = 0.13
class Item:
# Holds information representing an item in the store
def __init__(self, sku, name, quantity, price):
self.sku = sku
self.name = name
self.quantity = quantity
self.price = price
return
... |
7bbc8182a1c0cc2a79dc7163e771f643cd8ac67b | 666sempron999/Abramyan-tasks- | /Begin(40)/15.py | 502 | 3.953125 | 4 | """
Begin15 ◦ . Дана площадь S круга. Найти его диаметр D и длину L окружности,
ограничивающей этот круг, учитывая, что L = 2·π·R, S = π·R 2 . В качестве
значения π использовать 3.14.
"""
import math as m
S = int(input("Введите S: "))
while S == 0:
S = int(input("Введите S: "))
D = pow((S/m.pi),(1/2))
... |
3e08f8819c771d882f5351a6982618b0b0a450d3 | SelvorWhim/competitive | /Codewars/Mod4Regex.py | 552 | 3.78125 | 4 | import re
'''
idea: an integer is divisible by 4 in each of 3 cases:
1. it's a single digit divisible by 4
2. it ends in an odd digit followed by an even digit that's not divisible by 4
3. it ends in an even digit followed by an even digit that is divisible by 4
the rest deals with the formatting as described.
tests s... |
f1888362d86f7b8aeb64ea90c346a32a1fda0787 | zingesCodingDojo/DojoAssignments | /Python/PythonOOP/Carlos_PlayingWithModules_0509.py | 2,908 | 4.65625 | 5 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
# dir(urllib2)
# help(urllib2)
"""
class User
By now, you should have a better understanding of the user class we showed you at the beginning of this chapter!
So far we've learned how to do a handful of things:
Define new classes
Add attributes that des... |
58b4f4121abf092b8357db974697cb76d87d8124 | bllanos/python-learning-exercises | /learnPythonTheHardWay/ex19/ex19_drill3.py | 143 | 3.53125 | 4 | def inputAndPrint(*args):
for val in args:
print "You entered %r" % raw_input("%s: " % val)
inputAndPrint("Prompt 1", "Prompt 2")
|
86301c40713f6b319de7938a32cfa7ea566a946e | novoru/CS | /01/fib/fib3.py | 355 | 3.734375 | 4 | import time
from typing import Dict
memo: Dict[int, int] = { 0: 0, 1: 1 }
def fib3(n: int) -> int:
if n not in memo:
memo[n] = fib3(n-1) + fib3(n-2)
return memo[n]
if __name__ == "__main__":
start_time = time.time()
n = 40
print("fib3(%d)=%d"%(n, fib3(n)))
print("execution time: %s [... |
ddb00e62cb2f8e88ab743e13badef92950b0075a | ChrisJaunes/generating_test_paper | /Generator/genProgramming/p17.py | 2,253 | 3.640625 | 4 | import random
from sample import ProgrammingProblemDesc, ProgrammingProblemSTD
def generatorProblemDesc() -> ProgrammingProblemDesc:
return ProgrammingProblemDesc("有多少小于当前数字的数字", """
给你一个数组nums,对于其中每个元素nums[i],
请你统计数组中比它小的所有数字的数目。
换而言之,对于每个nums[i]你必须计算出有效的j的数量,
其中 j 满足j != i 且 nums[j] < nums[i]。
以数组形式返回答案。
示例 1... |
872931efab8fc52b170b51787e7f2c73961a672f | baby-Jie/StudyResources | /Coding/normal/python/projects/DemoProjects/PythonDemos1/com/smx/pythondemos1/algorithm/leetcodes/strings/125_验证回文串.py | 275 | 3.734375 | 4 | class Solution:
def isPalindrome(self, s: str) -> bool:
s = s.lower()
temp = ""
for item in s:
if item.isalnum():
temp = temp + item
return temp == temp[::-1]
s = Solution()
print(s.isPalindrome("race a car")) |
3080b66653c55378cbdbd4052905717d7fbf00c8 | atharva07/python-files | /functions3.py | 637 | 3.78125 | 4 | def change_name(mylist):
mylist.append(5)
print('values inside a function',mylist)
return
def make_name(mylist1):
mylist1.append(4)
print('values inside a function',mylist1)
return
mylist1 = [56,67,34]
make_name(mylist1)
print('values outside a function', mylist1)
mylist = [34,45,667]
change_... |
6be78b2e262e484d88238515381eb9ad2a62eab9 | nuria/study | /algorithms2/week4/plot.py | 1,036 | 3.75 | 4 |
# plot graph with networkx
# http://networkx.lanl.gov/tutorial/tutorial.html#graph-generators-and-graph-operations
import csv as csv;
import networkx as nx;
import matplotlib.pyplot as plt
#---------------------------- main program ---------------------
#f = open('./g3.txt','rb');
f = open('./testCase7.txt','rb');... |
af5e8e5b0c780ca8db67ae02ad5fe59f75795258 | phucduongBKDN/100exercies | /100 exercise/no45.py | 271 | 3.546875 | 4 | #Two Sum IV - Input is a BST
input = [5,3,6,2,4,0,7] #tree
target = 9
def twoSum(input,target):
for i in range(len(input)):
sub = 0
sub = target - input[i]
if sub in input:
return True
return False
print(twoSum(input,target))
|
ab137dbba2445fe55f1a6e5d5552a89f4f40266f | szarbartosz/asd-python | /trees/BST.py | 1,931 | 3.859375 | 4 | class BSTNode:
def __init__(self, key, value):
self.key = key
self.value = value
self.parent = None
self.left = None
self.right = None
def insert(root, node):
if root is None:
root = node
else:
if node.key <= root.key:
if root.left is None... |
04f3c0f4b314aba56eb2ad3d68e665bb46561d6a | divyatejakotteti/100DaysOfCode | /Day 63/CompanyLogo.py | 1,340 | 4.3125 | 4 | '''
A newly opened multinational brand has decided to base their company logo on the three most common characters in the company name. They are now trying out various combinations of company names and logos based on this condition. Given a string
, which is the company name in lowercase letters, your task is to fin... |
12bf7773047b8cae2fcc5f8ce04bd4efa438601c | Richard-D/python_excrise | /algotithm/quickSort.py | 308 | 4 | 4 | def quickSort(array):
if len( array ) < 2:
return array
else:
pivot = array[1]
less = [i for i in array[1:] if i <= pivot]
grater = [i for i in array[1:] if i > pivot]
return quickSort( less ) + [pivot] + quickSort( grater )
print(quickSort([10,5,2,3,5,8,7,1,2])) |
50f60b163ff0281804bf66cf2ed6ee82e926cd6f | prakriti-gupta/tic-tac-toe | /aaa.py | 2,385 | 4.25 | 4 | from tkinter import *
import random
class Application(Frame):
"""A GUI application which which generates random number and gets user input"""
def __init__(self, master): #initialize newly created Application object
"""Initialize the frame"""
Frame.__init__(self, master) # super(Applica... |
e65c12dcffe444215f4e2a10ef0eb0406a630d5c | hsuweibo/Pygame-Snake | /main.py | 5,039 | 3.71875 | 4 | import tkinter
import tkinter.messagebox
import pygame
from game import Game
from direction import Direction
"""
This module contains all the logic for setting up a display and rendering the snake game using the pygame module.
The main procedure maintains a while loop updating the display constantly.
"""
# Customiza... |
a009307c3ee1dd5151e4d56e0887a33ce6fcbe36 | ramyasutraye/python-programming-27 | /beginner level/+ve,-ve.py | 138 | 4.15625 | 4 | a=input("enter the number: ")
if(a>0):
print("a is positive number")
elif(a<0):
print("a is negative number")
else:
print("a is zero")
|
9a5067e51a6c752a4520da19486c96cd63e027ba | realbakari/python-program | /Random/Two Avenues/edge_define_sol.py | 3,197 | 3.8125 | 4 | class Edge:
def __init__(self, vertex1, vertex2, weight):
self.vertex1 = vertex1
self.vertex2 = vertex2
self.weight = weight
class Graph:
def __init__(self, vertices, edges):
self.vertices = vertices
self.edges = edges
class DisjointSet:
def __init__(self, vertice... |
4cb2cf16f4ac158b1908c12c9f03f705dbec40c4 | dmc200/Python-Projects | /Scripts/intro.py | 451 | 3.703125 | 4 | greeting = "Hello"
name = 'Michael'
# Use replace() function
# my_message = my_message.replace('World', 'Universe')
# Concat Strings
# message = greeting + ', ' + name + '. Welcome!'
# message = '{}, {}. Welcome!'.format(greeting, name)
# f-string's
message = f'{greeting}, {name.upper()}. Welcome!'
# get methods ... |
7a4b1fee4ec237cde46961fda603d90dc2e64f8f | MAPLE-Robot-Subgoaling/IPT | /data/HW5/hw5_107.py | 595 | 4.21875 | 4 | def main():
print()
width = int(input("Please enter the width of the box: "))
height = int(input("Please enter the height of the box: "))
symbolOutline = input("Please enter a symbol for the box outline: ")
symbolFill = input("Please enter a symbol for the box fill: ")
print()
for i in range... |
4a57487984144099464755e1216a07ad3e91c65b | wen089130/ziliao | /yibu.py | 3,016 | 3.546875 | 4 | """
The module for asynchronous running tasks in Tk GUI.
"""
import tkinter as tk
from concurrent import futures
from typing import Callable, Generic, List, TypeVar
_EVENT_PERIOD_MS = 100
_THREAD_POOL = futures.ThreadPoolExecutor(5, 'pool')
T = TypeVar('T')
class _Promise(Generic[T]):
def __init__(self, future... |
f60b45384fe3ad99c42a14b52cf63aa6b7928fca | hazzarux/project_euler | /src/p2.py | 708 | 3.796875 | 4 | '''
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms... |
036e5c391449581183be7664ea2993998581314e | Kvazar78/Skillbox | /8_algoritm_for/task_83_1.py | 467 | 4.09375 | 4 | # Выведите третью степень каждого нечётного числа в диапазоне от
# единицы до указанного пользователем числа включительно.
# Для этого используйте шаг внутри функции range.
n = int(input('Введи число: '))
for i in range(1, n +1, 2):
print(f'Третья степень нечетного числа {i} - {i ** 3}') |
2d28ced6c9b6162b0c78013ecdff686f0d4344ad | owaiskazi19/Practice-Problems | /Tree/bfs_iterative.py | 993 | 3.875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
... |
9d949db5bc18c25bfa2997593486dc1b10a3d8c9 | SayantanMitra87/Python-Tutorial | /PythonTutorial/Exercises/Exercises/exercise-2/ex2.py | 246 | 3.765625 | 4 | # Exercise 2: Comments and Pound Characters
# A comment, this is so you can read your program later.
print("I could have code like this.")
print("Hi # there.")
# You can also use a comment to "disable" or comment out code
print("This will run.") |
7ce50f0e3dd1aeb0e6a1a690b2fbddb9f6f993e2 | maryamkh/MyPractices | /Merge_Intervals_Solution1.py | 1,083 | 3.890625 | 4 | # Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals,
#and return an array of the non-overlapping intervals that cover all the intervals in the input.
#Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
#Output: [[1,6],[8,10],[15,18]]
#Explanation: Since intervals [1,3] and [... |
1e39b0039c6217def118bcceb4deb04039d60c20 | JuanDavidEspitia/python-course-master | /code/operadores_relaciones/Operadores_Logicos.py | 477 | 4.15625 | 4 | # Operadores boleanos
print(2+4 == 8)
print(2+4 == 6)
# Existen tres tipos de operadores logicos
# NOT
# AND
# OR
print(not True == False)
print(not True == True)
print("*********** AND ***********")
print(True and True)
print(True and False)
print(False and False)
print("*********** OR ***********")
print(True or Tru... |
627e79a0af9b062d40cf73e095613da276650e30 | rodrigovegajaldin/codigo_python | /programas_1/codigo17.py | 415 | 3.90625 | 4 | #este programa es para probar los diccionarios
dic = {'rodri' : 1 , 'elias' : 2 , 'brian' : 3}
print((dic.keys()).count('rodri'))
#a,b,c=dic
#print(a,b,c)
#lista = sorted(dic)
#print(lista)
#print(sorted(dic))
#print('hola',dic)
#del dic['rodri']
#for key in dic:
# print('hola:',key)
#print(sorted(dic)[0])
#va... |
c73ec4c0ceca4e458504ce39680d388e33fc690b | YDD9/cs-study | /graph/binaryTree_minimum.py | 762 | 4.125 | 4 | # Python program to find minimum depth of a given Binary Tree
# Tree node
class Node:
def __init__(self , key):
self.data = key
self.left = None
self.right = None
def minDepth(root):
# Corner Case.Should never be hit unless the code is
# called on root = NULL
if not root:
... |
f80677fce43e6d26f5cd62e12365d10cadc08bb2 | mwenz27/python_onsite_2019 | /week_02/10_classes_objects_methods/03_dog.py | 2,236 | 4.46875 | 4 | '''
Building on the dog exercise in the previous section:
1. Create a dog class and make the functions from the last class methods of the dog class.
2. Add an __init__() method that sets the following attributes:
- name
- color
- age
- is_hungry (should be a boolean)
- percent_full
Note: is... |
a696e5ecec2cb41a33f730fa79051929cb1c2374 | gohan8895/Intek-project | /Fundamental-Data-Structure-and-Algorithms/products_of_other_numbers/product_other_num.py | 1,177 | 4.1875 | 4 | def get_products_of_other_numbers(ls):
"""
Return a list of products
Parameter:
----------------
a list of integers, for ex: [1, 7, 3, 4]
Return:
-----------------
A list of integer:
List of products or each index calculate the product of
every integer except the integ... |
bd14a1aaaa8095ce270cba80aef7d5e20cfd4dbd | torisoper/SGBTT | /(v11)finalProject (1).py | 16,654 | 3.625 | 4 | # Tori, Teelin, Spencer, Geraldine, Ben
# Code Final Project - Fauxtoshopsnapgram
import gui
import random
from gui import *
from functools import partial
import image
from image import *
import urllib
import simplejson as json
picture = None
filepath = None
# ---------------------------- drawArt() Function ------... |
350c03f591ce805e26fe8d1eba747becaf82d863 | OmarFaruq502/Python-Basics | /Challenges 35-44/043.py | 985 | 4.3125 | 4 | #------------------------------------
# Problem 043
#------------------------------------
Question = """
------------------------------------------------------------------------------------
Ask which direction the user wants to count (up or down). If they select up, then ask
them for the top number and then count fr... |
4a15cf6baf83a80cd0ada975a0a28779c6687f77 | SyTuan10/C4T16 | /Session7/conrua.py | 111 | 3.515625 | 4 | from turtle import *
n = int(input("Nhap n: "))
for i in range(n):
forward(100)
left(360/n)
mainloop() |
8629337d5ac574837a563427a965de2eb371ba8e | SV-ZeroOne/Python-Projects | /Random/functionsInPython.py | 1,488 | 4.40625 | 4 | #Python Functions
#starts with defining the name_of_function():
# doSomethingInFunction
#if no params is given then Default is applied
def name_of_function(argument='Default'):
'''
Docstring explains function.
'''
print(f"Hello {argument}")
name_of_function()
name_of_function("Steve")
print()
def a... |
2cc28d97547199d53ff0b67131c092d7084b4324 | mritu301/https-leetcode.com- | /Duplicate Zeros.py | 619 | 3.5 | 4 | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
temp2 = arr.copy()
length = len(temp2)
temp1 = []
i = 0
flag = False
while i < length :
if temp2[i] == 0 ... |
28ec5afc1f569bc993c06b63f75bba01018adba8 | christopher-burke/warmups | /python/codingbat/src/missing_char.py | 1,061 | 4.1875 | 4 | #!/usr/bin/env python3
"""Missing Character.
Given a non-empty string and an int n, return a new
string where the char at index n has been removed.
The value of n will be a valid index of a char in
the original string(i.e. n will be in the range
0..len(str)-1 inclusive).
missing_char('kitten', 1) == 'ktten'
missin... |
41e7f9a8463f749479b6bed46f5b9e2acac191bd | dongbo910220/leetcode_ | /array/713. Subarray Product Less Than K Medium.py | 1,983 | 4.03125 | 4 | '''
Your are given an array of positive integers nums.
Count and print the number of (contiguous) subarrays where the product of all the elements in the subarray is less than k.
Example 1:
Input: nums = [10, 5, 2, 6], k = 100
Output: 8
Explanation: The 8 subarrays that have product less than 100 are: [10], [5], [2], ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.