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 |
|---|---|---|---|---|---|---|
9e8630fe99777f756318a3fa39d6e47cbefacdc1 | matleg/various_python_scripts | /pytest_catch_expected_exception.py | 602 | 3.625 | 4 | def moyenne(*nombres):
taille = len(nombres)
if taille == 0:
return None
somme = 0
for nombre in nombres:
if not isinstance(nombre, int):
raise TypeError("'%s' n'est pas un entier" % str(nombre))
somme += nombre
return somme / taille
# cas simples
assert moyenne... |
4bb93dc7f11df11af9a5a680d824d1e37d197647 | matleg/various_python_scripts | /f_string_memo.py | 1,314 | 3.640625 | 4 | # Memo from : https://medium.com/bitgrit-data-science-publication/python-f-strings-tricks-you-should-know-7ce094a25d43
# Formatting numbers
number = 330
print(f"number: {number:.2f}") # decimal
print(f"hex: {number:#0x}") # hex
print(f"binary: {number:b}") # binary
print(f"octal: {number:o}") # octal
print(f"scie... |
dfa3fab1312f2e0b54fe27c8a8b5a62a09873b74 | rnyorke/PythonProjects | /PythonProject7.py | 691 | 3.6875 | 4 | # 25 pts
loopNumber = 0
while (loopNumber <= 300):
if loopNumber %2 == 1:
print loopNumber
loopNumber = loopNumber + 1
# 25 pts
list1 = [2, 3, "Hello", "haha", "CS is awesome", 17, "lol", "hello", 727, 7, 10]
x = 0
while (x <= 10):
print list1[x]
x = x + 1
# 50 pts
import random
ra... |
838fdf5d8d24feaa89d08ef78f434be1247e5756 | spohlson/Linked-Lists | /circular_linked.py | 1,557 | 4.21875 | 4 | """ Implement a circular linked list """
class Node(object):
def __init__(self, data = None, next = None):
self.data = data
self.next = next
def __str__(self):
# Node data in string form
return str(self.data)
class CircleLinkedList(object):
def __init__(self):
self.head = None
self.tail = None
se... |
8a3a64b3f721e7ed219fa6c43c4b42d31c1ba014 | ben-mcginty/MathCode | /floyd's algorithm.py | 380 | 3.6875 | 4 | def findDuplicate(nums):
tortoise = nums[0]
hare = nums[0]
while True:
tortoise = nums[tortoise]
hare = nums[nums[hare]]
if tortoise == hare:
break
ptr1 = nums[0]
ptr2 = tortoise
while ptr1 != ptr2:
ptr1 = nums[ptr1]
ptr2 = nums[p... |
d7bc3ace4c64c32e3b21ac2d12d6284dcbdd63dc | jenish1231/python-design-patterns | /1. Creational Patterns/5. Prototype/main.py | 1,754 | 3.53125 | 4 | import copy
class Player:
name = None
def set_name(self, name):
self.name = name
def set_skill(self, stricker_skill, midfielder_skill, defender_skill):
self.stricker_skill = stricker_skill
self.midfielder_skill = midfielder_skill
self.defender_skill = defender_skill
def clone(self):
return copy.copy(... |
4eb809ef1a09e8cb3268494acabda59d912066ee | Pulkit2699/N-Queens...-with-a-Boulder | /nqueens.py | 6,197 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 16 18:37:37 2020
@author: pulkit
"""
import numpy as np
import random
def succ(state, boulderX, boulderY):
succList = []
for i in range(len(state)):
for j in range(len(state)):
succState = state.copy()
succState[i] = ... |
2e7ff4d7b42c3d4790ed607f388c0a6bda09d7dc | mbonifasi2019139/python-intermedio | /app.py | 431 | 3.703125 | 4 | print("--------------Bienvenido------------")
number = int(input("Ingrese un numero de 1 a 10: "))
path = "./myfiles/"
myfile = open("./myfiles/tabla-n.txt", "wt")
result = 0
if number >= 1 and number <= 10:
for iterator in range(1,11):
result = iterator * number
line = f"{number} x {iterator} = {... |
a16b6218dda21efb0b3ac0aaa5d1ab62cdadc84c | abhisharma1601/Python_Projects | /tic-tac-toe.py | 2,929 | 3.9375 | 4 | print("Tic - Tac -Toe")
print("player 1 please choose one 'x' or 'o'")
player_1 = input()
if player_1 == "x":
player_2 = "o"
print("player 2 got:o")
else:
player_2="x"
print("player 1 got:o")
mylist = ["", "", "", "", "", "", "", "", "", ""]
def print_board():
print(mylist[0] + "\t|" + mylist[1] ... |
2581dc910feb8d1f063cf495d2bdc409a6cf06c9 | josephc2195/3153-assignments | /eight-queens/main.py | 7,394 | 4.125 | 4 | from numpy import random
class Queens:
#initializes the class and variables needed for class:
def __init__(self):
self.restarts = 0
self.moves = 0
self.board = self.makeBoard()
#gets the current number of heuristic
self.h... |
56fcf653effc79c4b8371d94f5102088b7253dcb | ParkerCS/ch-tkinter-sdemirjian | /tkinter_8ball.py | 2,493 | 4.59375 | 5 | # MAGIC 8-BALL (25pts)
# Create a tkinter app which acts as a "Magic 8-ball" fortune teller
# The user asks a yes/no question that they want an answer to.
# Then the user clicks a button, and your program displays
# the "magic" random answer to their question.
# Your program will have the following properties:
# - Use ... |
4d180cef406e2083553401ff00cad9eed62b9365 | bonthusaireddy/projecteuler.net | /In python/1.py | 201 | 3.765625 | 4 | n = int(input("Enter a natural numbaer: "))
sum3 = 0
sum5 = 0
for i in range(n):
if i % 3 == 0:
sum3 = sum3 + i
continue
if i % 5 == 0:
sum5 = sum5 + i
print(sum3+sum5)
|
e0e8a0babdc036c0cf021449943e352869bf8404 | pontakornth/algorithm-bot | /algorithms/merge_sort.py | 1,301 | 3.546875 | 4 | from algorithms import utils
from math import floor
def merge(llist: list, start: int, mid: int, end: int):
sequence = []
temp_list = []
left = llist[start:mid + 1]
right = llist[mid + 1:end + 1]
temp_index = 0
while len(left) and len(right):
if left[0] < right[0]:
temp_li... |
e703fe501c59c099bbc141ec0bf1cc8c5c452048 | otisscott/1114-Stuff | /Homework 3/oms275_hw3_q3.py | 514 | 3.796875 | 4 | # Otis Scott
# CS - UY 1114
# 26 Sept 2018
# Homework 3
days = ["Mon", "Tues", "Wed", "Thurs", "Fri", "Sat", "Sun"]
rate = 0
day = days.index(input("Enter the day the call started: "))
time = int(input("Enter the time the call was started at (hhmm)"))
duration = int(input("Enter the duration of the call (in minutes)"... |
c58ee48a4a7e734e1a35b550face23ecd007c3d4 | otisscott/1114-Stuff | /Lab 5/multistar.py | 273 | 3.84375 | 4 | # Otis Scott
# CS - UY 1114
# 4 Oct 2018
# Homework 4
import turtle
import time
times = int(input("How many stars: "))
times = times * 5
length = 20
angle = 144
for each in range(0, times):
turtle.forward(length)
turtle.right(angle)
length += 10
time.sleep(5)
|
177d3eab59e3d085ecf439000724af22d151213f | otisscott/1114-Stuff | /Lab 2/volumeofsphere.py | 349 | 3.953125 | 4 | # Otis Scott
#CS - UY 1114
# 13 Sept 2018
# Lab 3
pi = 22 / 7
radius_1 = 1.5
radius_2 = 3.0
radius_3 = 5.2
volume_1 = (4/3)*pi*radius_1**3
volume_2 = (4/3)*pi*radius_2**3
volume_3 = (4/3)*pi*radius_3**3
print("volume of ball 1 in cm:")
print(volume_1)
print("volume of ball 2 in cm:")
print(volume_2)
print("volume of... |
e39e0dcff94b1416043dd5124c81bf8186e95809 | otisscott/1114-Stuff | /Lab 6/sqrprinter.py | 269 | 4.125 | 4 | inp = int(input("Enter a positive integer: "))
for rows in range(inp):
row = ""
for columns in range(inp):
if columns < rows:
row += "#"
elif rows < columns:
row += "$"
else:
row += "%"
print(row)
|
05863c6ae1ad7713732aa74b645a48e8d95a0e3b | otisscott/1114-Stuff | /Homework 6/oms275_hw6.py | 2,743 | 4.03125 | 4 | # Otis Scott
# CS - UY 1114
# 10 Oct 2018
# Homework 5
def print_top (offset) :
# signature: int -> NoneType
print(offset * ' ' + '^')
def print_middle (offset , width) :
# signature: int , int -> NoneType
print(offset * ' ' + '/' + width * ' ' + '\\')
def print_bottom (offset , width):
# sign... |
31eb59136bb6947d5ec03a70ea581ad276375dc7 | otisscott/1114-Stuff | /Lab 2/shittycalendar.py | 212 | 4.09375 | 4 | userDays = int(input("Please enter number of days:"))
weeks = str(userDays // 7)
days = str(userDays % 7)
userDays = str(userDays)
print(userDays + " days is equal to " + weeks + " week and " + days + " days")
|
ad608cd56dd0019920087c779e26f69e97d9882a | otisscott/1114-Stuff | /Lab 2/simplecalculator.py | 490 | 4.25 | 4 | firstInt = int(input("Please enter the first integer:"))
secondInt = int((input("Please enter the second integer:")))
simpSum = str(firstInt + secondInt)
simpDif = str(firstInt - secondInt)
simpProd = str(firstInt * secondInt)
simpQuot = str(firstInt // secondInt)
simpRem = str(firstInt % secondInt)
print("This sum i... |
604f3b0458f09c4abc8820c101e96c418d06c1b0 | vikhil0609/color_detecting_in_an_image | /colors/colors/spiders/for_excel.py | 674 | 3.890625 | 4 | import csv
class Excel:
def __init__(self,fields,rows):
print("Excel created")
self.fields = fields
self.rows = rows
# name of csv file
self.filename = "colors.csv"
def main(self):
# writing to csv file
with open(self.filename, 'w') as csvfile:
... |
c276ef4d3ccee8af723d236e341c6b8a3c989327 | juanspinelli/pythoncientifico | /solutions/python/spanish_deck.py | 200 | 3.859375 | 4 | import itertools
DECK_NUMBERS = range(1, 13)
DECK_SUITS = ('OROS', 'COPAS', 'ESPADAS', 'BASTOS')
for number, suit in itertools.product(DECK_NUMBERS, DECK_SUITS):
print(f'{number:>2} de {suit}')
|
f20257184d73f7444df1379f97b6b841d4dc7935 | Abilityguy/Tic-Tac-Toe | /logic.py | 4,897 | 3.984375 | 4 | import random
from copy import deepcopy
# Basic Helper functions to track the board and calculate computer moves
class Game:
def __init__(self, player = 'o', computer = 'x'):
self.player = player
self.computer = computer
self.board = board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
... |
7eb55bfc6c6f23d132c85ff5217c76381290b621 | ngvlz/advent-of-code-2020 | /day09/day9_2.py | 1,368 | 3.6875 | 4 | import json
data = json.loads(open('input.json').read())
def validate_num(num_list):
valid_num = []
for x in range(len(num_list)):
for num in num_list[x+1:]:
valid_num.append(num_list[x] + num)
return valid_num
def find_invalid_num(queue):
while queue:
try:
l... |
fd4a4c28266370f798ed3043863933f156781f95 | ngvlz/advent-of-code-2020 | /day15/day15_1+2.py | 753 | 3.640625 | 4 | with open('input', 'r') as program:
nlist = program.read()
nlist = nlist.split(',')
nlist = list(map(int, nlist))
def find_next_number(number_list, target_number):
number_dict = {}
for idx, n in enumerate(nlist):
number_dict[n] = idx + 1
turn = len(number_dict) + 1
next_number = 0
... |
6f0cb2d42343987c32067f038502547114b46511 | aleckramarczyk/project-euler | /smallestmultiple.py | 839 | 4.125 | 4 | #2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
#
#What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
def main():
found = False
num = 2520
#any number that is divisible by 1 through 20 will be a multi... |
f16eea39c7cfedd1ec3dc32df8c082c3bd25437c | Pranali-002/PYAssignment2 | /Arithmatics.py | 201 | 3.546875 | 4 |
def Add(no1,no2):
ans = no1+no2
return ans
def Sub(no1,no2):
ans = no1-no2
return ans
def Mul(no1,no2):
ans = no1*no2
return ans
def Div(no1,no2):
ans = no1/no2
return ans |
e9a558717d0240a600605e46541b0207ad58f5b2 | othee86/ml | /simulator.py | 4,517 | 3.59375 | 4 |
"""
This is Santa Uncertain Gifts Simulator
"""
import os
import numpy as np
import math
import random
import click
class Horse:
def __init__(self, num):
self.weight = max(0, np.random.normal(5,2,1)[0])
self.name = 'horse_' + str(num)
class Ball:
def __init__(self, num):
self.weight ... |
48847c7d55b79864d3c3ce3d323dc643881585fc | newera-systems/repo-entrevue | /exercice_1.py | 1,121 | 3.796875 | 4 | def findNext(number):
# On accepte seulement l'ensemble des entiers
if not isinstance(number, int) :
return False
# Conversion vers un "string"
number_s = str(number)
processing_negative_number = False
swap_1 = None
swap_2 = None
# Si nombre entier negatif
if number < 0 :
... |
eacbc7af74f6b103b6b17d33f6a4448fa3ba7a9d | Andrea-09/Tarea_FP_00366519 | /Factorial.py | 146 | 3.96875 | 4 | print("Ingrese el numero del cual quiere saber el factorial:")
x = int(input())
acum = 1
for i in range(1, x+1):
acum = i*acum
print(acum) |
3a9a34ebc28a51086f1230b8f8d6e296da0f2d74 | hashtag-yashtag/K-Means-From-Scratch | /KMeans.py | 3,599 | 3.65625 | 4 | import math
import numpy as np
from sklearn.datasets import make_moons
import matplotlib.pyplot as plt
import pylab
#200 random numbers
np.random.seed(200)
#Change the value of K depending on the number of clusters needed
K = 3
# make_moons is a dataset in sklearn
X, _ = make_moons(n_samples=500, random_state=42, no... |
a548aa4c5b44ff50b4d39cb8c467930adb387288 | greylord1996/MAP | /src/optimize.py | 1,194 | 3.6875 | 4 | """Implementation of the cross-entropy optimization method."""
import numpy as np
import scipy as sp
def minimize(func, x0):
"""Minimize scalar function using cross-entropy optimization method.
Args:
func (ObjectiveFunction): Function to minimize.
x0 (numpy.ndarray): Starting point (typical... |
f403aaed015f6ce2f4489cf7dfa2182fb4ed02f3 | jtomaspm/python_learn | /life/functions.py | 761 | 3.71875 | 4 | import random
# 2-3 survives
#100
#011
#000
# 4+ dies
#100 100
#111 --> 101
#100 100
# 1- dies
#000 000
#011 --> 001
#000 000
# birth 3
#100 100
#001 --> 011
#100 100
def generate_matrix(board):
for y in range(len(board))
for x in range(len())
def generate_random_lif... |
b4e5a78867851327acfb414acf3fdb219fbc948d | AnshulAngaria/Synchron-X | /compiler.py | 1,833 | 3.5 | 4 | input_file = open("main.sx",'r')
current_variables = []
current_functions = []
def parse_line(tokens):
instruction = tokens[0]
if instruction == "[" and tokens[-1]=="]":
# it is comment instruction; ignore it
# (i m nopping here just to show how it works)
print "\tnop"
pass
elif instruction == "int":
# d... |
df720237ebe306ad2726b90013d9b14de44976c0 | bestofothers/TextAdventure | /text.py | 2,782 | 3.796875 | 4 | #!/bin/python
import copy
verbs = ["look", "walk", "take", "bag", "map"]
nouns = ["north", "east", "south", "west", "n", "s", "e", "w"]
bag = []
player_x = 1
player_y = 1
maze = [
[1,1,1,1,1,1,1,1,1,1],
[1,0,2,0,0,0,0,0,0,1],
[1,1,1,1,0,0,0,0,0,1],
[1,0,0,1,1,1,0,0,0,1],
[1,0,0,0,0,1,0,0,0,1],
[1,0,0,0,0,1,1,... |
e26223e21d3e3d4efb2a34a5d75eab4248cc7a12 | anastasiiavoronina/python_itea2020 | /py_itea2020_classes/lesson02/my_class.py | 1,487 | 3.640625 | 4 | class Phone:
type_ = 'Mobile phone'
def __init__(self, model, imei, phone_number):
self.model = model
self.imei = imei
self.phone_number = phone_number
def call(self, to_number):
print(f'Calling from {self.phone_number} to {to_number}')
class Satellitephone:
# def m... |
400e9a269202aaf73d8c57a36b34cbac65a88d46 | anastasiiavoronina/python_itea2020 | /py_itea2020_classes/lesson04/new_example.py | 869 | 3.6875 | 4 | class Person:
def __new__(cls, *args, **kwargs):
print('Calling new')
person_object = super().__new__(cls)
person_object.age = 25
return person_object
def __init__(self, first_name, surname):
print('Calling init')
self._first_name = first_name
self._surn... |
53bfe4d2a4a989302f4dae54d7fa4bb106da5d9d | anastasiiavoronina/python_itea2020 | /py_itea2020_classes/lesson01/lesson01_task02.py | 376 | 4.21875 | 4 | dict_countries = {
'Ukraine': 'Kiev',
'Poland' : 'Warsaw',
'Great Britain' : 'London',
'France' : 'Paris',
'Belarus': 'Minsk'
}
list_countries = ['Spain', 'Poland', 'Ukraine', 'France', 'Italy', ' Norway', 'Greece']
for country in list_countries:
if country in dict_countries:
print(dic... |
e816b46637f3a3d186367d0cb13f8a300ab0f154 | anastasiiavoronina/python_itea2020 | /py_itea2020_classes/lesson02/lesson02_tasks/lesson2_task01.py | 745 | 3.78125 | 4 | class Car:
def __init__(self, mark, model, price):
self.mark = mark
self.model = model
self.price = price
def drive(self):
print(f'Car {self.model} is starting to move')
def stop(self):
print(f'Car {self.model} is stopping')
def beep(self):
print('Beep... |
d76d24fd7219f83b35e306c654f5b8ab8fab78b2 | yasindindar/Class4-CS101Module-Week9 | /Answer for Question 1.py | 569 | 3.96875 | 4 | from queue import Queue
class Stack(Queue):
'''Variant of Queue that retrieves most recently added entries first.'''
def _init(self, maxsize):
self.queue = []
def _qsize(self):
return len(self.queue)
def _put(self, item):
self.queue.append(item)
def _get(se... |
6a98ff1d1c49c725e14b9427e8c8a0ecb2bcee1c | Meghashrestha/pythonassignment-sorting | /i.py | 363 | 3.671875 | 4 |
#tower of hanoi
def TowerOfHanoi(n , source, target, midway):
if n == 1:
print("Move disk 1 source" ,source ,"to target" ,target)
return
TowerOfHanoi( n -1, source, midway, target)
print("Move disk" ,n ,"from source" ,source ,"to target" ,target)
TowerOfHanoi( n -1, midway, target, sou... |
872ecf31bf078b6669bd800436a3409c93468759 | jeremy-wischusen/codingbat | /python/stringone/combo_string_test.py | 783 | 4 | 4 | """
Given 2 strings, a and b, return a string of the form short+long+short,
with the shorter string on the outside and the longer string on the inside.
The strings will not be the same length, but they may be empty (length 0).
combo_string('Hello', 'hi') → 'hiHellohi'
combo_string('hi', 'Hello') → 'hiHellohi'
comb... |
31a827247618a3cca526678c51c28fcb85190809 | jeremy-wischusen/codingbat | /python/warmupone/sleep_in_test.py | 798 | 3.953125 | 4 | """
Warmup-1 > sleep_in
prev | next | chance
The parameter weekday is True if it is a weekday, and the parameter vacation is True if we are on vacation.
We sleep in if it is not a weekday or we're on vacation. Return True if we sleep in.
sleep_in(False, False) → True
sleep_in(True, False) → False
sleep_in(False,... |
2d7f1d5d950ead81c5b484c23bfc791244aa4fd3 | jeremy-wischusen/codingbat | /python/stringone/first_half_test.py | 534 | 4.0625 | 4 | """
Given a string of even length, return the first half. So the string "WooHoo" yields "Woo".
assert first_half('WooHoo') == 'Woo'
assert first_half('HelloThere') == 'Hello'
assert first_half('abcdef') == 'abc'
"""
"""
Solution
"""
def first_half(str):
l = len(str)
if l > 1:
mid = l / 2
... |
ee9d9d9256c74a84275211c616b8e4f1bf3b22b9 | jeremy-wischusen/codingbat | /python/logicone/caught_speeding_test.py | 819 | 4.1875 | 4 | """
You are driving a little too fast, and a police officer stops you.
Write code to compute the result, encoded as an int value:
0=no ticket, 1=small ticket, 2=big ticket.
If speed is 60 or less, the result is 0.
If speed is between 61 and 80 inclusive, the result is 1.
If speed is 81 or more, the result is 2.
... |
4ff884865098372b1a36adf246a0a481bf3d15f6 | achuzhoy/pickaroom | /random1.py | 3,039 | 3.859375 | 4 | #!/usr/bin/env python
#for this script to works- you need:
# a db on the localhost
# a table named vacation with 2 columns:roomname,family (strings), while roomname is the primary key
# 3 arguments (username,password, dbname)
import random
import MySQLdb
import sys
def print_results(cursor):
sql = "select * from ... |
0402582973c02059b321abbb747c2d8c3d1616b6 | psimpson625/Random_Stuff | /20210612_Functions.py | 6,837 | 3.96875 | 4 | # Question 1: Implement a function 'ingredients' that takes a recipe
# and returns a dictionary of the ingredients needed.
def ingredients(recipe):
"""
>>> ganache = 'semi-sweet chocolate: 224g\\nheavy cream: 224g\\nChop chocolate, place in a bowl. Heat cream until it simmers.\\nAdd cream to bowl, let stand f... |
c0f16640d39fe318258f79efaf3d631f4d7ca811 | andreaorlando333/EserciziTPSIT | /Python/DisegnaPoligono.py | 171 | 3.828125 | 4 | import turtle
t = turtle.Turtle()
n = int(input("Inserisci numero di lati : "))
for k in range(n):
turtle.forward(100)
turtle.right(360 / n) |
45d2b303ba87d2b159870bb77f42affe52052936 | windowCoder/100daysofPython | /functions_intro.py | 349 | 3.96875 | 4 | your_name = input("What is your name? ")
your_loc = input("What is your location ")
def greet_with(name, loc):
print(f"Hello, {name}! What is it like in {your_loc}?\n")
greet_with(your_name, your_loc)
def simple_math(a,b,c):
print("\nSimple Math Time!")
print(a+2)
print(b*2)
print(c/2)
s... |
8ac4b2d444b8ef3fe630b38ffc19a808a276dbe2 | iampradeepraj/Local_Development | /PySpark/Python/ZTM/First program.py | 142 | 3.875 | 4 | print("Hi GoodMorning!!!")
name= input("what is my name: ")
age = input("What is your age: ")
print("Welcome",name,"your age is",age) |
73388a811e728d768416260c8f8cac553228a863 | tjdgus3160/algorithm | /BOJ/Silver5/여우는 어떻게 울지?.py | 313 | 3.5625 | 4 | # 9536번
import sys
input=sys.stdin.readline
for _ in range(int(input())):
arr=input().split()
sound=set()
while True:
s=input().rstrip('\n')
if s=='what does the fox say?':
break
_,_,k=s.split()
sound.add(k)
print(*[i for i in arr if i not in sound]) |
5a2224a0af1da53adbeacabb0f6984d093845d86 | tjdgus3160/algorithm | /BOJ/Silver4/팬그램.py | 522 | 3.59375 | 4 | # 10384번
from collections import defaultdict
import sys
input=sys.stdin.readline
for v in range(int(input())):
s=input().rstrip()
dic=defaultdict(int)
for i in s:
if i.isalpha():
dic[i.lower()]+=1
if len(dic)<26:
print(f"Case {v+1}: Not a pangram")
elif min(dic.values())... |
abef24abe66205a46dbc161a9b907151296a7c0e | tjdgus3160/algorithm | /CodeUp/재귀함수/(재귀함수)우박수(3n+1)(basic).py | 159 | 3.890625 | 4 | def find(n):
if n==1:
print(1)
return
print(n)
if n%2==1:
find(3*n+1)
else:
find(n//2)
n=int(input())
find(n)
|
aa5837ed10c7ab1c83f1330a372b76179b33db68 | tjdgus3160/algorithm | /프로그래머스/DFS_BFS/여행경로.py | 639 | 3.921875 | 4 | # hint: dfs중 티켓이 0이되면 옳바른 경로를 찾은것
def dfs(tickets,path):
if not tickets:
return path
for i,ticket in enumerate(tickets):
if path[-1]==ticket[0]:
path.append(ticket[1])
tickets.pop(i)
tmp=dfs(tickets,path)
if tmp:
return tmp
... |
154bee0c3d9f40810d2693af6b115e25ebd890bb | tjdgus3160/algorithm | /CodeUp/재귀함수/(재귀함수)피보나치 수열.py | 105 | 3.78125 | 4 | def fibo(n):
if n<=2:
return 1
return fibo(n-1)+fibo(n-2)
n=int(input())
print(fibo(n))
|
51e21d83ba3edd1404271dba0aed9d3ca823d302 | tjdgus3160/algorithm | /CodeUp/관리자 추천 문제/윤년 판별.py | 74 | 3.546875 | 4 | n=int(input())
print("yes" if (n%4==0 and n%100!=0)or n%400==0 else "no")
|
af1ef8b6837deec2de38278564e515bb854d92d8 | sandeep-skb/Data-Structures | /Python/Trees/diameter.py | 1,465 | 4.25 | 4 | class Node:
def __init__(self, val):
self.data = val
self.left = None
self.right = None
def height(node):
if node == None:
return 0
return (max(height(node.left), height(node.right))+1)
def diameter(node):
'''
The diameter of a tree (sometimes called the width) is the number of nodes on th... |
04b293e819b642b0755f35e10fd270879f0b5a32 | sandeep-skb/Data-Structures | /Python/Linked-list/Singly-Linked-List/exchange_by_2.py | 879 | 4.1875 | 4 |
def traverse(node):
if node != None:
print(node.data)
traverse(node.next)
def exchange(node):
prev = Node(0)
prev.next = node
head = prev
while((node != None) and (node.next != None)):
prev.next = node.next
temp = node.next.next
node.next.next = node
... |
a9ad9bec49d90eb125d2e2b3cf40f077b48f3e61 | sandeep-skb/Data-Structures | /Python/Trees/level_order_traversal.py | 514 | 3.625 | 4 | class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def levelOrderTraversal(node):
q = []
q.append(node)
while(len(q) != 0):
node = q.pop(0)
print(node.data, end=" ")
if node.left != None:
q.append(node.left)
if node.right != None:
... |
794cc48f4a3afab49bee3a61a551cdca49a6ee98 | sandeep-skb/Data-Structures | /Python/Trees/reverse_level_order.py | 757 | 3.9375 | 4 | class Node:
def __init__(self, val):
self.data = val
self.left = None
self.right = None
def reverseLevelOrder(node):
if node == None:
print("Node is empty, illegal input")
return
q = [node]
s = []
while(len(q) != 0):
tmp = q.pop(0)
if tmp.right != None:
q.append(tmp.right... |
f0be4c7265343d7cdbe81d5b7f748bc58887822a | agentnova/LuminarPython | /Luminaarpython/objectoriented/intro.py | 622 | 3.515625 | 4 | # class
# blueprint,plan,design,design pattern
# object
# real world entity,constructed using design pattern
# reference
# if we want to perform an operation on object then we need to create reference
# class classname
# static variable/class variable used to save memory loss
class Person:
# method
def set... |
b473608e2726dce7e51194ac7174ad2ffbd53643 | agentnova/LuminarPython | /Luminaarpython/Looping/numberrange.py | 306 | 3.9375 | 4 | # print numbers from lower limit to uper limit
low=int(input("enter lower limit :"))
upper=int(input("enter upper limit :"))
evensum=0
oddsum=0
for i in range(low,(upper+1)):
if(i%2==0):
evensum=evensum+i
else:
oddsum=oddsum+i
print("even sum :",evensum)
print("odd sum :",oddsum)
|
2a5154658dec00c3028dc96cf4c1f0471dd68b3a | agentnova/LuminarPython | /Luminaarpython/Multitasking/pgm4.py | 472 | 3.65625 | 4 | from threading import *
import time
def squares(num):
for n in num:
time.sleep(1)
print(n**2)
def double(num):
for n in num:
time.sleep(1)
print(2*n)
num=[1,2,3,4,5,6]
begintime=time.time()
print("bdegin",begintime)
t1=Thread(target=squares,args=(num,))
t1.start()
t2=Thread(... |
b8358a04ba7b08d18663763d3834a8770f12f0a1 | agentnova/LuminarPython | /Luminaarpython/Looping/multiplicationtable.py | 112 | 3.90625 | 4 | #multiplication table
i=1
n=int(input("enter number :"))
sum=0
while(i<=10):
print(i,"*",n,"=",i*n)
i+=1 |
16c3306c60e122ad255f78c46aeb456b079d8d91 | agentnova/LuminarPython | /Luminaarpython/collections/listdemo/linearsearch.py | 414 | 3.921875 | 4 |
# print(lst[3:7])
# print(lst[1:])
# print(lst[:6])
# print(lst[-1])
#
# num=int(input("enter the number to search :"))
# flag=0
# for i in lst:
# if(i==num):
# flag=1
# if(flag==1):
# print("found")
# else:
# print("not found")
lst=[1,2,3,4,5,6,7,8,9,10,11,12]
#if 6 print 3,4
num=int(input("ente... |
ca9c4e0ee0e318877af3e79666235937e4c0fd64 | agentnova/LuminarPython | /Luminaarpython/objectoriented/multipleInheritense.py | 308 | 3.84375 | 4 | class Parent:
def m1(self):
print("inside parent1")
class Child:
def m2(self):
print("inside child")
class SubChild(Parent,Child):
def m3(self):
print("inside subchild")
#parent
p=Parent()
p.m1()
#child
c=Child()
c.m2()
#Subchild
sb=SubChild()
sb.m1()
sb.m2()
sb.m3() |
9a6daa296d79e784735d54ba328af94800f341c4 | agentnova/LuminarPython | /Luminaarpython/objectoriented/constructor2.py | 301 | 3.546875 | 4 | class Person:
# method
def __init__(self, name, age, gender):
self.age = age
self.name = name
self.gender = gender
def PrintValues(self):
print(self.name)
print(self.age)
print(self.gender)
obj = Person("arjun",20,"male")
obj.PrintValues() |
4293730bc0abda70e94867df8dc9b399dabddab1 | agentnova/LuminarPython | /Luminaarpython/objectoriented/fileEmp.py | 585 | 3.59375 | 4 | class Employee:
def __init__(self,Eid,Ename,Designation,Salary):
# this method initialises instance variables
self.Eid=Eid # instance variable
self.Ename=Ename
self.Designation=Designation
self.Salary=Salary
def PrintValues(self):
print(self.Eid)
print(sel... |
751622e20718f568d69ce4faa8eda5881ebeb616 | agentnova/LuminarPython | /Luminaarpython/regex/validate Vehicle registr.py | 236 | 3.515625 | 4 | # validate all vehicle registration number
from re import *
rule='[Kk][Ll][0-9]{2}[a-z]{2}\d{4}'
regno=input("Enter the vehicle number :")
matcher=fullmatch(rule,regno)
if not matcher==None:
print("Valid")
else:
print("invalid") |
f6209d0d02b0f2cfcdd3d0cff3f0908c1fcf0ca7 | nshefeek/work | /snippets/digit.py | 602 | 3.59375 | 4 | '''
# Sample code to perform I/O:
name = raw_input() # Reading input from STDIN
print 'Hi, %s.' % name # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
'''
# Write your code here
import itertools
N = int(input())
digit = input().... |
4a04175c4580b1f1045f0697e6f2aaf43cabd164 | JSisques/Python-Toolbox | /Seccion 03 - Estructuras de datos/01-Listas.py | 2,418 | 4.59375 | 5 | '''
Una lista es una variable que contiene varios datos o variables de cualquier tipo
Se puede crear una lista vacia utilizando []
Los elementos de las tienen posiciones, siendo la primera posicion la 0 y la ultima la longitud de la lista menos 1
'''
miLista = ["Javi", "Perro", 6, True, 7.5]
listaVacia = []
'''
Para ... |
a309f848cc6480e61dab0cc08c5cda2cac0b890e | JSisques/Python-Toolbox | /Seccion 04 - Funciones/01-Funciones.py | 2,801 | 4.1875 | 4 | '''
Una funcion en programación es un tipo de sentencia que puede o no tener valores de entrada (parametros) y que puede devolver o no un valor de retorno
La sintaxis de los metodos o funciones es la siguiente: nombreMetodo(parametros separados por comas)
Ejemplos:
1. comprobarLetra(letra)
2. comprobarResultado... |
a056b7e665d164e1f6570b3b294dca15177c283b | cndaqiang/txt2dic | /Script/txt2dic.py | 678 | 3.734375 | 4 | #!/usr/bin/env python3
#-*- coding:utf-8 -*-
#本脚本参考自[使用python提取英文文章中的单词及出现的次数(原创)](http://www.51testing.com/html/53/61753-154953.html)
import re
import string
#输出文件
f = open("output.txt","w")
#输入文件
r = open("input.txt","r")
strs =r.read()
##使用正则表达式,把单词提出出来,并都修改为小写格式
s = re.findall("\w+",str.lower(strs))
#去除列表中的重复项,并排序
... |
5289dbd66d7481eb62f1b1394e8c0d1e6ed0fe97 | spmassey/code-bucket | /fizzbuzz.py | 369 | 3.5 | 4 | #!/usr/bin/python
for i in range(1,101):
stdout = ''
fizz = False
buzz = False
if i%3 == 0:
stdout += 'Fizz'
fizz = True
if i%5 == 0:
stdout += 'Buzz'
buzz = True
if fizz is False and buzz is False:
... |
9df458b078d535856d88f8eec3622634c5342c78 | zabcdefghijklmnopqrstuvwxy/AI-Study | /1.numpy/topic72/topic72.py | 99 | 3.546875 | 4 | import numpy as np
arr=np.arange(25,dtype=int).reshape(5,5)
arr[[0,1],] = arr[[1,0],]
print(arr) |
3a35fdabcdce00465003f0558e93a3c5c60200a7 | zabcdefghijklmnopqrstuvwxy/AI-Study | /1.numpy/topic41/topic41.py | 2,886 | 3.546875 | 4 |
#numpy.ufunc.reduce
#method
#ufunc.reduce(a, axis=0, dtype=None, out=None, keepdims=False, initial=<no value>, where=True)
#Reduces a’s dimension by one, by applying ufunc along one axis.
#Let a.shape = (N_0, ..., N_i, ..., N_{M-1}). Then ufunc.reduce(a, axis=i)[k_0, ..,k_{i-1}, k_{i+1}, .., k_{M-1}] = the result of... |
dac456345780fe6ced123598995a6e2285a89ef2 | zabcdefghijklmnopqrstuvwxy/AI-Study | /1.numpy/topic59/topic59.py | 1,558 | 4.4375 | 4 | #argsort(a, axis=-1, kind='quicksort', order=None)
# Returns the indices that would sort an array.
#
# Perform an indirect sort along the given axis using the algorithm specified
# by the `kind` keyword. It returns an array of indices of the same shape as
# `a` that index data along the given axis in so... |
06a0d9a7bae458a466f608057a2cf64c9bd1c17d | ryankuhle/unit2lesson1 | /stats.py | 1,591 | 3.640625 | 4 | #Needed imports: pandas and scipy.stats
import pandas as pd
from scipy.stats import mode
#Raw Data
data = '''Region,Alcohol,Tobacco
North,6.47,4.03
Yorkshire,6.13,3.76
Northeast,6.19,3.77
East Midlands,4.89,3.34
West Midlands,5.63,3.47
East Anglia,4.52,2.92
Southeast,5.89,3.20
Southwest,4.79,2.71
Wales,5.27,3.53
Scotl... |
70fe8989f68755f991c6a7196567c55185000442 | sharp-math-8/4-Inputs | /code.py | 153 | 3.96875 | 4 | # colelct the planet the user lives on
planet = input("What planet do you come from? >>>")
print( "Cool! I am from planet {} too!.".format( planet ) )
|
0add5d9bcab734baa48b5bfc76db3e12b8be0617 | pratikv06/Python-Practice | /Object Oriented/2_class.py | 850 | 4.1875 | 4 | class Dog():
def __init__(self, name, age):
''' Its like constructor - called when object is created (once)'''
# self - represent object of that instance
self.name = name
self.age = age
def get_name(self):
''' Display dog name'''
print("Name: " + self.... |
73a2a3f6faa7a252fdd0a626e041b76471fee615 | mutiantong/python | /_1_syntax_practice/_1_learning_pyhont_version4/-6 chapter/_6_1_reference_count.py | 1,527 | 3.78125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: 6-1-引用计数
Description :
Author : 'Sam Yong'
date: 2018/7/2
-------------------------------------------------
Change Activity:
2018/7/2:
--------------------------... |
e20fc581758a81bbf31eab53c665ad50df8fed3f | mutiantong/python | /_1_syntax_practice/_1_learning_pyhont_version4/-29 chapter_overwrite/_4_add_radd_iadd.py | 769 | 3.609375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: _4_add_radd_iadd
Description :
Author : 'Sam Yong'
date: 2018/7/16
-------------------------------------------------
Change Activity:
2018/7/16:
----------------... |
da80667c24d919c8891a4c8e2417d3b5fc96be13 | ohaz/adventofcode2020 | /day1/day1.py | 399 | 3.53125 | 4 | from file_reader import get_file_entries_numbers
from itertools import combinations
import math
def calculator(combination_size, filename='day1/input.txt'):
numbers = get_file_entries_numbers(filename)
for element in combinations(numbers, combination_size):
if sum(element) == 2020:
print(ma... |
16c4ec559a0b036dfaa71dd7078b3ce64a29600b | WilliamBrown42/kf-magicked-admin | /magicked_admin/chatbot/commands/command.py | 605 | 3.515625 | 4 | class Command:
"""
Abstract for creating commands. By default contains the functions (XYZ)
"""
def __init__(self, server, admin_only=True):
self.server = server
self.admin_only = admin_only
self.not_auth_message = "You're not authorised to use that command."
def authorise(se... |
8649cd8bba34972940868c0bd5201552ffc82158 | Yougigun/algorithem | /graph/depth_first_search.py | 405 | 3.890625 | 4 | visited = set()
def depth_first_search(graph,node):
if (node in visited): return
visited.add(node)
print(node)
for adjacent_node in graph[node]:
depth_first_search(graph,adjacent_node)
graph = dict()
graph["4"] = ["50","7"]
graph["50"] = ["55","90"]
graph["7"] = ["87","2"]
graph["55"] ... |
dd6d8e13564dc5e2c3d6565b634e60a49f966354 | Ahmad-Shafique/Python-Problem-Solving | /Problem solutions/3.py | 239 | 3.734375 | 4 |
def WhileInput(func):
while True:
i=input()
if(i!=os.linesep):
func(int(i))
else:
break
dictionary=dict()
def AddDictionaryItem(item):
dictionary[item] = item*item
WhileInput(AddDictionaryItem)
print(dictionary)
|
7c6c57a9003552e1fe24abc19980e8305df84b88 | Ahmad-Shafique/Python-Problem-Solving | /Problem solutions/13.py | 444 | 3.84375 | 4 |
def checkNumberOfDigits(string):
number = 0
for item in string:
if item.isdigit():
number +=1
return number
def checkNumberOfLetters(string):
number = 0
for item in string:
if item.isalpha():
number +=1
return number
def QuestionThiteen():
Input = input();
letters = checkNumberOfLetters(Input);
d... |
cdf4eab8a48fdb3a53b29b621af8fd9e6c3f62b1 | Ahmad-Shafique/Python-Problem-Solving | /Problem solutions/6.py | 242 | 3.546875 | 4 | def QuestionSix():
import math;
C=50;
H=30;
D=input();
inputList = []
result = []
inputList = D.split(',');
for item in inputList:
Q = math.sqrt((2*C*int(item))/H);
result.append(str(Q));
print(','.join(result));
QuestionSix() |
e8d33a1ece746205af79bc212c4533f33dc582b2 | Tianyu00/algorithms | /week2_algorithmic_warmup/6_last_digit_of_the_sum_of_fibonacci_numbers/fibonacci_sum_last_digit.py | 779 | 3.75 | 4 | # Uses python3
import sys
def fibonacci_sum_naive(n):
if n <= 2:
return n
fn = []
m = 10
fn.append(0)
fn.append(1)
fn.append(1)
while not((fn[-2] == fn[0]) & (fn[-1] == fn[1])):
fn.append( (fn[-1]+fn[-2]) % m)
del fn[-1]
del fn[-1]
length = len(fn)
return (su... |
4b3ae4110bf8ffed0dedab281d30289a7a95d6f9 | oliviamoyer/Projects | /Moyer_CreditCard.py | 2,968 | 3.765625 | 4 | # Olivia Moyer
# 001
# import
import datetime as dt
# define functions
def sumdigits(a):
try:
# sum of the first two digits of the cvv
total=int(a[0])+int(a[1])
return total
except:
False
# returns true if credit card number is 16 and doesn't start w/ 0
def cr... |
0bc0ba0eeb61705a5342d99647a415a742514926 | ebcitron/Algorithms | /stock_prices/stock_prices.py | 1,025 | 4.0625 | 4 | #!/usr/bin/python
import argparse
def find_max_profit(prices):
#Set max profit to nothing
maxProfit = None
#For every single price at i besides the last one, we compare price at i to each that comes after
for i in range(0, len(prices)-2):
#Here we find out the max profit possible from each selling point in... |
6843b8eb414082077e647f2918b88b97993671cb | DAM8/PythonMisc | /helloClass.py | 176 | 3.5 | 4 | class Dog():
def init(self, name):
self.name = name
def sit(self):
print(self.name +" is sitting")
my_dog = Dog()
print("my_dog is a great dog!")
#my_dog.sit() |
dac4d1019a59d9e67e1603c429d067d9871103c1 | stubhbw/python | /another/13.循环控制.py | 666 | 3.859375 | 4 | # 循环控制
# for循环 break continue return
import time
# else 在循环结束后调用
# 当程序非正常结束时ending不会执行
s = 'hello'
for k in s:
print(k)
# time.sleep(1)
else:
print("ending")
# 当break打断循环触发时不会走else
for k in s:
print(k)
if k == 'l':
break;
else:
print("ending")
# continue 跳过循环的后续代码块
for k in s:
if k... |
2005a7ed44d54d703930891b6b17ab555cc9da3b | zewuchen/data-analysis | /Funcoes Pandas/Logica CSV 11.py | 825 | 3.859375 | 4 | import pandas as pd
df = pd.read_csv("Logica CSV 09-12.csv")
homem = df.loc[df["gender"] == "male"]
hMax = homem["grade"].max()
hMin = homem["grade"].min()
homemMax = homem.loc[homem["grade"] == hMax]
homemMin = homem.loc[homem["grade"] == hMin]
mulher = df.loc[df["gender"] == "female"]
mMax = mulher["grade"].max... |
98d4688a1f84c738acc68c69f5cb09b88d208fcd | shtnk/Iteration | /Python/7-continue.py | 123 | 3.78125 | 4 | # There is no continue label in python
i = 0
while i < 10:
i += 1
print("Hello")
if i == 5:
continue
print("World")
|
37127d1c5443c98b47ad33c7ca105d6183b1d1c8 | marwin-ko/dsp | /python/q5_datetime.py | 1,240 | 3.625 | 4 | ###################################### Q5 ######################################
from datetime import date
def num_days(start,stop):
if '-' in start and stop:
start = start.split('-')
stop = stop.split('-')
if start[1].isalpha() and stop[1].isalpha():
start[1] = d[start[1]]
... |
4ee1f5c913ba7ab977969aca57ed2503afc94556 | jwepman/CSCI4448-HW4 | /playmaster/Week.py | 1,272 | 3.75 | 4 | #Week.py - week class handles keeping track of week data for a student
# Josh Wepman, joshua.wepman@colorado.edu and Kyle Poole, 2kylepoole@gmail.com
import datetime
import PlayObject
class Week(object):
myPlayList = set([]) #set of play objects to play
weekStartDate = None #this is a start date for the week, lastin... |
84755c76a8bc06efef4213fd5416da640e7265d2 | jwepman/CSCI4448-HW4 | /playmaster/PlayObject.py | 1,177 | 3.546875 | 4 | #PlayObject.py - parent class for PlayList and AssignmentList -- provides general specification for these objects to implement
#Josh Wepman, joshua.wepman@colorado.edu and Kyle Poole, 2kylepoole@gmail.com
import datetime
class PlayObject(object):
song = None #corresponding song
requiredPlayCount = 1
currentPlayCoun... |
b2190821036bc7ad34e06bf130afa517f1cb6b7c | sbhawesh/Python_datastructure | /SelectionSort.py | 257 | 3.5 | 4 | arr = [3,5,1,7,8,12,9,2,2,0]
for i in range(len(arr)):
min=arr[i]
l=i+1
for x in range(l,len(arr)) :
if(min>arr[x]):
min=arr[x]
index=x
if(min<arr[i]):
arr[index]=arr[i]
arr[i]=min
for j in range(0,len(arr)):
print(arr[j])
|
be6026566dac889bf5703eaa19addeaaa8101c5a | mfy-royce/51cto1 | /pythonds/algorithm300/q3.py | 5,858 | 3.5 | 4 | #!/usr/bin/python
# encoding: utf-8
"""
author:Royce
contact:mfy-111@163.com
@file: q3.py
@time: 19:49
@welcom to learn ai
"""
from pythonds.algorithm300.segtree import Segtree
class Solution():
def count_small_number(self, nums):
if len(nums) == 0:
return []
res = []
max_n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.