blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
fa966cde9da500e83f3a427ba0893485fc0e2e1b
damianquijano/PythonCurso3
/Scripts/Tkinter/2-Boton.py
2,918
4.03125
4
# Ejemplo de creación y configuración del control botón que es agregado a la ventana principal. # Intente entender el funcionamiento del programa. Primero debe ajecutarlo para darse cuenta lo que hace, y luego entender cómo lo hace. # Experimente modificando, quitando, agregando instrucciones y valores con el fin de o...
944a9e5487dab90021248695d9e19283de2e4113
ChenLaiHong/pythonBase
/test/exam/矩阵各列的平均值.py
735
3.75
4
""" 【问题描述】编写程序计算一个5*5的矩阵s中每列的平均值。 【输入形式】标准输入的每一行表示矩阵的一行,以空格作为间隔。 【输出形式】标准输出的一行为各列的平均值,以空格作为间隔。 【样例输入】 1.0 2.0 3.0 4.0 5.0 2.0 3.0 4.0 5.0 1.0 3.0 4.0 5.0 1.0 2.0 4.0 5.0 1.0 2.0 3.0 5.0 1.0 2.0 3.0 4.0 【样例输出】3.0 3.0 3.0 3.0 3.0 """ temp = [] for i in range(5):...
5877cae61a219dca85a8c0580498d83e0ce93baa
halliejr/comp110-21f-workspace
/exercises/ex03/happy_trees.py
338
3.6875
4
"""Drawing forests in a loop.""" __author__ = "730249177" # The string constant for the pine tree emoji TREE: str = '\U0001F332' space1: str = "" + TREE depth: int = int(input("Depth: ")) if depth > 0: print(TREE) while depth > 1: depth = depth - 1 TREE = TREE + space1 print(TREE) el...
d882dc95bbc00bed51ee7ce8227cdd3c60333bab
xu1718191411/AT_CODE_BEGINNER_SELECTION
/CONTEXT_167/registration.py
112
3.6875
4
S = input() T = input() a = T[0:-1] if (a == S) and (len(T) > len(S)): print("Yes") else: print("No")
f22db5eaa6ddc15d6079070f5c4aeecf1714cf71
mervegrbz/snake-game-
/snake.py
3,089
3.5625
4
from turtle import* import random import time delay=0.07 screen=Screen() screen.setup(500, 500) screen.tracer(0) width=500 height=500 screen.bgcolor('green') snake=Turtle() snake.shape("square") snake.shapesize(1.3,1) snake.penup() dx =20 dy =0 snake.speed() face="no" snakesize=1 start=True snake.color("black") he...
4f315706a6653228c83b85333c98c327bf9e3af1
tcoolb007/pitch
/main.py
9,975
3.578125
4
import cards import pdb # define class 'Player' class Team(): def __init__(self,name,t1,t2): self.name = name self.t1 = t1 self.t2 = t2 self.pile = [] self.trump_pile = [] self.points = 0 self.pts_queue = 0 t1.join_team(self) t2.join_team(se...
4bc25b9302afb43fc338b365f07f51e8a7da77f9
Jayhello/python_utils
/python_utils/numpy_operate/flip_arr.py
535
3.75
4
# _*_ coding:utf-8 _*_ import numpy as np def flip_arr(): arr = np.arange(6).reshape(2, 3) print arr # [[0 1 2] # [3 4 5]] print np.fliplr(arr) # [[2 1 0] # [5 4 3]] print arr[:, ::-1] # [[2 1 0] # [5 4 3]] print np.flipud(arr) # [[3 4 5] # [0 1 2]] print ...
43de3680aae8ac479f5870ebee470eb5b280d285
shadowezz/A-December-of-Algorithms-2019
/December-06/solution.py
622
4
4
import math def is_prime(number): if (number < 2): return False else: root = math.floor(math.sqrt(number)) for num in range(2, root + 1): if (number % num == 0): return False return True def fibprime(number): def helper(prev, current, number): ...
023a7814ead0f7afbc68736b41dc2d00473b5635
ToBoldlyCode/Coding-Challenges
/Leetcode/575 Distribute Candies.py
366
3.546875
4
class Solution(object): def distributeCandies(self, candies): """ :type candies: List[int] :rtype: int """ unique = set(candies) num_unique = len(unique) half_candies = len(candies)/2 if num_unique < half_candies: return num_unique...
6b624878af2a736eceff18b35eacd46c9efd3a2b
saurabh17jan/ds_algo
/interestingQuestion/mySoln/001_two_sum.py
529
3.515625
4
# 1. Two Sum # Leet # Given nums = [2, 7, 11, 15], target = 9, # Because nums[0] + nums[1] = 2 + 7 = 9, # return [0, 1]. # python3 class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: l = len(nums) ans = [] # print(l) for x in range(len(nums)): f...
ce7b5a055831094a667758d3f5fe97573292afe0
lijiliang123/newtest
/Game.py
1,834
4.125
4
""" :一个猜数字小游戏 :利用random.randint()生成一个随机数 :玩游戏者通过提示最终猜到这个随机数 """ import random import pickle from datetime import datetime,date tips = """ Please select the game level: 1. Grade 1; 2. Grade 2; 3. Grade 3; """ #print(tips) print('{0:*^150}'.format(tips)) grade = int(input('You select the Grade: ')) if grade == 1: ...
1479a27a0f9324adf65eafb2fb2c1ebe5db66cd9
Bradford-Chen/-python
/03-字符串格式化.py
1,381
4.03125
4
# %s 字符串的占位符, 可以放置任何内容(数字) # %d 数字的占位符 # 例题1: # print('李白,字太白,701年出生,《静夜思》') # print('杜甫,字子美,712年出生,《登高》') # print('王维,字摩诘,701年出生,《九月九日忆山东兄弟》') # name1 = input('请输入名字:') # name2 = input('请输入字:') # year = input('请输入出生年:') # poem = input('请输入诗词:') # s1 = name1 + ',字' + name2 + ',' + year + '年出生,《' + poem + '》' # print...
a4de215db5183909c59c84732c8b671f4d820981
Oumar96/travelingstrategy-1
/server/data/helper_class/url_helper.py
1,208
3.5625
4
class UrlHelper: """ Class used to convert base API links to useable ones that can be parsed """ def __init__(self, api): self.api = api def get_currency_api(self, country_iso): """ Gets the currency API link for a given country :param country_iso: Name of the cou...
83b2b4e01ea9e92356b029ddc975c437a57972d9
ShaheerC/python_fundamentals1
/exercise6_1.py
461
4
4
home_km = 0 while True: print("Would you like to walk or run?") walk_run = input() if walk_run == "walk": home_km+=1 print("Distance from home is {} km.".format(home_km)) elif walk_run == "run": home_km+=5 print("Distance from home is {} km.".format(home_km)) elif wa...
6e8a1708c3be862b2ef3c06e247f38b637711ad6
zhucebuliaolongchuan/my-leetcode
/DFS/LC323_NumberOfConnectedComponentsInAnUndirectedGraph.py
1,247
3.953125
4
""" 323. Number of Connected Components in an Undirected Graph Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph. Example 1: 0 3 | | 1 --- 2 4 Given n...
fd584127b017a7b2f46bf85c0c1ca92bc19cf0f6
benbradley747/Predictions-Bot
/bot/classes/prediction.py
4,895
3.5
4
class Prediction: def __init__(self, prompt, creator): """ str : The prompt for this prediction """ self.prompt = str(prompt) """ User : User object for the creator of this prediction """ self.creator = creator """ bool : Determines whether this prediction is resolved or n...
f6321dce245a18c4ebab5c979ec392db9479b412
deshpr/ML_Assignment_Three
/hw2.py
6,084
3.984375
4
# course: TCSS555 # Homework 2 # date: 10/16/2018 # name: Martine De Cock # description: Training and testing decision trees with discrete-values attributes import sys import math import pandas as pd class DecisionNode: # A DecisionNode contains an attribute and a dictionary of children. # The attribute is...
1a32fea22430a392be95176040d0f994491acf3d
kholmatov/algorithm
/TreeNode_remove_val.py
3,543
3.875
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def find_node_and_parent(self, root, key): parent = None while root and root.val != key: parent = root if...
c511f47c5eb939725a66b8451b2e672891579f93
iWonder118/atcoder
/python/ABC094/C.py
246
3.578125
4
n = int(input()) numbers = list(map(int, input().split())) sorted_number = sorted(numbers) for i in range(n): if numbers[i] <= sorted_number[n // 2 - 1]: print(sorted_number[n // 2]) else: print(sorted_number[n // 2 - 1])
e126862e7d723df96e32f1f1e2d1d0b3ac707d0d
alikslee/Python-itheima-2019
/01-Python核心编程/代码/07-面向对象/03-面向对象其他/hm_04_类方法.py
299
3.59375
4
# 1. 定义类:私有类属性,类方法获取这个私有类属性 class Dog(object): __tooth = 10 # 定义类方法 @classmethod def get_tooth(cls): return cls.__tooth # 2. 创建对象,调用类方法 wangcai = Dog() result = wangcai.get_tooth() print(result)
89259f3c41df4b3cfd012f669a9976203c44b182
sunitakunwar/python_assignment_dec1
/number 2.py
205
4.34375
4
'''Write a Python program which accepts the radius of a circle from the user and compute the area.''' from math import pi r = float(input ("enter a radius:")) A = (pi*r*r) print("The area is:%.3f" %A )
33042b290288dd2ce61c5dfe400cefdbf832fdea
flybetter/Life_is_short_you_need_python
/learn/Lesson/Lesson_7_class.py
1,346
4.40625
4
#!/usr/bin/python # -*- coding: utf-8 -*- """ @project= Life_is_short_you_need_python @file= Lesson_7_class @author= wubingyu @create_time= 2017/12/17 上午10:49 """ class Employee: pass john = Employee() # Create an empty employee record # Fill the fields of the record john.name = 'John Doe' john.dept = 'comput...
79d98cd4cf0b78c5bdb344dd962a0c7ab9ec9c3e
cqulpj/pyside2demos
/matplotdemo/example2.py
311
3.734375
4
import matplotlib.pyplot as plt from pylab import * x = linspace(0, 5, 10) y = x ** 2 fig = plt.figure() axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1) axes.plot(x, y, 'r') axes.set_xlabel('x') axes.set_ylabel('y') axes.set_title('title') plt.show()
b02c17ef4e5d1d8911e117bbd8de02cab0ca8486
BlueDi/Augmented-Maps
/src/pyramid.py
6,631
3.515625
4
import cv2 as cv import numpy as np import glob import yaml # pyramid line color line_color = (0, 0, 0) # pyramid line thickness line_thickness = 22 # pyramid distance between points line_size = 10 # color of the base of the pyramid fill_color = (0, 255, 0) def calculate_pyramid(homography, image_test, pos_x, pos_y)...
d13e08bdcb8be81a187b03b9d865b38220117f19
uu64/project-euler
/problem010.py
450
3.609375
4
# -*- coding: utf-8 -*- MAX = 2000000 MAX_ROOT = MAX**0.5 def main(): # 2以外の偶数は素数じゃないので予め除く numbers = [i for i in range(3, MAX+1, 2)] idx = 0 while True: n = numbers[idx] if n > MAX_ROOT: break numbers = list(filter(lambda x: x<=n or x%n!=0, numbers)) idx += ...
00601734894864ce862668352fde269830808456
heraditcation/TD
/td1/ex02.py
607
3.8125
4
""" __author__ = "Andrew PICORNELL" __copyright__ = "Copyright 2020, All rights reserved" __version__ = "1.0.0" __email__ = "andrew.picornell@etu.u-pec.fr // " __github__ = "https://github.com/heraditcation" __linkedin__ = "https://www.linkedin.com/in/andrewpicornell/" __status__ = "C/Python Dev + Master Git/Shell (zsh...
d44d7f0023b65514b8151f09bf1cb94498ecf3ce
peltierchip/The-Python-Workbook
/Exercise_book/Exercise_60_RoulettePayouts.py
1,178
3.8125
4
#!~/anaconda3/bin/python from random import randint red = [1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36] green = [0, 37] while True: roulette_result = randint(0, 37) #inclusive, 0 is 0 and 37 is 00 if roulette_result in red: rvb = "Red" elif roulette_result in green: ...
503386f1465c84feef8a9f36ce552d8a5e1e3c0b
Artarin/Python-Trashbox
/fucking_fibonacci.py
383
3.71875
4
#решение авторов: #n = int(input()) #if n == 0: # print(0) #else: # a, b = 0, 1 # for i in range(2, n + 1): # a, b = b, a + b # print(b) num = int(input()) fMinusTwo = 0 fMinusOne = 1 for i in range (2,num+1): f = fMinusOne+fMinusTwo fMinusTwo = fMinusOne fMinusOne = f if num ...
f8ee7b0e18795ab1b87e88333ddceb731a0d7f89
mattheusphilipe/SD2019-2
/src/main.py
1,807
4.15625
4
class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.next = None class ListaCircularEncadeada: # Constructor to create a empty circular linked list def __init__(self): self.head = None modifiedWord = "" # Function to inse...
e5047919b0efd520cd6a866ff57d54ef6a5c1009
kinyashov/training_projects
/Fraction/Fraction.py
2,392
3.875
4
"""Создать класс Fraction, который должен иметь два поля: числитель a и знаменатель b. Оба поля должны быть типа int. Реализовать методы: сокращение дробей, сравнение, сложение и умножение. """ def find_nod(n, d): while d: n, d = d, n % d return n class Fraction: def __init__(self, a=1, b=1): ...
0a98d8c698da6cb05330b7113efaa00d9c1b04e5
ihuanglei/classical-algorithm
/python/algorithm/leapyear.py
266
3.796875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # author: huanglei # 闰年 for year in range(1700, 2022): if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0: print('{} 是闰年'.format(year)) else: print('{} 是平年'.format(year))
4edc37c0a0395a24c3910f13b3717460772ed713
LuckyJoey/Python
/ex29.py
172
3.84375
4
people = 20 cats = 30 dogs = 15 if people < cats: print("<") if people > cats: print(">") if people >= dogs: print(">=") if people <= dogs: print("<=")
7a95b47ef7214f1014754096c295fccbbcb99b19
jhirtzel/demos-tutorials
/AutomateTheBoringStuff/mclip.py
635
3.71875
4
#! python3 # mclip.py - A multi-clipboard program TEXT = { 'agree': """Yes, I agree. That sounds fine to me.""", 'busy': """Sorry, I have a conflict. Can we reschedule?""", 'upsell': """Would you consider upgrading to a monthly donation?""" } import sys, pyperclip if len(sys.argv) < 2: print('Usage: ...
714fae9b4b0950a20c00b3428aa5a4708a761ab7
sldion/DNACC
/Other Code/MayaVi-1.5/build/lib/mayavi/Filters/Vorticity.py
6,662
3.53125
4
""" This filter computes the vorticity of an input vector field. For convenience, the filter allows one to optionally pass-through the given input vector field. The filter also allows the user to show the component of the vorticity along a particular cartesian co-ordinate axes. This code is distributed under the con...
f64d78d5d0389aa150cb8251f5cf0882a5bd176a
karamzad/project
/StaDistance.py
852
3.5
4
#!/usr/bin/env python # this program reads stations position from an input file and calculate the minimum distance between stations. import numpy as np from pyrocko import orthodrome def all_dist(lats, lons): nl = len(lats) dis = np.zeros([nl,nl]) for ind in range(0, nl): dis[ind] = orthodr...
fbeeb6859ec10a05b4dfbb706e4e920ad01dbc62
kiranmahi2593/k
/dictionaries.py
2,480
4.375
4
#--------------------------Dictionaries-------------------------------------# def Create_dict(DictInput): Userdict = dict() for i in range(DictInput): UserDictKey = input("Enter the Key:") UserDictValue = input("Enter the Value:") Userdict[UserDictKey] = UserDictValue ...
06626cf5898e87d57dedccc3d36cb509e12b4d7b
alessandrrra/algoritmoprogramacao2_pilha
/ativ_pilha/pilha.py
632
3.65625
4
from node import Node class Pilha: def __init__(self): self.top = None self._size = 0 def inserir(self, elem): #inserir elemento node = Node(elem) node.next = self.top self.top = node self.size = self.size + 1 def tirar(self): ...
d63acf300790a429956106f7fad18f43fc2bc2a1
komararyna/Homework6
/task5.py
179
3.953125
4
line = str(input('insert your phrase:')) x = line.split(" ") a = 0 for el in x: if len(el) > a: a = len(el) print(el) elif len(el) == a: print(el)
6ef3137acc880533eae91236644b0606c72c768d
ES-DOC/esdoc-docs
/cmip5/mindmaps/Software/TextTranslate.py
262
3.640625
4
#!/usr/bin/python #translate mindmap text nodes into xml format. import re import fileinput #f=open(-,'r') #for line in f: for line in fileinput.input(): if re.match("^<text>",line): line=line.replace('[','<') line=line.replace(']','>') print line,
e52aa0dbfbd79cb2aacb984bd0a0f725eb53c53b
abhishekjee2411/python_for_qa_synechron
/class_ops.py
344
3.671875
4
class Dog: def __init__(self,breed,color): # "self" is the brain of the object self.breed=breed self.color=color def speak(self): print("bhou...bhou") def jump(self): print("I am jumping") def __del__(self): print("Good Bye!") tommy=Dog("german shepherd","brown") tommy.speak() tommy.jump() print(...
f1138fa859be397557de678dbab75ab82635cda6
losvaldote/python_cinves
/Ejercicios/Jrincon_suma_35.py
1,592
4.09375
4
# coding: utf-8 # # TAREA COSMO # # Problema1: multiplos de 3 y 5 # In[2]: def multiple(valor,multiple): #se define la operacion multiplo mult = valor % multiple #donde i sera el valor de del rango y multiple sera el numero el cual queramos que sea multiplo if mult==0: return True ...
f0c33495a5886b6db5c601e265771971d27d1479
pinakiganguly/Python
/Coursera_projects(Introduction_to_scripting _in _Python/Course2_Differ_in_file_contents.py
3,856
3.828125
4
""" Project for Week 4 of "Python Data Representations". Find differences in file contents. Be sure to read the project description page for further information about the expected behavior of the program. """ IDENTICAL = -1 def singleline_diff(line1, line2): """ Inputs: line1 - first single line strin...
6cbc9e69418ef00ade74504021068783303d9639
guotian001/DataStructure-python-
/chapt10_sort_second/test.py
518
3.953125
4
# encoding:utf-8 ''' 插入排序 ''' def insertionSort(list, N): for i in range(1,N): # 将一个元素插入到前面的有序序列中去 temp = list[i] # 找到位置 j = i while list[j-1]>temp and j>0: list[j] = list[j-1] j-=1 list[j] = temp if __name__ == '__main__': # list = [1,2...
4ff1f2927d26d76fdae7e35648889ddf7d58f83f
bright-night-sky/algorithm_study
/백준/Bronze/Bronze 3/1942번 아직 안품.py
1,007
3.65625
4
# https://www.acmicpc.net/problem/1942 # 세 개의 입력 for i in range(0, 3): # 한 줄에 시작하는 시각, 끝나는 시각 입력 start_time, end_time = input().split(' ') # 3의 배수의 갯수를 저장할 변수 count = 0 # 시작하는 시각과 끝나는 시각에 콜론(:)을 떼어내고 숫자로 만들기 start_time = start_time.replace(':', '') start_time = int(start_time) end_time...
a2307171880389c6795464d48d4acc2516eba116
venkateshelangovan/IIT-H-Course-Work-
/Placement Preparation - IIT H - Leetcode/Arrays/Easy - Number of Good Pairs - Leetcode 1512.py
890
3.734375
4
""" Given an array of integers nums. A pair (i,j) is called good if nums[i] == nums[j] and i < j. Return the number of good pairs. Example 1: Input: nums = [1,2,3,1,1,3] Output: 4 Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed. Example 2: Input: nums = [1,1,1,1] Output: 6 Explanation: Ea...
61d1c23ea53c84e4fdbafe17128958833a7966da
wttttt-wang/leetcode_withTopics
/Backtracking/combination-sum-iii.py
747
3.515625
4
""" Combination Sum III @ Backtracking: Nothing special """ class Solution(object): def combinationSum3(self, k, n): """ :type k: int :type n: int :rtype: List[List[int]] """ if k < 0 or n < 0: return [] results = [] self.helper(1, k, [],...
9d229fe847bc3b7987d13c74dda4a60d4c797c11
bmatejek/addax
/data_structures/graph.py
9,960
3.890625
4
import struct class Graph(object): def __init__(self, prefix, directed, vertex_colored, edge_colored): """ Graph class defines the basic graph structure for addax used for clustering commmunities, motif discovery, and generating random examples @param prefix: a string to referenc...
1da280f12f2320bc0e85b1608e198d1897a0831f
kagfupanda/pythonfp
/week8/8_11.py
647
3.96875
4
#8_11.py #Author Siddharth Srinivasan def main(): print("Enter daily average temperature below. Leave empty when finish.\n") hdd, cdd, hot, cool = 0, 0, 0, 0 date = 1 try: temp = input("Day#{} :".format(date)) while temp != "": temp = int(temp) if temp > 80: ...
0fdcaada98fb9062ef78baa44b4844d73a6afecc
sGeetanjali/CAPpython
/dictionary.py
655
4
4
''' empty={} print(type(empty)) print(empty == dict()) a =dict(one=1, two=2, three=3) b ={"one": 1,"two": 2,"three": 3} print(a == b) ''' my_dict ={"name": "Anjali","reg_no": 117098,"contact": 865876987,"course": 'MCA'} print(my_dict) print(my_dict ['name']) my_dict ['name'] = "Saroha" print(my_dict) my_dict ['...
faa724befa725ef9da1e102c82182a9daaedcf41
madewithkode/asciiEncDec
/ascii.py
1,869
3.90625
4
# Simple ASCII Encoder and Decoder Program with GUI # By Prince Kelvin Onyenanu import tkinter as tk from tkinter import filedialog as fd from tkinter import messagebox as mb import string root = tk.Tk() root.title("ASCII Encoder|Decoder") root.resizable(0,0) ToEncode_sv = tk.StringVar() ToDecode_sv = t...
8e99cf8e437fb797020e266eda60bb76a2827c43
Hvbyte/cursoemvideo-PYTHON
/Exercicios/ex029_radar_eletronico.py
365
3.71875
4
from time import sleep velocidade = float(input('Qual a velocidade atual do carro? ')) print('Um instante...') sleep(2) multa = (velocidade - 80) * 7 if velocidade>80: print('MULTADO! Você está acima da velocidade permitida que 80Km/h ') print('Você deve pagar uma multa no valor R${:.2f}'.format(multa)) print('...
5a61b7c8dd41f336a63e6a9dcbb5804ba810904b
Ramhawkz47/Experimental
/chatterBot/ParrotBot/test123.py
767
3.703125
4
print("existing command are:") print("") d={} for s in open("test.txt", "r", encoding="utf-8"): print(s) for i in range(len(s)): if(s[i:i+3]=="---"): a=s[0:i-1] b=s[i+4:(len(s)-1)] d[a]=b print(d) print("enter input:(type 'bye' to exit)") x=0 m= input...
a0cef5e3f93ffa593fd72a7b0a3bd6d396363055
baizeedrony/PythonFile
/PythonClass.py
956
4.09375
4
class user: name = '' email = '' password = '' login = False def __init__(self,name,email,password): self.name = name self.email = email self.password = password def login(self): email = input("enter your email:") password = input("enter you...
cdab29b559703335ab71b5d2d5b6131fdf689bed
sarthakjain95/UPESx162
/SEM I/CSE/PYTHON/meraArmStrong.py
696
3.984375
4
# UPESx162 # CSE / Python3 Programs # ArmstrongNumber # Recommended execution on https://repl.it/languages/python3 def isArmstrongNumber(number): if number==None: return -1 else: number=list(str(number)) sum=0 for digit in number: sum+= int(digit)**3 if str(sum)==''.join(number): return True else:...
5b5c224db4a98ef068403846bc3a7a1387280c50
joao-conde/competitive-programming
/resources/examples/dijkstra.py
1,389
3.796875
4
from heapq import heappush, heappop def dijkstra(graph, src): dists = [float("inf")] * len(graph) dists[src] = 0 visited = set() pq = [(0, src)] while len(pq) > 0: (_, cur) = heappop(pq) if cur in visited: continue visited.add(cur) # for each neighbor...
2a908c5fe5309265b930f2729b390abbcea35c56
Satily/leetcode_python_solution
/solutions/solution437.py
889
3.703125
4
from data_structure import TreeNode, build_binary_tree class Solution: def pathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: int """ if root is None: return 0 def travel(root, path_sum): ns = path_sum[-1] + ro...
54dbdb3ec2d459447c0f940d1824afee8a385b67
hireach/pythonPra
/1_25前/day10_30_1.py
2,436
3.515625
4
from tkinter import * import urllib.parse import urllib.request import json class Page: page = 1 a2dict = {} allc = [] page1 = Page() def nameBtnFn(): page1.page = 1 starname = var_name.get() starnameurl = urllib.parse.quote(starname) #把明星的名字编码成url编码 url = "http://mobilecdn.kugou.com/api/v3/search/song?forma...
c467a1821d660f5df7d7bd512e206f1bbaff86d7
claudioLamelas/projects
/python/mclip.py
989
4.0625
4
#! python3 # mclip.py - Dependendo da palavra chave dada, é copiada uma mensagem para o clipboard TEXT = {'agree': """Yes, I agree. That sounds fine to me.""", 'busy': """Sorry, can we do this later this week or next week?""", 'upsell': """Would you consider making this a monthly donation?"""} ...
721ac2a3f410a889ab412752fd7db8b26456f6e1
666sempron999/Abramyan-tasks-
/Begin(40)/21.py
1,115
4.125
4
''' Даны координаты трех вершин треугольника: (x 1 , y 1 ), (x 2 , y 2 ), (x 3 , y 3 ). Найти его периметр и площадь, используя формулу для расстояния меж- ду двумя точками на плоскости (см. задание Begin20). Для нахождения площади треугольника со сторонами a, b, c использовать формулу Герона: S = √ p·(p − a)·(p...
2b52c0e751ee76e4d00f6285d0bb90a9f5dd8dd3
digital-witch/Cry-Posting-Simulator
/cry_posting_simulator.py
1,137
3.546875
4
import keyboard import random keys = ['q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m'] def missedKey(key): keyboard.send('backspace') def fatFinger(key): to_write = '' if key == 'p' or key == 'l' or key == 'm': to_write = keys[keys.index(ke...
415d519223b63e71ffc9363f857c103c0a7ab8eb
RaphaelfsOliveira/workspace_python
/python_zumbi/py_functions/dicionarios.py
250
3.859375
4
d = {} d['a'] = 'alpha' d['o'] = 'omega' d['g'] = 'gama' print('Chaves: ', d.keys()) print('Valores: ', d.values()) print('a' in d) #perguntando se tem no dicionario print('x' in d) for chave in d: print(chave) print(chave, '->', d[chave])
017382f57200745ccd37899d638ea5dde51a92a7
IgorCalbo/Python-studies
/ex068.py
578
3.640625
4
import random n, pc, s, v = 0, 0, 0, 0 while True: n = int(input("Digite um número: ")) pc = random.randint(0, 50) escolha = input("Você escolhe par ou impar? ").strip().lower() if escolha == "par": epc = "impar" elif escolha == "impar": epc = "par" else: print("Escolha inválida") break s = n + pc if s ...
ff815ad52ef1a233977db0c33a03526e7a8919ad
subasreeM/subasree
/2power.py
70
3.640625
4
ab=int(input()) if(ab & (ab-1) == 0): print("yes") else: print("no")
abdcdee8e834786d7c066a5b4dbae7e8620cc1ad
hieuptch2012001/class_python
/Geometry/geometry.py
1,365
4.0625
4
from math import sqrt from math import pow class Geometry(): def __init__(self): pass def distance(self, x1, y1, x2, y2): return sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2) * 1.0) def middle(self, x1, y1, x2, y2): a = (x1 + x2) / 2 b = (y1 + y2) / 2 print(f"midpoint: (...
1d45d12325e2bb0d1109808050f962772ee4a2bc
ecoidealist/ITFDN100_7-1-1
/docs/lib/Exception Handling/7.2/7.2_Figure-7.py
1,454
3.765625
4
# ------------------------------------------------------------------------ # # Title: Assignment 07 # Description: Research Exception Handling & Pickling in Python # ChangeLog (Who,When,What): # Kstevens,11-20-19,Modified code to complete assignment 7 # -------------------------------------------------------------...
662640a6c77ef25ac94cca18667076d9f7c15bbd
gokulrajsambathkumar/odd
/maxno.py
114
3.671875
4
a=input() b=input() c=input() if(a>b) and (a>c): print(a) elif(b>c) and(b>a): print(b) else: print(c)
e0a474c9581ede545495fad4544bc2854c75480d
singularity014/DSAlgorithms
/Search_Algorithms/binary_search.py
864
4.09375
4
""" author: Praful code: Binary Search """ def binary_search(item, sorted_list): """ given an item to find and a sorted list, search the item in the list and reutrn the position of the item in the list :param item: item to search :param sorted_list: sorted list (Binary search always requi...
257b2084f7d8d6a574fb7667d8a82bdb0cc9c12c
Bawya1098/Hackerrank
/hackerrank/hackerrank/minimax.py
297
3.96875
4
arr = [1, 2, 3, 4, 5] list = [] def minimaxsum(arr): for num in range(0, len(arr)): value = arr.pop(0) result = sum(arr) list.append(result) arr.append(value) print(min(list), end=' ') print(max(list)) if __name__ == '__main__': minimaxsum(arr)
6979f36b7beff56e57b2b1019e68724aa112b297
aoschwartz7/HarvardCS50
/pset6/readability.py
909
3.890625
4
import re import math # Count the number of letters, words, and sentences per text. # Coleman-Liau index formula: # index = 0.0588 * L - 0.296 * S - 15.8 # where L is the average number of letters per 100 words in the text, # and S is the average number of sentences per 100 words in the text. # regex source for ...
1a9ce574bdc564b3bec0ff4cd28746f84e723d38
append-knowledge/pythondjango
/1/EXAM 2/overriding.py
329
3.84375
4
class Teacher(): def deta(self,name,age): self.name=name self.age=age print('teacher deta',self.name,self.age) class Student(Teacher): def deta(self,name,age): self.name = name self.age = age print('student deta',self.name,self.age) obj1=Student() obj1.deta('Lijo...
43b200e6d07b718bead9db96cbbf2bf45455d0da
Jeffrey1202/comp9021
/midterm/test.py
3,668
4.28125
4
# Defines two classes, Point() and Triangle(). # An object for the second class is created by passing named arguments, # point_1, point_2 and point_3, to its constructor. # Such an object can be modified by changing one point, two or three points # thanks to the method change_point_or_points(). # At any stage, the...
8e776e93a34ec8e9bde2658c42b9267e9bc7df29
m-g-shahriar/python
/date_time.py
234
3.796875
4
import datetime time=datetime.datetime.now() print("Current Date and time 24 hour") #for 24 hour print(time.strftime("%Y-%m-%d %H:%M:%S")) #for 12 hour print("\n") print("12 hour") print(time.strftime("%Y-%m-%d %I:%M:%S"))
639a4da8da9c394dd977f4bcddc3db4a74c5f031
handaeho/lab_dl
/ch04_Neural_Network_Learning/ex09_2_Layer_Neural_Network.py
10,990
3.703125
4
""" 2-Layer(2층 신경망)으로 이루어진 Neural-Network(신경망) """ import numpy as np from dataset.mnist import load_mnist class TwoLayerNetwork: def __init__(self, input_size, hidden_size, output_size, weight_init_std=0.01): """ 클래스에서 사용할 변수 초기화 Input : 784개(28x28) hidden_layer_1 : 뉴런 32개 ...
78eb8a3af748425b0dca6311ef585673c0a405f7
sallymroberts/coding_exercises
/ic15_fib.py
963
4
4
fibs = {0: 0, 1: 1} def get_fib(n): """ Get nth fibonacci number Arguments: n [Integer] index of fibonacci number Returns: [Integer] nth number in fibonacci sequence """ if n in fibs: return fibs[n] else: fibs[n] = get_fib(n-1) + get_fib(n-2) return fib...
0bedc160a1c6ece80ee98fb7c42584a22cecf1a0
sajibAdhi/py4e
/Using Python to Access Web Data/Week6/Extracting Data from JSON/code.py
278
3.625
4
import urllib.request import urllib.parse import urllib.error import json url = input("Enter Url - ") data = urllib.request.urlopen(url).read() jsonData = json.loads(data) count = 0 for sJSData in jsonData['comments']: count = count + int(sJSData['count']) print(count)
9979b99235b5a290576e6cacb1649026353fea4e
hsuweibo/lc-problems
/84-LargestRectangleInHistogram.py
3,138
3.84375
4
import unittest class Solution: # The largest rectangle can be obtained by iterating over all height[i], finding heights[r] and heights[l], # where l < i and heights[l] is the first bar < heights[i], and r > i and height[r] is the first bar < heights[i], # then multiplying the height (h = height[i]) by th...
5b9e3329e2a2f5d3770d321f2180d86d02b090a2
TimVan1596/ACM-ICPC
/python/course/leetcode/35. Search Insert Position.py
2,649
4
4
# -*- coding:utf-8 -*- # @Time:2020/6/24 11:11 # @Author:TimVan # @File:35. Search Insert Position.py # @Software:PyCharm # 35. Search Insert Position.py # Given a sorted array and a target value, return the index if the target is found. # If not, return the index where it would be if it were inserted in order. # You ...
85e654ec82e14975533a172bb1497330ad967c54
YerraboluHimajaReddy/LalithaClass
/LalithaPythonClass/Inheritance/Triangle.py
1,180
4.125
4
from LalithaPythonClass.Inheritance.Polygon import Polygon # if u want to call parent class constructor we should create constructor in the child class and call the parent constructor method in the child class constructor method class Triangle(Polygon): def __init__(self): Polygon.__init__(self,3) def...
1a8f0a744be57e257ff9ab073f3d67f0cc52ae17
akimi-yano/algorithm-practice
/lc/935.KnightDialer.py
2,530
3.515625
4
# 935. Knight Dialer # Medium # 631 # 262 # Add to List # Share # The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in t...
c27c21dbff92bdeb1de1d3cedb9a62117a57e436
cleversokol/python_sber
/module3/3_2_9.py
302
3.578125
4
import re import sys pattern = re.compile(r'z.{3}z') for line in sys.stdin: line = line.rstrip() if re.search(pattern, line) != None: print(line) #string = "zzxzz" #string = "zzz" #if re.search(pattern, string) != None: # print(string) #else: # print("no")
3e1e1a4a024102765fcb554f61cebbb0b5eb2ac3
cleissomfb/algoritmos2-2018-2
/Aula 3/Exercício 2/calcula_numero_meio.py
939
4.15625
4
#Digitar três números e separa o númnero da esquerda, do meio e o da esquerda. lista_num = [1, 2, 3] def num_direita(): direita_num = lista_num[0] for indice_direita in lista_num: if indice_direita > direita_num: direita_num = indice_direita return direita_num def num_esqueda(): e...
2b409f23aa369efd86f0a89d36164bb3baa8960e
Supriya-N/DeckOfCards
/linkedlist.py
1,198
3.984375
4
# # Implementation of a singly linked list. Add a method called “getNum(n). # getNum(n) should return the data item from the node in the nth spot in the list. # class Node(object): def __init__(self, data=None, nextNode=None): self.data = data self.nextNode = nextNode class linkedList(...
899a36b390a8e5f9ccadb673d2951ebd556e77e6
alex-gsantos/cursos_em_video
/desafio88.py
1,703
4.15625
4
''' Faça um programa que ajude um jogador da mega sena a criar palpites. O programa vai perguntar quantos jogos serão gerados e vai sortear 6 números entre 1 e 60 para cada jogo, cadastrando tudo em uma lista composta. Não pode haver números repetidos na mesma lista. ''' import random from time import sleep ...
0f343b3c342677191b2b40a9e8c2d2159cc41170
mriahi1/subscribers
/main.py
1,233
3.578125
4
# Import the modules import requests import json # Make it a bit prettier.. print "-" * 30 print "This will show the Most Popular Videos on YouTube" print "-" * 30 # Get the feed key = "AIzaSyD0Cl6YtiqkDsEzQvhXG6J-0zerEkFQbUY" channel = "UC6nSFpj9HTCZ5t-N3Rm3-HA&" def sub_count(key, channelID): api = "https://...
6a2ee3214b61b086a108cc9c6551ac62f9ccc44e
kolevatov/python_lessons
/week4/4_8.py
663
3.890625
4
# Сложение без сложения """ Напишите рекурсивную функцию sum(a, b), возвращающую сумму двух целых неотрицательных чисел. Из всех арифметических операций допускаются только +1 и -1. Также нельзя использовать циклы. Формат ввода Вводятся два целых числа. Формат вывода Выведите ответ на задачу. """ def sum(a,...
80f67535fdecc0bc56f951ffc94c223a43ea550a
AI-Jiny/Python-Practice
/Problem/01_입출력과 사칙연산/05_A+B.py
106
3.578125
4
a = input() a = a.split(" ") total = 0 for i in a: #total += i total = total + int(i) print(total)
a120e9c35a964d26212222cb75679e17f50822eb
mshadloo/Algorithm
/chapter 1/1-3.py
616
3.765625
4
def removeDuplicate1(str): checker = 0 i = 0 while i < len(str): intVal = ord(str[i]) - ord('a') if (checker & (1 << intVal) > 0): str = str[:i] + str[i + 1:]; else: checker |= (1 << intVal) i += 1 return str def removeDuplicate2(str): s...
0dea962fde11537cfdbc40158eeead453c5acc44
JeffryHermanto/Python-Programming
/07 Classes/16_multiple_inheritance.py
425
3.6875
4
# Multiple Inheritance class Employee: def greet(self): print("Employee Greet") class Person: def greet(self): print("Person Greet") class Manager(Employee, Person): pass manager = Manager() manager.greet() # A good example of multiple inheritance class Flyer: def fly(slef): ...
f0dd3f24674b66f74566add2020d8549279eef79
mattlehrer/exercism
/python/anagram/anagram.py
300
3.984375
4
def find_anagrams(word, candidates): alphabetically = ''.join(sorted(word.lower())) anagrams = [] for candidate in candidates: if alphabetically == ''.join(sorted(candidate.lower())) and word.lower() != candidate.lower(): anagrams.append(candidate) return anagrams
95e6d4efc87b1a8559bbfe347cd4a080463ce3ae
ljia2/leetcode.py
/solutions/trie/212.Word.Search.II.py
3,000
4.0625
4
class TrieNode: def __init__(self): self.dic = dict() self.word = None class Solution(object): def findWords(self, board, words): """ Given a 2D board and a list of words from the dictionary, find all words in the board. Each word must be constructed from letters of seq...
d4fda9ee42c25732610c9476601039217ceabe4a
nevinlazarus/Data61
/business/api-scraper.py
3,689
3.765625
4
#!/usr/bin/python import math import urllib import re import requests import json import unicodedata #returns #top[0] = y #top[1] = x #takes in a number of points, 2 strings (coordinates), returns a list of coordinates #the coordinates are listed as two lists, x coordinates, y coordinates. It is up to the #user to ...
92014744683db151d865bf375969a1691ad6823a
BParesh89/The_Modern_Python3_Bootcamp
/fileio/copy_reverse.py
291
3.75
4
def copy_and_reverse(filename, filename_reversed): with open(filename_reversed, "w") as file_reversed: with open(filename, "r") as file: file_text = file.read() reversed_text = file_text[::-1] file_reversed.write(reversed_text) copy_and_reverse('story.txt', 'story_reversed.txt')
d16928ab25efc0455b17ee592bca1f8ac88e35d8
rajeshkr2016/training
/chapter3_set_add_pop_intersection_symmetric/6-sets_pop.py
520
4.375
4
''' we can remove and return an item using the pop() method. Set being unordered, there is no way of determining which item will be popped. It is completely arbitrary. We can also remove all items from a set using clear(). ''' # initialize my_set # Output: set of unique elements my_set = set("HelloWorld") print(my_se...
7558b0c37d5ad72bfe3f830ad1a7539bee8bc74f
akshaybjadhav/Attendance-Using-Face-Recognition
/checked.py
218
3.609375
4
from datetime import datetime, timedelta now = datetime.now() current_date = now.strftime("%d/%m/%Y") current_time = now.strftime("%H:%M:%S") print(current_time) print(current_date) ottm="01/01/2000" print(ottm)
73ba8de52c084faa2c91dbfac55397b6a1f00308
NyangUk/Python
/day9/11.py
532
4.09375
4
#queue # put() ,get()으로 넣고 빼고 한다. import queue #선입선출 q = queue.Queue() for i in range(3): # 큐에 집어 넣기 q.put(i) while not q.empty(): # 큐가 비어있으면 반복문 나오기 print(q.get(), end =' ') #후입선출 큐 lq = queue.LifoQueue() for i in range(3): # 큐에 집어 넣기 lq.put(i) while not lq.empty(): # 큐가 비어있으면 반복문 나오기 ...
39150797035fc32670b6857d576780956ef798da
NeyBrito/Phyton
/Scripts-Python/pythontest/venv/desafio35.py
382
4.125
4
print ('======Calculador de Triângulos======') r1 = float(input('Tamanho da primeira reta: ')) r2 = float(input('Tamanho da segunda reta: ')) r3 = float(input('Tamanho da terceira reta: ')) if (r2 - r3)< r1 < r2 + r3 and (r1 - r3) < r2 < r1 + r3 and (r1 - r2)< r3 < r1 + r2: print('Estas retas formam um triângulo!'...
da7228e10470ba769a9b95e85dbef6fee418a4fe
wooloba/LeetCode861Challenge
/559. Maximum Depth of N-ary Tree.py
724
3.796875
4
#################### # Yaozhi Lu # # Aug 23 2018 # #################### #Origin: https://leetcode.com/problems/maximum-depth-of-n-ary-tree/description/ """ # Definition for a Node. class Node(object): def __init__(self, val, children): self.val = val self.children = children """ class ...
ce0e58ba7de538c169325a0cf1579d0e3ab9fc3a
tlennen/hackerrank-practice
/Python Practice/nested_lists.py
569
3.734375
4
if __name__ == '__main__': # https://www.hackerrank.com/challenges/nested-list/problem?h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen arr = []; for _ in range(int(input())): name = input() score = float(input()) arr.append([score,name]) arr.sort() if len(arr)!=0: ...
e3bf4508588b5eb944b5eafcf7de086b7790dfa6
pinesol/intro-ds-hai
/src/data_utils.py
16,326
4.0625
4
'''Functions used to parse data that are not specific to a particular file.''' import numpy as np import pandas as pd # DEPRECATED def parseFile(filename, useful_columns): '''Read the given csv file as a dataframe, keeping only the columns in useful_columns.''' data = pd.read_table(filename, sep=',') data...
d69c6278c31ceae9185747cead3468cfffbe74b6
sejongkang/Baekjoon_programming
/3.Deque/10866_덱.py
704
3.578125
4
from sys import stdin deque = [] for _ in range(int(stdin.readline())): arr = stdin.readline().split() if arr[0] == 'push_front': deque.insert(0, arr[1]) if arr[0] == 'push_back': deque.append(arr[1]) elif arr[0] == 'pop_front': if deque: print(deque.pop(0)) else: print(-...