blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
88e1e334294b1fb980b199274859ffe363a236ca | Kane610/hassio | /appdaemon/apps/media/tv.py | 2,785 | 3.546875 | 4 | from base import Base
import datetime
import time
from typing import Tuple, Union
"""
This app implements the basic functionality for tv/remote/media_player automations
Following use-cases:
- Turn on TV when I start playing on my media player
it automatically pauses for an amount of time to give the TV
a chance t... |
4e911005717ce696d825aea9afc6c5974fb3437a | YP4US/PythonBasics | /if statment/if.py | 98 | 3.875 | 4 | x=5
y=6
z=7
if x<y:
print("x is less than y")
if x<y<z:
print("x and y are less than z") |
6395807a2b1a5a5eab87cb8f0e9e4d788796e815 | PatiKoszi/FirstStepsPython | /sortowanieBabelkowe.py | 320 | 3.84375 | 4 | def sortowanieBabelkowe(lista):
for i in range(len(lista)):
for j in range(len(lista)-1):
if lista[j] > lista[j+1]:
swap(lista, j, j+1)
print(lista)
def swap(lista, a, b):
lista[a], lista[b] = lista[b], lista[a]
lista = [6,1,5,8,-5,-2,0]
sortowanieBabelkowe(lista) |
b8223e559d226b426a3eb75adff92a8320a9a804 | xenron/sandbox-github-clone | /xcv58/LeetCode/Populating-Next-Right-Pointers-in-Each-Node/Solution.py | 678 | 3.921875 | 4 | # Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
class Solution:
# @param root, a tree node
# @return nothing
def connect(self, root):
while root is not None:
... |
be5de42630e6722ab916175ac0a45b293b9ac5cf | ziamajr/CS5590PythonLabAssignment | /CS5590 Lesson 2 Assignment/Task 2/Task 2.py | 749 | 4.125 | 4 | #David Ziama - ClassID #3
#Task 2: - Write a Python program to check if a string contains all letters of the alphabet
#June 22, 2017
#Print out description of program with a space
print("This program will check if a string contains all letters of the alphabet")
print("\n")
#Ask user to enter their string
us... |
735ec5addf56051d3c4c0026e627d14c5963ffc9 | Kristjan-O-Ragnarsson/RamCard | /Main.py | 1,179 | 3.765625 | 4 | """
Guðmundur
main class
24/4/2017
"""
from Functions import *
from Game import Game
from Player import Player
from CardSplitter import CardSplitter
class Main:
"""Main Class"""
@staticmethod
def main():
"""Main Function"""
player_count = intinput("Sláðu inn hversu margir... |
4fa86acaa5856420d689940b1cacea56e8548be0 | vincentiusmartin/teacup | /draft/old stuff/add_kmer.py | 1,962 | 3.609375 | 4 | # This script adds kmer features to the existing data
import pandas as pd
NEW_DATA_PATH = "../data/generated/training_kmer.csv"
DATA_PATH = "../data/generated/training.csv"
def get_seq(data):
'''
This function returns the list of sequences from the data
in a numpy array
Input: input data as a dataframe
Output: ... |
2a4f4ec7bc304431a52738978e21618c2817d845 | jsoendermann/project-euler-python | /004.py | 254 | 3.53125 | 4 | def is_palindrome_number(n):
s = str(n)
return s == s[::-1]
maximum = 0
for i in range(999, 0, -1):
for j in range(999, 0, -1):
if is_palindrome_number(i*j):
if i*j > maximum:
maximum = i*j
print(maximum)
|
e244ba3681b230eb8ac7f8c3308b735dec45e697 | alpharol/algorithm_python3 | /leetcode/0301-0400/0367.有效的完全平方数.py | 906 | 3.5 | 4 | #https://leetcode-cn.com/problems/valid-perfect-square/solution/xun-huan-mi-yun-suan-by-loulan/
"""
给定一个正整数 num,编写一个函数,如果 num 是一个完全平方数,则返回 True,否则返回 False。
说明:不要使用任何内置的库函数,如 sqrt。
示例 1:输入:16;输出:True
示例 2:输入:14;输出:False
"""
class Solution:
def isPerfectSquare(self, num: int):
l,r = 0,num
... |
ba34967bc31f469c66d0806029a832801462c5e7 | kamilhabrych/python-semestr5-lista5 | /zad5_1.py | 188 | 3.59375 | 4 | l = [3,'alfa',2.71,'kot']
l[0] = 4
l[3] = 'pies'
print(l)
l2 = l
print()
print(l)
print(l2)
l2[0] = 98
print()
print(l)
print(l2)
l3=l.copy()
l3[0] = 24
print()
print(l)
print(l3) |
0a33a9e902fb037ea7721c90ee608f835f5323c0 | ioxnr/homework | /hw7/3.py | 1,060 | 3.734375 | 4 | class Cell:
def __init__(self, amount):
self.amount = amount
def __str__(self):
return f'Результат операции равен {self.amount}'
def __add__(self, other):
return Cell(self.amount + other.amount)
def __sub__(self, other):
if self.amount - other.amount > 0:
... |
577147731328ed439abf97fb3f6ce3ffc88cba14 | Aasthaengg/IBMdataset | /Python_codes/p03711/s554784788.py | 198 | 3.578125 | 4 | group = [[1, 3, 5, 7, 8, 10, 12], [4, 6, 9, 11], [2]]
x, y = map(int, input().split())
for i in range(3):
if x in group[i] and y in group[i]:
print("Yes")
exit()
print("No") |
2717e1fb2eb46a911493ff83a148ef4db00588a9 | pk5280/Python | /hr_TowerBreaker.py | 259 | 3.546875 | 4 | def towerBreakers(n, m):
if m==1:
return 2
else:
return 2 if n%2==0 else 1
if __name__ == '__main__':
n = 3
m = 2
print(n,m)
print(towerBreakers(n, m))
n = 4
m = 5
print(n,m)
print(towerBreakers(n, m)) |
256ea1085b68045f3a053362f63834ef4b21dded | Robson-55/Blockchain-python | /block.py | 734 | 3.546875 | 4 | # Generates the class Block
from datetime import datetime
from hashlib import sha256
class Block:
def __init__(self,transactions,previous_hash,nonce=0):
self.timestamp=datetime.now()
self.transactions=transactions
self.previous_hash=previous_hash
self.nonce=nonce
self.hash=self.generate_hash()
d... |
3a453d70adcceeda368bce5ba5ba01319d139a4a | vasketo/EOI | /Python/Día 5/funciónvalidaremail.py | 506 | 4.1875 | 4 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Solicitar al usuario que ingrese su dirección email. Imprimir un mensaje indicando si la dirección es válida o no,
# valiéndose de una función para decidirlo. Una dirección se considerará válida si contiene el símbolo "@".
def validar(email):
if "@" in email:
... |
daa7e4c1bb5a40626ae1f1efe21171468340e6c9 | python-practices/py-practices | /string_examples.py | 559 | 4.3125 | 4 |
# string with parameter example
print("My name is %s and weight is %d\n" % ("John", 27))
para_str = """this is a long string that is made up of
several lines and non-printable characters such as
TAB ( \t ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
... |
f097b482de173204aea8afd4e7f5615baee17a8f | yasserhussain1110/grokking-algo-solutions | /Chapter4/max.py | 189 | 3.828125 | 4 | def maximum(arr):
if len(arr) == 0:
return None
elif len(arr) == 1:
return arr[0]
else:
return max(arr[0], maximum(arr[1:]))
print(maximum([1,2,7,3]))
|
9c69019d96de765d16748a4d3a3eb144edc4cb0a | Lucas-Garciia/FATEC-MECATRONICA-LUCAS-GARCIA-0001 | /LTP1-2020-2/pratica13/prog02.py | 260 | 4 | 4 | no1 = int(input("informe um valor"))
no2 = int(input("informe outro valor"))
print("soma", no1+no2)
print("produto:", no1*no2)
print("divisao:", no1/no2)
print("divisao inteira:", no1//no2)
print("resto da divisao:", no1%no2)
print("potenciação:",no1**no2)
|
d8f100c9b9a9addefddf4b044560d3d18948d89c | VHSCODE/PracticePython-Exercises | /exercise5.py | 258 | 3.9375 | 4 | a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
def duplicate(list1,list2):
lista= []
for i in list1:
if i in list2:
lista.append(i)
print(lista)
duplicate(a, b)
|
a22f71233e8b8ba668ef584ce19030879dfa6a56 | zervas/ekf_test | /scripts/sampling.py | 1,850 | 3.671875 | 4 | import math
import numpy as np
import scipy.stats
import timeit
import matplotlib.pyplot as plt
def sample_normal_twelve(mu, sigma):
""" Sample from a normal distribution using 12 uniform samples;
"""
# Return sample from N(0, sigma)
x = 0.5 * np.sum(np.random.uniform(-sigma, sigma, 12))
return m... |
2980ff0789fe973af4f1d6559be3ff7181ba00db | Franciscwb/EstudosPython | /Cursoemvideosexercicios/obter limite.py | 1,203 | 4.09375 | 4 | '''
print('Esta é a Loja Saint Grail.')
print('Seja Bem-Vindo!')
print('Aqui quem fala é o vendedor Francis de Almeida')
print('Faremos uma análise de crédito.Para tal, digite o seguintes dados')
'''
from datetime import date
data_de_hoje = date.today
def linha():
print('=' * 30)
def obter_limite():
if... |
5c060c006b12c3dd01bd47863f66ca2d0cc79e81 | Neil-Opena/CSE337-Scripting | /CSE373/hw4.py | 7,430 | 3.515625 | 4 | import sys
import math
import queue
import cProfile
import re
class EdgeNode():
def __init__(self, y, next_edge=None):
self.y = y
self.next = next_edge
def __str__(self):
return str(self.y)
class Graph():
def __init__(self):
self.num_vertices = 0
self.num_edges = 0
... |
68ab5b1ccd97f552cb00907b722104d685c7c6f0 | kazamari/CodeAbbey | /014_modular-calculator.py | 1,214 | 3.90625 | 4 | '''
Input data will have:
initial integer number in the first line;
one or more lines describing operations, in form sign value where sign is either + or * and value is an integer;
last line in the same form, but with sign % instead and number by which the result should be divided to get the
remainder.... |
1be3e29d90253023efb410921ecc0a2414861bf8 | Ras-al-Ghul/RSA-Python-Implementation | /primegeneration.py | 2,260 | 3.546875 | 4 | #To generate random primes in the range CONST_MIN to CONST_MAX
#The generated primes are 8 digits in length here because max value of message string for
#CONST_BYTE=4 is 1874160
import random
CONST_MIN=21272296
CONST_MAX=23242658
def rand_prime():
if CONST_MIN%2==0:
CONST_MINSS=CONST_MIN+1
else:
CON... |
7d7e67bacba0e9cd7d754c6feb9d760541b549c2 | Waseem6409/PIAIC | /Sum of digits in integer.py | 1,166 | 4.09375 | 4 | while True:
while True:
try:
num1 = int(input('\nInput integer:'))
except ValueError:
print("\nPlease enter only number")
else:
break
sum=0
... |
b084823d0a8eb92c6a48bc620983d7f664d5c6b0 | dgibbs11a2b/Module-8-Lab-Activity | /Problem2SumofTen.py | 906 | 4.4375 | 4 | #----------------------------------------
#David Gibbs
#March 8, 2020
#
#This program contains a function which takes two inputs
#from the user, calculates the sum, and then prints to
#the screen whether the value is less than, greater than,
#or equal to 10.
#----------------------------------------
x = int(input("Ent... |
9930ee3aab489a8a2fdd8a33a259b3cba271496e | tobereborn/python-recipes | /lng/itertools_groupby.py | 209 | 3.828125 | 4 | # -*- coding: utf-8 -*-
import itertools
def main():
for key, group in itertools.groupby('AaaBbaaaaaBcCaAA', lambda c: c.upper()):
print(key, list(group))
if __name__ == '__main__':
main()
|
cd26603b55a95255fdfa45d978059f640b1754a0 | traciarms/techcrunch | /articles.py | 6,660 | 3.65625 | 4 | import csv
import re
import bs4
import requests
class TechCrunchScraper:
"""
This is the main class used to scrape posts from the TechCrunch website.
It will execute several methods. The process includes:
1. Get all links for articles
2. For each post, scrape its content to look for business that... |
b4c7d14ba03ec17f6f97483da98e16ea34ce7a49 | UCDPA-derekbaker/digital_marketing | /data_analytics_for_marketing.py | 1,259 | 3.546875 | 4 | # This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press ... |
d7eb9d03a61024c1456f36b74b6b78fddcb06ebe | VinogradovAU/myproject | /algoritm/less-2/less_2_task_5.py | 1,309 | 3.921875 | 4 | # https://app.diagrams.net/?lightbox=1&highlight=0000ff&edit=_blank&layers=1&nav=1&page-id=D4vCSPD4o9B4h8Km3Lkl&title=lesson_2#Uhttps%3A%2F%2Fdrive.google.com%2Fuc%3Fid%3D1oqjejCmAcK220vNU4lrkN6D77-34MiOX%26export%3Ddownload
# 8. Посчитать, сколько раз встречается определенная цифра в введенной последовательности чисе... |
8a3d454a32d2dc78cd2c990ede67df5e295a1487 | vipulthakur07/Assignment3 | /frequency of object.py | 140 | 3.6875 | 4 | a=["apple","banana","orange","apple","apple","hello","banana"]
b=input("enter the object : ")
print(b," ","occurs"," ",a.count(b)," times")
|
f3a948440876594267b2fecff3e5a89e283a17b0 | almetzler/Corona-cation | /APIStuff.py | 4,135 | 3.671875 | 4 | '''
Game Plan:
1) Make a list of Countries
2) Get the date of their first case
3) Get Date of 50th case
4) find number of days between 1 and 100
5) put in all in a csv on github
list of (country name , days from day 1 to day 50)
6) maybe also create a json file of day by day number of cases
{country name:[(day,... |
35524c364f5767ba1121f8e7601280fac3366c7f | sjNT/checkio | /Elementary/Three Words.py | 1,255 | 4.21875 | 4 | """
Давайте научим наших роботов отличать слова от чисел.
Дана строка со словами и числами, разделенными пробелами (один пробел между словами и/или числами).
Слова состоят только из букв. Вам нужно проверить есть ли в исходной строке три слова подряд.
Для примера, в строке "start 5 one two three 7 end" есть три слова... |
8f6f3e5b83f7be512d2437d0bdfccb87d79d7fae | leandro-matos/python-scripts | /aula01/ex4.py | 419 | 3.578125 | 4 | text = input('Digite algo: ')
print('')
print(f'O tipo primitivo desse valor é: {type(text)}')
print(f'Tem espaços ? {text.isspace()}')
print(f'É númerico ? {text.isnumeric()}')
print(f'É alfabético ? {text.isalpha()}')
print(f'É alfanumérico ? {text.isalnum()}')
print(f'Está em maiúsculas? {text.isupper()}')
print(f'E... |
9a78f0305a97ace517e5f51c60d35beb4922b72b | kirkwood-cis-121-17/exercises | /chapter-7/ex_7_2.py | 658 | 4.5 | 4 | # Programming Exercise 7-2
#
# Program to display a list of random integers.
# This program takes no input,
# it loops through a list of integers and exchanges them for random integers,
# then displays the list on a single line.
# to use the random functions, import the random module
# Define the mai... |
a3b4e30c0d20af6b09bead85ee3385b1057a010c | chengtianle1997/algs4_princeton | /2.3 Quick Sort/QuickSelect.py | 533 | 3.71875 | 4 | import random
class UnitTest():
def GenerateRandArray(self, n, min, max):
arr = []
arr = [random.randint(min, max) for x in range(n)]
return arr
def isSorted(self, alist):
for i in range(len(alist) - 1):
if alist[i] > alist[i + 1]:
return False
... |
659b6131f6d5427585165149109ee41951bfa97f | Anupsingh1587/Basic-of-Python | /Dictionary_CH11.py | 913 | 4.09375 | 4 | # Dictionary is a collection which is unordered , changeable and indexed. NO duplicate numbers.
# Dictionaries are written in the curly brackets and they have key and values
#Exercise 1
dict={"Brand":"Ford","Model":"Mustang","Year":"1964"}
x=dict["Model"]
y=dict["Brand"]
z=dict["Year"]
print(x)
print(y)
prin... |
f718af2f91794ff491ed4b12620439011f9160f8 | schoentr/data-structures-and-algorithms | /code-challanges/401/queue_with_stacks/stacks_and_queues.py | 970 | 4.03125 | 4 | class Queue():
front = None
rear = None
def enqueue(self,value):
node = Node(value)
if not self.front:
self.front = node
self.rear = node
else:
self.rear._next= node
self.rear = node
def dequeue(self):
self.... |
2a7422dff14b4fb11b8d88ba9c87ce67fd3a325e | DDao19/python_nov_2017 | /alexis_Moreno/python_fundamentals/stringsList.py | 729 | 4.15625 | 4 | # #######find and replace############
# words = "It's thanksgiving day. It's my birthday, too!"
# print words.find("day"),'-',words.replace("day","month",1)
# ######## MIN and MAX numberes##########
# x= [2,54,-2,7,12,98]
# print 'this is the highest num in list x :', max(x)
# print 'this is the lowest num:', min(x)... |
4ce24d109727157b0e8c6ed46a4481b6c1340cd9 | RenegaDe1288/pythonProject | /lesson25/mission6.py | 5,455 | 3.75 | 4 | import random
class House:
day = 1
money = 100
fridge = 50
cat_eat = 30
dirt = 0
spend_moneu = 0
def dirt_day(self):
self.dirt += 5
def __str__(self):
print(
'\n\tДенег: {}, Еды: {}, Кошачьей еды: {}, Грязь: {}'.format(self.money, self.fridge, self.cat_eat... |
0f20b42f6ab8fd4d12ee303afd0dbd5c6cb6aa09 | garvitsaxena06/Python-learning | /11.py | 91 | 4.15625 | 4 | #to find absolute value of a number
num = int(input("Enter the number: "))
print(abs(num))
|
78d17b02b678712553df5a3024cb299adbe207f8 | BIAOXYZ/variousCodes | /_CodeTopics/LeetCode/201-400/000382/000382_impl_newlib_like_official.py3 | 879 | 3.640625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
import random
class Solution:
def __init__(self, head: Optional[ListNode]):
self.arr = []
while head:
self.arr.append(head.val)
... |
d4d837fdaf08be5b27da098dec6c8b3f52fe455f | DemecosChambers/PythonNotes | /input function for your name.py | 183 | 4.0625 | 4 | fnam = input ("May I have your first name, please?")
Inam = input ("May I have your last name, please?")
print ("Thank you.")
print ("Your name is:" "" + Inam + "" + fnam + ".") |
52b98aa6b313686e843debf34be320048168057d | sambreen27/nyu_cff_python | /bmimetric.py | 151 | 4.0625 | 4 | #Name: Saba Ambreen
#Lesson 3.3: BMI Metric
kg = float(input())
height = float(input())
BMI = (kg/(height * height))
print("bmi is: {:.10f}".format(BMI))
|
c038ec5c820c5e298e8d7d02bf761a21017e402d | bobowang2017/python_study | /matplotlib/example03.py | 567 | 3.578125 | 4 | # coding: utf-8
import matplotlib.pyplot as plt
from matplotlib import animation
x = [i for i in range(1, 10)]
y = list(map(lambda s: pow(s, 2), x))
data = [x, y]
im = plt.imshow(data, cmap='gray')
def animate(i):
data = [[s + i for s in x], [s + i for s in y]]
im.set_array(data)
print(data)
plt.plot... |
45d26c91a615352c745f00fbcaf032d1c3ae1947 | ZhaobinMo/COMS-W4995-Applied-ML | /HW1/task1/fib.py | 261 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 2 17:52:22 2019
@author: Zhaobin
"""
def fib(n):
"""return the result of the Fibonacci sequence
"""
f_n_1 = 0
f_n = 1
for i in range(n):
f_n, f_n_1 = f_n_1, f_n+f_n_1
return f_n_1 |
6394d23a7fa4560254ea0855cfd7ba438c270f18 | supercoding1126/money-counter | /finished-project-money-counter.py | 663 | 4.1875 | 4 | # Money conting machine
# By SuperCoding
# Python 3.8.5
# Mac os
name = input('\n\n\n\nWhat do you want to buy: ') # Ask them what they want to buy
num = int(input("How many do you want to buy: ")) # Ask them how much
cost = int(input('How much does it cost: ')) # Ask them how much it cost
tax = 0.14975 # Tax number... |
a8b6146fa4a95c98d05ef07bbafcb959beb359f5 | ShahzaibSE/Learn-Python | /FileSystem_ClassWork/writeFile.py | 553 | 3.90625 | 4 | #Writing to a files.
# with open('files/myFile.txt','w') as file_object:
# file_object.write("I love programming\n");
# file_object.write("I really love programming\n");
# # content = file_object.readable()
# # print("Files Content");
# # print(content);
#Opening a file in both read & write mode.
w... |
db4ce0179b3ed8c7de80c25c72f9ddcc5281cad2 | arav02/tasklist_week1 | /ginortS.py | 362 | 3.765625 | 4 | s=input()
lower=[]
upper=[]
odd=[]
even=[]
a=sorted(s)
for i in a:
if i.islower():
lower.append(i)
elif i.isupper():
upper.append(i)
elif int(i)%2!=0:
odd.append(i)
else:
even.append(i)
lower=''.join(lower)
upper=''.join(upper)
odd=''.join(odd)
even=''... |
524f07aa4ab3299a002cea641e058fb333b0527c | boosungkim/Snake4d | /src/keybuf.py | 1,639 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun May 31 21:40:41 2020
@author: maurop
"""
#==============================================================================
# Key buffer
#==============================================================================
class KeyBuffer:
'''
Key Buffer
is a simple bu... |
da8bfbcdc542f4d7e7db2dd19fadb826ad8a75ec | TristonStuart/IMail-Python-Version- | /IMail [Python]/mailRoom.py | 2,581 | 3.96875 | 4 | import socket
import sys
print("This is the Console")
print("Commands start with '/' type '/tutorial' to get started :)")
print(' ')
sender = "DEFAULT"
def command():
consoleInput = input()
if consoleInput == '/help':
print(' > Help Menue <');
print(' >> /tutorial : Gives a tutor... |
64ced267a31391a0f0e9cf22aeb3197941c4556b | mergederg/deuterium | /game/gamesrc/objects/deuterium/ships/ship.py | 2,620 | 3.78125 | 4 | """
Root class for ships. Everything inheriting from this (and you should inherit from this rather than @create them
directly) will have the properties and behaviors outlined below.
Basic Rooms:
When each ship is constructed, its at_object_creation makes certain Rooms (ev.Room) -- a Cargo Bay (which is where
cargo g... |
89d0e248a140ac61806a741921372617af31a96f | InbarStrull/CL--Substitution-Cipher-Decryption | /permutation.py | 2,329 | 3.71875 | 4 | import random
import math
import language_model
class Permutation:
def __init__(self, perm):
self.perm = perm # dictionary, perm[ord(char[i])] = ord(char[j])
# replace char[i] with char[j]
self.chars = [i for i in self.perm] # Sigma
def get_char... |
cbd51438d27178c0f4ae6a2e8a0041b46cf15397 | Daniiarz/python07.01 | /lesson7/lesson7.py | 876 | 3.734375 | 4 | # for i in range(10):
# if i == 5:
# continue
# print(i)
# def a_div_b(a, b):
# for i in range(33333333333333333333333333333333):
# if i == 5:
# print(i)
# print("До break")
# break
#
# return a / b
#
#
# print(a_div_b(2, 2))
#
#
def take_students(nu... |
20e8c4d541bd08828598d720adc21d5d70cb22f0 | SimeonTsvetanov/Coding-Lessons | /SoftUni Lessons/Python Development/Python Advanced January 2020/Python OOP/19. TESTING/02. Test Cat.py | 1,809 | 4.25 | 4 | import unittest
# For testing remove or comment the class CAT:
class Cat:
def __init__(self, name):
self.name = name
self.fed = False
self.sleepy = False
self.size = 0
def eat(self):
if self.fed:
raise Exception('Already fed.')
self.... |
bb29bc2726124b86a033c1eb062343562ecdf862 | openstate/datasets | /government_domain_names/create_list.py | 6,710 | 3.765625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv, codecs, cStringIO
import json
import re
class UTF8Recoder:
"""
Iterator that reads an encoded stream and reencodes the input to UTF-8
"""
def __init__(self, f, encoding):
self.reader = codecs.getreader(encoding)(f)
def __iter__(sel... |
b8dbcd3781cd4ec7fbb806d9424829b61fe29acd | bluescheung/Pypractice | /dir.py | 140 | 3.5 | 4 | #!usr/bin/env python3
import os
def dir():
L= [ x for x in os.listdir('.') if os.path.isdir(x)]
for i in L:
print i
dir()
|
d213da6205c664bd8bae2167dcab64fcb29837a9 | magedu-pythons/python-19 | /P19054-yangxingxing/week6#7/practice/sample_sort3.py | 1,001 | 3.546875 | 4 | # 重复练习
import random
limit = 30
list1 = [0] * limit
for i in range(limit):
list1[i] = random.randint(1, 50)
print(list1)
print()
# 简单选择排序
#for i in range(limit-1):
# max_index = i
# for y in range(i+1, limit):
# if list1[y] > list1[max_index]:
# max_index = y
# if max_index != i:
# ... |
c3ad6404b8fedbb0e382d903f89d0d675d21495d | daniel-reich/ubiquitous-fiesta | /u3kiw2gTY3S3ngJqo_20.py | 98 | 3.71875 | 4 |
def superheroes(heroes):
return sorted([i for i in heroes if "man" in i and "oman" not in i])
|
4bb29914f965e55dfbc0cebfb8ff32949e0913df | maximillianus/python-scripts | /py-sqlite/createdb.py | 2,006 | 3.796875 | 4 | import sqlite3
DBNAME = 'example.db'
def create_conn(dbname):
try:
conn = sqlite3.connect(dbname)
cur = conn.cursor()
return conn, cur
except sqlite3.Error as e:
print('SQLite3 Error connecting to db: %s' % e)
return False, False
except Exception as e:
print... |
92b0bc4fff4fa908d830d95166916d07822cba48 | aditiagrawal30/Python | /bubble_sort.py | 625 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 30 11:10:40 2020
@author: Aditi Agrawal
"""
def bubble_sort(nums):
# Set swapped to True so the loop looks run atleast once
swapped = True
while swapped:
swapped = False
for i in range(len(nums)-1):
if nums[i]>nums[i+1... |
0fc66c2cd01b763621e358450b52df3b24fff9d5 | waffle-iron/MITx-6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python | /week1/ProblemSet1/Problem Set 1.py | 921 | 3.71875 | 4 | # Problem 1
s = 'dgrgaxwupkxokiolhai'
num_vowels = 0
for letter in s:
if letter == 'a' or letter == 'e' or letter == 'i' or letter == 'o' or letter == 'u':
num_vowels += 1
print(num_vowels)
# Problem 2
s = 'azcbobobegghaklbokbob'
num_bobs = 0
for idx in range(len(s)):
if s[idx] == 'b' and idx >= 2:
... |
6d49e272c613da8e73afd49a23965b0cc5f4e208 | joaofel-u/uri_solutions | /1340.py | 2,295 | 4.0625 | 4 | # -*- coding:utf-8 -*-
# metodo para insercao em uma fila de prioridade
def priority_queue_insertion(queue, value):
inserted = False
for i in range(len(queue)):
if queue[i] >= value:
queue.insert(i, value)
inserted = True
if not inserted:
queue.append(value)
# faz ... |
e7340996fa28a7a32b0409ad841d916ae90cb7f5 | Zacherybignall/csc_442 | /Ross Piraino/RPsteg.py | 1,007 | 3.578125 | 4 | #Ross Piraino 5/8/2020
#Made for python 3
from sys import stdin, argv
DEBUG = True
#default values for interval and offset
interval = 1
offset = 0
#reads the args and stores them as their variables
for arg in argv:
if arg[1] == "s":
mode = "s"
elif arg[1] == "r":
mode = "r"
... |
2a351a1b2cd9c9b07851cdbc4bb2fec1129625c6 | yuyaxiong/interveiw_algorithm | /LeetCode/二叉搜索树/98.py | 1,870 | 3.875 | 4 | # Definition for a binary tree node.
# 98. 验证二叉搜索树
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
if root is None:
return True
... |
3fe2b0e345e71b86bbec46694611f8d030f86e80 | naveenselvan/hackerranksolutions | /Capitalize.py | 487 | 3.84375 | 4 | # Complete the solve function below.
def solve(s):
c='1 W 2 R 3g'
if s=='1 w 2 r 3g':
return c
else:
return s.title()
#One Test Case will not pass using title() so for that particular input o/p is hardcoded!! :p If you want proper solution see below
def solve(s):
c... |
0c3207084c7fe023b05fee39047ac658c9f38c21 | Han-Seung-min/Man_School_Programming | /김민범/Python Basic Training01.py | 2,068 | 4.09375 | 4 | # Python Basic Training01
# 1번
a = int(input("숫자입력>"))
print(a)
print("%d" % (a ** 3))
print("-" * 30)
# 2번
a = int(input("숫자입력>"))
print("%d" % (a%3))
print("-" * 30)
# 3번
a = int(input("a 입력"))
b = int(input("b 입력"))
print("%d" % (a//b))
print("-" * 30)
# 4번
print("'작은 따옴표가 들어간 string'")
print("-" * 30)
# 5... |
635baea540b2d7ca3459ffc5bf35193545418f75 | LuisOrnelas-dev/DatAcademyWeek1 | /reto1.py | 744 | 3.75 | 4 | import math
def area(base, altura ,lados):
area = (base * altura) / 2
rel1 = altura/base
rel2 = math.sqrt (3) /2
print (rel1)
print (rel2)
if rel1 == rel2:
tipo = "equilatero"
else:
if lados == 0:
tipo = "escaleno"
else:
tipo = "isoceles"
... |
56a541e3aba01830e07be7617ede5a3e1c928eae | alirezaghey/leetcode-solutions | /python/binary-search.py | 467 | 3.703125 | 4 | from typing import List
class Solution:
# Time complexity: O(log n)
# Space complexity: O(1)
def search(self, nums: List[int], target: int) -> int:
left, right = 0, len(nums)-1
while left <= right:
mid = left + (right - left)//2
if target > nums[mid]:
... |
7b4ad81ad78cf840004b896d27a8c0cf310e7936 | dawidsielski/Python-learning | /modules training/average.py | 122 | 3.703125 | 4 | l = [1,2,3,4,5,88]
def average(numbers):
return sum(numbers)/len(numbers)
print(average(l))
print(average([5,6,7])) |
7ac523f9bdaf166d52b283394f60a78bc912ef30 | hanwgyu/algorithm_problem_solving | /Leetcode/1650.py | 952 | 3.71875 | 4 | """
# Definition for a Node.
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
self.parent = None
"""
class Solution:
def lowestCommonAncestor_1(self, p: 'Node', q: 'Node') -> 'Node':
"""
방문한 노드를 기록
O(H) / O(H... |
7dc2bff4b19392ce52856d53870462c410f051e2 | isneace/Queue-Organizer | /Lab6.py | 3,382 | 3.765625 | 4 | """
Date: 10/4/2018
Developer: Isaac Neace
Program: Lab 6
Description: Opens a .dat file and splits up each task according to how long it takes
For example if there is a process that takes 3 seconds it will go into
Queue 1. If the process is longer than 3 seconds it will go into queue ... |
6ddc7392654ed9acd3348c7fd6e656688a3f352a | lnugraha/pysketch | /Creational Design Pattern/abstract_factory.py | 793 | 4.0625 | 4 | class Dog:
def speak(self):
return "Woof!"
def __str__(self):
return "Dog"
class DogFactory:
def get_pet(self):
return Dog()
def get_food(self):
return "Dog Food"
class PetStore:
def __init__(self, pet_factory=None):
self._pet_factory = p... |
293f96d11c8210eda9d8e3cefc1bc95132b42368 | narinn-star/Python | /Review/Chapter08/8-06.py | 504 | 3.625 | 4 | class Card:
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
def getRank(self):
return self.rank
def getSuit(self):
return self.suit
def __repr__(self):
return "Card('{}', '{}')".format(self.rank, self.suit)
def __eq__(self, ot... |
1ec9c1ee1d938499a8b837d112f5f43025d9f28d | leleluv1122/Python | /py1/final_practice/13-3.py | 489 | 3.578125 | 4 | def main():
txt = input("파일명을 입력하세요: ")
infile = open(txt, "r")
s = infile.readline()
print(s)
items = s.split()
lst = [eval(x) for x in items]
print(len(lst), "개의 점수가 있습니다.")
total = 0
for i in range(len(lst)):
total += lst[i]
print("총 점수는 " + str(total) + " 입니다. ")
... |
d7819214b93935a8765a356934e254ed6f6e9444 | WyldWilly/python_SelfTaughtBook | /Docstring.py | 184 | 4.0625 | 4 | #!/usr/bin/env python3
def add(x,y):
"""
Returns x + y.
:param x: int.
:param y: int.
:return: int sum of x and y.
"""
return x + y
j = add(5,10)
print(j) |
ffc71cc16f64039f11505f4ab34f6475ba864940 | alexander-450/terminal-calculator | /py_club_calculator.py | 4,125 | 4.1875 | 4 | import time
# Calculator
# welcome message and asking for the operation to perform
def welcome():
list_of_operation = ['addition', 'subtraction', 'division', 'multiply']
print('Hello User\n')
print(f'Operation you can perform => {list_of_operation}')
time.sleep(1)
users_request = input('Please wha... |
44cbc3f5ff323bbb2505d72392c3ace610d7a795 | mikemcd3912/CS361_Content_Generator_Microservice | /life_generator/gui/title.py | 564 | 4.28125 | 4 | # Name: Joshua Fogus
# Last Modified: February 11, 2021
# Description: A title label for the application.
import tkinter as tk
from tkinter import font
def title(parent, text):
""" Creates a title line attached to the given parent,
with the given text. Returns the label. """
tk_label = tk.Label(pa... |
41fb69abf407da6702944ec82295f3167246a900 | anuragrana/2019-Indian-general-election | /election_data_analysis.py | 4,064 | 3.65625 | 4 | import json
with open("election_data.json", "r") as f:
data = f.read()
data = json.loads(data)
def candidates_two_constituency():
candidates = dict()
for constituency in data:
for candidate in constituency["candidates"]:
if candidate["party_name"] == "independent":
... |
1bab83e7040ee6baecdf81dd27402bab4563b828 | shadow1666/Tkinter-Projects | /2_basics/basics6_images.py | 846 | 3.796875 | 4 | #Images
import tkinter
from PIL import ImageTk, Image
#Define window
root = tkinter.Tk()
root.title('Image Basics!')
root.iconbitmap('thinking.ico')
root.geometry('700x700')
#Define functions
def make_image():
'''print an image'''
global cat_image
#Using PIL for jpg
cat_image = ImageT... |
68cfe8c865e50c162b224657cf99e594b742109f | yoshi-lyosha/Track_race_gaem | /top_gaem.py | 4,670 | 3.734375 | 4 | import random
import os
import platform
if platform.system() == 'Windows':
from msvcrt import getch
else:
print("")
STRING_N = 20
COLUMN_N = 70
GOAL = 20000
START_SCORE = 0
CAR_X = 1
GAME_STATUS = 'On'
# вероятность что каждый n-ый объект трассы будет препятствием, где n - complexity
complexity = 5
car_sym... |
00605bc11c29b39a0d6668b3682a8e1e440267d6 | seanchen513/leetcode | /sorting/1366_rank_teams_by_votes.py | 6,073 | 4.3125 | 4 | """
1366. Rank Teams by Votes
Medium
In a special ranking system, each voter gives a rank from highest to lowest to all teams participated in the competition.
The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position t... |
52313679cadb9e8e4cb3dc03bad256f9355403e6 | Free-Geter/python_learning | /Basic/Basic_Science1.py | 12,450 | 3.78125 | 4 | import numpy as np
# numpy.around() 函数返回指定数字的四舍五入值。
# numpy.around(a,decimals)
# 参数说明:
# a: 数组。
# decimals: 舍入的小数位数。 默认值为 0。 如果为负,整数将四舍五入到小数点左侧的位置。
# numpy.floor() 返回数字的下舍整数。
# numpy.ceil() 返回数字的上入整数。
import numpy as np
a = np.array([1.0,4.55, 123, 0.567, 25.532])
print ('原数组:')
print (a)
print ('around 舍入后:')
print (... |
33c7adbd009fe22ac95eabb9383346ca3f66dcb4 | Introduction-to-Programming-OSOWSKI/3-3-factorial-alyssaurbanski23 | /main.py | 120 | 3.59375 | 4 | def factorial(x, y):
for i in range (1, 5):
print(i)
return "done"
print (factorial(1, 5))
|
a824bdc6e6d9bfd5166b5a31ba4856a8a9c412b6 | vodkaground-study/koi | /초등부_1.py | 759 | 3.734375 | 4 | '''
n개의 막대기에대한 높이정보가 주어질때, 오른쪽에서 보면 몇개가 보이나?
'''
# 2 <= n <= 100,000
stick_cnt = int(input('막대기 개수 >> '))
# 각각의 막대기 높이 입력 :: 1 <= h <= 100,000
stick_height = []
for i in range(stick_cnt) :
stick_height.append(int(input(str(i) + "번째 막대기 높이 >> ")))
def solution() :
viewHeight = 0
viewCnt = 0
stick_hei... |
e0b859a225691a080b0db162e7a6b515d843e7ff | jiangsy163/pythonProject | /venv/Lib/site-packages/commodity/sequences.py | 1,633 | 3.671875 | 4 | # -*- coding:utf-8; tab-width:4; mode:python -*-
import itertools
from functools import reduce
def uniq(alist):
'''
>>> list(uniq([1, 2, 2, 3, 2, 3, 5]))
[1, 2, 3, 5]
'''
s = set()
for i in alist:
if i in s:
continue
s.add(i)
yield i
def merge(*args):
... |
974edeedefe2e93e689a60874cc9c2271d22bfd8 | TheRealJenius/TheForge | /Functions.py | 1,044 | 3.625 | 4 | def add(x,y):
return x + y #+ for add, - for subtraction
print (add (4,5))
#adding as a test
def power(o,p):
return o**p #** for power, * for multiply
print (power (3,4))
def nodec(j,k):
return j//k #/ divide, // divide without a decimal
return j%k #returns the remainder of the division
print(nodec(... |
9dcc08ccb20d15ca19e3e382444a3e6b70b2bb09 | mike006322/Algorithms1 | /HW6/Median.py | 2,176 | 3.875 | 4 | # 2 heaps, HeapLow and HeapHigh, both with extract min but HeapLow will input numbers as negative
# HeapHigh.heaplist[1] = min element in HeapHigh
# -1*HeapLow.heaplist[1] = max element in HeapLow
# HeapHigh.currentSize = the size of heap high
# HeapLow.currentSize = the size of heap Low
# say that Heap High will alway... |
f9f31d91cb500ed5bd23b7d6998881492079f1dd | drdarshan/pytorch-dist | /torch/nn/modules/dropout.py | 3,955 | 3.796875 | 4 | from .module import Module
class Dropout(Module):
"""Randomly zeroes some of the elements of the input tensor.
The elements to zero are randomized on every forward call.
Args:
p: probability of an element to be zeroed. Default: 0.5
inplace: If set to True, will do this operation in-place. ... |
afc298e2a88e57d31ab70f24214cfdbf1eeeccd6 | akhilsai0099/Python-Practice | /Sorting_algorithms/insertion_sort.py | 275 | 4.125 | 4 | def insertion_sort(array):
for i in range(1,len(array)):
key = array[i]
j = i -1
while j >=0 and key < array[j]:
array[j+1]= array[j]
j -= 1
array[j+1] = key
return array
print(insertion_sort([12,1,53,21,2]))
|
f05dc9720cca147c4bf0deae25ec9165125b329f | mines-nancy-tcss5ac-2018/td1-ManonLanzeroti | /TD1 Pb 55 Lanzeroti.py | 1,385 | 3.578125 | 4 | def rev(chaine): #inverse la chaine de caractre
rev_chaine = ""
for lettre in chaine:
rev_chaine = lettre + rev_chaine
return rev_chaine
def nombreinverse(nombre): #renvoie le nombre dont les chiffres sont inverss
chaine = str(nombre)
rev_chaine = ""
for lettre in chaine:
... |
fd9b1a9942ce87493299fabde43f8fcbd457c470 | August1s/LeetCode | /剑指Offer/No16数值的整数次方.py | 496 | 3.671875 | 4 |
# 直接循环会超时。复杂度O(n)
# 注意到,pow(3,6) = pow(9,3) = 9*pow(81*1)
# 也就是 pow(x, n) = pow(x*x, n//2) 或 x * pow(x*x, n//2)
# 时间复杂度是O(logn)
def myPow(self, x: float, n: int) -> float:
def Rec(i, j):
if j==0:
return 1
if j==1:
return i
if j==-1:
return 1... |
4424048024d63670c23128cf7d333da6a4a79e5d | edwardmoradian/Python-Basics | /String Processing - Using the In Operator.py | 175 | 4.09375 | 4 | ## In and Not In
def main():
s = "How now brown cow?"
if "now" in s:
print("yes, now is in s")
if "now" not in s:
print("It is not is s") |
b4594bb3cfad7130ca33a6bcbe4bed9f160bf6fa | maston14/Leetcode_PY | /Base 7 504.py | 783 | 3.625 | 4 | # Origin
class Solution(object):
def convertToBase7(self, num):
"""
:type num: int
:rtype: str
"""
ret = ''
neg = num < 0
num = abs(num)
while num != 0:
bit = num % 7
num = num / 7
ret = str(bit) + ret
if ne... |
e5014b5b0881eb6039d6c7772a52123d3758d9a1 | Jieken/PythonCoding | /DataStructures/Heap/Heap.py | 1,652 | 4.09375 | 4 | class Heap:
def __init__(self):
self.__data = []
self.__weight = 0
self.__size = 0
def __swap(self, r, l):
temp = self.__data[r]
self.__data[r] = self.__data[l]
self.__data[l] = temp
def insert(self, item):
self.__data.append(item)
... |
259305de1ed58dbeff583353cd012ef41aea4707 | kapilaramji/python_problems | /20_string_match.py | 336 | 3.765625 | 4 | Given 2 strings, a and b, return the number of the positions where they contain the same length 2 substring. So "xxcaazz" and "xxbaaz" yields 3, since the "xx", "aa", and "az" substrings appear in the same place in both strings.
string_match('xxcaazz', 'xxbaaz') → 3
string_match('abc', 'abc') → 2
string_match('abc', ... |
22f01c6ba250432e2aff9090695a32bafc2d1e1f | maggieee/code-challenges | /reverse-integer.py | 291 | 3.609375 | 4 | class Solution:
def reverse(self, x: int) -> int:
strng = str(x)
negative = False
if strng[0] == "-":
negative = True
if negative == True:
return int(strng[1::-1])*(-1)
else:
return int(strng[::-1]) |
5da8682f81e769e5d76f06777ac9aa14f4f5bb85 | Tyrannas/ComputationIntelligence | /assignment02/nn_regression_plot.py | 5,243 | 3.875 | 4 | import matplotlib.pyplot as plt
import numpy as np
"""
Computational Intelligence TU - Graz
Assignment 2: Neural networks
Part 1: Regression with neural networks
This file contains functions for plotting.
"""
__author__ = 'bellec,subramoney'
def plot_mse_vs_neurons(train_mses, test_mses, n_hidden_neurons_list):
... |
1bc5dc3db882420f67180dbd9eb361a111299bbc | PigsGoMoo/LeetCode | /multiply-strings/multiply-strings.py | 553 | 3.5625 | 4 | class Solution:
def multiply(self, num1: str, num2: str) -> str:
res = 0
carry1 = 1
# Based on how we multiply normally. 32 * 26 = 6 * 2 + 6 * 30 + 20 * 2 + 20 * 30
# Or: (6 * 2) + (6 * 3 * 10) + (2 * 10 * 2) + (2 * 10 * 3 * 10)
for i in num1[::-1]:
c... |
63092961537c235c915a0584b4128f0478bf8519 | lucianohdonato/aulas_python3_basico | /netspeedy.py | 291 | 4 | 4 | #!/usr/bin/python3
#-*- coding: UTF-8 -*-
tamanho = float(input("Qual o tamanho do arquivo? (em MiB)"))
velocidade = float(input("Qual a velocidade do Link de internet? (em Mbps)"))
speedy = (tamanho * 8) / velocidade
print('Seu tempo de download estimnado é de' , speedy , 'segundos.')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.