blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
f1b3a4323014bd8f78fa1744c04b3b102c888a5c | christina57/lc-python | /lc-python/src/lock/291. Word Pattern II.py | 1,708 | 3.9375 | 4 | """
291. Word Pattern II
Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty substring in str.
Examples:
pattern = "abab", str = "redblueredblue" should return true.
pattern = "aaaa", str = ... |
11d8f281fabaa5b5d44692a71b8004dccaba6b27 | hirenhk15/ga-learner-dst-repo | /basecamp/10_Probability_of_the_Loan_Defaulters/code.py | 1,706 | 3.5625 | 4 | # --------------
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Load the dataframe
df = pd.read_csv(path)
#Code starts here
# TASK 1
# Probability p(A) for the event that fico credit score is greater than 700
p_a = len(df[df['fico'] > 700])/ len(df)
# Probability p(B) for th... |
90ca31e787c0be31675bf6e72e9d984ca3957ba2 | pylinx64/sun_python_14 | /sun_python_14/elka.py | 768 | 3.953125 | 4 | import turtle
t = turtle.Pen()
def star(n):
'''рисует звездочку'''
t.left(90)
t.forward(3*n)
t.color("orange", "yellow") # цвет карандаша, цвет заливки
t.begin_fill() # начало заливка
t.left(126)
for i in range(5):
t.forward(n/5)
t.right(144)
t.forward(n/5)
t.left(72)
t.e... |
87f075deda8f0bf0a7091f4db09ccae8d11f462b | ElderVivot/python-cursoemvideo | /Ex012.py | 167 | 3.6875 | 4 | preco = float(input('Digite o valor produto: '))
desconto = preco * 0.95
print('O valor final do produto após o cálculo do desconto dado é {:.2f}'.format(desconto)) |
6c3ba39b9318806444770ba500bc33a0b0000ff0 | pfreisleben/Blue | /Modulo1/Aula 10 - While/Desafio.py | 1,577 | 4.09375 | 4 | """ Desenvolver um programa para verificar a nota do aluno em uma prova com 10
questões, o programa deve perguntar ao aluno a resposta de cada questão e ao
final comparar com o gabarito da prova assim calcular o total de acertos e a
nota (atribuir 1 ponto por resposta certa). Após cada aluno utilizar o sistema
dev... |
6ca94d7f14b294ea5da1090e0981cd7c7d1591e9 | Tee1er/ai4all-berkeley-driving | /driving/roadmap.py | 5,401 | 3.515625 | 4 | from math import pi, sin, cos, floor, ceil
import numpy as np
from random import random
from matplotlib.patches import Circle, Rectangle
# all angles in this file are in RADIANS unless otherwise noted
LINEWIDTH = 50.0
def angle_diff(a, b):
"""Calculate the difference in angles between -pi and pi"""
delta = a-b
... |
fc9f6fe10a56bae0da7940787273b420bee73f6f | EoJin-Kim/CodingTest | /이진탐색/정렬된 배열에서 특정 수의 개수 구하기.py | 379 | 3.515625 | 4 | from bisect import bisect_left,bisect_right
def count_by_range(array,left_value,right_value):
right_index=bisect_right(array,right_value)
left_index=bisect_left(array,left_value)
return right_index-left_index
n,x = map(int,input().split())
array = list(map(int,input().split()))
count = count_by_range(arr... |
7b3a791043ddf4841c8da0a767c1044b17df1d49 | Arina-prog/Python_homeworks | /homeworks 5/task_5_10.py | 286 | 3.875 | 4 | # Create a regular expressions to check if string meets some requirements
# #10. stextsel kanonavor artahaytutyun ev stugel te str-um handipum e miqani pahanj
str1 = " es unem %d hat %s " % (2, "shun")
str2 = " es chem sirum voch %s voch %s " % ("katu", "shun")
print(str1)
print(str2) |
87e5cda21d549c3572aff0988f106a58f579876f | joaocmd/Advent-Of-Code-2018 | /5/sol1.py | 1,066 | 3.5625 | 4 | import string
def main():
fp = open("input.txt", "r")
#Remove newline
line = (fp.readline())[:-1]
fp.close()
#Part 1
print(len(reactPolymers(line)))
#Part 2
results = {}
for c in string.ascii_lowercase:
res = removeElement(line, c)
res = reactPolymers(res)
... |
f51b2e1f73a977298d71152e6d914874f4b4217d | oryband/code-playground | /depth-first-search/tree.py | 291 | 3.578125 | 4 | """This file implements a simple tree node."""
class Node:
"""Tree node simple implentation."""
def __init__(self, v:int, left:'Node'=None, right:'Node'=None):
self.v = v
self.left = left
self.right = right
def __str__(self):
return str(self.v)
|
f29cd6753322209e2de93303aa0debf8417b138a | Vitaliy-Koziak/Homework_6 | /Home work 2_4.py | 876 | 3.703125 | 4 | #Знайти максимальний елемент серед мінімальних елементів стовпців матриці.
import random
m = int(input("Input M:"))
n = int(input("Input N:"))
numbers = [[0] * n for i in range(m)]
for i in range(m):
for j in range(n):
numbers[i][j] = random.randint(1,30)
for i in range(m):
for j in range(n):
... |
c62fe5a2808486c363c4a1046203018400e05967 | ANKerD/competitive-programming-constests | /uri/upsolving/1441/code.py | 227 | 3.578125 | 4 | while True:
n = int(raw_input())
if n == 0: break
ans = n
while n != 1:
# print n, i
if n % 2 == 0:
n = n/2
else:
n = 3*n+1
ans = max(ans, n)
print ans |
1d7f90800c6e0e4f102b66901193b3edba74bcc1 | liangrui-online/algori | /水王问题.py | 1,415 | 3.84375 | 4 | """
水王问题:
已知一个数组,找出其中出现次数超过半数的数
"""
def solution_naive(data):
from collections import defaultdict
counter = defaultdict(int)
for item in data:
counter[item] += 1
target, num = None, 0
for char, n in counter.items():
if n > num:
target = char
num = n
... |
67345e8527f64bdef3011258ed75f098fdc818f1 | QuantumManiac/cs50 | /pset6/similarities/test.py | 130 | 4.0625 | 4 | string = "hello"
substring = []
n = 3
for i in range(len(string) - n + 1):
substring.append(string[i:n + i])
print(substring)
|
d09e73be564d66863b3e8b745caed6098745a823 | wesselb/ARHC | /arhc/huffman.py | 1,249 | 3.890625 | 4 | from node import Node
import sys
class Huffman:
"""
Construct a symbol code via the Huffman algorithm.
:param symbols: List of symbols that represents the alphabet.
"""
def __init__(self, symbols):
self.build(symbols)
def build(self, symbols):
""" Build a tree of symbols acc... |
da5529cb8578aa547e05f3821426ede8add05590 | Swathi-16-oss/python- | /sales tax.py | 265 | 3.8125 | 4 | '''calculating sales tax:
cost of item*sales tax of rate in decimal part=sales tax
calculating price of an item:
cost of item+sales tax=total cost of item'''
itemcost=60
salestax=7.5
salestax=7.5/100
total=itemcost*salestax
print("%.2f"%total)
#o/p:4.50
|
ef4ccf21d7229ecec425e906e1faa9f78ca24fcf | bagusdewantoro/zedshaw | /ex43test.py | 6,198 | 3.671875 | 4 | from sys import exit
from random import randint
from textwrap import dedent
class Adegan(object):
def masuk(self):
print("Adegan ini belum di-set")
print("Subclass it and implement enter().")
exit(1)
class Mesin(object):
def __init__(self, peta_adegan):
self.peta_adegan = pet... |
a7a70c1fab0030337ff929f3565d584679db6d16 | tlfhmy/PythonStudy | /Tkinter/Entry.py | 754 | 3.625 | 4 | import tkinter as tk
from tkinter import ttk
win = tk.Tk()
win.geometry("800x600")
win.title("Entry")
win.resizable(0, 0)
aLable = ttk.Label(win, text="A Lable")
aLable.grid(column=0, row=0)
def clickMe():
#action.configure(text="** I have been Clicked! **")
#aLable.configure(foreground='red')
action.co... |
fd6ab0f62eb49e328cef63372005bde1d7151bff | sfitzsimmons/Exercises | /NumberRange.py | 361 | 4.3125 | 4 | # this exercise wants me to test whether a number is within 100 of 1000 or 2000.
given_number = int(input("Enter number: "))
if 900 < given_number < 1100:
print("Your number is within 100 of 1000.")
elif 1900 < given_number < 2100:
print("Your number is within 100 of 2000")
else:
print("Your numb... |
7b359ce76cc5e39a8f837d5726370bd5b7db025b | Hassan6678/Image_processing | /MLP.py | 2,358 | 3.859375 | 4 | from sklearn.neural_network import MLPClassifier
import Data
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
d = Data.load_my_dataset()
X, y = d.data, d.target
train_X, test_X, train_y, test_y = train_test_split(X, y,
train_size... |
05cc5dfaba953171d908446cf9b487d3803147e8 | FelixOpolka/Statistical-Learning-Algorithms | /common/Tester.py | 2,989 | 3.96875 | 4 | """Tester for various predictors. Given a data set file (csv)
the tester loads the data sets, separates it into training and
test set and performs the training and subsequent testing."""
# Currently, only classification tests supported
import csv
from random import shuffle
def __parse(string):
"""Parses a given... |
b461e31da1b8d04215671e9b827ab89f106fce24 | mattshakespeare/pythonPractise | /random.py | 3,243 | 4.03125 | 4 | #outputs random int between 1 - 100
import random
print(random.randint(1,100))
print()
#outputs random entity from a list of fruit
fruit = ["Grapes", "Orange", "Banana", "Grapefruit", "Honeydew Melon", "Strawberry", "Watermelon"]
print(random.choice(fruit))
print()
#user and computer choose heads or tails
#if user =... |
f0f0d8e4a4d18ef2a0eb28e43d62bc8cb14cc7c1 | masuda350/hangman | /Problems/Checking email/main.py | 386 | 3.8125 | 4 | def check_email(string):
length_string = len(string)
at = string.find('@')
if length_string == len(string.replace(' ', '')):
return string.find('.', at, length_string) > at + 1
return False
# Another solution 1
# if '@' in string and ' ' not in string and '@.' not in string:
# r... |
642cf30ccfb6a00ef74b187f9864ed7c0d964da7 | beccam/tournament-results_2 | /tournament.py | 4,447 | 3.625 | 4 | #!/usr/bin/env python
#
# tournament.py -- implementation of a Swiss-system tournament
#
import psycopg2
def connect():
"""Connect to the PostgreSQL database. Returns a database connection."""
""" Will connect with the tournament database. """
return psycopg2.connect("dbname=tournament")
def deleteMat... |
14e7622a487ae12f73725f2edff16dbf77c3f42a | Priyankavad/Python-Programs | /Hcf.py | 531 | 4.1875 | 4 | # defining a function to calculate HCF
def calculate_hcf(h, p):
# selecting the smaller number
if h > p:
smaller = p
else:
smaller = h
for i in range(1,smaller + 1):
if((h % i == 0) and (p % i == 0)):
hcf = i
return hcf
# taking input from... |
fc46870652eb4c2e095ae5f753e5ab703f28359e | MasumTech/URI-Online-Judge-Solution-in-Python | /URI-1013.py | 128 | 3.53125 | 4 | row_input = input().split(" ")
a, b, c = row_input
greatest = max(int(a), int(b), int(c))
print(str(greatest) + ' eh o maior') |
ccd6b8b35096bbf3522de9fa7973055264a30e69 | zhangjh12492/python_used | /head_first/chapter5/class_used_1.py | 1,200 | 3.625 | 4 | from head_first.chapter5.filter_speed_2 import sanitize
class Athlete:
name = ''
dob = ''
times = []
filename = ''
def __init__(self, filename=''):
self.filename = filename
def top3(self):
return sorted(set([sanitize(t) for t in self.times]))[0:3]
def get_coach_data(self... |
4971419f604f342ea8c09943c7069a3cf3e93288 | tanzoniteblack/Hangman | /src/loadDic.py | 523 | 3.75 | 4 | def loadDic(lang = "en"):
"""Load file lang_dict.txt and pick a word from it at random"""
# import random library to make choice
from random import choice
# Read dictionary line by line and turn into list
dictionary = open(lang+"_dict.txt").readlines()
# return random entry with \n (new line) character stripped a... |
19503ae16969204cebd1c69e94206fcbc48669d3 | Ujjal-Baniya/CompetitiveProgramming-python | /Youtube tricks for competitive/stack_implementation.py | 1,488 | 3.953125 | 4 | ### write your solution below this line ###
class Stack:
def __init__(self, size):
self.size = size
self.data = [None]* self.size
self.top = -1
def push(self,val):
if not self.isFull():
self.data.append(val)
self.top += 1
def isFull(self):
if... |
8bfcf06865e2cf7b23bc7c58435ca81250b7930f | Tonaay/Learning-Python | /Python Files/prac02.py | 3,296 | 4.125 | 4 | #Tony Van
#UP821148
import math
def circumferenceOfCircle():
radius = eval(input("Enter Radius :"))
circumference = 2 * math.pi * radius
print("The circumference is", circumference)
def areaofCircle():
radius = eval(input("Enter Radius :"))
Area = math.pi * radius**2
print("The area is", ... |
4857c78c79f8f566b79dda8d6115e17ea9920391 | hernandez87v/Zookeeper | /Problems/Sum/task.py | 100 | 3.578125 | 4 | # put your python code here
n = int(input())
n2 = int(input())
n3 = int(input())
print(n + n2 + n3)
|
880a4e2fe9147fca7fbd91b954a30790832db9c0 | renukadeshmukh/Leetcode_Solutions | /helpers/linked_list_helper.py | 513 | 3.828125 | 4 |
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class LinkedList:
@staticmethod
def printLinkedList(head):
cur = head
while cur != None:
print(cur.val, '-->>')
cur = cur.next
@staticmethod
def array_to_linkedlis... |
6857220bc1479c12da478462c80709b2233b8d90 | RachelMurt/Python | /Ice cream.py | 316 | 4.125 | 4 | flavour = input("What is your favourite ice cream flavour?: ")
if flavour == 'mint chocolate chip':
print ("The best flavour! You have great taste!")
elif flavour == 'cookie dough':
print ("A good choice!")
elif flavour == 'cherry':
print ("Why?")
else:
print ("That's alright, I guess.")
|
dc0b060b1dd8892a93ecf8cdbff479b475f4b56e | rohith2506/Algo-world | /interviewbit/bin_search/search2d.py | 378 | 3.625 | 4 | '''
Start at top-right
1) top - bottom by checking with the last element of each row in the array
2) Then go right - left until you find the element
elegant solution
'''
class Solution:
def searchMatrix(self, A, B):
m, n = len(A), len(A[0])
i, j = 0, n - 1
while i < m and j >= 0:
if A[i][j] == B: return 1
... |
fffed9df6ff0926e463c160ce427dbcc597e929e | vovakpro13/PythonLabs | /Lab_3/task_1.py | 421 | 3.640625 | 4 | N = int(input('Enter N:'))
if 0 <= N <= 10:
for row in range(1, N + 1):
res = ''
for col in range(1, row + 1):
res += ' ' + str(N - row + col)
print(' ' * (N - 1) + res)
for row in range(1, N + 1):
res = ''
for col in range(1, row + 1):
res +=... |
99709c7a255a960957ebae16230e877bb71cf94b | ericfourrier/scikit-learn | /examples/mixture/plot_gmm_sin.py | 3,242 | 3.6875 | 4 | """
=================================
Gaussian Mixture Model Sine Curve
=================================
This example highlights the advantages of the Dirichlet Process:
complexity control and dealing with sparse data. The dataset is formed
by 100 points loosely spaced following a noisy sine curve. The fit by
the GMM... |
30fbc3ca908882c11ca9584c7006c7bb3b0c1931 | amit4tech/DG-Python | /Session 1-6/linear_search.py | 350 | 3.734375 | 4 | n = int(input("Enter your number:"))
l = [1, 23,34,6,23,3,123,12,-23, 123, 82, 928,100,6,9,324,2,2,34,23,4,2,12,42]
if n in l:
print("Yes found")
else:
print("Not found")
# i = 0
# while i < len(l):
# if l[i] == n:
# print("Yes at index:", i)
# break
# i = i + 1
# if i >= len(... |
b862c409d237fa858a3ce9df33ec4f8f6b3ff4e3 | rafaelperazzo/programacao-web | /moodledata/vpl_data/22/usersdata/130/11991/submittedfiles/av1_2.py | 377 | 4 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
import math
a=input('Digite o valor de a:')
b=input('Digite o valor de b:')
c=input('Digite o valor de c:')
d=input('Digite o valor de d:')
if a==c or b==d:
if b!=d or a!=c:
if a!=b or b!=c or c!=d:
print('V')
else:
prin... |
06a9f84cd999dd240c01897d89882f96a500fc4e | techiethrive/mad_libs_generator | /main.py | 552 | 4.21875 | 4 | """ Mad Libs Generator
----------------------------------------
"""
//Loop back to this point once code finishes
loop = 1
while (loop < 10):
// All the questions that the program asks the user
noun = input("Choose a noun: ")
p_nou = input("Choose a noun: ")
// Displays the story based on the users input
pri... |
11110aef1bc7307757c98c4eb8fa860f7939cb49 | RaulNinoSalas/Programacion-practicas | /Practica5/P5E5.py | 562 | 4.125 | 4 | """RAUL NIO SALAS, DAW 1. PRACTICA 5 EJERCICIO 5
Escriu un programa que te demani dos nombres cada vegada ms grans i els guardi en una llista.
Per a terminar d'escriure els nombres, escriu un nombre que no sigui major a l'anterior. El
programa termina escribint la llista de nombres.."""
numeros=[ ]
n1=raw_input(... |
0d3ceceb1ff8a9bc62a2749191e6409a1ecbbf42 | GuilhermeOS/JovemProgramadorSENAC | /atividadeAvaliativa/ex07.py | 241 | 4.15625 | 4 | numero = int(input("Informe um número inteiro e positivo: "))
soma = 1
if type(numero) == int and numero > 0:
for n in range(1, numero + 1):
soma += 1/n
print(soma)
else:
print("Digite um número inteiro e positivo!") |
d6cf11e4ae7e0425e8989f5a3f5208dcfed261d9 | spake/perl2python | /perl2python.py | 783 | 3.59375 | 4 | # perl2python python module
# by george caley!
# has a few functions that come in handy
import sys
ARGV = sys.argv[1:]
def num(s):
"""Converts a variable to the appropriate number type."""
if type(s) == str:
if len(s) == 0:
return 0
elif "." in s:
return float(s)
else:
return int(s)
elif type(s) ==... |
49ecf060a318b20c43265038b2e4e23e0052022f | hanyang7427/study | /machine_learning/83/lemma.py | 415 | 3.609375 | 4 | import nltk.stem as ns
words=['table', 'probably', 'wolves', 'playing', 'is', 'dog',
'the ', 'beeches', 'grounded', 'dreamt', 'envision']
lemmatizer = ns.WordNetLemmatizer()
for word in words:
lemma = lemmatizer.lemmatize(word, pos='n')
print(lemma)
print('-' * 80)
lemmatizer = ns.WordNetLemmatizer()
for... |
051180f7a152b0dad1e5d475d2688d17bf80856e | Undersent/Algorithms | /Lista6/PrimAlg.py | 1,957 | 3.75 | 4 | from Lista6 import Queue
def shortestPath(graph, start):
# cost, start_vertex , parent
priorityQueue = Queue.BinHeap()
priorityQueue.insert([0,['0',-1,0]])
mstTree = []
#print("abc", priorityQueue.delMin())
# visited set
seen = set()
while True:
_, info = priorityQueue.delMin()... |
2a0f8ed434e0fcab731bd05a5c6e7fe31fcb7409 | hmoshabbar/python_oops_concept-program- | /python oops concept.py | 551 | 3.9375 | 4 | # define a class with name
class student:
def __init__(self,name,roll_no,email): # define initialization that class
self.name=name
self.roll_no=roll_no
self.email=email
def display_student(self):
print "Student Name:",self.name
print "Student Roll_no:",self.roll_n... |
59c1756642006d0ed131b2209d19baa4fcb6cb94 | mrshu/wiki-corpora-generator | /wikilangs.py | 1,256 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import wikipedia
import click
import Queue
def clean_title(title):
return title.encode('ascii', 'ignore').lower()\
.replace('/', '_').replace(' ', '_')
def dump_page(title, lang, path):
wikipedia.set_lang(lang)
p... |
a511caeabf5f97fadcf638a71416754ad5283c31 | mikaylakonst/ExampleCode | /loopsandvariables.py | 556 | 4.1875 | 4 | # Function definitions go at the top of your file
# returns the total of all the numbers from 1 to n
def numbers(n):
total = 0
for i in range(1, n + 1):
total = total + i
return total
# returns a string with all the numbers from 1 to n
def numbersString(n):
wholeString = ""
for i in range(1, n + 1):
... |
a4bc901203f790fbeb2e42df1c1a05bad7087b3a | uchenna-j-edeh/dailly_problems | /after_twittr/max_consec_sum.py | 1,128 | 3.96875 | 4 | """
Good morning! Here's your coding interview problem for today.
This problem was asked by Amazon.
Given an array of numbers, find the maximum sum of any contiguous subarray of the array.
For example, given the array [34, -50, 42, 14, -5, 86], the maximum sum would be 137, since we would take elements 42, 14, -... |
65ffdbca9ee9f0f96989791fc7c99bdc78b584a7 | FelipeDreissig/Prog-em-Py---CursoEmVideo | /Mundo 3/02 - Listas - p1/Ex081.py | 662 | 3.71875 | 4 | ## listtinha boba
cond = 's'
c = 1
quant = 0
l = []
while cond=='s':
if c == 1:
n_aux = int(input(f'Digite o 1º número:'))
l.append(n_aux)
else:
n = int(input(f'Digite o {c}º valor:'))
l.append(n)
c = c + 1
quant = quant + 1
cond = str(input('Deseja continuar? [S/N]')... |
ec58bb7ad75f30ca3e08e76cf77a14456b4b5ca4 | luliyucoordinate/Leetcode | /src/0932-Beautiful-Array/0932.py | 369 | 3.703125 | 4 | class Solution:
def beautifulArray(self, N):
"""
:type N: int
:rtype: List[int]
"""
result = [1]
while len(result) < N:
result = [i * 2 - 1 for i in result] + [i * 2 for i in result]
return [i for i in result if i <= N]
if __name__ == "__main__":
... |
1910b96f9fac61161d5a2d29343375353e62c648 | yunxifeng/pythonstudy | /03python--高级语法/08--p12.py | 1,044 | 3.984375 | 4 | # 死锁问题案例
import threading
import time
lock_1 = threading.Lock()
lock_2 = threading.Lock()
def func_1():
print("func_1 starting")
lock_1.acquire()
print("func_1 申请了lock_1")
time.sleep(2)
print("func_1 等待申请 lock_2")
lock_2.acquire()
print("func_1 申请了lock_2")
lock_1.release()
print... |
2416975b15f0904217d4aad238e17507a59e623e | adityacd/StatisticalCalculator | /Statistics/Proportion.py | 245 | 3.578125 | 4 | from Calculator.Division import division
from Calculator.Addition import addition
def proportion(lst):
t = 0
for n in lst:
if (n % 2) == 0:
t = addition(t, 1)
value = division(len(lst), t)
return value
|
50f4cdd5b497adfcb37422fb3ff235f0c5f4a219 | BradyBassett/Simple-ATM | /main.py | 6,805 | 4.09375 | 4 | # Use snake cases from now on instead of camel cases when writing python
# PROTOTYPE VERSION
import random
import time
class Accounts:
# Defining Account instance variables.
def __init__(self, pin, balance, annualInterestRate=3.4):
self.pin = pin
self.balance = balance
sel... |
d032ef1a11c3f3b671ce09004efe9f7a0706c635 | James-Rouse/Number-Guessing-Game | /guessing_game.py | 2,199 | 4.15625 | 4 | # Going for the "exceeds" grade. Pls reject me if I don't meet that bar.
import random
print("Welcome to the Number Guessing Game!")
print("There is no HIGHSCORE. This should be easy for you.")
answer_number = random.randrange(1, 11)
player_trys = 1
high_score = "placeholder"
while True:
try:
player_gues... |
6a53f844836a2f878b3840f5ebcc8a738d0d17c3 | matheuscordeiro/HackerRank | /Random Problems/Grading Students/solution.py | 1,669 | 4.40625 | 4 | #!/usr/local/bin/python3
"""Task
HackerLand University has the following grading policy:
- Every student receives a grade in the inclusive range from 0 to 100.
- Any grade less than 40 is a failing grade.
Sam is a professor at the university and likes to round each student's grade according to these rules:
- If ... |
bac32ba211c0c82d4fa164db4c821ce3fbd01516 | robjamesd220/kairos_gpt3 | /Programming_with_GPT-3/GPT-3_Python/semantic_search.py | 1,879 | 3.625 | 4 | # Importing Dependencies
from chronological import read_prompt, fetch_max_search_doc, main
# Creates a seamntic search over the given document 'animal.txt' to fetch the top_most response
async def fetch_top_animal(query):
# function read_prompt takes in the text file animals.txt and split on ',' -- similar ... |
4abfc0fd0ff3888828df98572a6ddf44e20731a5 | rogerroxbr/Treinamento-Analytics | /Trabalhos/Pedro Thiago/14_9/ex4.8.py | 440 | 4.15625 | 4 | num1 = float(input('Digite o primeiro número:\n'))
num2 = float(input('Digite o segundo número:\n'))
operation = input('Qual operação você deseja fazer? (+ , -, /)\n')
if operation[0] == '+':
var = num1 + num2
elif operation[0] == '-':
var = num1 - num2
elif operation[0] == '/':
var = num1 / num2
elif ope... |
1c48ba5001da1481a317415ce19de53263f310c4 | AndreeaMihaelaP/Python | /Lab_1/Ex_1.py | 467 | 3.5 | 4 | # Find The largest common divisor of multiple numbers. Define a function with variable number of parameters to resolve this.
def cmmdc(*multipleNumbers):
result = multipleNumbers[0]
for x in multipleNumbers[1:]:
if result < x:
temp = result
result = x
x = temp
... |
4d0d9bf07a707079f8253629258c1c19677306cc | je-castelan/Algorithms_Python | /Leetcode/reverse_number.py | 925 | 3.828125 | 4 | # https://leetcode.com/problems/reverse-integer/
# Reverse digits of an integer.
# Example1: x = 123, return 321
# Example2: x = -123, return -321
# Solucion O(n)
def reverse_number(number):
sign = 1 if number >= 0 else -1
number = abs(number)
position = len(str(number))
new_number = 0
wh... |
94ca45b5bb76251b1368ef346b974c8b226e7c2e | GreatEki/site_blocker | /site_blocker.py | 1,603 | 3.546875 | 4 | import time
from datetime import datetime as dt
# Creating a custom variable of datetime - 'dt'
host_test = "hosts"
host_path = r"C:\Windows\System32\drivers\etc\hosts"
redirect = '127.0.0.1'
website_list = ["www.facebook.com", "facebook.com", "www.instagram.com", "instagram.com"]
while True:
if dt (dt.now().year... |
b83a63103d131da09062db6e828ea5cbb153e02f | Sandip-Dhakal/Python_class_files | /tutorial2.py | 194 | 3.921875 | 4 | a=2
b=3
c=b/a
print(c)
print(int(c))
print(str(c))
t ="23.4"
f=float(t)
print("The number is", f+1)
print("The number is "+ t)
print("The number is", t)
print("The number is {:.3f}".format(f))
|
b3a241c032ba5a41d061809dc7f2f45de3e4663e | Anjalipatil18/Function-Questions-From-Saral-In-python | /list_change.py | 265 | 3.96875 | 4 | def list_change(list1, list2):
new_list=[]
i=0
while i<len(list1):
if i<list1[i] :
multiply=list1[i]*list2[i]
new_list.append(multiply)
i=i+1
return new_list
multiple_list=list_change([5, 10, 50, 20], [2, 20, 3, 5])
print multiple_list
|
9a2da9b8853060473a93083843ced7d89eaf0df9 | pzy636588/jfsdkjfkj | /截取字符串.py | 508 | 3.59375 | 4 | # _*_coding: UTF-8_*_
# 开发团队: 彭大工程师
# 开发人员: penghong
# 开发时间: 2020/10/12 21:29
# 文件名称: 截取字符串
# 开发工具: PyCharm
str2='人生苦短,我用python!'
sub1=str2[1]
sub2=str2[2:5]
sub3=str2[:5] #从左边开始截取5个字符
sub4=str2[5:] #从第6个字符截取
print('原字符串',str2)
print(sub1+'\n'+sub2+'\n'+sub3+'\n'+sub4+'\n')
try:
... |
7908e4fde4bac55b1a62392e52be77fb30ee9072 | lixiang2017/leetcode | /problems/1328.0_Break_a_Palindrome.py | 730 | 3.734375 | 4 | '''
T: O(N)
S: O(N)
Runtime: 51 ms, faster than 55.08% of Python3 online submissions for Break a Palindrome.
Memory Usage: 13.8 MB, less than 61.62% of Python3 online submissions for Break a Palindrome.
'''
class Solution:
def breakPalindrome(self, palindrome: str) -> str:
p = palindrome
if len(p) ... |
d425e6c299197f754249ab6f5b7021363bd1a8c2 | Styrkar1/HR_PY1_Commits | /Hopaverk10/addtolist.py | 429 | 4.28125 | 4 | def triple_list(x):
x = []
y = []
z = []
a = []
newchar = ""
while newchar.upper() != "EXIT":
newchar = input("Enter value to be added to list: ")
x.append(newchar)
y.append(newchar)
z.append(newchar)
a.extend(x)
a.extend(y)
a.extend(z)
... |
06702fd88feac0beb117f68733f814e33a7da6d0 | bog287/Student_Lab_Management | /UI/printeaza.py | 1,960 | 3.625 | 4 | def printMainMenu():
"""
Afiseaza meniul principal
"""
print("\n")
print("####MENIU PRINCIPAL####")
print("[1] - Meniu studenti")
print("[2] - Meniu probleme")
print("[3] - Meniu asignari")
print("[4] - Meniu statistici")
print("[0] - Exit")
def printStudMenu():
"""
Afis... |
1a5b5ce5db4fbd13fbdf3bf5bb0cc4ba5f7ce97f | XuLongjia/DataStructure-Algorithm | /数据结构(python)/11 insertSort.py | 684 | 3.875 | 4 | #!usr/bin/python
# -*- coding:utf-8 -*-
def insertSort(ls):
'''插入排序,时间复杂度为n方,属于稳定排序'''
n = len(ls)
for j in range(1,n):
i = j #i代表内层
#从右边取出一个元素,然后插入到左边正确的位置中
while i >0:
if ls[i] < ls[i-1]:
ls[i],ls[i-1] = ls[i-1],ls[i]
else:
... |
e088c6e707733b152f6dcb0f0549f48c53edf1aa | freesoul84/python_codes | /other_python_codes/perfect_.py | 344 | 3.78125 | 4 | test=int(input())
def fact(n):
if n<2:
f=1
else:
f=n*fact(n-1)
return f
for _ in range(test):
number=int(input())
sum1=0
temp=number
while number>0:
r=number%10
sum1+=fact(r)
number=number//10
if sum1==temp:
print("Perfect")
else:
... |
4cab7cfe068117dfb18b1b96b598b080594ccdef | wesley-998/Python-Exercicies | /030_impar-par.py | 155 | 3.84375 | 4 | n = int(input('Digite um valor: '))
n1 = n%2
print(n1)
if n1 == 0:
print('{} é Par!'.format(n))
else:
print('{} é Impar!'.format(n))
|
8ed6b103d45d0cd67fb566fa743c6c75c6527c58 | kaharkapil/Python-Programs | /marks.py | 527 | 3.84375 | 4 | # input of 5 subjects marks
hin=int(input("Enter marks of hindi:"))
eng=int(input("Enter marks of english:"))
maths=int(input("Enter marks of maths:"))
sci=int(input("Enter marks of science:"))
san=int(input("Enter marks of sanscrit:"))
count=0
if hin<33:
count=count+1
if eng<33:
count=count+1
if maths<33:
cou... |
f7482f9cb1a98b868ee834e510aa774d6ac44b35 | meethu/LeetCode | /solutions/0098.validate-binary-search-tree/validate-binary-search-tree.py | 1,242 | 3.890625 | 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 isValidBST(self, root: TreeNode) -> bool:
inorder = self.inorder(root)
return inorder == list(sorted(set(inorder)))
... |
133c8348115f6f383ddb90e49c354efeaf97cc28 | rg3915/python-experience | /others/redundancy/redundancia2.py | 4,293 | 3.765625 | 4 | # -*- coding: utf-8 -*-
from redundancia import redun_palavra_palavra, redun_palavra_frase, redun_frase_frase
def remover_aspas(texto):
'''
Remove aspas, caso o texto contenha aspas no começo e no final da frase.
Args:
texto (str): Frase.
Returns:
str: Frase corrigida.
'''
ret... |
d4c4249f54236534e050682374fd068fd1f30928 | vaibhavk1103/hackerrank_30_days_of_code_python | /Day2_30DoC.py | 212 | 3.6875 | 4 | mealcost = float(input())
tippercent = int(input())
taxpercent = int(input())
tip = mealcost * (tippercent/100)
tax = mealcost * (taxpercent/100)
totalcost = mealcost + tip + tax
print(round(totalcost)) |
9374f53a88e2b38f1bebd774ea5ba445cf8f2577 | EricMoura/Aprendendo-Python | /Exercícios de Introdução/Ex011.py | 226 | 3.703125 | 4 | larg = float(input('Qual a largura da parede? '))
alt = float(input('Qual a altura da parede? '))
area = larg*alt
latas = area/2
print(f'A área da parede é {area}m² e é preciso {latas}L de tinta para pintá-la!') |
d1511d4335e3427a9099f3e73321bb485bb19968 | vithuren27/python-bmi-calculator-application | /bmi.py | 2,442 | 3.90625 | 4 | from tkinter import *
root = Tk()
root.title("BMI Calculator")
root.configure(width=100, height=100)
root.configure(bg="black")
def calc():
BMI = BMI_val(mass.get(), height.get())
Stat = getStatus()
stat.set(Stat)
bmi_Val.set(format(BMI, ".2f"))
def BMI_val(mass, height):
return mas... |
333191daa96b494b6cb28817912aba3f3f9d2254 | saurabh17jan/ds_algo | /sorting_tech/selection_sort.py | 807 | 4.09375 | 4 | # Python program for implementation of Selection Sort
# https://www.geeksforgeeks.org/selection-sort
# Time Complexity: O(n2) as there are two nested loops.
# Auxiliary Space: O(1)
# The good thing about selection sort is it never makes more than O(n) swaps and can be useful when memory write is a costly operation.
... |
4357811e7d3402a224a28af458b9a2eb581c7d1f | practicewitharjya/wayToPython | /Day 6_File/fileWrite2.py | 137 | 3.6875 | 4 | # Handle the file as read and write mode
f = open("python.txt", "r+")
f.write("I am writing some more line in same file")
print(f.read()) |
96f13b48f31ea1f16f1953459bd74c0c5e503a94 | nayanika2304/DataStructuresPractice | /Practise_linked_list/find_intersection.py | 1,330 | 3.890625 | 4 | '''
Given two (singly) linked lists, determine if the two lists intersect. Return the intersecting
node. Note that the intersection is defined based on reference, not value. That is, if the kth
node of the first linked list is the exact same node (by reference) as the jth node of the second
linked list, then they are i... |
e863c4cf8ce0e3ee3f45f004f7e370255ad5d3b8 | vishnusak/DojoAssignments | /Flask-Login_Registration/MySQLConnect.py | 1,413 | 3.5 | 4 | import MySQLdb as ms
class Sql(object):
""" Sql: Class to provide an abstraction for connecting and querying against MySQL server """
def __init__(self, host, db, user='root', pwd='1979', port=3306):
self.host = host
self.user = user
self.pwd = pwd
self.db = db
self.port... |
23a640f579748a1ad34d464ad7ee31495b09cca6 | JohnBracken/Monte-Carlo-Simulation-in-Python | /roulette.py | 2,629 | 3.546875 | 4 | #Monte Carlo simulation of roulette wheel
from numpy import random
from matplotlib import pyplot as plt
#Part 1. Outside bets, 5$ bets on red.
#Roulette spins, bet on red, 90 spins a night for a whole year.
land_on_red = list(random.binomial(n=90, p = 18/38, size = 365))
#Gains and losses for each night playing ro... |
deccbdb26b8d8f08ebe459fbfe56d9a144b0687b | CeciFerrari16/Esercizi-Python-1 | /es28.py | 701 | 3.59375 | 4 | # Esercizio 28 , Gara studenti
''' Dato un elenco di studenti partecipanti a una gara sportiva di lancio del peso (nome utente, lancio ),
visualizza il valore del lancio del vincitore ( valore massimo)'''
indice = 0
studenti = ["Giacomo", "Gianmarco", "Gianluca", "Gianfranco", "Fausto", "Luigi"]
lancio = [1.2, 1.4, 1.... |
3c76359601daef3db963daa6ab41022a515419b6 | utkarshbhardwaj22/TRAINING1 | /venv/Practice107.py | 1,476 | 3.53125 | 4 | """
Random Forest
1. n -> How many decision trees to be used in our model
2. Dataset shall be divided into n number of subsets.
"""
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
... |
134c88ac472ffef8f3bcac3261cffee27ba65d31 | simonRos/Python | /AssignEight/AssignEight.py | 1,231 | 3.96875 | 4 | #Simon Rosner
#3/21/2016
#This program reads dollar amounts from a text file
#and writes a text file with equivelant pound and euro amounts
#constants
USDperGBP = 0.7 #Dollars per Pound
USDperEUR = 0.89#Dollars per Euro
inFile = "dolla.txt" #name of input file
outFile = "out.txt" #name of output file
de... |
fc3a8f34596014405d8878c62837507f0799aca2 | mly135/mycode | /PycharmProjects/Test/练习/20170912_函数.py | 706 | 4.03125 | 4 | #coding=utf-8
# 测试函数
def printname(str):
"输出姓名"
print str
# 调用函数
printname("I")
printname(str="love")
# 测试函数
def printNameAndAge(name,age):
print "姓名:",name,"年龄",age
# 调用测试
printNameAndAge(age="23",name="张三")
# 测试函数 缺省参数
def printNameAndAge(name,age="25"):
print "姓名:",name,"年龄",age
# 调用... |
c0d89e2bffe5bbe841921f4283b4aeda5df76897 | shreyanshu/sudoku_project | /s.py | 716 | 3.59375 | 4 | # -*- coding: utf-8 -*-
''' This module solves a sudoku, This is actually written by Peter Norvig
Code and Explanation can be found here : norvig.com/sudoku.html'''
def cross(A, B):
return [a+b for a in A for b in B]
digits = '123456789'
rows = 'ABCDEFGHI'
cols = digits
squares = cross(rows, cols)
unitlist = ([c... |
533f34d5e37dc188e2d67343e31e160044ddb0f3 | qmnguyenw/python_py4e | /geeksforgeeks/python/easy/19_19.py | 3,818 | 3.75 | 4 | Generating all possible Subsequences using Recursion
Given an array. The task is to generate and print all of the possible
subsequences of the given array using recursion.
**Examples:**
Input : [1, 2, 3]
Output : [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]
Input ... |
ad5d56ffea1d841f2e2664cc54a95fa44847204d | chuma99/Programming | /element.py | 5,052 | 4.1875 | 4 | #11-13-18
#In this assignment, I was able to import a csv file of the elements on the periodic table, and import them into my code. From there,
#I was able to access the elements of the file and complete tasks using them, all through user input.
#Sources: https://www.shanelynn.ie/python-pandas-read_csv-load-data-fro... |
3f9b32441b6b1fe1147d380591d0a061e97c5e02 | gabriellee/HackerSchool | /parsedata_keepscores.py | 1,565 | 3.703125 | 4 | #!/usr/bin/env python
'''parse data from csv into people class'''
import numpy as np
import re
def ParseCsv(path):
'''parses data from csv genrated by learning styles survey into student objects with learning style info
Each row is a person, column 1 contains names
the other columns correspond to learning style ... |
4a242aa225b0cb4ddec23576702795e55f8db720 | KKosukeee/CodingQuestions | /LeetCode/268_missing_number.py | 910 | 3.765625 | 4 | """
Solution for 268. Missing Number
https://leetcode.com/problems/missing-number/
"""
class Solution:
"""
Runtime: 140 ms, faster than 99.55% of Python3 online submissions for Missing Number.
Memory Usage: 15.1 MB, less than 6.45% of Python3 online submissions for Missing Number.
"""
def missingNum... |
4c275951df85b640416457ea779b048c10a82937 | Yuggeo/1.2 | /task1.py | 197 | 3.734375 | 4 | x = list(input())
def funct(x):
ans = None
if int(x[0]) < int(x[1]):
ans = x[1]
if int(x[0]) < int(x[2]):
ans = x[2]
ans = int(x[0])
return ans
print(funct(x)) |
f90f338819308cb0822eab8b590f800dcfd5b31e | VolatileDream/advent-of-code | /2020/day-22/main.py | 3,771 | 3.546875 | 4 | #!/usr/bin/python3
import argparse
import collections
import re
import sys
import typing
def load_file(filename):
contents = []
with open(filename, 'r') as f:
for line in f:
line = line.strip() # remove trailing newline
contents.append(line)
return contents
def load_groups(filename):
# beca... |
d326db41baaedaab1a768edd3d117f48824decd0 | AnanthKumarVasamsetti/design_patterns | /chain of responsibility/chain_of_responsibility.py | 1,899 | 3.984375 | 4 | """
Chain of responsibility: In this structural pattern the processing of any given request is handled through a chain of handlers.
Request is passed across the chain of handlers until it is fulfilled.
Example : In following example there will be display of processors which would to take the re... |
3724d56ee454453cd13c55f6956ce463a54b2e6e | hemerocallis/python-courses | /python_course_week1.py | 2,518 | 4.28125 | 4 |
# coding: utf-8
# In[1]:
# Считать отдельными операторами два целых числа, получить: сумму, разность, результат целочисленного деления,
# частное, остаток от деления, третью степень первого числа и вторую степень второго числа
# и вывести их отдельными операторами вывода.
a = int(input())
b = int(input())
print(... |
0ab33dd1c3bd14c89fae805821b6e3f937404b82 | NotAKernel/python-tutorials | /messages.py | 612 | 3.6875 | 4 | def show_messages(messages):
"""Shows text messages."""
for message in messages:
print(message)
messages = ['Hello, Daniel', 'How are you?']
typed_messages = ['Hello, James', 'I am alright']
def send_messages(typed_messages, delivered_messages):
"""Receives and prints messages."""
while typed_mess... |
83bbaa920b062293ffb0265c8a05c9c4d4efa74a | srikarsharan097/Payment-Card-OCR | /Project Code/printing_records.py | 462 | 3.515625 | 4 | import sqlite3 as sqlitedb
print("\nConnecting to database..")
con = sqlitedb.connect('PaymentCards_DB.sqlite')
print("\nConnected.")
print("\nCreating cursor..")
cur = con.cursor()
print("\nCreated.")
print("\nDetails printing..\n")
cur.execute("SELECT * FROM CARDOWNERDETAILS")
col_name_list = [tuple[... |
3a482bc058088107b91b333869515c854ae8d436 | sarazhan/compiti_inf | /numero29.py | 1,623 | 3.875 | 4 | '''
esercizio pag.73 numero 29: dato un elenco di città con l'indicazione per ciascuna di esse del nome della temperatura massima e minima registrate un giorno
si devono contare quante città hanno superato nel giorno un valore prefissato per l'escursione termica ottenuta per differenza tra temperatura massima e minima ... |
876ca04bb2e9078610dae49904221814e624bf91 | ashusao/Deep_Learning_Exercises | /Ex_1/hw1_knn.py | 1,498 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on
@author: fame
"""
import numpy as np
def compute_euclidean_distances( X, Y ) :
"""
Compute the Euclidean distance between two matricess X and Y
Input:
X: N-by-D numpy array train
Y: M-by-D numpy array test
Should return dist: M-by-N numpy ar... |
8d05e4b76ddde8b398a921f7e561acb03236ad56 | joshsizer/free_code_camp | /algorithms/no_repeats/no_repeats.py | 3,300 | 3.671875 | 4 | """
Created on Sun May 2 2021
Copyright (c) 2021 - Joshua Sizer
This code is licensed under MIT license (see
LICENSE for details)
"""
def perm_alone(str):
"""
Get the permutations of an input string that
don't have consecutive repeat letters.
For example, cbc has permutations: cbc, cbc,
ccb, ccb,... |
1d245a584c81f3f25f059f703eafff8d5c57b8a0 | daminton/code_wars | /python/break_camel_case.py | 312 | 3.90625 | 4 | #Complete the solution so that the function will break up camel casing, using a space between words.
def solution(s):
list = []
for i in s:
if i == i.upper():
list.append(" "),
list.append(i)
else:
list.append(i)
return ''.join(list) |
42bafe600e918fc7634b4ca1738bd92f7798d251 | alex-vegan/100daysofcode-with-python-course | /days/day012/hangman.py | 3,928 | 4.15625 | 4 | import random
WORDLIST_FILENAME = "words.txt"
def loadWords(file=WORDLIST_FILENAME):
"""
Returns a list of valid words. Words are strings of lowercase letters.
"""
print("Loading word list from file...")
inFile = open(file, 'r')
line = inFile.readline()
wordlist = line.split()
print(l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.