blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
fd2b0a017cb1fdf89202bd4c8f2684d8e6d9e74e | yuzhishuo/python | /practice/algorithm/1/5.py | 796 | 4.1875 | 4 | 'You want to implement a queue that sorts items by a given priority and always returns the item with the highest priority on each pop operation.'
import heapq
class PriorityQueue:
def __init__(self):
self._queue = []
self._index = 0
def push (self,item,priority):
' warnning : <priorit... |
c254ed5af8f8faf02b03e13668017dcfdfef7dc8 | Sirly/practice_python_programs | /Binary2Text.py | 718 | 3.671875 | 4 | # Name: Kevin Nakashima
# Class: CPSC 223P
# Date: 02/07/2017
# File: Binary2Text.py
# converts a binary set to a string
#Imports=======================================================================
#T2B===========================================================================
def Bin2Text(binary):
tex... |
961e00d7ff2d3eeb5b94070da0d17d9ca573ef3c | eecs110/winter2019 | /course-files/projects/project_01/option1_graphics/demos/demo3_drag_event.py | 972 | 4 | 4 | '''
This demo shows you how you can create a new image by clicking the screen.
'''
from tkinter import Canvas, Tk
import helpers
import utilities
import time
import random
gui = Tk()
gui.title('Tour of options...')
# initialize canvas:
window_width = gui.winfo_screenwidth()
window_height = gui.winfo_screenheight()
ca... |
debf0f2dad245f2aba423d136628ee79af9718e2 | daniloaleixo/hacker-rank | /CrackingTheCode_track/DataStructures/01.Arrays_left_rot.py | 1,207 | 4.46875 | 4 | #!/usr/bin/python
# A left rotation operation on an array of size shifts each of the array's elements unit to the left. For example, if left rotations are performed on array , then the array would become .
# Given an array of integers and a number, , perform left rotations on the array. Then print the updated ar... |
5d2de9643d816c74970b031b8f61b3c470c89dd8 | nunrib/Curso-em-video-Python-3 | /MUNDO 2/ex041.py | 725 | 3.96875 | 4 | from datetime import date
anonascimento = int(input('Digite o seu ano de nascimento: '))
anoatual = date.today().year
ano = anoatual - anonascimento
if ano <= 9:
print(f'Você tem {ano} anos e é um atleta da categoria \033[1;30mMIRIM\033[m!')
elif ano <= 14:
print(f'Você tem {ano} anos e é um atleta da ca... |
d5026eea847c4d48f5a41ba659ac6f75ff5bffd1 | testtatto/project_euler | /problem9.py | 1,224 | 3.890625 | 4 | """
ピタゴラス数(ピタゴラスの定理を満たす自然数)とは a < b < c で以下の式を満たす数の組である.
a^2 + b^2 = c^2
例えば, 32 + 42 = 9 + 16 = 25 = 52 である.
a + b + c = 1000 となるピタゴラスの三つ組が一つだけ存在する.
これらの積 abc を計算しなさい.
"""
import math
if __name__ == '__main__':
a = 1
b = 2
summary = 0
combination_list = []
# aは最小のため、333までを考えればよく、bはcより小さいため、500ま... |
6d40d14a235a9d434d6cf63a9c6a9409ea6fd3e9 | Jithin0801/DS-and-Algorithms | /BinarySearchTreePython/Node.py | 1,503 | 3.671875 | 4 | class Node:
data = None
leftChild = None
rightChild = None
def __init__(self, data):
self.data = data
@property
def getData(self):
return self.data
@getData.setter
def setData(self, data):
self.data = data
@property
def getLeftChild(self):
... |
57ec9f1b3b661a4400687724a946e132d170a10a | arthurpbarros/URI | /Iniciante/2717.py | 160 | 3.75 | 4 | rem_m = int(input())
p1,p2 = input().split()
p1 = int(p1)
p2 = int(p2)
if (rem_m >= (p1+p2)):
print ("Farei hoje!")
else:
print ("Deixa para amanha!")
|
2c0e1ad5626ef2241fd4936a12864714e21d3efe | santoshikalaskar/Basic_Advance_python_program | /descriptors.py | 1,580 | 4.46875 | 4 | """
-These are special type of protocols used to set, get or delete any instance from a class.
-This is simillar to getter and setter method used in other programming language like java in encapsulation
-There are 3 predefined descriptors in python. Three different methods that are __getters__(),
__setters__(), an... |
ce64c13136fa732150df6b6738afb941c59ac9b3 | dongttang/baekjoon_algorithm | /1934.py | 278 | 3.765625 | 4 | count = int(input(""))
for i in range(0, count):
raw_data = input("").split(" ")
a = int(raw_data[0])
b = int(raw_data[1])
LCM = a if a >= b else b
while True:
if LCM % a == 0 and LCM % b == 0:
break
LCM += 1
print(LCM)
|
1f88394a2eb8f89cf9bcb6c448086170631029c2 | EllieYoon87/Lab5New | /TimeClient.py | 677 | 3.84375 | 4 | from Time import Time
t1 = Time( 21 , 45 , 22 ) #9:45:22 pm
t2 = Time( 5, 23 , 17) #5:23:17 am
t3 = Time( 13 , 23, 55) #1:23:55 pm
t4 = Time(7 , 52 , 23) #7:52:23 am
t5 = Time(18,43,23) #6:43:23 pm
print(t1.toString())
print("hours =", t1.getHours())
print("minutes =",t1.getMinutes())
print("seconds =",t1.getSeconds(... |
63da7161f46fcd10dcd3e36bdc3b8a88e0ade8ce | Lazurle/Python_Ehon | /8,クラスとオブジェクト/create_object02.py | 442 | 4.03125 | 4 | # ◆ コンストラクタ
# オブジェクトの生成時、自動的に呼び出される特殊なメソッド
class Book:
def __init__(self, t, p): # コンストラクタ、メソッド名は必ず「__init__」にします。
self.title = t
self.price = p
def printPrice(self, num):
print(self.title, ":", num, "冊で", (self.price * num), "円")
book1 = Book("絵本", 1680)
book1.printPrice(2)
|
be081fd811fb2d437ed933e5bd90c90dfb9ed86d | ssarangi/pygyan | /RegressionClassifier.py | 1,083 | 3.765625 | 4 | import numpy as np
class RegressionClassifier:
def __init__(self, num_variables, learning_rate, threshold):
self.num_variables = num_variables
self.threshold = np.full(num_variables + 1, threshold)
self.learning_rate = learning_rate
# Training data is in the form of a numpy array with ... |
4a980d9963294561e14ce3c515a3388c0db29c52 | LuciaSkal/engeto_academie_python | /project2.py | 1,823 | 3.875 | 4 | import random
def game():
print('*' * 90)
print('''
Welcome, to the COWS and BULLS game.
I have chosen number from 0 to 9 arranged in a random order.
You need to input a 4 digit number as a guess at what I have chosen.
Let's play...
''')
print('*' * 90)
cislo = tajny_cislo(4)
# ... |
94da7470591d1bf56dea4a7961332687dba58c60 | OpensourceBooks/python_gui | /tkinter/5.py | 528 | 3.59375 | 4 | from tkinter import *
class App():
def __init__(self):
self.number = 0
def widget(self):
self.root = Tk()
self.root.title("app")
self.button = Button(self.root, text="Hello, world!",command = self.click,width=50,height=5)
def pack(self):
self.button.pack()
#... |
0f6633f03b958e1c606f41ec4c82e660b6dfd350 | UdayQxf2/tsqa-basic | /BMI-calculator/03_BMI_calculator.py | 2,937 | 5.125 | 5 | """
We will use this script to learn Python to absolute beginners
The script is an example of BMI_Calculator implemented in Python
The BMI_Calculator:
# Get the weight(Kg) of the user
# Get the height(m) of the user
# Caculate the BMI using the formula
BMI=weight in kg/height in meters*height in me... |
0bbec211978813544b63e5af7944d543c9e85974 | MrOrz/leetcode | /rotate-list.py | 1,116 | 3.984375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @param k, an integer
# @return a ListNode
def rotateRight(self, head, k):
# Find the length of the linked li... |
9dac9c860557e5756a07bb2ac9a9a05079848071 | FelipePassos09/Curso-em-Video-Python-mod1 | /Exercícios/Exercicio22.py | 706 | 4.28125 | 4 | # -- Crie um programa que leia o nome completo de uma pessoa e mostre:
#-- O nome com todas as letras maiúsculas.
#-- O nome com todas minúsculas.
#-- Quantas letras ao todo ele tem (sem considerar os espaços).
#-- Quantas letras tem o primeiro nome.
nome = str(input('Diga seu nome completo: ')).strip()
nm = no... |
9115eebd05a95e117f1ab99ee2d630e8f7930268 | BhagyashreeKarale/dichackathon | /6.py | 218 | 3.609375 | 4 | # Q6.Write a Python script to add a key to a dictionary.
# Sample Dictionary : {0: 10, 1: 20}
# Expected Result : {0: 10, 1: 20, 2: 30}
SampleDictionary = {0: 10, 1: 20}
SampleDictionary[2]=30
print(SampleDictionary)
|
f1f1f45df43dedd6a8bceb43e09e20c12e6ea443 | sailskisurf23/sidepeices | /3door_sim.py | 915 | 3.96875 | 4 | #want to model simulation of 3 doors fallacy - Monty Hall problem
import random as r
def montysim(switch):
doors = ['Door1','Door2','Door3']
winning_door = r.choice(doors)
first_pick = r.choice(doors)
dummy_door_poss = [e for e in doors if e not in [winning_door, first_pick]]
dummy_door = r.choice... |
8c82b06e410a7abb91cfce861d89e1690f72dff1 | MilesTide/FEDSOMRGBHOGFC | /Test03.py | 217 | 3.921875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# @author: peidehao
import pandas as pd
# df = pd.read_csv('rb.csv', index_col='时间')
# print(df)
# df = df.where()
# print(df)
list1 = [1,2,3,4,5,6]
print(list1[-3:]) |
846011ea82a6b8691d125f5b8f4530ce183fa3db | rahul-tuli/APS | /Problems/Forming Magic Square/forming_magic_square.py | 3,751 | 3.5 | 4 | from itertools import permutations
def formingMagicSquare(s: [[int]], cache=True) -> int:
"""
Finds the minimum cost required to transform s into a magic square.
:pre-conditions: s is a matrix of order 3 (i.e. of shape 3x3).
:param s: The matrix to be transformed into a magic square.
:return: The ... |
8420ecb8f6ab440954d1a91a13e70d4c1924ee50 | stazman/python-practice | /python-multiskill-practice.py | 501 | 3.796875 | 4 | # File handling and Regex practice: Searching for a word in a file
import re
article = "We should all be so lucky as to come from fun parents. My parents were fun, and we always had a good time."
def quickwordsearch(word, filepath):
openfile = open(filepath, "r")
readfile = openfile.read()
findword = re.search... |
0c9e54d0fcc7deb2750dc09c0ade5f19d4ddf0f8 | dongyingname/pythonStudy | /Data Science/np/usefulOperations.py | 957 | 3.578125 | 4 | # %%
import numpy as np
x = np.array([[1, 2], [3, 4]])
y = np.array([[5, 6], [7, 8]])
v = np.array([9, 10])
w = np.array([11, 12])
# Inner product of vectors; both produce 219
print(v.dot(w))
print(np.dot(v, w))
# Matrix / vector product; both produce the rank 1 array [29 67]
print(x.dot(v))
print(np.dot(x, v))
# ... |
52a2535b1f6f1258409a3ae4590c1904a982814d | NanZhang715/AlgorithmCHUNZHAO | /Week_03/myPow.py | 1,553 | 3.875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
实现 pow(x, n),即计算 x 的 n 次幂函数(即,xn)。
示例 1:
输入:x = 2.00000, n = 10
输出:1024.00000
链接:https://leetcode-cn.com/problems/powx-n
"""
class Solution:
def myPow(self, x: float, n: int) -> float:
"""
思路: 递归, 类似二分治
时间复杂度:O(logn), 递归的层数
... |
9e8d01a976bab68b92213a2f69996b606ce21b8a | pulinghao/LeetCode_Python | /树与图/1028. 从先序遍历还原二叉树.py | 1,393 | 3.703125 | 4 | #!/usr/bin/env python
# _*_coding:utf-8 _*_
"""
@Time :2020/6/18 8:12 下午
@Author :pulinghao@baidu.com
@File :1028. 从先序遍历还原二叉树.py
@Description :
"""
import leetcode_utils
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solu... |
1976ba2401526adf4b678bf8d391cd7e844ea48e | frank217/Algorithm-study | /Implementation/22. Generate Parentheses.py | 980 | 3.515625 | 4 | '''
https://leetcode.com/problems/generate-parentheses/
'''
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
dic = {}
return self.helper(n,n)
def helper(self, l:int,r:int) -> List[str]:
if l == 0 and r ==0:
return [""]
result = []
... |
c976666af6b250015034b8743904a7488979a5ec | in-silico/in-silico | /crypto/prog.py | 149 | 3.578125 | 4 |
archivo= open("texto.txt","r")
s=""
for i in archivo:
s+=i.strip()
cad=""
for i in s:
if i.isalpha():
cad+=i.upper()
print cad
|
b5b27927c433c387a799186c300c58d1d09a9aa0 | bithu30/myRepo | /python_snippets/workday_coding_test/calc_wfreq.py | 970 | 3.84375 | 4 | from word_freq import WordFreq
import argparse
import sys
'''
The method is the main area where we fetch wikipedia content
and get the Word Frequencies claculated through methods in
the 'WordFreq' class in word_freq module
'''
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-pid", require... |
512fbf7709509e8284da309b77d87615b86bccae | rhysshannon/lpthw | /ex44e.py | 1,184 | 4.15625 | 4 | class Other(object):
def override(self):
print("OTHER override()")
def implicit(self):
print("OTHER implicit()")
def altered(self):
print("OTHER altered()")
class Child(object):
def __init__(self):
self.other = Other()
def implicit(self):
... |
6e068fe6c9f7785de9d54abc9bbfd806a2f84772 | bharadwaj08/Python | /Classes.py | 299 | 3.546875 | 4 | # -*- coding: utf-8 -*-
#Example 1
class MyClass:
i = 123
def f(self):
return 'hello world'
print (MyClass.i)
#Example 2
class Complex:
def __init__(self, realpart, imagpart):
self.r = realpart
self.i = imagpart
x = Complex(3.0, 4.5)
print (x.r, x.i) |
a6f8c0838f46b21c18685ad24d3e67737fa92413 | Aakanshakowerjani/Linked_List-Codes | /LinkedList_Insertion.py | 2,260 | 4.09375 | 4 | class LinkedList:
def __init__(self, data, next_node=None):
self.data = data
self.next_node = next_node
def add_node_inlast(self, data):
if self.next_node != None:
self.next_node.add_node_inlast(data)
else:
self.next_node = LinkedList(data)
... |
b4b960badb013c8d7ac8ee1e671213675faf9fdd | Hoan1028/IS340 | /IS340_ExtraCredit1_2.py | 460 | 4.15625 | 4 | #Ch 3. Decisions Problem 2
#Program takes user name, wage, hours and prints total pay
def main():
#prompt user for input and initialize pay variable
name = input("Enter name:")
wage = float(input("Enter wage:"))
hours = float(input("Enter hours:"))
pay = 0.0
#calculate wage with overtime and without
if ho... |
37a251e11e2b03e08a4211f45ff77cdd024f5142 | lection/leetcode-practice | /dp/363/lc_363_v2.py | 2,091 | 3.71875 | 4 | """
在leetcode上了试了试 m^2 * n^2的循环,没有超时,目前考虑使用这种迭代手段。
先对原始matrix进行m*n的预计算,每个cell存放从0,0到m,n的矩形和。
matrix[m][n] = matrix[m][n] + matrix[m-1][n] + matrix[m][n-1] - matrix[m-1][n-1]
然后进行一轮m^2*n^2的迭代,遍历所有矩形,找出最大值。
矩形 m1n1m2n2 的值为
r = matrix[m2][n2] - matrix[m2][n1] - matrix[m1][n2] + matrix[m1][n1]
如果 r == k 则可以提前返回
==========... |
dba3ddcd42f33f427583c0b2f0b92a2a5c52abce | jmromer/shop_listings | /lib/services/key_terms.py | 1,074 | 3.5 | 4 | """
Given a corpus of Etsy shop listing data, determine the most meaningful terms
across the corpus.
"""
from typing import List
from sklearn.feature_extraction.text import TfidfVectorizer
STOP_WORDS: List[str] = [
'about', 'all', 'also', 'and', 'any', 'are', 'but', 'can', 'com', 'etc',
'etsy', 'for', 'here'... |
dea70e7f39b571540866c2ee546e2b43d0c78b09 | imn00133/algorithm | /BaekJoonOnlineJudge/CodePlus/200DataStructure/Main/baekjoon_9093_pythonic.py | 884 | 3.875 | 4 | # https://www.acmicpc.net/problem/9093
# Solving Date: 20.03.21.
# list연산이 적게 들어가서 그런지 더 빠르다.
import sys
input = sys.stdin.readline
def main():
test_case_num = int(input().strip())
for test_num in range(test_case_num):
word_list = input().split()
reverse_str = ""
for word in word_list... |
8fac691882cfbf33cc7c5bdbcf46e79574314c5d | booleanShudhanshu/rock_papper_scissor_game.py | /Rock_Paper_Scissors_Game.py | 1,982 | 4.46875 | 4 | # Author- Shudhanshu Raj
# Make a rock-paper-scissors game where it is the player vs the computer.
# The computer’s answer will be randomly generated, while the program will ask the user for their input.
# This project will better your understanding of while loops and if statements.
# rock paper-----winner papper... |
a40fd3e7668b013a356cfa8559e993e770cc7231 | feleHaile/my-isc-work | /python_work_RW/13-numpy-calculations.py | 2,314 | 4.3125 | 4 | print
print "Calculations and Operations on Numpy Arrays Exercise"
print
import numpy as np # importing the numpy library, with shortcut of np
# part 1 - array calculations
a = np.array([range(4), range(10,14)]) # creating an array 2x4 with ranges
b = np.array([2, -1, 1, 0]) # creating an array from a list
# multip... |
d3063839de21911a56846cb93c0fb3a5849b65a7 | zuigehulu/AID1811 | /pbase/day07/code/dict1.py | 240 | 3.75 | 4 | str1 = input("请输入一段字符串")
d ={}
for x in str1:
# if x not in d:
# d[x]=1
# else:
# d[x]=d[x] +1
d[x] = str1.count(x)
print(d)
for x in d.items():
# print(x,':',y,'次')
print("%s:%s次"%x)
|
17208c86254af29b9b8d383f3d952f2432e29cd0 | Keyan9898/program | /34.py | 136 | 4 | 4 | a=input('enter the pgm')
num__line=0
with open(s'r')asf:
for line in f:
n_line++1
print('number of line in a paragraph')
print(n_lines)
|
14c5597075d7c6040e4f3ead995fae57fce0a88f | Shotzo/mate-computacional | /alumnos/AleFCortes/notas/CA2.py | 1,008 | 3.59375 | 4 | import numpy
# Basado en el código de Allen B. Downey
class CADrawer(object):
"""Dibuja el CA usando matplotlib"""
def __init__(self):
# we only need to import pyplot if a PyplotDrawer
# gets instantiated
global pyplot
import matplotlib.pyplot as pyplot
def draw... |
12307adedec4b9a1bbbf5cefa9fe1249b5577d06 | AIFFEL-SSAC-CodingMaster3/Jinho | /ch09/Valid_Parentheses_20.py | 694 | 3.828125 | 4 | class Solution:
def isValid(self, s: str) -> bool:
the_list = []
for spel in list(s):
if spel in ( '[', '(', '{' ):
the_list.append(spel)
elif the_list:
pop_val = the_list.pop()
if pop_val == '(' and sp... |
f9c255c9df9e45e5b13b7bc5eff8fc190b647acd | realabja/powercoders | /week4/Teusday/app.py | 279 | 3.828125 | 4 |
def check(input):
list_of_parantehsis = new list
for i in input:
if i is in ["{","["]
list_of_parantehsis.append(i)
if i is in ["}", "]"]
list_of_parantehsis.pop()
if list_of_parantehsis is not empty:
raise error
|
56c2724c2dd9ed6517a51a0748867c13e8b74c92 | sabrinachen321/LeetCode | /python/0204-countPrimes.py | 445 | 3.8125 | 4 | import math
class Solution(object):
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
if n <= 2:
return 0
isPrime = [True] * (n)
isPrime[0] = isPrime[1] = False
for i in range(2, int(math.sqrt(n)) + 1):
if isPrime[i]:
... |
33cfb946765faa25948ee29599f5fa65a9d22d4a | hector-han/leetcode | /prob0075.py | 1,432 | 4.28125 | 4 | """
颜色分类
medium
Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
"""
from typing import... |
cebc44da551f3379ee4da94c621c28fe4151a8b9 | andersonarp2810/sqlite3-com-python3 | /consultar.py | 1,409 | 3.515625 | 4 | # -*- coding: utf-8 -*-
import sqlite3
conn = sqlite3.connect('dados.db')
cursor = conn.cursor()
while (True):
print("-Consultar: Livros- 1: Todos - 2: Por id - 3: Por título - 4: Por autor - 5: Por editora - 0: Sair")
opcao = int(input(": "))
if (opcao == 0):
break
elif (opcao == 1):
... |
cfcae626be89947959bdbc584b55f44387fc9a63 | IsacLopesS/Teoria_dos_Grafos | /codigos_de _grafos_python/trab. 1 grafos/trab. 1 grafos/main.py | 1,445 | 3.828125 | 4 | #Declaracoes de importacao
import caminho_minimo
import time
#Leitura do arquivo fonte do grafo
fileName = input("arquivo do grafo: ")
file = open(fileName)
str = file.readline()
str = str.split(" ")
numVertices = int(str[0])
numArestas = int(str[1])
#Preenchimento das estruturas de dados
listaAdj = [[] ... |
813a0389e69a3588cadf03e5e1a2e5341fde2fa0 | ParthBibekar/Rosalind-Solutions | /Bioinformatics stronghold/FIB/FIB.py | 257 | 3.9375 | 4 | number_of_months = int(input("Number of months: "))
k = int(input("Number of pairs every pair produces: "))
n1,n2 = 1,1
counted = 0
while counted < number_of_months:
print(n1)
new_number = k*n1 + n2
n1 = n2
n2 = new_number
counted += 1
|
71b7f4dc390b903ccf76a91bdbafb89017972f70 | su-ram/Problem-Solving | /프로그래머스/토스_Q5.py | 387 | 3.625 | 4 | from collections import deque
def solution(fruitWeights, k):
answer = []
window = fruitWeights[:k]
window = deque(window)
max_num = set([max(window)])
for i in range(k, len(fruitWeights)):
window.popleft()
window.append(fruitWeights[i])
max_num.add(max(window))
return sor... |
55b2f6a0dd50a3255870ac1baa7d030f7a1484a8 | pqnguyen/CompetitiveProgramming | /platforms/leetcode/CountofSmallerNumbersAfterSelfMergeSort.py | 734 | 3.78125 | 4 | from typing import List
class Solution:
def countSmaller(self, nums: List[int]) -> List[int]:
counts = [0] * len(nums)
def mergesort(enum):
half = len(enum) // 2
if half:
left, right = mergesort(enum[:half]), mergesort(enum[half:])
for i in ... |
b32d1179d89891cbb21f46ba376f789034bd5db6 | Ge-shi/LeetCode_python | /easy/206. 反转链表.py | 505 | 3.90625 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def reverseList(head: ListNode) -> ListNode:
"""
cur = head
pre = None
while cur:
nextNode = cur.next
cur.next = pre
pre = cur
cur = nextNode
return pre
"""
"""递归"""
... |
ee40b3a9b9266d5fc93506bdb367b08c7e71ca24 | barshag/LeetCodeChallenges | /30DaysAprilCHallenge/K-closet.py | 239 | 3.625 | 4 | import math
def sortfirst(val):
return val[0]
points = [[1,3],[-2,2]]
K = 1
retList =[]
for point in points:
retList.append ([math.sqrt(point[0]**2+point[1]**2), point])
retList.sort(key =sortfirst)
print (retList[:K])
|
5766e63e419cf72299e4ac3bfaa6e8cfffcb5324 | Chandraa-Mahadik/CryptoNotification | /New folder/project_report.md | 2,328 | 3.6875 | 4 | Title :
Bitcoin Price Notification.
Aim: The objective of this project is to use python to get the price of bitcoin (BTC) from a website (API URL) and send notification of the same on Telegram app.
Also mail notification is received on the user's gmail account.
The price of Bitcoin and other cryptocurriencies change ... |
061dd95c3c97dd5b1e2a72b65fd392735b2e54b0 | DKelle/AsciiAdventure | /PotionShop.py | 1,556 | 3.6875 | 4 | import Tools
from scanner import scan
from Potion import potion
import random
def init(player):
Tools.clearScreen()
print "You have",player.getMoney(),"dollars."
Tools.createPotionShop()
healthPotion = getHealthPotion(player)
strengthPotion = getStrengthPotion(player)
potions... |
4757df19a1bf8ab453ef1b388b989e99f5bdf47b | Randdyy/Myfirst-Codes | /class/lianxi/reload.py | 788 | 3.53125 | 4 | class MyList():
__mylist = []
def __init__(self, *args):
for i in args:
self.__mylist.append(i)
def __sub__(self, x):
for i in range(0, len(self.__mylist)):
self.__mylist[i] = self.__mylist[i] - x
return self.__mylist
def __add__(self, x):
for ... |
ee8b18e75ca1e62079cd06870e12a0853e0ddb2b | jacksonpradolima/ufpr-ci182-trabalhos | /201802/Matematica/CI182MAT1/9 - Três espiãs demais/codigo/main.py | 2,866 | 3.53125 | 4 | # -*- coding: utf-8 -*-
import pandas as pd
import tkinter as tk
from tkinter import *
# Comandos para configuração da telas
root = Tk() # Comandos principa
text = tk.Text()
def tela_inicial():
root.resizable(0, 0) # Edita o tamanho da tel
# Leitura e "print" da tabela externa
tabela = pd.read_table('P... |
1bd3a4f5c2a4b1c182afd314ed5980cbf5fc0140 | drewatienza/My-Dev-Learning-Tracker | /Notes/Python/find_the_oldest.py | 585 | 4.28125 | 4 | # Given the below class:
class Cat:
species = 'mammal'
def __init__(self, name, age):
self.name = name
self.age = age
# 1 Instantiate the Cat object with 3 cats
meowmeow = Cat('MeowMeow', 6)
felix = Cat('Felix', 10)
garfield = Cat('Garfield', 2)
# 2 Create a function that finds the oldes c... |
1dde9b80f92b93f309cc2c32fc7c6e02ee4fb7cd | akki2825/marathi-bible-speech-dataset | /utils.py | 385 | 3.546875 | 4 | from typing import List
def read_file(input_file: str) -> List[str]:
with open(input_file) as f:
return f.readlines()
def write_file(output_file: str, input_lst: List[str],new_line=False):
with open(output_file, "w+") as f:
for item in input_lst:
if new_line:
f.wr... |
2f166af8e8faed2118459577a0f7bcc3f369ac43 | kesia-barros/exercicios-python | /ex001 a ex114/ex029.py | 200 | 3.828125 | 4 | vel = float(input("Qual sua velocidade? "))
if vel > 80:
multa = (vel - 80) * 7
print("Você foi multado em {} reais!!!".format(multa))
else:
print("Está tudo certo, dirija com cuidado!") |
9234c07be681453b223d281fa4d7aa300f99fd28 | simonchalder/Python_BlackJack | /blackjack.py | 5,810 | 3.78125 | 4 | from random import choice as rc
import random
from time import sleep
class Player:
def __init__(self):
self.deck = (1,2,3,4,5,6,7,8,9,10)
self.suits = ('H','D','C','S')
self.hand = []
self.name = ''
self.pot = 100
self.bet = 0
def add_card(sel... |
b6f32cd3b966adad264c453be4d909ffaa34632b | zoopss/random-bits-and-pieces | /HHW_Winter/q3.py | 710 | 4.15625 | 4 | num1 = int(raw_input("Enter the number of entries to be recorded...")) #Take counter input
dict1 = {} #Create blank dictionary
for i in range(0,num1): #Loop through to add all entries
... |
0382cc22849756a5c8610afc6ae5a4076e419f94 | cnicacio/atividades_python | /lists/06_17_exercicio_02_lista.py | 813 | 4.0625 | 4 | '''
02 - Crie um programa que vai ler vários números e colocar em uma lista. Depois
disso, crie duas listas extras que vão conter apenas os valores pares e os valores
ímpares digitados, respectivamente. Ao final, mostre o conteúdo das três listas
geradas.
'''
lista = []
lista_par = []
lista_impar = []
while True:
... |
804f2417f97e400813d3a34aec2905a77f755a9f | panye819/python3_study | /section-1-python-basic/02-python-basic/06-data-manipulate/variable-01.py | 798 | 3.5 | 4 | #!/user/bin/python3
# -*- coding:utf-8 -*-
"""
从一个集合中获得最大或者最小的N个元素列表
可以使用
"""
import heapq
nums = [1,8,2,23,7,-4,18,23,42,37,2]
print(heapq.nlargest(3,nums))
print(heapq.nsmallest(3,nums))
portfolio = [
{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'AAPL', 'shares': 50, 'price': 543.22},
{'name': 'FB',... |
3ae000b1b6774fea83d6ac7fd5e84abb36579baf | poplol240/programs | /random_programs/GG_help_2.py | 185 | 4.1875 | 4 | # "eo" = even or odd
even_odd = input("Pick a number and I will tell you if it's even or odd: ")
if int(even_odd) % 2 == 0:
print("It's even")
else:
print("It's odd")
|
780b77a9cdea98a69e47489f096933754ef466bb | jameskaron/LeetCode | /character/ReverseString.py | 1,329 | 4 | 4 | # 编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。
# 不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。
# 你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。
class Solution:
# 双指针
def reverseString_one(self, s: list) -> list:
# 两个指针要同时移动
e_idx = len(s)-1
for f_idx in range(int(len(s)/2)):
print("... |
3a89c52ca15a42b4bfa32aa8cf408c9491488bf3 | vitusik/Huji-Into-To-CS | /ex11/priority_queue.py | 7,137 | 4.0625 | 4 | from node import *
from string_task import *
from priority_queue_iterator import *
class PriorityQueue():
def __init__(self,tasks =[]):
"""
:param tasks: list of tasks, comes in StringTask type
initializes the queue with the given tasks
"""
self.__head = None
... |
4f5116ba970487dde2ec56eb888b820036de4309 | EasternBlaze/ppawar.github.io | /Fall2019/CSE101-F19/labs/Lab8/lab8.py | 3,375 | 4.3125 | 4 |
# Part 1
def dictionary_test():
d = {'one': 'hana', 'two': 'dul', 'three': 'set'}
# As you try these 6 examples below, be sure to understand what
# each example is trying to teach you about dictionaries.
print('\n1. keys')
for key in d:
print(key)
""" Uncomment one more example at a... |
ad65f84b7e263e420d352e079be79e197bc2b1dc | gravur1/littleLabs | /SecretSanta/secretSanta.py | 371 | 3.96875 | 4 | #!/usr/bin/python3
import random
names = ["joao", "maria", "claus", "julie", "Ashley", "Noah"]
selected = []
i=0
while(len(selected) < len(names)):
name = names[i]
randomName=(random.choice(names))
if(randomName != name):
if(randomName not in selected):
i += 1
print("The Secret friend of",name, "is", rand... |
a152987d9f8c3549f8ad9694fa8c89299e4ef402 | khonnsu/learningpython | /exe01.py | 673 | 3.84375 | 4 | #calcula e imprime ano em que usuário terá 100 anos de idade
import datetime # usa módulo para conseguir ano atual
name = input("escreva seu nome: ") # lê string após imprimir a frase descrita
age = int(input("escreva sua idade: ")) # faz o mesmo da anterior porém transforma em int
loops = int(input("numer... |
680843a57535e52c87133ddab172750e9ee05279 | LuisAlbizo/TDC_Py | /basicos.py | 1,606 | 3.609375 | 4 | from os import system
def mostrarTexto(arc,filai,filaf):
f=open(arc,"r")
lins=f.readlines()
f.close()
lines=[]
for el in lins:
lines.append(el[:-1])
for i in range(filai-1, filaf):
print lines[i]
def limpiar():
if system("cls")!=0:
system("clear")
def pausa(m="Presione enter"):
raw_input(m)
limpiar()
... |
b69d604150e83d1311a60d9f0cc55cce7af2b328 | jasonng17/LeetCode | /history/testcodes.py | 2,282 | 3.71875 | 4 | #!/usr/bin/env python3
"""
@author: darklord
"""
'''
Rotate 2D matrix by 90 degrees
'''
from copy import deepcopy
A = [[1,2,3],
[4,5,6],
[7,8,9]]
A = [[1,2],
[3,4]]
#results = deepcopy(A)
n = len(A)
for x in range(0,n):
for y in range(n-1,-1,-1):
A[y][n-x-1] = A[x][y]
'''
Implement a LRU... |
0f39f9a45b17652c571dc06528f4ca62b05c7359 | natterra/python3 | /Modulo1/exercicio014.py | 286 | 4.1875 | 4 | #Exercício Python 14: Escreva um programa que converta uma temperatura digitando em graus Celsius e converta para graus Fahrenheit.
temperatura = float(input("Digite a temperatura em celsius: "))
print("{} ºC equivalem a {:.1f}º fahrenheit.".format(temperatura, temperatura*1.8+32)) |
23439eb84adb7f74a1ec12dacd4c80ae88b4afbf | almehj/project-euler | /old/problem0060/check.py | 218 | 3.734375 | 4 | #!/usr/bin/env python
import sys
from prime_numbers import is_prime
base = sys.argv[1:]
print(base)
for n1 in base:
for n2 in base:
if n1 != n2:
print(n1+n2,is_prime(int(n1+n2)))
|
79f24e49e4118b58b1c2d22fe78c0ec7df57b313 | edukatiau/ClassLogic | /Aula 1/1_Python.py | 179 | 3.703125 | 4 | nota1 = int(input(Insira a nota 1: ))
nota2 = int(input(Insira a nota 2: ))
media = (nota1 + nota2) / 2
if(media >= 7):
print("Aprovado!")
print(f"Sua média é: {media}")
|
5dfab02bb39299ed6700080f3cb00f8cf746af75 | valleyceo/code_journal | /1. Problems/a. Bits/0. Template/b. Operation - Add.py | 90 | 3.546875 | 4 | # Iterative Addition
def add(a, b):
return a if b == 0 else add(a ^ b, (a & b) << 1)
|
6c07785e36447d20b0a3a58936ad15f0b2d087f2 | AndreyAAleksandrov/GBPython | /Algorythm/Lesson2_Task4.py | 401 | 3.671875 | 4 | # 4. Найти сумму n элементов следующего ряда чисел: 1, -0.5, 0.25,
# -0.125,… Количество элементов (n) вводится с клавиатуры.
n = int(input('Введите количество элементов: '))
series_number = 1
sum = 0
for i in range(n):
sum += series_number
series_number /= -2
print(f'Сумма {sum}') |
ecc58224e214df64d938d648794e949933c7f3c5 | elijabesu/ossu-cs | /1--6.00.1x/exercises/02.while-1.py | 201 | 4.21875 | 4 | # 1. Convert the following into code that uses a while loop.
#
# prints 2
# prints 4
# prints 6
# prints 8
# prints 10
# prints Goodbye!
n = 0
while n < 10:
n += 2
print(n)
print("Goodbye!") |
75b9a0cffea054e350788e1398fedbcd37f02680 | chenshl/py_study_demo | /Study/StudyOne/showJson.py | 239 | 3.921875 | 4 | # -*- coding:utf-8 -*-
import json
name = input("请输入您的姓名:")
phone = input("请输入您的电话号码:")
dict1 = {"name": name, "phone": phone}
json1 = json.dumps(dict1, ensure_ascii=False, indent=4)
print(json1) |
ca93425bbfb81bbb9aac71921e8cf2bae0839655 | carlypecora/import-csv-file | /import.py | 2,406 | 3.53125 | 4 | import csv
import argparse
NEW_CSV_LIST = []
def reformat_csv(csv_filename):
with open(csv_filename, "r") as f:
readable_csv = csv.reader(f)
header = next(readable_csv)
beginning_range_index = 9
ending_range_index = 24
i = 0
for row in readable_csv:
j = ... |
87704cf342d6ef057ebd0e4120578c7121dddb17 | cjim8889/Practice | /PartitionList.py | 1,443 | 3.65625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
l = head
resultHead = None
resultTail = None
... |
aca86094e3e3e6af89b8b162f2fbae4ae4635f9c | adaveniprashanth/MyData | /MySQL/mysql_database_triggers.py | 2,742 | 4.125 | 4 | print("welcome to database triggers")
import sqlite3
# python code for running the commands:
# sql='SELECT x FROM myTable WHERE x LIKE %s'
# args=[beginningOfString+'%']
# cursor.execute(sql,args)
# beginningOfString += '%'
# cursor.execute("SELECT x FROM myTable WHERE x LIKE ?", (beginningOfString,) )
#AUTOINCREMENT... |
3dfd853d9f64c91c1e8b8b7d79078de2dfc0cd83 | bianca-campos/pythonExercises | /Chapter6-BiancaCampos.py | 463 | 4.34375 | 4 | #exercise 6
# Use find and string slicing to extract the portion of the string after the colon
# character and then use the float function to convert the extracted string into a floating point number.
str = "X-DSPAM-Confidence:0.8475"
find_ini = str.find(":")
find_fin = str[find_ini + 1:]
print(float(find_fin))
#exer... |
be0bbb1c1541d099543fc833c42d9bc84f6f7448 | simonrg/ai-prototypes | /tic_tac_toe/TicTacToe.py | 6,183 | 4.0625 | 4 | # Tic-Tac-Toe
# Basic game loop structure
# - move_input()
# - update_board()
# - render_board()
# WIN_SET contains sets of all the spots on the board that equal a win
import random
class Tictactoe:
#constructor
def __init__(self):
#static set of valid 'win' moves
self.WIN_SET = (
(0,... |
42582044d4aae72a6e56af6ecdaf8050c7ddc5d2 | Aasthaj01/DSA-questions | /array/even_odd_subarray.py | 781 | 3.5 | 4 | # max sum of continuous subarray
def max_alternating_subarray(arr, n):
res = 1
curr = 1
for i in range(1, n):
if (arr[i]%2 == 0 and arr[i-1]%2 !=0) or (arr[i-1]%2 == 0 and arr[i]%2 !=0):
curr+=1
res = max(res, curr)
else:
curr = 1
return res
... |
035f30c36350af1644a9e69a834650148cdbca17 | AdamBures/ALGHORITHMS-PYTHON | /selection_sort.py | 310 | 3.890625 | 4 | def selectionSort(arr):
for i in range(len(arr)):
minimum = i
for j in range(i+1,len(arr)):
if arr[j] < arr[minimum]:
minimum = j
arr[minimum],arr[i] = arr[i], arr[minimum]
return arr
arr = [5,1,3,4,6,7]
print(selectionSort(arr))
|
761aa66ea119112ec409f060d91507fea09e3b95 | liucheng2912/py | /leecode/easy/207/1431.py | 341 | 4.03125 | 4 | """
思路:
选出数组最大值
遍历数组计算最大值减去值后,是否小于等于extra值
"""
def f(n,m):
l=[]
result=max(n)
for i in n:
if result-i<=m:
l.append(True)
else:
l.append(False)
return l
candies = [4,2,1,1,2]
extraCandies = 1
print(f(candies, extraCandies)) |
e05a544de8ed4748bdfe942b5d6754a129df9024 | WorasitSangjan/afs505_u1 | /assignment3/ex19_1.py | 1,315 | 4.15625 | 4 | # Create a function for the number of cheese and crackers
def cheese_and_crackers(cheese_count, boxes_of_crackers):
# Display the sentence witht the number of cheeses
print(f"You have {cheese_count} cheeses!")
# Display the sentence witht the number of crackers
print(f"You have {boxes_of_crackers} boxes... |
6cddfc0af5ed0765d38fdbe730a25f6e117870e4 | bmoretz/Daily-Coding-Problem | /py/dcp/problems/recursion/boxes.py | 1,368 | 3.859375 | 4 | """Boxes.
You have a stack of n boxes, with widths w_1, heights h_1, and depths d_1. The
boxes cannot be rotated and can only be stacked on top of one another if each box
in the stack is strictly larger than the box above it in width, height and depth.
Implement a method to compute teh height of the tallest possible... |
d445d3ea9daae961ebb498f9e0a4cc2fa192c09e | Bobslegend61/python_sandbox | /variable.py | 311 | 3.84375 | 4 | # This is a single line comment in python
# This a multiline
# comment
# in
# python
# VARIABLES
name = 'Alabi'
print(name)
# Assign multiple
# x, y, z = "Orange", "Mango", "Strawberry"
# print(x)
# print(y)
# print(z)
# Asign a value to multiple variables
x = y = z = "Oranges"
print(x)
print(z)
print(y)
|
f7dd9de478eb3b1b5c162691cc2ca51bc9daf8e8 | mujolocal/puzzles_templates | /temp.py | 796 | 4.03125 | 4 | def sort_by(lists):
lista,listb = lists.split("|")
lists = list(zip(lista.split(","),listb.split(",")))
sorted_lists = merge_sort(lists)
return ",".join([word[1] for word in sorted_lists])
def merge_sort(lists):
if len(lists)==1:
return lists
if len(lists)>1:
left,right = split(... |
a491a11a91952719b5b2cc89d0dbf3fb6d92c471 | titoadaam/Tito-Adam-Perwirayudha_I0320101_Tiffany-Bella-Nagari_Tugas4 | /soal6.py | 654 | 3.8125 | 4 | #Keluaran program biner
print(" KELUARAN DARI OPERATOR BITWISE")
print("""
==================================================""")
a = 4 #4 = 0000 0100
b = 11 #11 = 0000 1011
#4 | 11
c = a | b #15 = 0000 1111
print("Hasil dari 4|11 adalah :", c)
#4 >> 11
c = a >> b #0 = 0000 0000
print("H... |
c49955be6d6677eb04106713a04b917202d6393a | YuanShisong/pythonstudy | /day4/04生成器.py | 579 | 3.625 | 4 |
# yield关键字
a = (i**3 for i in range(4))
print(type(a)) # <class 'generator'>
def gen():
for i in range(4):
yield i**2
print(gen) # <function gen at 0x0000000001EC4B70>
mygen = gen()
print(mygen) # <generator object gen at 0x0000000001E34FC0>
print('\n------------')
def func():
for i in range(4):
... |
b564d17448e4a38f3169d6f9ff9f8b4a849f8bc4 | shartrooper/My-python-scripts | /Python scripts/Rookie/catnapping.py | 3,758 | 4.21875 | 4 | ##Multiline Strings with Triple Quotes
print('''Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Bob''')
#Another way to write comments
"""This is a test Python program.
Written by Al Sweigart al@inventwithpython.com
This program was designed for Python 3... |
e587cd5ba5b9ddb0b747f4ee0a364c3450ad2c51 | ChenZoo/Cat | /SiameseKitten.py | 260 | 3.5 | 4 |
class Cat(object):
def __init__(self):
print("I am Cat!")
class SiameseKitten(Cat):
def __init__(self):
super(SiameseKitten, self).__init__()
print("I am SiameseKitten!")
SiameseKitten()
|
81c761c5c08449a71db1d43498ee345269351ec1 | jai22034/Assignment_5 | /question4.py | 430 | 3.9375 | 4 | points= int(input('Enter the points,must be under 200 : '))
if points < 50:
print("Sorry! No prize this time.")
if points >= 51 and points <= 150:
print("Congratulations! You won a [WOODEN DOG]!")
elif points >=151 and points <= 180:
print("Congratulations! You won a [BOOK]!")
elif points >= ... |
1a4a2680dc3ddbb05dd9632177bfe9ee9f5a157f | alextangchao/program-practice | /UVa/101.py | 1,762 | 3.640625 | 4 | def findplace(a):
for i in range(len(store)):
for k in range(len(store[i])):
if store[i][k] == a:
return i, k
def back(row, col):
for i in store[row][col:]:
store[row].remove(i)
store[i] = [i]
def valid(a, b):
if a == b:
return True
return ... |
47dcae802684e242e79543ce624b2f49cf879731 | Yet-sun/python_mylab | /Lab_projects/lab6/Lab6_04.py | 2,528 | 3.5625 | 4 | '''
需求:
继续模拟登录函数。
编写函数装饰器,为多个函数加上认证功能
(用户的账号密码来源于文件,文件内容请自定义,
请使用上下文管理协议读取文件)。
要求登录成功一次,在超时时间(2分钟)内无需重复登录,
超过了超时时间,则必须重新登录。
'''
import time
def authentication(func):
user = {'name': None, 'login_time': None, 'timeout': 120} # 这里需要非常注意,一开始我弄成了全局变量,没有考虑,后面修改这里面的值就有问题了,放在装饰器里,就不用考虑了
# 作用是存放我们需要知道的用户名还有运行函数的时间还... |
281dfd2ece5bfb5849151a3d60780b598b99f506 | Jaehocho629/lecture_4 | /vector_eq.py | 441 | 3.59375 | 4 | class Vector2D:
def __init__(self,x,y):
self.x = x
self.y = y
def eq(self , other):
return self.x == other.x and self.y == other.y
def __eq__(self , other):
return self.x == other.x and self.y == other.y
# def __add__(self , other):
# return Vecto... |
3368bb94d54da9e1949a8f671d2706433215993f | PhenixI/introduction-of-computer-udacity | /lesson6/fastfibonacci.py | 476 | 3.96875 | 4 | #Define a faster fibonacci procedure that will enable us to computer
#fibonacci(36).
def fibonacci(n):
pre_2 = 0
pre_1 = 1
if n == 0:
return pre_2
if n == 1:
return pre_1
i = 2
while i<=n:
sum = pre_1+pre_2
pre_2 = pre_1
pre_1 = sum
i += 1
r... |
c7546e89d67b6ffc38ce0517ed56ac023b8e3c02 | malughanshyam/GoldExplorerReinforcementLearning | /RUN_ME.py | 4,274 | 3.5625 | 4 | '''
Created on Nov 11, 2015
@author: NiharKhetan, Ghanshyam Malu
@desc : Grid world for reinforcement learning
1. Report learned values by value iteration
2. Implement Q learning with initial e = 0.9
3. Set reward at each step to be 0. Report results.
@Usage : ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.