blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
7e40acf91acd9dd755ffa1e2e6f819f147cf5779 | meltopian/learningtocode | /tasks/task_12hrtime.py | 969 | 3.953125 | 4 | # Create a program that takes user input
# and converts a 12h time (e.g. 4:53pm, 6:00am)
# into into a 24h time (e.g. 16:53, 06:00)
print('please enter an am or pm time, for example 4:00pm, and i will convert it to 24hr time')
time = input()
split_time = time.split(":")
if 'p' in split_time[1]:
split_time[0] = ... |
d4ebc370a69806dff8d30456528fb750f2ebde75 | Glittering/netEase | /firstbook/firstBook/demos/wordsStatistics/test_word.py | 372 | 3.546875 | 4 | #coding:utf-8
import string
path = 'Walden.txt'
with open(path,'r') as f:
words = [word.strip(string.punctuation).lower() for word in f.read().split()]
words_index=set(words)
word = {word:words.count(word) for word in words_index}
for word_get in sorted(word,key = lambda x: word[x],reverse= True):
pr... |
279049551c0ffa7d50284ceabb533decf38c4830 | merediiii/pytcode | /maxProfit.py | 364 | 3.671875 | 4 | # -*- coding: utf-8 -*-
from typing import List
class Solution:
def maxProfit(self, prices: List[int]) -> int:
r = 0
a = 0x3f3f3f3f
for i in range(0,len(prices)):
a = min(a,prices[i])
r = max(r, prices[i] - a)
return r
if __name__ == '__main__':
s = Solu... |
fda80dc78e5dffa95ed33bcb58cae6423ce45d99 | br3ndonland/algorithms | /py/algorythms/tutorials/talkpython_async_05_threading.py | 1,042 | 4.3125 | 4 | """
Talk Python Training: Async Techniques and Examples in Python
---
Course: https://training.talkpython.fm/
Code: https://github.com/talkpython/async-techniques-python-course
Chapter 5: Threading
This is a simple demonstration of how background, or "daemon," threads allow
other work to continue in the foreground.
"... |
faa2a8a164bf348b746c58aab300d2ab4e6f5aed | soniakash1998/Optical-Flow | /PA2_1.py | 5,830 | 3.578125 | 4 | __author__ = 'khushboo_agarwal'
#import libraries
import math
from scipy import signal
from PIL import Image
import numpy as np
from numpy import *
from matplotlib import pyplot as plt
from pylab import *
import cv2
import random
'''
1. Lucas-Kanade method is basically an estimate of the movement of interesting
featu... |
48c028fbe194d9b88bae60ac1a4a69ee7dae892f | Atadeno/Projet_RO_Groupe_8 | /croisement.py | 7,625 | 3.609375 | 4 | import ordonnancement as ord
import job
import random
### Croisement ###
def swap(A, B, i, j):
TEMP_B = B[j]
B[j] = A[i]
A[i] = TEMP_B
return A, B
# prend deux listes d'entiers entrée
# croise ces deux listes d'entiers
# retourne les deux listes d'entiers croisées
def croiser_liste(L, M):
try:
... |
ae82e44d50d0f24b1a20b1cb78c2a911f47240cc | avishek088/py-tictactoe | /TicTacToeGame.py | 3,773 | 3.671875 | 4 | from itertools import cycle
from colorama import init, Fore, Style
init()
def game_board(game_map, player=0, row=0, col=0, just_display=False):
try:
if(game_map[row][col] != 0):
print("This position is occupied ! Please choose another ...")
return game_map, False
print(" ... |
1af07fa51b4b364184fa587778add8fe02586ad9 | archu997/codekata | /working.py | 231 | 3.875 | 4 | def workingDay(day):
work=['monday','tuesday','wednesay','thursday','friday','saturday']
if day in work:
return True
else:
return False
day=raw_input("Enter a day")
day=day.lower()
print workingDay(day)
|
6f01bda382ad3bb0fbeec369c65c8a85ac6007ec | arpita-ak/APS-2020 | /Hackerrank solutions/Medium- Climbing the Leaderboard.py | 987 | 3.921875 | 4 | """
Climbing the Leaderboard: https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem
"""
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the climbingLeaderboard function below.
def climbingLeaderboard(s, scores, a, alice):
uniq=[0]*(s+a)
j=0... |
2ea8ccb0b4969ad8262f04e78d1316703d8aff72 | paularodriguez/python-core-and-advance-course | /sec11-lambdas/decorator_strings.py | 451 | 4.3125 | 4 | # The hello function takes a name and it will return Hello under that name and then even create a decorator
# function called howareyou that will take the result of the hello function and it will append a string
# called "How are you" at the end
# Hello (name)
# howareyou()
def howareyou(fun):
def inner(n):
... |
f81c26622f99a75af43fb439ebf150a319f04507 | obada320/My-Codes | /Python learning/old.py | 456 | 4.03125 | 4 | name1 = str(input('Enter name '))
age1 = float(input('Enter age '))
name2 = str(input('Enter name '))
age2 = float(input('Enter age '))
name3 = str(input('Enter name '))
age3 = float(input('Enter age '))
if age1 > age2:
if age1 > age3:
print(name1,' is the oldest')
if age2 > age1:
if ... |
151cc645d92a0f59c510e55ffde4157d0fb320d7 | kinghoward63/hello-world | /Module 1-Problem 2.py | 236 | 3.90625 | 4 | #Dante Howard
#4/23/2019
#Problem 2 this will tell you the numberof day the week you returned on
day=int(input("number0-8"))
gone=int('How ling were you gone?"))
gone%7
((gone%7)+day)
print(((gone%7)+day)%7)
|
edae72ce9e44e9ab712a4135adf2d877cfc0e3fb | ridersw/Karumanchi---Algorithms | /InsertionSort.py | 356 | 4.15625 | 4 | def insertionSort(elements):
for swi in range(1, len(elements)):
anchor = elements[swi]
swj = swi - 1
while swj >= 0 and elements[swj] > anchor:
elements[swj+1] = elements[swj]
swj -= 1
elements[swj+1] = anchor
if __name__ == "__main__":
elements = [11, 9, 29, 7, 2, 15, 28]
inser... |
b3a803ce3de9c52547df7fe5e1093f86d99348db | hal00010001/PythonProjects | /af_semana9.py | 4,089 | 4.125 | 4 | #!/usr/bin/python3
#coding: utf-8
import random
# Inicio do exercicio 1
# Faça um algoritmo que solicite ao usuário números e os armazene em uma matriz 6x6. Em seguida, crie um vetor que armazene os elementos da diagonal principal da matriz.
def exercicio1():
vetor = [0]*6
matriz = [0]*6
for i in range(6)... |
a487f40fe1a1f9fd900c3ff4812850b9219370a2 | JamesRoth/Unit3 | /betterAdditionGameDemo.py | 593 | 3.9375 | 4 | #James Roth
#2/28/18
#betterAdditionGameDemo.py - the name says it all
from random import randint
numCorrect=0
numIncorrect=0
while numCorrect<5:
num1=randint(-10,10)
num2=randint(-10,10)
print("You've had", numCorrect, "correct answers, and", numIncorrect, "incorrect answers.")
answer=int(input("What ... |
3b8ff5aa837b81e2b25175b3f966e91b552aee1c | SmartPracticeschool/llSPS-INT-2749-Garbage-Classification | /Preprocessed and Model/Model.py | 980 | 3.625 | 4 | #Importing The Model Building Libraries
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
#Initializing The Model
model = Sequential()
#Loading The Prepocessed Data
from Preprocessed import *... |
70deb2dc69056571aee0f2a654fa3b77c4ca014f | XenonShawn/Sudoku | /sudoku.py | 3,410 | 3.984375 | 4 | from sys import argv, stderr
from time import time
def main() -> None:
# Get the board
board = input_board()
print("Input Board:")
print_board(board)
start = time()
if check_board_validity(board):
solve(board)
print("Result:")
print_board(board)
else:
print(... |
c677818a25890aa90139253b963bc0de48db9d3f | excaliware/python | /temperature.py | 520 | 4.03125 | 4 | """
Convert temprature from Celsius to Fahrenheit or vice versa.
"""
import sys
def main():
if len(sys.argv) == 3:
mode = str(sys.argv[1])
value = int(sys.argv[2])
else:
print_usage()
exit(-1)
if mode == 'f':
print("%.1f" % f2c(value))
elif mode == 'c':
print("%.1f" % c2f(value))
else:
prin... |
15cc10a850e7a0f9ca1932ee46527e6adef30c5a | ledunn/dev-sprint2 | /chap6.py | 578 | 3.9375 | 4 | # Enter your answers for chapter 6 here
# Name: Lauren Dunn
# Ex. 6.6
def first(word):
return word[0]
def last(word):
return word[-1]
def middle(word):
return word[1:-1]
print middle('')
#middle() doesn't work with two letter, one, or no letter strings.
def is_palindrome(word):
if len(word)<2:
pass
elif... |
dc63d6a556cc465d7e6aadaa281e0c238632f4d4 | javierfdz10/shopping_cart | /shopping_cart.py | 4,655 | 4 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 15 13:12:24 2018
@author: Javier
"""
#Our e-shop sells the following products:
# 1. Guitar: $1000
# 2. Pick box: $5
# 3. Guitar Strings: $10
# Create a function named checkout that takes a list that represents a shopping cart and returns the... |
7224bdeea7e8e55e953dd1be9e0ef932621a7259 | Jcoder2022/ConditionalStatementsInPython | /conditionalStmt.py | 2,820 | 4.3125 | 4 |
# if it's hot
# It's a hot day
# Drink plenty of water
# otherwise if it's cold
# It's a cold day
# Wear warm clothes
# otherwise
# It's a lovely day
weather = "cold"
is_hot = True
is_cold = True
if is_hot:
print("It's a hot day")
print("Drink plenty of water")
elif is_cold:
print("It... |
b61314b7915fac3f3f4e4f0b7423166f262cbd69 | NavTheRaj/python_lab | /pickle_veg.py | 3,513 | 4.5625 | 5 | #WAP TO DEMONSTRATE DICTIONAARY OPERATIONS IN PYTHON
veg_dict={'Brinjal':10,'Cabbage':20,'Pumpkin':25}
print("-------------------\n")
#print("1.View list\n2.Add a new vegetable\n3.Change the price of an vegetable\n4.Delete the vegetable\n5.Quit!")
choice=0
while choice != 5 :
print("1.View list\n2.Add a new veg... |
3181050086a4ea4b6c1f46f27535633e334b5f74 | Rodrigs22/ExerciciosCursoEmvideo | /ex040.py | 2,561 | 3.625 | 4 | #cores
cores = {'limpa': '\033[m',
'amarelo': '\033[33m',
'vermelho': '\033[31m',
'verde': '\033[32m',
'ciano': '\033[36m'}
#estética
print(cores['amarelo'])
print('-=' * 22)
print(cores['limpa'])
print(cores['ciano'])
print('CALCULE A MÉDIA DO SEU ALUNO !')
print(cores['limpa'])
pri... |
00b40818d5e09b739d65797b096994d9992b9de5 | damodardikonda/Python-Basics | /roaster2.py | 1,658 | 3.578125 | 4 | import json
import sqlite3
dbname = "roster.sqlite"
conn = sqlite3.connect(dbname)
cur = conn.cursor()
cur.executescript('''
DROP TABLE IF EXISTS User;
DROP TABLE IF EXISTS Course;
DROP TABLE IF EXISTS Member;
CREATE TABLE User (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
name TEXT UNIQUE
);
CREA... |
ac60d2a0aef3355678bc3b29500a052492be65f5 | wymen98/Stemmer_vs_WordNet-NLP- | /stemming.py | 2,231 | 3.671875 | 4 | #Stemming
#use to find out the stem of the word
#PorterStemmer is the most popular Stemmer to be used
from nltk.stem import PorterStemmer
stemmer = PorterStemmer()
print(stemmer.stem('Working'))
print(stemmer.stem('Worked'))
#------------------------------------------------------
#SnowballStemmer is support... |
5737255b1c47f67d729375cebea98157bf495f41 | KreefS/bX6RzMFSRh | /Python Code/Told you I'd make this.py | 832 | 3.75 | 4 | import turtle
def writing():
turtle.penup()
turtle.colormode(255)
turtle.color(0,255,0)
turtle.goto(30,-30)
turtle.pendown()
turtle.write("Bitcoin be like", False, align="center", font=("Arial", 16, "normal"))
turtle.penup()
def graph():
turtle.color(0,0,0)
turtle.goto(0... |
c43356b86addc1386a3dbf146b14199e14550fd3 | IanSkapin/AsteroidsPygletTutorial | /game/util.py | 180 | 3.671875 | 4 | import math
def distance(a=(0, 0), b=(0, 0)):
"""Returns the distance between two points"""
return math.sqrt((a[0] - b[0]) ** 2 +
(a[1] - b[1]) ** 2) |
c2fb2001167731b45df07cb751ef21b1575bc306 | TravisLeeWolf/ATBS | /Chapter_1/stringS.py | 162 | 4.09375 | 4 | # String Concatenation
print('Alice + Bob')
print('Alice' + 'Bob')
print('Alice + 5 using str')
print('Alice' + str('5'))
print('Alice * 5')
print('Alice' * 5)
|
a83ca2f770ff723b1791a35f10d372c9c9c6a7cf | zhangxl97/leetcode | /1_100/Q_11_20.py | 12,297 | 3.703125 | 4 | from typing import List
def connect_nodes(nums):
if nums != []:
head = ListNode()
p = head
for n in nums:
p.next = ListNode(n)
p = p.next
return head.next
else:
return None
def print_nodes(head):
# if head is not None:
# print(head.... |
e1799f60ff803a226c7e8976de5d500589332b1c | pigate/py_graph_ex | /graph.py | 11,552 | 4.21875 | 4 | """Python graph class, demonstrating
essential facts and functionalities of graphs
"""
class Graph(object):
def __init__(self, graph_dict={}):
"""initializes a graph object """
self.__graph_dict = graph_dict
def vertices(self):
"""returns vertices of a graph"""
return self.__graph_dict.keys()
d... |
9c703fd4b62e8edc365623ee1967131385c092c9 | weepwood/CodeBase | /Python/UseCase/字符串的格式化.py | 293 | 3.921875 | 4 | name = "Halo"
age = 18
print("Hi, I'm %s. I'm %d" % (name, age))
print("Hi, I'm {}. I'm {}" .format(name, age))
# 括号更换对应索引
print("Hi, I'm {0}. I'm {0}. I'm {1}." .format(name, age))
# 3.6 版本 f-string 括号内可以替换为表达式
print(f"Hi, I'm {name}. I'm {age+1}")
|
7eaf8fe30cc748b7a787022cee4531dbd25ee320 | binchen15/leet-python | /tree/trie/prob677.py | 1,814 | 3.796875 | 4 | # 677 Map Sum pairs using trie
class MapSum(object):
class Node(object):
def __init__(self):
self.children = {}
self.val = 0
#self.isLeaf = False
def __init__(self):
"""
Initialize your data structure here.
"""
self.root ... |
73766357be4db9a68cfedb7f19c76508b922c3e5 | seven320/AtCoder | /49/C.py | 711 | 3.546875 | 4 | # encoding:utf-8
import copy
import random
import bisect #bisect_left これで二部探索の大小検索が行える
import fractions #最小公倍数などはこっち
import math
import sys
mod = 10**9+7
sys.setrecursionlimit(mod) # 再帰回数上限はでdefault1000
S = str(input())
S = list(S)
S.reverse()
S = "".join(S)
def check(T):
if len(S) == 0:
return 1
add... |
e13b6c6053309e260dad25417825735c6bd9e542 | ICS3U-Programming-Layla-M/Unit4-03-Python | /power_of_two.py | 1,054 | 4.46875 | 4 | #!/usr/bin/env python3
# Created by: Layla Michel
# Created on: May 25, 2021
# This program asks the user to input a number and then
# displays the square of all numbers from 0 to that number
def main():
# ask the user to input a whole number
number_as_string = input("Enter a whole number: ")
try:
... |
af6c26ec432482878ef4443dfdfbed6103b08b1c | VeroWrede/CodingDojo | /assignments/python/hw3.py | 192 | 3.609375 | 4 | # for num in range(1000):
# if num % 2 == 1:
# print(num)
# print([num for num in range(1000000) if num%5 == 0])
a = [1, 2, 5, 10, 255, 3]
print(sum(list(a)))
print(sum(list(a))/len(a)) |
5bf2db322b4ec416c72b79ac27717c0c1baf6bc0 | Rhysoshea/Algos | /Algorithmic_Toolbox/week2_algorithmic_warmup/test.py | 98 | 4.03125 | 4 | #python3
string = 'hydrogen'
for index, letter in enumerate(string):
print ((letter, index))
|
7a77be05d0b0a9d073e7650283e38f205115e9cf | Abhijith-1997/pythonprojects | /flow controls/flow12.py | 497 | 4.1875 | 4 | num1=int(input("enter the number"))
num2=int(input("enter ur number"))
num3=int(input("enter the number"))
if(num1>num2)&(num1>num3):
if(num2>num3):
print("largest number",num2)
else:
print("largest number",num3)
elif(num2>num1)&(num2>num3):
if(num1>num3):
print("largest number",num1)
... |
1d44989e8088c6e8d46ec43fae48cf515b4b5940 | gglee89/machine-learning | /HW5-Algorithm/divide_and_conquer.py | 734 | 3.8125 | 4 | def Merge(B, C, A):
i = j = k = 0
p = len(B)
q = len(C)
while i < p and j < q:
if B[i] <= C[j]:
A[k] = B[i]
i = i + 1
else:
A[k] = C[j]
j = j + 1
k = k + 1
if i == p:
A[k:p+q] = C[j:q]
else:
A[k:p+q] = B[i... |
53e70027da58bcc838029e6db73146dedcd78521 | mayaragualberto/URIOnlineJudge | /Python/1159.py | 296 | 3.84375 | 4 | while 1:
soma=0
X=int(input())
if X==0:
break
if X%2==0:
for i in range(5):
soma=soma+X
X+=2
print(soma)
elif X%2!=0:
X+=1
for i in range(5):
soma=soma+X
X+=2
print(soma)
|
8f1059fdf4865428abfa315fcee8f0515713b8dc | danielcr10/python2 | /pandas9/templatecorredores.py | 703 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
DataFrame Corredores
"""
import pandas as pd
import matplotlib.pyplot as plt
dfCorredores = pd.read_excel('corredores.xlsx',index_col=0,header =0,decimal ='.')
print('\n1- DataFrame dfCorredores')
print('\n2-index renomeado para num')
print('\n3- Nome do(s) vencedor(es)... |
0e36f804a926299bd4473740e355acd038b1db4e | SoMuchCode/multizip | /multizip.py | 3,122 | 3.703125 | 4 | #!/usr/bin/env python
#
# multizip.py
# version 0.3
# perform zip operations on multiple files and/or multiple folders.
# Python 3.6
# CLM 20170117
#
# USAGE: multizip.py /path/to/files/you/want/to/compress/ /optional/output/dir/
# By default output files will be created in directory where multizip is invoked.
try:
... |
a505e862f0fa98d859186a77fce840a55fed9e64 | hunthunt2010/compilers | /ToolChainDemo/PLYDemo.py | 1,683 | 3.671875 | 4 | #Basic Grammar for the demo language
#START -> S $
#SEN -> PVQ ADJECTIVE NOUN
# | PVQ NOUN
#PVQ -> PRONOUN VERB QUANTITY
#List Of possible tokens
tokens = (
'PRONOUN',
'VERB',
'QUANTITY',
'ADJECTIVE',
'NOUN',
)
#RegEx for the tokens
t_PRONOUN = r'(I|we|she|he)'
t_VERB ... |
70ef5c43bf3a1dbfe79cf265ee17b1a92ce11a7d | LorenzoVaralo/ExerciciosCursoEmVideo | /Mundo 2/Ex059.py | 1,262 | 4.0625 | 4 | #Crie um programa que leia dois valores e mostre um menu na tela:
# [ 1 ] Somar
# [ 2 ] Multiplicar
# [ 3 ] Maior
# [ 4 ] Novos numeros
# [ 5 ] Sair do programa
#Seu programa deverá realizar a operação solicitada em cada caso.
menu = 4
enfeite = '-=' * 20
while menu != 5:
if menu == 4:
n1 = int(i... |
3cdc953ef442ccc3ee2ce7dc410f8e602730ac4a | markku63/mooc-tira-s20 | /Viikko_6/subtrees.py | 870 | 4.09375 | 4 | from collections import namedtuple
def count(node):
if not node:
return 0
elif not node.left and not node.right:
return 1
else:
return 1 + count(node.left) + count(node.right)
def diff(node):
if not (node and (node.left or node.right)):
# Tyhjä solmu tai lehti
r... |
94a550e7cba888a65d250ce203c51295f53d3f3d | orionwills/python-exercises | /4.3_control_structures_exercises.py | 10,047 | 4.40625 | 4 | # prompt the user for a day of the week, print out whether the day is Monday or not
day_chosen = input('Choose a day of the week: ')
if day_chosen == 'Monday':
print(day_chosen)
# 2. prompt the user for a day of the week, print out whether the day is a weekday or a weekend
day_chosen = input('Choose a day of the... |
3249ab22180267b47eef216486990b187e47efda | abhijitsahu/python | /project-02/forms.py | 2,166 | 3.609375 | 4 | """
pip install flask - WTF for WT forms
writing Python classes that will be representative of our forms
And then they will automatically be converted in the HTML forms within our
template
"""
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, PasswordField, SubmitField
from wtforms.validato... |
390add4ba278696cfa27726885e35104eac56f1a | beentaken/sgt | /misc/puzzles/takecard.py | 2,441 | 3.8125 | 4 | #!/usr/bin/env python
# Posted on rec.puzzles early in the morning of 2006-10-08:
#
# 1000 cards numbered 1 to 1000 are shuffled.
# One card at a time is dealt.
# You can take or leave each card as it is dealt.
# After you have taken your first card, you can only take a card if it is
# higher than the last one you too... |
29752f8274d1c7ab48c9c3db01398fb83fe56ee2 | aneesh786/Machine-Learning | /Albania suicide analysis - machine learning.py | 2,969 | 3.59375 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
#####input file######
df = pd.read_csv('C:\Aneesh\Kaggle\suicide-rates-overview-1985-to-2016\master.csv')
#####Input File for Albania Only#######
Albania = df[df.country == 'Albania']
###Remove the column 'HDI for yea... |
7544394599205d8177e3913faef9e679952f121f | lotabout/leetcode-solutions | /240-search-a-2d-matrix-ii.py | 1,323 | 3.6875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# https://leetcode.com/problems/search-a-2d-matrix-ii/description/
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix:
... |
a1ead97cf9eb5fbf75556d2759bff6f02168e05b | han8909227/data-structures | /src/binheap.py | 1,788 | 4.03125 | 4 | """Binheap data structure."""
class Binheap(object):
"""Binheap class for min heap."""
def __init__(self, iterable=None):
"""Will init a new instance of the min heap."""
self.size = 0
self.list = [None]
def push(self, data):
"""Will push a value into the Binheap class."""... |
e420bf626f0933266134afdff89da5e519f4e096 | MrHamdulay/csc3-capstone | /examples/data/Assignment_5/thmjad002/question4.py | 662 | 3.828125 | 4 | """Assignment 5, Question 4
Jadon Thomson
2014-04-14"""
import math
def graph_f():
function = input("Enter a function f(x):\n")
for y in range (10,-11,-1):
for x in range (-10,11):
function_value = eval(function)
function_value = round(function_value)
... |
56e9249a8ba83e40fd0277f98b0fba0c3b5d6c95 | DudeNr33/zerosegWeatherClock | /src/zerosegWeatherClock.py | 3,714 | 3.5 | 4 | """
07.11.2016
Andreas Finkler
Main module to run the raspiClock.
"""
# change this later
import sys
sys.path.append('/home/pi/programming/raspiClock')
import threading
import time
from datetime import datetime
import RPi.GPIO as GPIO
from src.weather import Weather
from src.display import Display
DEFAULT_UPDATE_IN... |
6f6cf2268bbdf4f1fa542112a910bd2c5d746966 | nathancmoore/code-katas | /digital_root/test_root.py | 1,026 | 3.546875 | 4 | """Test the functionality of digital_root."""
import pytest
from root import digital_root
def test_basic():
"""Basic unit tests provided by codewars."""
assert digital_root(16) == 7
assert digital_root(195) == 6
assert digital_root(992) == 2
assert digital_root(999999999999) == 9
assert digi... |
79d283652ae4bc3572785c9b820edd1ff908dab2 | i-m-alok/Project1 | /Problem1/problem_1.py | 6,387 | 3.796875 | 4 | #used the doubly linked list so the put operation can be easy for us.
class Node:
def __init__(self, key, value):
self.key=key
self.value=value
self.next=None
self.prev=None
#doublylinkedlist class I defined only those methods which are needed for LRU_Cache
class DoublyLinkedList:
... |
a2d59a496987f1b88679eebdcd77e7a414cb6ad7 | AkhtemWays/Algorithms-and-data-structures-coursera-specialization | /Algorithms on graphs/dijkstra.py | 2,378 | 3.90625 | 4 | #Uses python3
# Problem Description: Task: Given an directed graph with positive edge weights and with n vertices and m edges as well as two
# vertices u and v, compute the weight of a shortest path between u and v (that is, the minimum total weight of a path from u to v).
# Input Format: A graph is given in the standa... |
a3b26b9bab8f0b7002b47b3188b80a4945673f25 | kmarguerite/hello-pluto | /hw10.py | 3,651 | 4.125 | 4 | #!usr/bin/env Python 3
"""
Hangman Game!
This script will play a game of hangman against the computer!
To run this script from the commandline type
python hw10.py
Assumptions:
Everyone loves Harry Potter
Requirements:
Anaconda Python3
random
"""
from random import randint
# create a hangman class, use set_up an... |
875de887f7d109da692602f3879d5bfbf648c6df | DriveCurrent/hiring-challenge | /db.py | 1,933 | 3.75 | 4 | from datetime import timedelta
from random import sample, randint
class DataBase(object):
"""
Object emulating a database of metrics stored by dates_in_range
Example
-------
>>> from datetime import date
>>> db = DataBase()
>>> db.get_data('unique_visitors', date(2015, 1, 1), date(2015, 1... |
dc623905b96af67acf4ff21e0b324b0415cb10f6 | renruoxu/algorithms | /leetcode/trees/226_invert_binary_tree.py | 440 | 3.59375 | 4 | # https://leetcode.com/problems/invert-binary-tree/description/
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
self.helper(root)
return root
def helper(self, root):
if root == None:
return Non... |
93d9af7e28ee95d6c014c07ae689e8e15ca212ef | sersajar/interactive-python-rice | /fullCircle_examples/recipes.py | 1,474 | 3.625 | 4 | # crating a simple database
import apsw
# Opening/creating database
connection = apsw.Connection("cookbook1.db3")
cursor = connection.cursor()
sql = 'DROP TABLE IF EXISTS Recipes'
cursor.execute(sql)
sql = 'DROP TABLE IF EXISTS Instructions'
cursor.execute(sql)
sql = 'DROP TABLE IF EXISTS Ingredients'
cursor.execute(... |
8a15304e4d2cb1ee3998620e92c2a50a23ed5e60 | Kasiviswanathan3876/Indian-City-Name-Generator | /citynamespredictor.py | 1,826 | 3.515625 | 4 | from __future__ import print_function, division, absolute_import
import tflearn
from tflearn.data_utils import *
path = "indiancitynames.txt"
#Fixing maximum length of city names to be generated
maxlen = 20
X, Y, char_idx = \
textfile_to_semi_redundant_sequences(path, seq_maxlen=maxlen, redun_step=3)
#LSTM RNN... |
f486c90af037d83b199be96403f3e2d969ba392a | obviouslyghosts/dailychallenges | /ProjectEuler/046/pe-046.py | 1,131 | 3.96875 | 4 | """
It was proposed by Christian Goldbach that every odd composite number can be
written as the sum of a prime and twice a square.
9 = 7 + 2×1**2
15 = 7 + 2×2**2
21 = 3 + 2×3**2
25 = 7 + 2×3**2
27 = 19 + 2×2**2
33 = 31 + 2×1**2
It turns out that the conjecture was false.
What is the smallest odd composite that canno... |
2bef6fe4b671d9e71014980418e1e507043adba8 | Hariharasudhaan/Python_programs | /commonElements.py | 843 | 4.28125 | 4 | n1=int(input("Enter Size of an array 1:")) #getting Size of an Array 1
a1=[]
for i in range(0,n1,1): #Loop for getting Array 1
z1=int(input("Enter the element:"))
a1.append(z1)
n2=int(input("Enter Size of an array 2:")) #getting Size of an Array 2
a2=[]
for i i... |
8d362931f7633d9194e510bacf4d10f336ffb205 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2757/60727/317490.py | 202 | 3.8125 | 4 | a=input()
b=input()
if a=='5' and b=='1 2':
print (6)
elif a=='8' and b=='1 2':
print(18)
elif a=='7' and b=='1 2':
print(12)
elif a=='10' and b=='1 2':
print(36)
else:
print(3) |
7cb461bd557870d81dab5df113db66e74e3ecd1d | Cris-Morales/6.0001-Introduction-to-Computer-Science-and-Programming-in-Python- | /ps0.py | 226 | 4.03125 | 4 | """
Created Saturday March 28, 2020
@author: Cris Morales
"""
#problem set assignment
import math
x = int(input("Enter number x: "))
y = int(input("Enter number y: "))
print("x**y = ", x**y)
print("log(x) = ", int(math.log2(x))) |
7df06dd6db5d7b1049308988cdffe15cf45bc717 | cdavis4/CS_325 | /HW1/mergeTime.py | 1,533 | 3.90625 | 4 | import time,random
"""
Function random creates random values in array
input # of values desired, low range value and highest in range value
outputs array
"""
n = [100, 250, 500, 1000, 2500, 3000, 5000, 10000, 15000, 20000]
def randomArray(size,low,high):
randArray = []
i = 0
while i < size:
randN... |
9f9e704cd13e3aad01f816e8348872f04bba7489 | codeSmith12/PCAP-Training | /queue2.py | 854 | 3.703125 | 4 | class QueueError(IndexError): # Choose base class for the new exception.
def __init__(self):
IndexError.__init__(self)
class Queue:
def __init__(self):
self.list = []
def put(self, elem):
self.list = str(elem).split() + self.list
def get(self):
if len(self.list) <=0:... |
bc98dfeaf4bd2ff09119e6e8755a0d46760c1f83 | iamrishap/PythonBits | /InterviewBits/dp/word-break-1.py | 2,598 | 3.890625 | 4 | """
Given a string A and a dictionary of words B, determine if A can be segmented into a
space-separated sequence of one or more dictionary words.
Input Format:
The first argument is a string, A.
The second argument is an array of strings, B.
Output Format:
Return 0 / 1 ( 0 for false, 1 for true ) for this problem.
Con... |
d7a390f7940c4568b92c589308f50a59e96b7498 | karthikdandavathi/PythonPrograms | /InterviewPractice/FibonacciNumbers.py | 266 | 4.1875 | 4 | """"
Fibonacci numbers are numbers that are
1,1,2,3,5,8
i.e., if f(n) = f(n-1)+f(n-2) for n>2
"""
def run_main():
print(F(6))
def F(n):
if n == 0: return 0
elif n == 1: return 1
else: return F(n-1)+F(n-2)
if __name__ == "__main__":
run_main() |
80f48475a2442ba8abeb3f4626cfb023f3ea3b76 | headlulu888/python_l | /lesson1/hw5.py | 215 | 3.671875 | 4 | first_num = int(input('Введите первое число: \n'))
second_num = int(input('Введите второе число: \n'))
i = first_num - 1
while i <= second_num:
if i % 5 == 0:
print(i)
i += 1 |
e670cc67618cdcc82eca812782ee7455b7e782ef | prasadkhajone99/prime | /print_list.py | 108 | 3.59375 | 4 | l=str(input("Enter data...\n"))
l2=l.split()
l2=l2[::len(l2)-1]
print("first-",l2[0])
print("last-",l2[1])
|
dc8706dbf19d2d83d95f03dd3a495684ccac4cbb | zhiruchen/get_hands_dirty | /ds_application/quick_sort.py | 850 | 3.578125 | 4 | # encoding: utf-8
def quick_sort(alist):
do_sort(alist, 0, len(alist)-1)
def do_sort(alist, first, last):
if first < last:
_pos = partition(alist, first, last)
do_sort(alist, first, _pos-1)
do_sort(alist, _pos+1, last)
def partition(alist, first, last):
pivot_value = alist[firs... |
14862f3b6a347cb6ec86328448f4b815fd4a5a99 | Calendis/Moderately-Seafaring | /lib/Stat.py | 2,196 | 3.828125 | 4 | #Classes for stats
class Stat(object):
"""docstring for Stat"""
def __init__(self):
super(Stat, self).__init__()
self.name = "Default stat"
self.short_name = "STAT"
self.value = 0
self.temp_modifier = 0
def get_name(self, short=True):
if short:
return self.short_name
return self.name
def get_val... |
2d8e8f6abcab03351f087a55caf36e9476215951 | amithca/code | /MTech/Sem2/Lab/DSC523/Assignment2/Assignment2_Q1.py | 245 | 3.765625 | 4 | def minor_matrix(m, i, j):
# calculate the minor of the matrix (MM)
return [row[:j] + row[j+1:] for row in (m[:i]+m[i+1:])]
mtx_A = [[10, 20, 30], [40, 50, 60], [70, 80, 90]]
m1 = minor_matrix(mtx_A, 0, 1)
print(f'Matrix minor is:{m1}')
|
ab3810b536cbc9fb28290ef78d8017713331d2da | komalsorte/LeetCode | /Amazon/Array and String/3_LongestSubstringWithoutRepeatingCharacters.py | 903 | 3.8125 | 4 | __author__ = 'Komal Atul Sorte'
"""
Given a string, find the length of the longest substring without repeating characters.
"""
class Solution:
def longestSubstring(self, s):
if s == " ":
return 1
ele_list = list()
max = 0
res = ""
index, start = 0, 0
whi... |
6a26efaa39d1c3f4233f293c11c54f83868e01f7 | prernakaul22/Airbnb-Price-Analysis | /Project_Part3/PredictAL.py | 1,533 | 3.875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 6 22:15:42 2018
@author: katezeng
This module is for Predictive Analysis - Hypothesis Testing
- This component contains both the traditional statistical hypothesis testing, and the beginning of machine learning predictive analytics.
Her... |
76383345a67e47ec1600cdf200c8dda131817cc3 | VisualAcademy/PythonNote | /PythonNote/99_Etc/min_value_python.py | 520 | 3.890625 | 4 | def find_min(data, n):
min_value = float('inf') # 최솟값을 무한대로 초기화
for i in range(n):
if data[i] < min_value:
min_value = data[i] # 작은 데이터로 재 초기화
return min_value
def main():
# [1] Init
# [2] Input
data = [-10, -30, -20, -5, -15]
n = len(data)
# [3] Process: 최솟값만... |
2fa6ed04513777a98662ab6b043f6d33406a143c | leehour/ProgramProblem | /剑指offer/重建二叉树.py | 1,382 | 3.609375 | 4 | # -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin):
# write code here
if not pre or not tin or len(pre) != len(tin):
r... |
7237dcc130d0507a434c42ee3d9ea46c0a13e0fc | pombredanne/scratch-1 | /misc/chacha.py | 4,730 | 3.640625 | 4 | """
The ChaCha stream cipher
This module exports a single generator function: chacha. Given a key and
IV, it returns a generator iterator that produces the keystream a byte
at at time.
import chacha
key = b'It is Arthur King of the Britons'
iv = bytes(chacha.IVSIZE)
gen = chacha.chacha(key, iv)
[n... |
df402ade473194711a86d95dbbe43e5aee8584be | anttinevalainen/automating-GIS | /Final assignment/Visualizer.py | 14,384 | 3.5 | 4 | def Visualizer(YKR_ID, travelmode, traveltype, maptype, output_folder):
import geopandas as gpd
import os
from FileFinder import FileFinder
from TableJoiner import TableJoiner
import mapclassify
import matplotlib.pyplot as plt
import folium
'''Visualizes the travel times of a single YKR_... |
7d8125cc390c30bbe7d3c25e22b3c487991d81f4 | tuanmeo/python_toolbox_1 | /PYTHON/3_python_data_science_toolbox(1)/chap1_ownfunction.py | 5,649 | 3.734375 | 4 | #%%
# create a dictionary of lang and numbers of given langs
import pandas as pd
df = pd.read_csv('tweets.csv')
lang_count = {}
col = df['lang']
#iterate over lang column in DataFrame
for index in col:
#if lang is in lang_count, add 1:
if index in lang_count.keys():
lang_count[index] = lang_count[inde... |
1229cccc15469f1280791688069834a4e586bb61 | jnjnslab/python-sample | /10_file/readlines.py | 239 | 3.5 | 4 | #ファイルをオープンする
f = open('hello.txt', 'r', encoding='UTF-8')
#1行ごとのリストとして読み込む
datalist = f.readlines()
for data in datalist:
print(data,end='')
#ファイルをクローズする
f.close() |
79fb27bb506698b251535a2ba484723c14067665 | li-MacBook-Pro/li | /static/Mac/play/调用/数组中逆序对/nan.py | 7,377 | 3.546875 | 4 | from typing import List
class Solution:
def reversePairs(self, nums: List[int]) -> int:
size = len(nums)
if size < 2:
return 0
res = 0
for i in range(0, size - 1):
for j in range(i + 1, size):
if nums[i] > nums[j]:
res += 1
... |
a9a46f426e46cf080260fba1239b6031d090f23b | teacupwoozy/LPTHW | /ex5.py | 704 | 4 | 4 | name = 'Stacy Em'
age = 104 # not a lie
height = 99 # inches
weight = 407 # lbs
eyes = 'Purple'
teeth = 'White'
hair = 'Brown'
height_in_cm = height * 2.54
weight_in_kg = weight * 0.45359237
print(f"Let's talk about {name}.")
print(f"She's {height} inches tall.")
print(f"She's {weight} pounds heavy.")
print("Actually... |
48cc4217f70024e4cd78893e4879b3991b667716 | spectator05/KOSS | /week2/eratos.py | 282 | 3.640625 | 4 | import math
n = int(input("숫자를 입력하세요: "))
lst = [i for i in range(n + 1)]
lst[0] = 0
lst[1] = 0
for i in range(2, int(math.sqrt(n) + 1)):
for j in range(i * 2, n + 1, i):
lst[j] = 0
for i in range(len(lst)):
if lst[i] != 0:
print(lst[i])
|
41739cac22f1f9a052f4fda3b698a735a919993b | Tekorita/Cursopython | /clases/metodosestaticos.py | 606 | 3.875 | 4 | class Circulo:
#los metodos estaticos son aquellas funciones dentro de una clase que no contienen la palabra reservada self
#y para que sean estaticos se tienen que decorar
#los metodos estaticos son metodos que le pertenecen directamente a la clase y no a la instancia
@staticmethod
def pi():
return 3.1416
... |
b3d85a09d974e5e11dd53a783741a53b63d879d9 | AlexClowes/advent_of_code | /2019/22/small_shuffle.py | 554 | 3.5625 | 4 | def shuffle(instructions, card, deck_len):
for instr in instructions:
if instr == "deal into new stack":
card = -card - 1
elif instr.split()[0] == "cut":
card -= int(instr.split()[-1])
elif instr.split()[0] == "deal":
card *= int(instr.split()[-1])
... |
276ed1e63d8e5ea6c3db6a27669957331a6ba4d1 | ml758392/python_tedu | /python100例/Python100Cases-master/100examples/017.py | 330 | 3.828125 | 4 | string=input("输入字符串:")
alp=0
num=0
spa=0
oth=0
for i in range(len(string)):
if string[i].isspace():
spa+=1
elif string[i].isdigit():
num+=1
elif string[i].isalpha():
alp+=1
else:
oth+=1
print('space: ',spa)
print('digit: ',num)
print('alpha: ',alp)
print('other: ',oth)
|
28cad05248d1a5375bb37e4caf420889c640a6a9 | mbuhot/mbuhot-euler-solutions | /python/problem-023.py | 1,673 | 4.1875 | 4 | #! /usr/bin/env python3
import itertools
import factorization
description = """
Non-abundant sums
Problem 23
A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is ... |
163c809d1ddc4f55656c82e542730cd5587aec4c | HetDaftary/Competitive-Coding-Solutions | /Hackerrank-Solutions/Hackerrank-30-days-of-code/Day 20: Sorting/test.py | 517 | 4 | 4 | #!/bin/python3
import sys
def bubble_sort(n, a):
nos = 0
for i in range(n):
temp_nos = 0
for j in range(i + 1, n):
if a[i] > a[j]:
a[i], a[j] = a[j], a[i]
temp_nos += 1
nos += temp_nos
if (temp_nos == 0): break
return nos
... |
0441b5749eeb62666ea0cc4c2ae82353c97f0920 | adonaifariasdev/DevPro | /Práticas/Pr01.py | 1,911 | 3.9375 | 4 | # Faça um Programa para uma loja de tintas. O programa deverá pedir
# o tamanho em metros quadrados da área a ser pintada. Considere que
# a cobertura da tinta é de 1 litro para cada 6 metros quadrados e que
# a tinta é vendida em latas de 18 litros, que custam R$ 80,00 ou em
# galões de 3,6 litros, que custam R$ 25,00... |
3b296cfada4deb651d91ebe463dbf6cf47e35de7 | Aasthaengg/IBMdataset | /Python_codes/p03644/s000813566.py | 65 | 3.5 | 4 | n=int(input())
ans=1
while ans<=n:
ans*=2
ans//=2
print(ans)
|
4ed0ea016bfe406871e93d8ae52cbc81ef77fdd0 | TongMingLive/pytest | /study/魔法方法/描述符/Temperature.py | 1,203 | 4.34375 | 4 | # 练习要求:
# 1、先定义一个温度类,然后定义两个描述符类用于描述摄氏度和华氏度两个属性
# 2、要求两个属性会自动进行转换,也就是说你可以给摄氏度这个属性赋值,然后打印的华氏度属性是自动转换后的结果
class Celsius:
def __init__(self, value=25.0):
self.value = float(value)
def __get__(self, instance, owner):
return self.value
def __set__(self, instance, value):
self.value = fl... |
b21fa279100b3d822009907f76a253fd5aaebc1c | shivambatsgit/ParkingSystemPython | /system.py | 2,162 | 3.703125 | 4 | """
System module to manage the vehicles coming in and out of an entry-exit point
"""
from big_car import BigCar
from models.entry_exit import EntryExit
from models.floor import Floor
from data_init import parking_lot_obj as parking_lot
from small_car import SmallCar
from uuid import uuid4
class System:
def __in... |
e04c66850ec094d41cd3f99110c24ce9fbfad55d | hnnguyen45thinkful/Pirple-Coursework | /Python/loops2.py | 1,411 | 4.5625 | 5 | '''
Python Homework Assignment #6
Advanced Loops
By: Hieu Nguyen
'''
# Details:
# Create a function that takes in two parameters: rows, and columns, both of which are integers. The function should then proceed to draw a playing board (as in the examples from the lectures) the same number of rows and columns as spec... |
2b0f9bb6db1eabaa67ec31922eee69cf4d3b3673 | sektor23/AndreyP | /dz_3.1.py | 233 | 3.859375 | 4 | percent = int(input())
if percent == 1:
print(percent, 'процент')
elif percent > 1 and percent <= 4:
print(percent, 'процента')
else:
percent >= 5 and percent <= 20
print(percent, 'процентов')
|
e8b537c3b6092efa6870cd240b78dd63c831866f | AntonioCenteno/Miscelanea_002_Python | /Certámenes resueltos/Certamen 1 2014-1/pregunta-2.py | 1,618 | 3.921875 | 4 | #Primero, debemos pedir el ao en curso.
anio_actual = int(raw_input("Ingrese anio en curso: "))
#Ahora vamos pidiendo los codigos hasta que el usuario ingrese "fin"
cod = raw_input("Ingrese un codigo: ")
while cod != "fin":
#Desarmamos el codigo
anio_ingreso = int(cod[:4])
carrera = int(cod[4:7])
ranki... |
0e350cc2d0d43df757bb714368bd6a2e2b9db26a | AlEkramHossainAbir/Python1 | /reminder of two numbers.py | 172 | 3.90625 | 4 | #program name: reminder of two numbers
#author name: Al- Ekram hossain Abir
#a program to find reminder
a=int(input())
b=int(input())
c=a%b
print("reminder of two number is: ",c)
|
9d4a1224b4a4d98a822bcf9883243e9a01e6dfee | naoyasu/lrnpython | /test64_1.py | 118 | 3.75 | 4 | # http://tinyurl.com/jcg5qwp
a = input("type a number:")
b = input("tepe another:")
a = int(a)
b = int(b)
print(a/b)
|
d471f402cff83bf6c10a2dd2ed8cf0fc770b7359 | da-ferreira/algorithms | /Estruturas de Dados/minimo_stack.py | 1,464 | 4 | 4 | """
Implementação de Mínimo Stack
autor: David Ferreira de Almeida
O objeto do algoritmo é modificar a estrutura de dados
stack (pilha) de modo que o menor elemento possa ser acessado
em O(1). O elementos são adicionados em pares: o elemento
e o menor elemento da pilha.
"""
class Stack:
def __init__(se... |
08fa090859750f430dd97af978e42167760aff0b | AmandaCarvalhoo/BLASTOFF | /00 - Enunciados.py | 1,908 | 3.75 | 4 | """"
Teste de lógica BLASTOFF ------
FOI FEITO TODO EM LINGUAGEM PYTHON
OBS: Todas as questões foram respondidas exceto: QUESTÃO 13. Pois ainda não estudei matrizes.
Todas os arquivos que terminam com .._C significa que estão completos/resolvidos
#(feito)1- Dada as idades I, J, K, X, Y. Faça um algoritmo para ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.