blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
8cce9d3ce2042d73b3d771dfbf109e216ef36677 | ongsuwannoo/PSIT-61 | /Week 13/CaesarV2.py | 532 | 3.828125 | 4 | """CaesarV2"""
def check(num, text):
"""Check True Sentence in this function"""
result = ""
for i in text:
if i.isalpha():
ordi = 65 if i.isupper() else 97
i = chr((ord(i) - ordi + num) % 26 + ordi)
result += i
return result
def main(text):
"""Print True Sent... |
ddeab942816bff0a476fe0f872ecee3cdc21352e | ongsuwannoo/PSIT-61 | /Week 15/OneTwo.py | 169 | 3.625 | 4 | """OneTwo"""
def main(num):
"""Sn"""
lis = ['1', '2']
for i in range(2, num):
lis.append(lis[i-1]+lis[i-2])
print(lis[num-1])
main(int(input()))
|
00d87657a20978010cb84c790fe9b7127edc8f03 | ongsuwannoo/PSIT-61 | /Week 07/Hamburger.py | 158 | 3.78125 | 4 | """ Hamburger """
def main():
""" hammmmm """
num = int(input())
num1 = int(input())
print(('|'*num)+('*'*((num+num1)*2))+('|'*num1))
main()
|
803aa2044f18114b72acaa66d0412cdcb61a3d48 | Arsenault-CMSC201-Fall2019/Spring_2020_code_samples | /February_17_coding.py | 985 | 4.28125 | 4 | # Examples of code using while loops
# from Monday, Feb. 17
age = 0;
while (age < 18):
age = input("enter your age in years: ")
print ("If you’re 18 or older you should vote")
print ("that's the end of our story")
# compute 10! Using a while loop
product = 1
factor = 1
while factor <= 10:
product *= factor #or ... |
e7f171ee421609f0c28813cb89cb8869ca9510fe | Arsenault-CMSC201-Fall2019/Spring_2020_code_samples | /February_5_code.py | 408 | 4.1875 | 4 | ######################
#
# This is one way to write a block
# of comments
#
########################
"""
This is another way to write a block
of comments
"""
'''
This will work too
'''
verb = input("please enter a verb")
new_verb = verb + "ing"
print(new_verb)
principal = 10000
rate = 0.03/12
n_payments = 72
cost ... |
864d5005fbc7a132a7ee970d006bbf40503496e6 | Arsenault-CMSC201-Fall2019/Spring_2020_code_samples | /February_19_coding.py | 1,230 | 4.125 | 4 | #coding for Wednesday, February 19
# Printing new lines, or not
print("this produces two lines", "\n", "of output")
print("this produces one line", end="")
print("of output")
# printing out an integer
print("{:d} is the answer to the question".format(42))
#printing the same value as a float
print("{:f} is the answe... |
741e9ff4eae41db8725dadbdc7a966e4ea0fc533 | dabuu/FluentPython | /chap1/1.1.py | 1,514 | 3.875 | 4 | # coding:utf-8
"""
@file: 1.1.py
@time: 8/7/2018 11:50 PM
@contact: dabuwang
"""
import collections
from random import choice
Card = collections.namedtuple('Card', ['rank', 'suit'])
class FrenchDeck:
ranks = [str(n) for n in range(2, 11)] + list("JQKA")
suits = "spades hearts diamonds clubs".split()
de... |
7ad77a3e96164597296ccd08dc2e404e40e7a0e1 | jkgmr13/Leet | /palindrome number/palindrome_number.py | 241 | 3.546875 | 4 | class Solution:
def isPalindrome(self, x: int) -> bool:
if(x < 0): return False
else:
s = str(x)
for i in range(len(s)//2+1):
if(s[i]!=s[-i-1]): return False
return True |
a97621fbe263000dfc23931991c77850e559b56c | cztchoice/testrepo | /python_test/argparse_advance.py | 1,011 | 3.59375 | 4 | import argparse
parser = argparse.ArgumentParser(description="calculate X to the power of Y")
#parser.add_argument("echo", help="echo the string you use here")
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")
#parser.add_argument("-v", "--verbosity", action="c... |
17330908081718704a0b8ee7b59e228040dfcac3 | daniloams/Python | /desafio002.py | 214 | 3.78125 | 4 | nome = input('Oi, qual é o seu nome?')
dia = input('Qual o dia que você nasceu?')
mes = input('QUal foi o mês?')
ano = input('E de qual ano?')
print('Oi, seu nome é?', nome, 'você nasceu em:', dia, mes, ano)
|
912fce9c099c384cbde0305f7646dfaf8c8473f9 | aaabuabat/Algorithm-Design.github.io | /Maximal Independent Set And Clique.py | 4,333 | 3.71875 | 4 | '''
An algorithm that finds the largest independent-set in a
connected graph and another to find the largest clique in a connected graph.
'''
import copy
import numpy as np
from numpy import concatenate, zeros
from scipy.linalg import toeplitz
Count =0
#================== Maximal Independent Set Function ==========... |
94cd4d739dd171d8a23f6ca34f8ea12bf124053b | DanielSBrown/ScHoolboy-Queue | /app/database.py | 3,287 | 3.921875 | 4 | """
Basic Database Functionality
TODO:
Refactor into an object
Rearrange the queue
"""
from sqlite3 import connect
def connect_to_db():
"""
Wrapper function for db connection
"""
conn = connect('ScHoolboy_Queue.sqlite')
return conn
def disconnect_db(conn):
"""
Wrapper function to... |
4fdb89b4d389fe90da44d4b08345f3aba9382802 | kamurillUC/Asignacion3 | /main.py | 589 | 3.5 | 4 | from mis_funciones import *
#lavar_platos()
#ir_de_compras()
#cenar()
#limpiarConsola()
bandera = 0
respuesta = 0
limpiarConsola()
while bandera == 0:
print(f">< >< >< >< >< >< >< >< >< >< >< >< >< >< >< >< >< >< >< ><\nMenú de opciones:\n1. Lavar los platos\n2. Ir de compras\n3. Cenar\n4. Salir")
respue... |
fac48d71c94fd593abcc362f13b767b5126f1aba | manjiriabhyankar/hello-world | /PycharmProjects/PythonPractice/OddOrEven.py | 249 | 4.09375 | 4 | Num1=int(input("Hey, Enter a number \t"))
if Num1%2!=0:
print("You entered an odd number")
elif Num1==0:
print("That's an exception")
elif Num1%4==0:
print("You entered a number divisble by 4")
else:
print("It was an even number")
|
fb2015cc96c78a5f6a7b0bd40a1c379d4e3820ce | vinall/euler | /power_digit_sum.py | 704 | 3.609375 | 4 | def multiply(begin_num,multiplier):
remainder = 0
result = ""
i = len(begin_num)-1
while i >= 0:
temp = (int(begin_num[i])-int ('0'))*multiplier + remainder
remainder = int(temp/10)
result = str(int(temp%10)) + result
i-=1
if remainder != 0:
result = str(remai... |
a19657f20a709dfd7a42c9a0d36876d26cad4661 | vinall/euler | /fibonacci_2.py | 440 | 4.0625 | 4 |
def sum_even_number_in_fibonacci(num):
first = 1
second = 1
sum = 0
#for i in range(2,num):
while sum < num:
next_num = first + second
first = second
second = next_num
if next_num % 2 == 0:
sum = sum + next_num
print ("sum = " , sum)
return s... |
78cf2ef278f31694523d98147adce37280bea6b6 | willcohen/mit-6.00sc-python | /ps2/ps2_hangman.py | 3,456 | 4.25 | 4 | # 6.00 Problem Set 3
#
# Hangman
#
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
import random
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on ... |
9bddb3e937b19c4b2d413f20e0dd89cb460b5cb4 | sunseawq/auto-wrap-indent | /autowrapper.py | 4,663 | 3.703125 | 4 | #!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
"""Jerod Gawne, 2017-10-05
Text Wrap
https://www.hackerrank.com/challenges/text-wrap/
Editorial:
-This can be solved using the function textwrap.fill().
"""
import textwrap
import string, re
import argparse
import os.path
import sys, getopt
def indent(text, prefix, ... |
51526955fafd45ae104139a3cb4846426a5d0fc5 | marinadunn/ASTR400B_Dunn | /InClass/InClass7/CenterofMass.py | 7,871 | 3.53125 | 4 | # Edited original file on February 4, 2018
#Marina Dunn, Homework 4, ASTR400B
# Center of Mass Position and Velocity
# First, import relevant modules
import numpy as np
import astropy.units as u
from ReadFile import Read
#A class creates a new type of object, and has attributes that characterize it. CenterOfMass is t... |
c601fdf99f4691161aa0b75f8e75ca3cd0f53ab7 | rakshawankhede/AdventOfCode | /2015_day_5.py | 3,203 | 4.15625 | 4 | #!/usr/bin/python
import os
def get_input_file_path():
'''
This function will return path of input file for puzzle.
'''
source_dir = os.path.dirname(__file__)
input_filename = os.path.basename(__file__).replace('.py', '.txt')
return os.path.abspath(os.path.join(source_dir, 'puzzle_inputs', inp... |
52e5ac23137349c5d8a3a54d8ce7500a4a0a3670 | m-jora/Many-Menus | /SQLWrapper.py | 25,536 | 4.0625 | 4 | import sqlite3
from sqlite3 import Error
# Purpose: Connects to an existing database file
# @param db_file: an existing database file to connect to
def create_connection(db_file):
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
return None
... |
6e60a62ffe28e85b960cf5b78ba79594cd06fd69 | setishin/Homework | /Списки_15.py | 1,101 | 3.625 | 4 | print (' - ')
n = int(input()) #-
print (' - ')
n1=int(input()) #-
print (' ')
a = []
for i in range(n):
a.append([int(j) for j in input().split()])
print (' - ')
k = int(input()) #-
print (' - ')
k1=int(input()) #-
print (' ')
b = []
for i in range(k):
b.appen... |
9deaac8d07715f643837b1962a328b6273b34ebb | arizala13/interview_cake | /factorial_code.py | 251 | 3.875 | 4 | def factorial(n):
# a factorial is N!
count = 0
n_going_down = n
answer = 1
while n > count:
answer = answer * n_going_down
count += 1
n_going_down -= 1
print(answer)
return answer
factorial(11)
|
3892ee83ecc247e92abac626cad19c4d8285f715 | arizala13/interview_cake | /hash_map_example.py | 333 | 4.125 | 4 | def return_true_or(s):
count_chars = {}
for char in s:
if char in count_chars:
count_chars[char] += 1
else:
count_chars[char] = 1
print(count_chars)
return_true_or("racecar")
# practice of adding a value to a dictionary
# and keeping track of how many times its... |
1bf25a0621931ae5e1d89e390bf792a05733a86b | adreyer/Tic-Tac-Toe | /tictactoe/board.py | 3,264 | 3.90625 | 4 |
class BadMoveError(Exception):
pass
class Board:
""" a board for playing tictactoe on """
def __init__(self):
self.board = [[0 for j in range(3)] for i in range(3)]
self.next_move = 1
self.moves = []
def move(self,x, y):
""" make a move x,y
raises BadM... |
8947352eb177ff5c448172da4d3cecad55e346f0 | herrera-ignacio/automatetheboringstuff | /sysargv/pwlocker.py | 514 | 3.640625 | 4 | #! python 3
# pwlocker.py - An insecure password locker program
PASSWORDS = {'ignacioromanherrera@gmail.com' : 'testpw',
'testaccount': '1234',
'NASA': 'rocketman'}
import sys, pyperclip
if len(sys.argv) < 2:
print('Usage: python pwlocker.py [account] - copy account password')
sys.ex... |
752cc6c0cb99508534f86ebc25d55cec12dea6a5 | HappyTrigger/sanntid | /exercise/Oving1/exercise1py.py | 1,041 | 3.6875 | 4 |
from threading import Thread
import threading
i = 1
locke = threading.Lock();
def someThreadFunction():
global i
for j in range(0,100000):
locke.acquire()
i = i - 1
locke.release()
# Potentially useful thing:
# In Python you "import" a global variable, instead of "export"ing it when you dec... |
47648e1795c070a1befde14c48560ad1453666a9 | CaMeLCa5e/ListComp | /listcomp10.22.14.2.py | 158 | 3.640625 | 4 | # #listcomp10.22.14.2
string = "HEllO 12345 World"
numbers = [x for x in string if x.isdigit()]
print numbers
def double(q):
return q*2
print double(44)
|
b987f123317a7f8e3feaf6dac464732e13fec601 | Spideyboi21/jash_python_pdxcode | /python learning/test.py | 350 | 4.125 | 4 |
if -4 < -6:
print("True")
else:
print('False')
if "part" in "party!!!1":
print("True")
else:
print("False")
age = input('how old are you?')
if int(age)< 28 and int(age) >=0:
print("this is valid")
else:
print("not valid")
name = input('What is my name? ')
if name == "Jash":
print("that... |
022bddfcc020eb7273a2180a8d391d3fd383ecea | jldupont/jldupont.com | /trunk/Tests/PYTHON/TestClassMethods.py | 521 | 4.15625 | 4 | class X:
def m(cls, p):
print "X: cls=%s , p=%s" % (cls,p)
# required for X.m() to work
m = classmethod(m)
class Y(X):
def m(cls,p):
print "Y: cls=%s , p=%s" % (cls,p)
X.m(p)
# required for X.m() to work
m = classmethod(m)
if (__name__ == "__m... |
afedb63fe6ffa015239cb4a5b1b4e20522107dbc | alexlamouri/kaleidoscope | /kaleidoscope.py | 8,490 | 3.984375 | 4 | import turtle as t
import random
import time
import os
# ---------------------------SHAPE FUNCTIONS-------------------------------------
# Draw Basic Square
def draw_square(side, color):
'''
Draw a basic square with given side and color
PARAMETERS
side: int
color: string
RETURN
... |
51b8be30d0758a5c6d3ed8dd4a8f0fd52934f8d9 | RenanJochem98/a_star_8puzzle | /main.py | 1,564 | 3.578125 | 4 | from Board import Board
from BlindSearch import BlindSearch
from TwoStepsSearch import TwoStepsSearch
from OutOfPositionSearch import OutOfPositionSearch
from Input import Input
import time
print("")
print("#"*30)
print(" "*7+"INICIANDO BUSCA")
print("#"*30)
print("\n")
newInput = Input()
goalBoard = Board('goal')
sc... |
5a16e4db1268107dd5750c778211dd301bf652e6 | dtroupe18/SimpleKNN | /knn.py | 4,432 | 3.703125 | 4 | """
Simple KNN using euclidean distance
"""
import csv
import random
import math
import operator
from scipy.spatial.distance import cosine
def load_dataset(filename, split):
"""
:param filename: name of file to open
:param split: ratio of data to go into the training set
:return: training and test l... |
fec1f46f9f136bd76ff6617808163f9764566a3d | there915/Danube915 | /bmi.py | 1,091 | 3.734375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[178]:
class BMI:
def __init__(self,name,age,tizhong,shengao):
self.name = name
self.age = age
self.tizhong = tizhong
self.shengao = shengao
n = self.tizhong/(self.shengao*self.shengao)
if n<18.5:
d = "偏瘦"
... |
f3ae550e5e1b5661d8c3d24d64768a36074a9fc4 | vivekdarshan/Python | /13_sets.py | 197 | 4.125 | 4 | groceries = 'cereal', 'milk', 'starcrunch', 'beer', 'duct tape', 'lotion', 'beer'
print groceries
if 'milk' in groceries:
print "You already have milk!"
else:
print "Oh ya, you need milk!" |
699cf837d942a8902da18df62b5519fba18f3650 | OConnellErin/CS261_Heap | /max_heap.py | 610 | 3.578125 | 4 | # MaxHeap: A binary 'max' heap.
# Implement as many operations as possible with recursion.
# If you can't figure it out recursively, use a loop. (But then refactor
# your implementation into a recursive one!)
# Your implementation should pass the tests in test_max_heap.py.
# ERIN O'CONNELL
class MaxHeap:
def __... |
32005be7d35cae30be38699252118ed421eeb865 | sebadiaz-arg/dpub | /dpub/utils.py | 234 | 3.5625 | 4 | #!/usr/bin/env python3
#
# Copyright (C) 2020 Telefónica S.A. All Rights Reserved
#
def strip_double_quotes(what):
'''Strips double quotes from a string'''
if not what:
return what
return what.replace('"', '')
|
aebcd608e99f2be4498ab48e1bbe5dfa8b384b90 | mooniverse131/SolutionsVSC | /swbasic/mathematics/2609/2609.py | 225 | 3.796875 | 4 | def gcd(a,b):
while(b !=0):
a, b = b , a % b
return a
def lcm(a, b):
return int((a * b)/ gcd(a,b))
if __name__ == "__main__":
a , b = map(int, input().split())
print(gcd(a,b))
print(lcm(a,b)) |
3063af7d673b9d5f42597f1be6ab8aadcaf5ab65 | Ritvik-Shah/Sujay-Impossible-quiz | /Sujay.py | 2,541 | 3.59375 | 4 | from PIL import Image
import PIL
from docx import Document
import os
img = Image.open('Sujay.jpg')
img_dude = img.resize((100, 100), PIL.Image.ANTIALIAS)
img_dude.save('Meme_Sujay.jpg')
document = Document()
p1 = document.add_paragraph('When you pass the Sujay test, you be like')
paragraph = document.add_p... |
a045975cb8604eed34ae28d0a213083e95312813 | lipaul0703/Algorithm | /binary serch algorithm.py | 467 | 3.890625 | 4 | def binary_search(x, y):
x_low = 0
x_high = len(x) - 1
while x_low <= x_high:
x_mid = (x_low+x_high) // 2
if x[x_mid] == y:
return True, x_mid
elif x[x_mid] < y:
x_low = x_mid+1
elif x[x_mid] > y:
x_high = x_mid-1
else:
... |
82b473b6d4b8ce07c42b92870b91fee3fb5c8da5 | soonebabu/firstPY | /first.py | 318 | 4.21875 | 4 |
def checkPrime(num):
if num==1 or num==2 or prime(num):
return False
else:
return True
def prime(num):
for i in range(3,num-1):
if (num%i)==0:
return True
value = input('enter the value')
print(value)
if checkPrime(value):
print('prime')
else:
print('not')
|
aa5377b9f0a11e32cde4fa8c7ac47ca3bbb9f659 | BigBoiTom/Hangman-Game | /Hangman_Game.py | 2,686 | 4.15625 | 4 | import random, time
def play_again():
answer = input('Would you like to play again? yes/no: ').lower()
if answer == 'y' or answer == 'yes':
play_game()
elif answer == 'n' or answer == 'no':
print("Thanks for Playing!")
time.sleep(2)
exit()
else:
pass
def get_... |
bce57274ec4c1c0bc8511c763d32e481e5ce3dd4 | changmingMeng/ExecelTool | /Sqlite3Diver.py | 2,260 | 3.578125 | 4 | # encoding: utf-8
import sqlite3
# import time
# createtabsql1 = "create table if not exists scriptdata(id integer primary key autoincrement, name varchar(128), info varchar(128))"
class Sqlite3Driver(object):
'''''
The Sqlite3Driver class use to write the script data that parse from Excel file
'''
... |
c88569f9d3bbdc40d8925cee5e5377e8c53079b5 | zhuxinkai/python-by-pyCharm | /a few work/findallexample.py | 661 | 3.921875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#reuslt ['car', 'car', 'car', 'car'], 这与 re.match ,和 re.search 不同,直接返回包含一个值的数组。
import re
print(re.findall('car','this car is a bigcar .and find inn the car house .and carhouse is a buiding'))
# re.I 不区分大小写。
s ='this and that'
print(re.findall(r'(th\w+) and (th\w+)' ,s,re.I)... |
1e9b87bca4f32738e79e1dec5654589374328125 | juancoan/python | /Basic/WtihASDemo.py | 989 | 4.125 | 4 | """
WITH / AS keywords
"""
# print("Normal WRITE start")
# File2 = open("File_IO.txt", "w")
# File2.write("Trying to write to the file2.")
# File2.close() #If I do not write the close() statement, nothing will happen. ALWAYS write it
#
# print("Normal READ start")
# File3 = open("File_IO.txt", "r")
# for line in File... |
5d739fccb487bf269d4939fdfa0b673e463305e3 | juancoan/python | /Basic/Ejercicio.py | 657 | 3.875 | 4 | class Fruit(object):
def __init__(self):
print("This is the instance of Fruit class.")
def Nutrition(self):
print("Taking your fruits. ")
def Fruit_Shape(self):
print("Shape: Round.")
Fr = Fruit()
Fr.Nutrition()
Fr.Fruit_Shape()
class Orange(Fruit):
def __init__(self, Colorsi... |
3a136144b49f4e564b98cd44b97e77cf73866e93 | juancoan/python | /Basic/File2Read.py | 795 | 4.1875 | 4 |
my_file2 = open("File2Read.txt", 'r') #use the 'r' mode to read
print(str(my_file2.read())) #prints the read method, all the content of the file
my_file2.close()
print('#*'*20)
print("LINE BY LINE EXAMPLE......... Will print the first line only, unless I call that print method twice")
my_file_BY_LINE = open("File2Re... |
9a43507486b2ab6798f54e7f6ba80db7fda02b6f | juancoan/python | /Browser_Tests(System Variable 4 WebDriver Path)/Switch_Window_Focus.py | 2,005 | 3.53125 | 4 | from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from selenium import webdriver
class Switch_To_Window():
def Chrome_Method(self):
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://letskodeit.teachable.com/pages/practice")
... |
65c60cd0327f9f6f4566e295d0872ec090874d2e | marcgee1911/api_projects | /api_lbvserver_data_git.py | 1,098 | 3.515625 | 4 | # python script which uses locally stored username and password for authentication.
# The script uses the URL varaible to make an API call and returns the data.
import requests
from requests.auth import HTTPBasicAuth
import json
#functon to pull username from txt file on local machine
def get_username():
f = ope... |
1ae373d339028aa4626c8acc04c4153f77b4994d | franciscofabio/bootcamps | /udemy-python/Desafio/imc.py | 680 | 3.53125 | 4 | # Calculo de IMC - Ímdice de Massa Corporal
altura= float(input('Qual é a sua Altura em cm ?:'))
peso = float(input('Qual é o seu peso em kg ? :'))
IMC = peso / (altura/100)**2
print(IMC)
if IMC < 18.5:
print('Magreza')
elif IMC in float(range(18.5, 24.9)):
print('NORMAL')
elif IMC in float(range(25.0, 29.9... |
98c257ce8060570bec5b376805126b00e5d8adf9 | franciscofabio/bootcamps | /udemy-python/Lista/Concatenando_listas.py | 240 | 4.09375 | 4 | # Listas
# Amazenar mais de uma informação em variáveis
# Mater a sequencia dos dados em uma variável
numeros = [2, 3, 4, 5]
letras = ['a', 'b', 'c', 'd']
itens= [['item1','intem2'],['intem3', 'item4']]
print(itens[1][2])
|
b79df2cea35d75c4f8955c8de99f940869ad8e74 | franciscofabio/bootcamps | /udemy-python/Lista/Manipulacao_lista.py | 434 | 3.953125 | 4 | # Listas
# Amazenar mais de uma informação em variáveis
# Manter a sequencia dos dados em uma variável
cidade1 = 'Rio de Janeiro'
cidade2 = 'São paulo'
cidade3 = 'Salvador'
cidades = ['Fortaleza', 'Natal', 'São Luis', 'Teresina', 'Belém', 'Brasilia', 'Recife']
# 0 1 2 3 ... |
dee99db13f73abe86f4727971726c075cd71054b | j0netzky/basics-exercise-python | /python_exercise_koodikarpat/h3/h3_alkuluku.py | 1,111 | 3.78125 | 4 | def pyyda_syote(syote, virheilmoitus):
"""Kysyy käyttäjältä kokonaislukua käyttäen kysymyksenä parametrina annettua merkkijonoa. Virheellisen syötteen kohdalla käyttäjälle näytetään toisena parametrina annettu virheilmoitus. Käyttäjän antama kelvollinen syöte palautetaan kokonaislukuna. Hyväksyy vain luvut jotka ov... |
ff3a9762a169606803fda1e24a6427935ffdc0e7 | aldousjg/Python_Portfolio | /interactive_hangman_game.py | 1,305 | 3.953125 | 4 | from random import choice
words_list = ["batman", "robin", "joker", "twoface", "riddler", "penguin", "bane", "catwoman"]
word = choice(words_list)
hint = "-" * len(word)
hint_list = list(hint)
lives = 8
guesses = []
print("Let's play HANGMAN! Guess the batman character!")
while lives > 0:
print()
... |
97627ed27dfd0c2f75b0bf70c0d320c79404868e | norkator/pilkki-booster | /objects/game.py | 782 | 3.8125 | 4 | class Game(object):
# Class constructor
def __init__(self, x, y, x2, y2, strategy, state=0):
self.x = x # game window frame
self.y = y # game window frame
self.x2 = x2 # game window frame
self.y2 = y2 # game window frame
self.strategy = strategy # game strategy
... |
339fb07ecb4f50021f9b1b4e7d1c0a60ba7cd824 | jmkstewart/tetris-clone | /box.py | 1,603 | 3.671875 | 4 | import pygame
class Box(pygame.sprite.Sprite):
size = 30
draw_size = 28
relative_min_width = 0
relative_max_width = 12
def __init__(self, initial_position):
# All sprite classes should extend pygame.sprite.Sprite. This
# gives you several important internal methods that you p... |
49ad4028d7580725f91adb1406897fba6933c8ae | karvendhanm/corey_schafer_oops | /init_constructor.py | 803 | 3.640625 | 4 | class MyNum(object):
def __init__(self, value):
try:
val = int(value)
except ValueError:
value = 0
self.val = value
def increment(self):
self.val = self.val + 1
dd = MyNum(6.8)
dd.increment()
dd.increment()
print(dd.val)
dd = MyNum('Hello')
dd.incremen... |
18b276b00d3a5e076596b5c8612bc749f74a6442 | karvendhanm/corey_schafer_oops | /inheriting_the_constructor_1.py | 573 | 3.953125 | 4 | # Enhanced Example
import random
class Animal(object):
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name):
super().__init__(name)
# super(Dog, self).__init__(name) # In this method also we can call the parent class constructor instead of calling ... |
a09f2053bee13080ccd543eeed3f9533d32c41b9 | hansonhqma/CSCI_1100 | /HW6/hw6_part1.py | 3,854 | 3.546875 | 4 | '''
Author - Hanson Ma
hanson.hq.ma@gmail.com
https://www.github.com/hansonhqma
'''
class word: #class word to keep things tidy
def __init__(self, word):
self.word = word
self.likely = ""
self.outcome = ""
self.swappedvariants = set()
self.droppedvariants = set()
de... |
0314aa6dcd5038f0504fe0aa0ee59ba3507f43d2 | hansonhqma/CSCI_1100 | /HW7/drew7.1.py | 3,816 | 3.890625 | 4 | def found(dictionary, word): #start of defining functions
if word in dictionary:
return 0
else:
return 1
def replace(dictionary, word):
replist = set()
j = ''
for i in range(len(word))
characterlist = keys_dict[words[i]]
... |
341344d498cbaef5d247de25ddb0fd332a153549 | Cheevil/TheWarOnPi | /Classes/Movement.py | 713 | 3.765625 | 4 | import RPi.GPIO as IO # The Module that lets you control GPIO pins in the Raspberry Pi
class Movement: #The Movement Class for moving the robot
def __init__(self):
IO.setmode(GPIO.BCM)
self.wheelpins = [[0,1],[2,3]] #Array with sub-arrays that have to Input and Direction for both left and right
... |
c8d0ad7794a9bc386841f173cd92d54235fc6830 | Virender-yadav/restaurant-management-system | /hotelmanamgementsystem.py | 21,847 | 3.515625 | 4 | import pymysql
from tkinter import *
from tkinter import messagebox
conn=pymysql.connect(host="localhost",user="root",password="",db="hotelm")
mycursor=conn.cursor()
def staff_det():
mycursor.execute("SELECT * FROM staff_details ;")#short the rows and columns
#to fetch a single row=> fetchone()
#2. to ... |
ad15f131e92869c29ad489eab3d61d0c7476e609 | tsaihuangsd/Algorithms | /stock_prices/stock_prices.py | 1,376 | 3.96875 | 4 | #!/usr/bin/python
import argparse
def find_max_profit(prices):
# initiate max_profit to difference between first set of prices. Use it as benchmark for future comparison
max_profit = prices[1] - prices[0]
# iterate through prices list to define each buy price
for buy_price_index, buy_price in enumerate(price... |
f6c14b4d83e1dc0c987a1a987f33990441b987ca | mazelado/quiz | /quiz_cli/Quiz.py | 7,282 | 4 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on 5/14/19 2:01 PM
@author: matt
"""
import random
from string import ascii_uppercase
from typing import List
from quiz_cli.Question import Question
class Quiz(object):
"""
This is a class that is a collection of Question objects and additional meth... |
97a1a053f104f0ca341be024dd965970c934b3dd | pankypan/DesignPatterns | /behaviour_pattern/startegy.py | 1,072 | 4.03125 | 4 | """
策略模式
author: panky
"""
import abc
# 抽象算法类
class Strategy(metaclass=abc.ABCMeta):
@abc.abstractmethod
def algorithm_interface(self):
pass
# 具体算法 A
class ConcreteStrategyA(Strategy):
def algorithm_interface(self):
print("算法 A 实现")
# 具体算法 A
class ConcreteStrategyB(Strategy):
def a... |
5219e70f5cb40582681fd2f438d36667a1889856 | pankypan/DesignPatterns | /create_pattern/prototype.py | 1,768 | 4.03125 | 4 | import abc
from copy import copy, deepcopy
class Prototype(metaclass=abc.ABCMeta):
@abc.abstractmethod
def clone(self):
pass
@abc.abstractmethod
def deep_clone(self):
pass
# 工作经历类
class WorkExperience(object):
def __init__(self):
self._time_area = ''
self._compan... |
a7e564af3177325f9fc657f977016ca2ff421523 | fakeblanchett/lesbian_ipsum | /src/generator.py | 5,566 | 3.578125 | 4 | import sys,argparse, random, math
words = []
startString = "Lesbian ipsum dolor sit amet, "
terminators = ["?", ".", "!", ".", ".", ".", ".", "."]
intermediates = [";", ":", ",", ",", ","]
frequencyQueue = []
def generateText(wordCount, paragraphCount):
text = startString
paragraphSizes = []
while len(p... |
0ee0aa19c60cac91e5e5844704724c3081fc908d | AlexNilbak/Task_5 | /Task_5.py | 1,482 | 3.734375 | 4 | try:
file = open("data.txt", "r")
except:
print("Cannot open file\n")
exit()
def Read_int(filename):
f=0
z=0
x='0'
while (x!=' ') and (x!=''):
x=filename.read(1)
if (x==' ' or x=='') and (f!=0):
return z
if (x=='') and (f==0):
... |
a3a68e62dc789d56ca1116ff9cd3c3ed55c14829 | CircleZ3791117/CodingPractice | /source_code/728_SelfDividingNumbers.py | 3,996 | 4.25 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'circlezhou'
'''
Description:
A self-dividing number is a number that is divisible by every digit it contains.
For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.
Also, a self-dividing number is not allowed to co... |
bb3791029954dc19975cc9a8b9932ee5d8ab04a5 | CircleZ3791117/CodingPractice | /source_code/LC94_BinaryTreeInorderTraversal.py | 1,405 | 4.03125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Given a binary tree, return the inorder traversal of its nodes' values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [1,3,2]
Follow up: Recursive solution is trivial, could you do it iteratively?
"""
class TreeNode:
def __init__(self, x)... |
2b8c0626cf65434356a26f156ba7c617a91ce334 | CircleZ3791117/CodingPractice | /source_code/242_ValidAnagram.py | 680 | 4.09375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'circlezhou'
'''
Description:
Given two strings s and t , write a function to determine if t is an anagram of s.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
Note:
You may assume the stri... |
26011450db9d0b76c0a98934138414c855dd1056 | CircleZ3791117/CodingPractice | /source_code/349_IntersectionOfTwoArrays.py | 684 | 4 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'circlezhou'
'''
Description:
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Note:
Each element in the result must be unique.
The result can be in any order.
'''
class Solu... |
aae0e1b4f7efe3e967058062cb9695dea1542f67 | CircleZ3791117/CodingPractice | /source_code/1114_PrintInOrder.py | 4,479 | 4.28125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
Suppose we have a class:
public class Foo {
public void first() { print("first"); }
public void second() { print("second"); }
public void third() { print("third"); }
}
The same instance of Foo will be passed to three different threads. Thread A will call first(),... |
2b288daf013e5922487c56450d730b2132964121 | CircleZ3791117/CodingPractice | /source_code/483_RansomNote.py | 1,315 | 3.890625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'circlezhou'
'''
Description:
Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return fals... |
78e03f18166a4b395dd15395dba66fe83466ef01 | CircleZ3791117/CodingPractice | /source_code/LC279_PerfectSquares.py | 1,288 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
Example 1:
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.
Example 2:
Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.
"""
class Solution:
def numSquares... |
b59c11ab8b66839c2010bf88a1b7130da307405f | CircleZ3791117/CodingPractice | /source_code/627_SwapSalary.py | 1,810 | 3.734375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'circlezhou'
'''
Description:
Given a table salary, such as the one below, that has m=male and f=female values. Swap all f and m values (i.e., change all f values to m and vice versa) with a single update query and no intermediate temp table.
For example:
| i... |
5dc6a0ee116532a9546adaa63db6f82bfbdcf4a5 | CircleZ3791117/CodingPractice | /source_code/500_KeyboardRow.py | 1,576 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'circlezhou'
'''
Description:
Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below.
American keyboard
Example 1:
Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ... |
621b05650ac03949b36d1e9c5b43875a0bb1d274 | CircleZ3791117/CodingPractice | /source_code/LC200_NumberOfIslands.py | 2,470 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input:
11110
11010
11... |
80a1b64a82ff503d1d41333e893f449881ee87c6 | CircleZ3791117/CodingPractice | /source_code/717_1BitAnd2BitCharacters.py | 1,646 | 4.25 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'circlezhou'
'''
Description:
We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11).
Now given a string represented by several bits. Return whether the last charac... |
ff935fe0a87fbe0539bce9c276773eacbd9d06ed | yourspleenfell/python_fundamentals | /dictionary/dict.py | 831 | 4.1875 | 4 | # Create a dictionary containing information about yourself. Keys should include name, age, country of birth and favorite language.
# Write a function that will print something about the dictionary.
def aboutMe():
me = {
"first_name":"Dylan",
"last_name":"Arbuthnot",
"age":"26",
"bi... |
8bb828f552daadaa5a0c3a048c967eb4c07d6276 | yourspleenfell/python_fundamentals | /stars/stars.py | 612 | 4.09375 | 4 | # Part I - Create a function that takes a list of numbers and prints out *
# Part II - Modify function allowing a list containing integers and strings to be passed.
# When string is passed display first letter instead of *. you may use the .lower string method
def draw_stars(num_list):
num = ""
string = ""
... |
2fce7ec3b35d07750d65d706ded65c8d14540aca | strange-uncle/practise_algorithm | /Python/Data_Structure_and_Algorithm/linear_list.py | 4,172 | 3.84375 | 4 | # coding=UTF-8
import random
class LNode():
def __init__(self, elem, next_ = None):
self.elem = elem
self.next = next_
# h = LNode(1)
# h.next = LNode(2)
# h.next.next = LNode(3)
# h.next.next.next = LNode(4)
## 定义head变量,它指向表里的第一个元素,这时候元素的顺序是 1,2,3,4
# head = h
## 1. 表首端的插入,完成以后这head的元素顺序是10,1,2,3,4
# n1 = LNod... |
0ce1dfa8c1b94155f7520498c44da89a8d07e5fb | strange-uncle/practise_algorithm | /Python/Leetcode/leet_code_938_search_BST.py | 1,607 | 3.6875 | 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 __init__(self):
self.sum = 0
def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:
def middle_scan(n: TreeNo... |
50bf2cc87c256d4d06411036a4cfada7143ad326 | DAHarder/CodingPractice | /MathEquation.py | 853 | 4.09375 | 4 | def mathEquation():
import re
i = 0
while i < 5:
mathString = input(
"Enter a simple math equation in the format xx+xx (example: 12 + 44) You may only use the following four operators (+ - * /)")
mathString = mathString.replace(" ", "")
validationVar = re.search("^\d+[+*/... |
d4a7501e4079c19768ef5d029e2d3f632abaefb6 | ramanduh/algo-data-structure | /sort.py | 5,933 | 3.953125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import collections
import math
import pytest
class BubbleSort:
"""
Time: O(n**2)
Space: O(1)
"""
def sort(self, N):
j = len(N)
while j > 0:
# Iterate till j-1 because each iteration put the max at the end
for i i... |
b0ab58533ee9fda33ee2eaa979d2e110f86a338e | zl0bster/PY111-VP | /Tasks/b0_linear_search.py | 519 | 4 | 4 | """
This module implements some functions based on linear search algo
"""
from typing import Sequence
def min_search(arr: Sequence) -> int:
"""
Function that find minimal element in array
:param arr: Array containing numbers
:return: index of first occurrence of minimal element in array
"""
i... |
8111ea0a45a2a50ce6d13e54d2516395119636c1 | haiconmeo/doan2 | /inra_v1.py | 3,003 | 3.546875 | 4 | CHUOI,NHAYKEP,EOF ='CHUOI','\"','EOF'
class Token(object):
def __init__(self, type, value):
self.type = type
self.value = value
def __str__(self):
return 'Token({type}, {value})'.format(
type=self.type,
value=repr(self.value)
)
de... |
90a777d1dcad70bdc4bfcc220cf51f2bfd4257cc | HaripriyaS-dxc/assignment-dxc | /Assesments/Assessments-Python/day-3.py | 1,753 | 3.59375 | 4 | class Products:
def __init__(self,Id,Name,Category,Brand,Cost,Rating,Discount):
self.Id=Id
self.Name=Name
self.Category=Category
self.Brand=Brand
self.Cost=Cost
self.Rating=Rating
self.Discount=Discount
product1=Products(101,"Laptop","Electronics","HP",50000... |
11bf58488c1294b9253cee530866c78785d0bb9c | rajsudeep/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 557 | 4.03125 | 4 | #!/usr/bin/python3
"""
This module includes:
text_indentation
"""
def text_indentation(text):
"""
Prints a reformatted a text with double new line indentation
"""
txt_err = "text must be a string"
if not isinstance(text, str):
raise TypeError(txt_err)
print_str = ""
for i in t... |
8f7a4a7a3fd5c80a472e29be23ba0fbe5914b774 | rajsudeep/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/4-print_square.py | 515 | 3.90625 | 4 | #!/usr/bin/python3
"""
This module includes:
def_square
"""
def print_square(size):
"""
Prints a square represented by hashtags
"""
int_err = "size must be an integer"
val_err = "size must be >= 0"
float_err = "size must be an integer"
if not isinstance(size, int):
raise TypeErr... |
1b0efa0c40d9855ec5d6de15c60453202cdb6c95 | rajsudeep/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/12-roman_to_int.py | 866 | 3.609375 | 4 | #!/usr/bin/python3
def sym(sym):
if (sym == 'I'):
return 1
if (sym == 'V'):
return 5
if (sym == 'X'):
return 10
if (sym == 'L'):
return 50
if (sym == 'C'):
return 100
if (sym == 'D'):
return 500
if (sym == 'M'):
return 1000
return 0... |
6c893c57ed55ca71a2e4a2d7595bca9e1f7deb99 | rajsudeep/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/9-multiply_by_2.py | 123 | 3.734375 | 4 | #!/usr/bin/python3
def multiply_by_2(a_dictionary):
return {key: (value * 2) for (key, value) in a_dictionary.items()}
|
550899849626326299a26fc1c4f3f691df0399a1 | rajsudeep/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/square.py | 1,360 | 3.75 | 4 | #!/usr/bin/python3
"""
Class Square -
defines a square
"""
from models.rectangle import Rectangle
class Square(Rectangle):
""" defines a square """
print_symbol = '#'
def __init__(self, size, x=0, y=0, id=None):
""" initialize a square """
super().__init__(size, size, x, y, id)
@pr... |
85cf8a168bfe5325259b625bbdd4e74b4f597dc2 | rajsudeep/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/tests/test_models/test_square.py | 4,434 | 3.9375 | 4 | #!/usr/bin/python3
"""
Class SquareTest -
for testing models/rectangle.py
"""
import unittest
import os
import io
import contextlib
from models.square import Square
class SquareTest(unittest.TestCase):
""" unit tests for the square class """
def test_size(self):
r_s = Square(10, 0, 0, 1)
se... |
e27d1862ea49c791f5df6c7b7861e16d685deea0 | milanakdj/localfirstday | /paragraph.py | 577 | 4 | 4 | # a=input("""enter a paragraph
# and i will transfer it with correct formatting""")
# newstr=""
# sentences=a.split(".")
# newsentence=""
# for sentence in sentences:
# newsentence=sentence.strip()
# t=newsentence.capitalize()
# newstr=newstr+t+'.'
# print(newstr)
# a=input("""enter a paragraph
# and i... |
cdc075bb3a279301a6c8cf5225355a6b590b7ec8 | barfcat/python-class | /wk2-2-ipbinary.py | 1,106 | 3.640625 | 4 | #!/usr/bin/env python
#accept input and store it as variable ip_addr
ip_addr = raw_input("Please enter an IP address: ")
#convert the ip_addr string to a list
octets = ip_addr.split(".")
#create new list that I'm more comfortable using
network = octets[:]
#create network string
network_octet_1_str = network[0]
net... |
eee48b09bf2e41f2640c5a3a10ad86b07d4ec6a2 | barfcat/python-class | /wk4-3-uptimeinseconds.py | 2,044 | 3.59375 | 4 | #!/usr/bin/env python
uptime1 = 'twb-sf-881 uptime is 6 weeks, 4 days, 2 hours, 25 minutes'
uptime2 = '3750RJ uptime is 1 hour, 29 minutes'
uptime3 = 'CATS3560 uptime is 8 weeks, 4 days, 18 hours, 16 minutes'
uptime4 = 'rtr1 uptime is 5 years, 18 weeks, 8 hours, 23 minutes'
MINUTE_SECONDS = 60
HOUR_SECONDS = MINUTE_S... |
153c5b472d3cd6c3530c6295e2841b0c4bef7f25 | sas-003/Leet_Code_Interview_Problems_Solution | /perfectNumber.py | 274 | 3.796875 | 4 | def perfectSum(num):
sum = 0
for i in range (1,num ):
if ( num% i == 0):
sum = sum + i
if (num * 2 == sum):
print ("perfect num" )
else:
print ( 'Not a perfect Numbers' )
number = int ( input ( "please enter a number\t" ) )
perfectSum ( number )
|
3b310aa3feb2584630fb3d5867eacd96b9b01b15 | ntmk/ICS-Labs | /114-python/Python labs/MoreCalculations.py | 645 | 3.921875 | 4 | import math
# Program 1
base=float (input())
height=float (input())
area=0.5*(base*height)
print("%.1f" % area)
# Program 2
import math
a=float(input())
b=float(input())
c=(a*a+b*b)
print("%.2f" % math.sqrt(c))
# Program 3
import math
math.pi
radius= float(input())
area=math.pi*radius**2
print("%.3f" % area)
# ... |
60f09d49c807d7c3d4a897d8818b37040291bfb8 | ntmk/ICS-Labs | /114-python/Python labs/DrawingAHalfArrow.py | 533 | 4 | 4 | print ('Enter arrow base height: ')
arrow_base_height = int(input())
print ('Enter arrow base width: ')
arrow_base_width = int(input())
print ('Enter arrow head width: ')
arrow_head_width = int(input())
while arrow_head_width <= arrow_base_width:
print ('Enter arrow head width: ')
arrow_head_width = int(in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.