blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
9747b80f396d757bc2925703198d27d999377618 | KyeCook/PythonStudyMaterials | /LyndaStudy/LearningPython/Chapter 2/conditionals.py | 484 | 4.125 | 4 | ###########
#
#
# Conditional (if statements) statements introduction
#
#
###########
def main():
x, y = 1000, 100
# Conventional if statement
if(x < y):
st = "x is less than y"
elif(x == y):
st = "x is equal to y"
else:
st = "x is greater than y"
print(st)
# cond... |
c7566db58f00177620c8aca9646d1d7428146587 | rafaelperazzo/programacao-web | /moodledata/vpl_data/128/usersdata/215/44204/submittedfiles/al6.py | 126 | 3.78125 | 4 | # -*- coding: utf-8 -*-
num=int(input('digite n:'))
cont=0
for in range(2,n,1):
if n% i==0:
cont=cont+1
|
9f0e6907f18973c8bb602a879f26bac78c1131a7 | saralkbhagat/leetcode | /69.sqrtx.python3.py | 1,246 | 3.90625 | 4 | #
# [69] Sqrt(x)
#
# https://leetcode.com/problems/sqrtx/description/
#
# algorithms
# Easy (29.69%)
# Total Accepted: 286K
# Total Submissions: 963.3K
# Testcase Example: '4'
#
# Implement int sqrt(int x).
#
# Compute and return the square root of x, where x is guaranteed to be a
# non-negative inte... |
f60758df8380ac9c125ed5e34589da9289a67dfb | ngocthienta/pytest | /sad.py | 15,313 | 3.921875 | 4 | import math
import string
import pygame
pygame.init()
notes = ['a','b','c','d','e','f','g']
octaves = ['2','3','4','5']
conv = {'c#':'db','d#':'eb','f#':'gb','g#':'ab','a#':'bb'}
rm_val = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
def hello(name):
"""Prints a hello.
Takes one argument... |
e4f6a290432eea365f5b4199807eeeee6805de39 | lakshman-battini/Examples-from-Spark-The-Definitive-Guide | /code/Ch8-Joins.py | 12,481 | 4.375 | 4 | # Databricks notebook source
# A join brings together two sets of data, the left and the right, by comparing the value of one or more keys of the left and right and evaluating the result of a join expression that determines whether Spark should bring together the left set of data with the right set of data.
# The join... |
b66561e93f4c67b4e6a5958c54b9476b968e0b05 | shubam-garg/Python-Beginner | /Files_I/0/10_practice_test7.py | 251 | 3.90625 | 4 | # Write a program to find out the line no where python is present
log=True
i=1
with open("log_file.txt") as f:
while log:
log = f.readline()
if "python" in log.lower():
print(log)
print(f"{i}")
i+=1
|
7faacc2fd52ba6d7934d26fcf773c5b059ba8d82 | adamorin/BeginnerPython | /helloWorld.py | 1,546 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Python For Beginners Exercises
"""
# STRINGS
for j in range(1,5):
print(j)
x = 1
print("My number as a string is " + str(x))
#1
a = "cat"
v = "lettuce"
m = "quartz"
print("Here is an animal, vegetable, mineral:")
print(a,v,m)
print(a + "--" + v + "--" + m)
for ... |
7deaa755dc503cc19156d3cdffd8e0894101e6b7 | ameyp97/Auto-Mail | /noattachment.py | 1,608 | 3.53125 | 4 | #import libraries
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import json
#open json file to get sender and receiver details
with open("sample_json.JSON") as f:
data = json.load(f) #load all content of json file into data variable
sender=data['sender'] #sender ... |
04491e5413942bf0adc5a0c08b5091cca5cb7c94 | agcopenhaver/clusterpy-hd | /clusterpy/core/viz.py | 2,599 | 3.984375 | 4 | def showshape(shape, colorarray=None, colormap=None, alpha=None):
"""
Creates and displays a firgure for the given shape using Matplotlib
Parameters:
[Shape] is a Clusterpy layer.
[colorarray] is an array, with the same number of elements as areas in the
layer, that is used to categorize the areas a... |
e543b7e51b8bdedd05d6a0df5ee2fe730505c7d4 | chunmusic/datacamp_course_code | /Introduction to Deep Learning with PyTorch/ch1_exercises.py | 2,711 | 3.78125 | 4 | # Exercise_1
# Import torch
import torch
# Create random tensor of size 3 by 3
your_first_tensor = torch.rand(3, 3)
# Calculate the shape of the tensor
tensor_size = your_first_tensor.shape
# Print the values of the tensor and its shape
print(your_first_tensor)
print(tensor_size)
----------------------------------... |
e0dc04f8cff8c8220a5b7e26b7b7692f46b350ea | Rakeshgsekhar/code_practice_c_plus_plus | /codes/py/binearySearch.py | 739 | 3.9375 | 4 | def binerySearch(arr,searchElement,left,right):
if(left > right):
return False
mid = (right+left)//2
if arr[mid] == searchElement:
return True
elif searchElement < arr[mid]:
return binerySearch(arr,searchElement,left,mid-1)
else :
return binerySearch(arr,searchElemen... |
2b6e109c62b576b3647afa81c4df64927113ebb1 | pritam1997/python | /list_no.py | 164 | 3.8125 | 4 | n = int(input("Enter no. : "))
# like no. is 5
# printing 5 times and decrementing by 1 in loop (5-1)
l = []
for x in range(1,n+1):
l.append(x)
print(l)
|
8fc88ceac8e6ae719a57c6b3794793e05e75e119 | SebastienPoncelet/LeetCode | /stacks/155-min-stack.py | 2,015 | 3.9375 | 4 | # LINKED LIST SOLUTION --> NOT MOST EFFICIENT
# Runtime: 6036 ms, faster than 5.00% of Python3 online submissions for Min Stack.
# Memory Usage: 19.2 MB, less than 7.15% of Python3 online submissions for Min Stack.
class Node:
def __init__(self,data = None, next = None):
self.data = data
self.next... |
3b76106d49cbcda192261367116742843f88cba0 | mehranaman/Intro-to-computing-data-structures-and-algos- | /Assignments/Craps.py | 1,694 | 4 | 4 | #File: Craps.py
#Description: Computing the probabilty of winning at Craps.
#Name: Naman Mehra
#UTEID: nm26465
#Course name: CS303E
#Unique number: 51850
#Date created: Feb 24th, 2017
#Date last modified: Feb 24th, 2017
import random
def craps():
#starting the round- come out phase
m = random.randin... |
2517169cda62a42f0e3ceaa35fd879d481c4dc0d | petercort/ProjectEuler | /ProjectEuler/Problems/problem7.py | 616 | 3.953125 | 4 | ##By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
##What is the 10 001st prime number?
from ProjectEuler.Problems.problem3 import isPrime
def problem7Name() :
return "Problem 7"
def problem7Description() :
return "What is the 10,001st prime number?"
def probl... |
2e4692b47fa07e04e167aaeb7d0dbc3fcf76d592 | AmilyLightman/EE551-python-final-project | /code/taobao_test.py | 2,941 | 3.578125 | 4 | from selenium import webdriver
import time
import logging
import datetime
class AutoBuy(object):
logging.basicConfig()
def __init__(self):
self.driver = webdriver.Chrome()
self.name = "CARIEDO"
self.url = 'https://s.taobao.com'
self.buytime = "2019-11-30 11:00:00"
def my_i... |
1c828abe78bd1ff7f66a2909afd5b4232c224fec | UmansYou/py4e | /py4e_03/wk_06/wk_06_02.py | 770 | 3.546875 | 4 | import urllib.request, urllib.error, urllib.parse
import json
address = input("Enter a location: ")
serviceurl = 'http://py4e-data.dr-chuck.net/json?'
api_key = 42
parms = dict() # the dictionary is used to be a part the the URL later
parms['address'] = address
parms['key'] = api_key
url = serviceurl + urllib.parse... |
3dd68fa9403ce3e8926cdcdbcd737a56c681f5ff | Feedmemorekurama/py_course_bernadska | /homework_bernadska/hw_10/hello_users.py | 274 | 4 | 4 | roles = {
"admin": 'Markus',
"maintainer": 'Bobby',
"manager": 'Garry',
"developer": 'Carlos'}
name = input("My name is, ")
for role, names in roles.items():
if name in names:
print(f"Hello, {role}")
break
else:
print("Hello, Guess") |
2fa3af45d3bdc2ddbd90b602fd53a4b464c71d47 | Filipate/DataScienceJUN | /WEEK_4/day1/delivery/my_visualizing_functions_module.py | 1,575 | 3.828125 | 4 | # This file represents your module.
# Write the code...
"""
Limpiar caracteres y espacios de una lista desordenada. Para que una lista de cadenas sea uniforme
y esté lista para el análisis: eliminar espacios en blanco, eliminar símbolos de puntuación
y estandarizar el uso apropiado de mayúsculas
"""
import re
def cl... |
c22504251045429e753c47ac1d66d1052804cf30 | MurilloFagundesAS/Exercicios-ProgramacaoII-FATEC-2020-1 | /MatrizSomaMediaInversa/MatrizSomaMediaInversa.py | 526 | 3.578125 | 4 | matriz = []
for i in range(0, 20):
x = int(input('Acrescente um número para a Matriz: '))
matriz.append(x)
matriz.reverse()
soma = 0
media = 0
contador = 0
invertido = []
for item in matriz:
lista = []
lista.append(item)
soma += item
lista.append(soma)
contador+=1
media = soma / con... |
714a4366664a64f0dbbd1e68855160eae66e79c9 | Laura-Galeano/InteligenciaArtificial | /Perceptron/Perceptron.py | 2,966 | 4.25 | 4 | #Partimos con la implementación del perceptron en una clase independiente que luego entrenaremos.
# Para este ejemplo me basé en la implementación de Sebastian Raschka en el libro "Python Machine Learning".
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
class Perceptron:
"""Clasi... |
9f7160354916d2718edb90a03b8fa82ece7515bf | MariaJoseOrtiz/MasterPython | /07-Ejercicios/ejercicio7.py | 472 | 3.96875 | 4 | """
Ejercicio 7.
Hacer un programa que muestre todos los numeros impares
enre dos numero que decida el usuario
"""
numero1 = int(input("Introduzca el primer numero: "))
numero2= int(input("Introduzca el segundo numero: "))
if(numero1 < numero2):
for contador in range(numero1,numero2+1):
if contador % 2 ... |
719e3ec7b3ee01fb4bb6646a51240d6451583777 | louisraccoon/PyStudy | /chat_interface_func_tkinter.py | 508 | 3.515625 | 4 | from tkinter import *
#tkinter gui function
def FilteredMessage(EntryText):
"""
Filter out all useless white lines at the end of a string,
returns a new, beautifully filtered string.
"""
EndFiltered = ''
for i in range(len(EntryText)-1,-1,-1):
if EntryText[i]!='\n':
EndFilte... |
8f4af0690526d9b353fa3c6a07ac9e4fc2a3c156 | PedroGal1234/Unit3 | /changeComputer.py | 643 | 3.875 | 4 | #Pedro Gallino
#9/29/17
#changeComputer.py - tells the number change in coins
total = int(input('Enter the number of cents you need to give in cents: '))
q = 0
d = 0
n = 0
p = 0
while q < total:
q = q + 25
if q > total:
q = q-25
break
total = total - q
while d < total:
d = d + 10
if d... |
03cb382f5cdd0b5ed367c0969eb5850fca530ca0 | EunjuYang/algo-python | /insertionsort.py | 877 | 4.46875 | 4 | """
This code is written for education
Naive implementation of the algorithm
Algorithm1: Insertion Sort
"""
import pandas as pd
def main():
# Read input .txt file
data = pd.read_csv('./input.csv')
data = list(map(int, data.columns))
# Insertion sort O(n^2)
# iterate for key
# O(n) for this l... |
98911b1561445a0e39c13e62702adc5f24da70f2 | virajs/codeeval | /1-moderate/to-pi-or-not-to-pi/main1.py | 830 | 3.5 | 4 | import sys
# http://stackoverflow.com/questions/9004789/1000-digits-of-pi-in-python
def make_pi():
q, r, t, k, m, x = 1, 0, 1, 1, 3, 3
for j in range(21604): # experimentation to determine the loop value needed for 5k digits.
if 4 * q + r - t < m * t:
yield m
q, r, t, k, m, x =... |
57825d9597b4f739e8b82868a61fa049cf5de263 | ArchibaldChain/python-workspace | /CondaProject/DeepLearningStudy/cross_entropy.py | 606 | 3.921875 | 4 | import numpy as np
import math
# Write a function that takes as input two lists Y, P,
# and returns the float corresponding to their cross-entropy.
'''Below is the method that is thought by myself'''
# def cross_entropy(Y, P):
# crossEntropy = 0
# for i in range(len(Y)):
# crossEntropy -= Y[... |
822265b5cc6716b32270bff0077597a84798f0bc | aureliewouy/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/tests/test_models/test_square.py | 2,189 | 3.8125 | 4 | #!/usr/bin/python3
"""
Unittest for the Square class
"""
import unittest
from models.square import Square
class TestSquare(unittest.TestCase):
"""
Test for the Square class with unittest
"""
def test_size(self):
"""
Test initialize the class Square with the size
"""
tes... |
0121603989b32b5825aadf80ccfc26c81986688a | ALShum/leetcode | /0872-leaf_similar_trees.py | 1,180 | 3.875 | 4 | # DFS through recursion or iteratively
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool:
#l1 = self.getLeavesRecu... |
0dab62c4f44fdbf3f37b4098fa5fb21734051417 | LeonardoRichie/Jerryclass | /Jerry'sClass001.py | 272 | 3.90625 | 4 | x = int(input("input an integer value:"))
if x % 11 == 0:
print("a", end=" ")
if x % 9 == 0:
print("b", end=" ")
if x % 7 == 0:
print("c", end=" ")
if x % 2 == 0:
print("d", end=" ")
if x % 11 > 0 and x % 9 > 0 and x % 7 > 0 and x % 2 > 0:
print("e")
|
1bd5b5ebf063caf76c81a81169dedf635797f14d | tchaikousky/rpg-starter | /rpg-1.py | 2,278 | 3.78125 | 4 | import random
class Hero(Character):
# hero_health = 0
# hero_power = 0
def __init__(self):
self.health = random.randint(10, 15)
self.power = round(self.health/2)
# hero_health = self.health
# hero_power = self.power
def hero_attack(self, goblin):
goblin.health... |
5112f1358474603de2d2d4ca7f70ebd7507b4d93 | Yara7L/python_algorithm | /leetcode/39_stack.py | 2,168 | 4.1875 | 4 | # 设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
#
# push(x) -- 将元素x推入栈中。
# pop() -- 删除栈顶的元素。
# top() -- 获取栈顶元素。
# getMin() -- 检索栈中的最小元素。
# 示例:
# MinStack minStack = new MinStack();
# minStack.push(-2);
# minStack.push(0);
# minStack.push(-3);
# minStack.getMin(); --> 返回 -3.
# minStack.pop();
# minStack.top(); --> 返回... |
6ec1bf6f1697ccab34345253193aaa0b231edc13 | andrey-justo/offensive-content | /offensive_words.py | 1,587 | 3.71875 | 4 | # -*- coding: utf-8 -*-
'''
Created on Dec 7, 2016
@author: andrey.justo
Here we are using NLP to count all bad words from text
Also we use OneClassSVM to classify if the text belongs to the offensive phrase categorization or not.
You can see more about this classifier in http://scikit-learn.org/stable/auto_example... |
0caa26937e938984d31a4d38efbdde5327c7cfec | vabbybansal/Java | /Others/codes/TODO DP_7 743. Network Delay Time.py | 7,194 | 3.75 | 4 | # DP
# Learning : Use Djikstra's simply using heap
# There are N network nodes, labelled 1 to N.
#
# Given times, a list of travel times as directed edges times[i] = (u, v, w), where u is the source node, v is the target node, and w is the time it takes for a signal to travel from source to target.
#
# Now, we send ... |
92b3d4b537b9c8fcc091cb768fdfa1e5a6a7e4de | TEnders64/OnlinePython_Lectures | /archive/oop_demo.py | 1,370 | 3.796875 | 4 | cat = {}
cat['name'] = "Oscar"
cat['legs'] = 4
cat['fur'] = True
cat['color'] = "Black"
cat['food'] = "All the wildlife"
class Mammal(object):
def __init__(self):
self.breathes = True
self.fur = True
self.limbs = 4
self.hp = 50
def walk(self, w=1):
if w != 1:
print '\nmoving in a walking motion' * w
... |
5c5c38b44d3ca6b2510e36eec90c4609c72a324e | Asgavar/things | /codefights/arcade/intro/smooth_sailing/12_sort_by_height.py | 291 | 3.8125 | 4 | def sortByHeight(a):
heights = []
for person_or_tree in a:
if not person_or_tree == -1:
heights.append(person_or_tree)
heights.sort(reverse=True)
for index in range(len(a)):
if not a[index] == -1:
a[index] = heights.pop()
return a
|
97473b610925c9eaeaf6e82d08e9ff4ed857ba8b | savva-kotov/coursera-python-basics | /Система линейных уравнений - 1.py | 1,268 | 4.0625 | 4 | """
Даны вещественные числа a, b, c, d, e, f. Известно, что система линейных уравнений:
ax + by = e
cx + dy = f
имеет ровно одно решение. Выведите два числа x и y, являющиеся решением этой системы.
Формат ввода
Вводятся шесть чисел a, b, c, d, e, f
- коэффициенты уравнений системы.
Формат вывода
Выведите ответ на зад... |
a29646a192e104f0f0dec6c92a338640cbf78dcf | ChrisCooper/mostly-benevolent-infection | /models.py | 1,218 | 3.765625 | 4 | import fun
class User(object):
"""
A basic user with site version, email, and coaching relationships.
Relationships are stored as sets.
"""
def __init__(self):
self.email = fun.cool_email()
# Site version is a simple integer
self._site_version = 1
# The users th... |
becf1ac5cfe43d5d63264fe1397f32510aa9f5ce | devrihartle/sprintchallenge3.2 | /northwind.py | 1,034 | 4.03125 | 4 | import sqlite3
# create a connection
conn = sqlite3.connect('northwind_small.sqlite3')
# create a cursor
curs = conn.cursor()
# query to find 10 most expensive items in the database
expensive_items = """
SELECT *
FROM Product
ORDER BY UnitPrice DESC
LIMIT 10;
"""
# query to find average age of an employee at hire t... |
e0dc551793cf2516742a4c0f63079b9b55f6d5ac | sujitkc/automated-evaluation | /data/dsa/et/eoauiflm.py | 4,438 | 3.703125 | 4 | class Heap:
def __init__(self, size, default, marked = {}):
self.pos = [i for i in range(size)]
self.heap = [[i, default] for i in range(size)]
# print self.heap
self.size = size
def parent(self, n):
return (n-1)/2
def left(self, n):
return 2*n + 1
def... |
4b56336923660443fb8fe9c0820d0d8fd30f284b | sayantann11/Automation-scripts | /website_blocker/website_blocker.py | 3,386 | 3.578125 | 4 | import ctypes
import sys
from sys import platform
import os
from os import system
from elevate import elevate
class Blocker:
hosts_path = ''
redirect = "127.0.0.1"
website_list = []
os_number = 0
exit_blocker = False
def __init__(self, path, os_num):
self.hosts_path = r"" + path
... |
f41368216df190babca3d455fb768152036af9f8 | eakehun/macro | /mouseTest.py | 1,447 | 3.53125 | 4 | import mouse
from pynput.mouse import Button, Controller
import time
import pyautogui
# import time
# from pynput import mouse
# def on_click(x, y, button, pressed):
# if pressed == True:
# print(x,y)
# with mouse.Listener(on_click=on_click) as listener:
# listener.join()
# target
# x=384, y=150 ~... |
0366c00b2cbdd546f7da3ba9e8611dba308fd486 | CSemper/Optimise | /graphics.py | 5,715 | 3.890625 | 4 | # This is a program working as an Application Tracking System
from tkinter import Tk, Button, Label, END, Text, Checkbutton, IntVar, RIGHT
from tkmacosx import Button
import tkinter.font as tkFont
from main import red_list, yellow_list, green_list, answers_list
from datetime import date
#Now start creating the actual... |
9d68336cd46d75db659cced078c97ebc340db9de | TBernard97/MA_440_Project | /Algorithms/appr.py | 760 | 3.734375 | 4 | #REFERENCE https://stackabuse.com/association-rule-mining-via-apriori-algorithm-in-python/
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from apyori import apriori
uni_data = pd.read_csv('../Data/For-Profit-NOM.csv')
records = []
for i in range(0,42):
records.append([str(uni_data.valu... |
42c24711d447d4f7d422c995dc5dca7920c19df5 | localsnet/Python-Learn | /PCC/ch4/410slices.py | 323 | 4.46875 | 4 | #!/usr/bin/python3
pizzas=('Alando','Santiago','Borimo','Corsica')
print('The first three items in the list are: '+ str(pizzas[:3]))
print('Two items from the middle of the list are: '+ str(pizzas[1:3]))
print('The last three items in the list are: '+ str(pizzas[-3:]))
print(' Exclude the last item: '+ str(pizzas[:-1]... |
d2507bdf774a6c1c3ce5a1cd41ea0f451ced1acc | Daimond1900/mpython | /coding/def_study.py | 300 | 3.515625 | 4 | #函数实例
def add_num(a,b=10):
'''两个数字相加 '''
if str(type(a)) == "<class 'int'>" and str(type(b)) == "<class 'int'>" :
return a + b
else:
return None
addResult = add_num(1)
if addResult != None:
print(addResult)
else:
print('参数类型错误')
print(add_num.__doc__)
|
c9a801b3f475591890397bc8b81512979cc3393a | christine2623/Mao | /Standard deviation and correlation.py | 15,056 | 4.25 | 4 | # The Mean As The Center
"""
Interesting property about the mean:
If we subtract the mean of a set of numbers from each of the numbers, the differences will always add up to zero.
This is because the mean is the "center" of the data.
"""
# Make a list of values
import numpy
values = [2, 4, 5, -1, 0, 10, 8, 9]
# Compu... |
bb3798165a920fb5d2ab96441a994db402f58b29 | ArrayZoneYour/LeetCode | /043/Multiply Strings.py | 740 | 3.78125 | 4 | # /usr/bin/python
# coding: utf-8
class Solution:
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
result = 0
nums1 = []
nums2 = []
factor = 1
for el in num1[::-1]:
nums1.append((ord(el) ... |
f445a4cb0c9379deefcbef9892aa40160591e1e4 | ckkhandare/mini_python_part2 | /SET.py | 1,845 | 4.21875 | 4 | # set T is the base set
names=input("Enter in names separated by a comma: ")
splt= names.split(",")
t=set()
for i in splt:
t.add(i)
while True:
print("""\n1. delete element if exists otherwise do not show any errr""")
print("2. add a elemet")
print("3. create one more set")
print("4. union of 2... |
722c64ae6e05e792c90e3dce74f7190273b76a1a | dynotw/Leetcode-Lintcode | /LeetCode/101. Symmetric Tree.py | 1,848 | 4.21875 | 4 | # Question:
# Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
# For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
# 1
# / \
# 2 2
# / \ / \
# 3 4 4 3
# But the following [1,2,2,null,3,null,3] is not:
# 1
# / \
# 2 2
# \ \
# 3 ... |
74382ba40ca5c9a66582230734b215fc7735a421 | LennartElbe/codeEvo | /StudentProblem/10.21.11.8/3/1569572591.py | 737 | 3.703125 | 4 | import functools
import typing
import string
import random
import pytest
def leap(x: int):
"""Checks if a given year is a leap year(after 1582).
Args:
x: int(a year)
Returns:
True or False(or an exception).
"""
if x < 1582:
return("The gregorian calendar wasn'n inve... |
c5662ba44d3615e23866a049997eb88605bd8be0 | hwolff00/structs_algo | /sort_search/bubble_sort.py | 624 | 3.703125 | 4 | """Bubble Sort.
This is my life now. Why has my creator chosen this for me? Why have I
chosen this for myself?
O(N^2) quadratic runtime"""
class BubbleSort:
def __init__(self, nums):
self.nums = nums
def sort(self):
for i in range(len(self.nums)-1):
for j in range(len(se... |
86f1d55f0daca1e078444a311a68c3b6f91d5bf0 | sanghaisubham/Python_Codes | /Tic_Tac_Toe(2 Player).py | 5,993 | 3.90625 | 4 |
#Input The Symbol
def inputSymbol():
print('So select your Symbol -> X or O')
symbol=raw_input().upper()
while not(symbol=='X' or symbol=='O'):
print('So select your Symbol -> X or O')
symbol=raw_input().upper()
if symbol=='X':
return 'X'
else:
return 'O'
#Printing THE Board
def printboard(Boar... |
c0761c9b1e4997a4ab55ff839719f2ca958c8b69 | LeandroGelain/PersonalGit | /2018-2019/Aulas_Algoritmos_avançados/calculos.py | 1,273 | 3.84375 | 4 | class calcular(object):
def __init__(self):
pass
@classmethod
def fatorial(self, numero):
if numero == 0:
return 1
return numero * self.fatorial(numero-1)
@classmethod
def fibonacci(self, numero_elemento):
if numero_elemento <= 2:
return... |
09d7e35c9847559610d728f7c1602d0876331336 | jonastoussaint/Python-Tictactoe | /TicTacToe_JT.py | 9,361 | 3.984375 | 4 | '''''
Author: Jonas Toussaint
Assignment: Asignment 7
Purpose: Create a python tic-tac-toe game program using loops
and functions
'''
#import
import os
import time
import random
#Define the board
board = ["", " ", " ", " ", " ", " ", " ", " ", " ", " " , " ", " ", " ", " ", " ", " ", " "]
x = 0
y = 0
o = 0
ca =0
ans... |
bb60d6c06af6876ccd921e3e92a4852dbf3e59ea | starkizard/CrudeCode | /Codeforces/Practice/A2oJ Ladders/Ladder #14/Presents.py | 319 | 3.625 | 4 | # author: starkizard
# storing all in a mapping, checking from 1 to n , and printing
# checking for an element in maps take o(1) averagely
# sorting the dictionary (map) and then printing all the values
input()
n=list(map(int,input().split()))
d={}
c=1
for i in n:
d[i]=c
c+=1
print(*[d[i] for i in sorted(d)])
|
2aca4c07bcc0a66fb66c21352b99508dd1694894 | SHUHAIB-AREEKKAN/anand_python_solutions | /functional_pgm_ch6/problem1.py | 305 | 4.3125 | 4 | # anand python problem 1 6:1
# Implement a function product to multiply 2 numbers recursively using + and - operators only.
def multiply(x,y):
if x == 1 :
return y
elif y==1:
return x
elif x==0 or y==0:
return 0
else:
return x+multiply(x,y-1)
if __name__ == '__main__':
print multiply(8,4)
|
b44dbc3dda48fbbdad28841e99fd1631fc345e24 | vidhi1308/sig-python-tasks | /module_3/gcd.py | 280 | 3.578125 | 4 | print("name - VIDHI SHARMA roll no - 1900300100242")
print("enter first no")
x = int(input())
print("enter second no")
y = int(input())
if x>y:
small=y
else:
small=x
for i in range(1,small+1):
if((x%i==0)and(y%i==0)):
gcd=i
print("gcd = ", gcd)
|
7b4c68e2c90a90bd124a411964208185504c3aa7 | someshwarduggirala/itp-u4-c2-hangman-game | /hangman/game.py | 2,025 | 3.578125 | 4 | from .exceptions import *
import random
# Complete with your own, just for fun :)
LIST_OF_WORDS = ["rmotr","python","code"]
def _get_random_word(list_of_words):
if list_of_words:
return random.choice(list_of_words)
raise InvalidListOfWordsException ()
def _mask_word(word):
if word:
... |
23e9359994eab418028f0fd3368be94330e74441 | AnthonyQ98/Parallel-Lists-With-Python-College-Work | /Lab2.py | 2,006 | 3.84375 | 4 | """
Anthony Quinn
X00138635
01/02/2021
1D Lists - Lab 2
"""
salesmen_name = []
total_salesmen_sales = []
kitchen_counter = 1
total_sales = 0
overall_sales = 0
threshold_commission = 50000
commission_value = .15
total_commission = 0
print("-" * 50, "\n\t\t\tKitchen Sales System\n\n", "-" * 50)
number_of_salesmen = ... |
e3c0a580d012d2212b8b7ec190b2a261e25d4cf6 | jorgeso/test-robot | /servo.py | 2,966 | 3.6875 | 4 | #This gives us control of the Raspberry Pi's pins.
import RPi.GPIO as GPIO
# This is only used for time delays... standard Python stuff.
import time
# tell Pi which pin numbers we'll be using ot refer to the GPIO pins
# we will use the physical pin ordering
GPIO.setmode(GPIO.BOARD)
# We will tell the Broadcom CPU wh... |
870b283bebc0a193e1029513743ecffcd9f3ad71 | NilsahC/GlobalAIHubPythonCourse | /Homeworks/Homework 1.py | 532 | 4.21875 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Homework 1 question 1
# In[3]:
my_list = [1,3,5,7,9,11]
len(my_list)
# In[4]:
my_list_fh = my_list[0:3]
print(my_list_fh)
my_list_sh = my_list[3:6]
print(my_list_sh)
# In[5]:
my_list_sh.extend(my_list_fh)
print(my_list_sh)
# In[6]:
my_list = my_list_sh
print(my_... |
e024d61cdbb9610b6f02483047f06b4e60db85a5 | Wangjunling1/leetcode-learn | /python/721.py | 779 | 3.5 | 4 | # test=[["John", "johnsmith@mail.com", "john00@mail.com"], ["John", "johnnybravo@mail.com"], ["John", "johnsmith@mail.com", "john_newyork@mail.com"], ["Mary", "mary@mail.com"]]
test=[["David","David0@m.co","David1@m.co"],["David","David3@m.co","David4@m.co"],["David","David4@m.co","David5@m.co"],["David","David2@m.co",... |
8bf44c4718c44c230b4cac4d0fc5589c0313e31b | lexatnet/school | /python/17-pygame/01-ball/05-collision/engine/collision.py | 2,246 | 3.5 | 4 | def ball_to_box_collision(ball, box):
return {
'x': ball_to_box_collision_x(ball, box),
'y': ball_to_box_collision_y(ball, box)
}
def ball_to_box_collision_x(ball, box):
width = box['size']['width']
height = box['size']['height']
if (ball['rect'].left < 0) or (ball['rect'].right > width):
return... |
e8bc0dd04e4f5dad979d40013979eb08f1f33222 | funcube/wr | /abc.py | 822 | 3.75 | 4 | # tkinter 的 下拉式選單
import tkinter as tk
from tkinter import filedialog
from tkinter import ttk
window = tk.Tk()
window.title('這個是我的第一個視窗表')
window.geometry('500x300')
labelTop = tk.Label(window,text = '選擇你最愛的月份')
labelTop.grid(column=0, row=0)
comboExample = ttk.Combobox(window,
valu... |
c923097fbff045e992419bf03ffa508afd5faa14 | wangxuyongkang/1808 | /11day/输入字典.py | 260 | 3.8125 | 4 | lisa = []
for i in range(2):
d = {}
name = input("请输入名字")
sex = input("请输入性别")
age = input("请输入年龄")
d["name"] = name
d["sex"] = sex
d["age"] = age
lisa.append(d)
print(lisa)
for i in lisa:
for j in i.valuse():
print(j)
|
4264320ca25234489b08950249597b371cce9e81 | Frycu128/code-B | /Instrukcje sterujące/Podsumowanie.py | 2,358 | 3.953125 | 4 | # 1. Pozwól użytkownikowi wprowadzić dowolną liczbę imion ciągiem
# (np.jako jeden string rozdzielonych przecinkiem lub białym znakiem). Następnie powitaj każdą osobę na liście.
names = input('Wpisz kilka imion rozdielonych przecinkiem:')
names = names.replace(' ','').split(',')
for n in names:
print('Hello'... |
630e177dd93998f5e0ba6c6f81bd234b64c4d1ca | arffe/languages | /python/ball.py | 454 | 3.75 | 4 | #!/usr/bin/env python
class Ball:
def __init__(self, colour, size, direction):
self.colour = colour
self.size = size
self.direction = direction
def __str__(self):
msg = "I am now a " + self.size + ", " + self.colour + " ball"
return msg
def bounce(self):
if... |
d4318ddb5b1bc3706c2f94f4b9827d8007a9365c | vivekdhayaal/first-repo | /aoi/algorithms_data_structures/bin_search_tree.py | 1,901 | 4.09375 | 4 |
class BTreeNode:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def insert(root, value):
if root is None:
root = BTreeNode(value)
else:
if value < root.value:
if root.left is None:
root.left = BTreeNode(value)
els... |
8dd2a37f1637fa9323e52e53c483dcaf91cec1a9 | ongunbosnak/GlobalAIhubPythonHomeworks | /day_5_FinalHomework.py | 3,061 | 4.21875 | 4 | #Homework
#Create a Simple Student Management System:
# -One student must enter their name and surname.
# -A student who enter name and surname correctly should write "welcome" on the screen with print.
# The Student has the right to enter his/her name and surname incorrectly 3 times. For more than
# 3 inccorec... |
ad818c58e519f2b97dad6e6b923b5193dd2cf248 | TheJediCode/DOOM-Python | /doom2.py | 23,879 | 3.890625 | 4 | import time
import random
items = []
neighbor = random.choice(["Carmack", "John", "Romero"])
def print_p(message):
print(message)
time.sleep(2)
def play_again():
response = valid_input("\n\nPlay again? " "Yes or no\n", "yes", "no")
if "yes" in response:
game()
def valid_input(prompt, opti... |
3ea65bfb06680614dd84028443ac07ff92540164 | mosestembula/andelabs | /datatypes.py | 1,015 | 4.5625 | 5 | # this is a function testing different data types
# For strings, return its length.
# For None return string 'no value'
# For booleans return the boolean
# For integers return a string showing how it compares to hundred e.g. For numbers less than 100 eg 67, it returns 'less than 100' for numbers greater than 100 eg 403... |
cb77226e03260cd0e3cd497b7b173b00e44fd8d9 | Badhreesh/Digit-Recognizer | /utils.py | 3,430 | 3.71875 | 4 | # General imports
import numpy as np
import base64
import cv2
import math
from scipy import ndimage
def data_uri_to_cv2_img(uri):
"""
Convert a data URL to an OpenCV image
Credit: https://stackoverflow.com/a/54205640/2415512
: param uri : data URI representing a BW image
: returns : OpenCV image
... |
b033303891f52ba37e7005a7bace02ceae3228e6 | sp2013/prproject | /Assgn/kMeans_Clustering.py | 2,704 | 3.59375 | 4 | '''
kMeans_Clustering.py
Steps:
1. Select ‘c’ cluster centers.
2. Calculate the distance between each data point and cluster centers.
3. Assign the data point to the cluster center whose distance from the cluster center is minimum of all
the cluster centers..
4. Recalculate the new cluste... |
1c8d8dca60cfbfd24f8671a6cd29fc0c3b65772c | mivazq/Exercise_06 | /module.py | 3,245 | 3.859375 | 4 | from moduleElement import *
class Module(object):
module_count = 0
def __init__(self,ects,title,semester,grade=None):
"constructor for class module"
self.ects = ects
self.grade = grade
self.title = title
self.semester = semester
self.dates = []
self.... |
e565bb8477834422f684d90efa1feb3e47533450 | kevintoney/STATS-and-DATA-Science-Projects | /Spark/popular-movies-nicer.py | 1,285 | 3.515625 | 4 | from pyspark import SparkConf, SparkContext
def loadMovieNames():
movieNames = {}
with open("C:/SparkCourse/ml-100k/u.ITEM") as f:
for line in f:
fields = line.split('|')
movieNames[int(fields[0])] = fields[1]
return movieNames
#load movie names function by creating an empty... |
d3af74a8eb5cc316d5ee114e363ef536ef19fcfc | wooseong-dev/python | /python/exam_calculator(GUI version).py | 330 | 3.71875 | 4 |
'''import tkinter
w_calc = tkinter.Tk()
w_calc.title("GUI Calculator")
#tkinter.Label(w_calc, text="Calculator",borderwidth=300,pady=200,padx=100)
w_calc.mainloop()'''
import os
while True:
num = input("계산식 입력 >> ")
print("result : {}".format(eval(num)))
os.system("pause")
|
9c2c610cb52471e12ea4dcdc95f06195cc3562b3 | jamestylerwarren/python.dev | /MovieRental/open_file.py | 300 | 4.03125 | 4 | # ---- how to open and write/read to a file --- #
#always need to close a file that is opened
#open file and write ('w'), read ('r'), etc to a file
#open construct automatically closes file, no need for f.close
with open('my_file.txt', 'r') as f:
#f.write("hello world")
print(f.readline()) |
c3c961f75d52526bd21a54a24e3ea6d80f2a6a44 | catter-unprg28/t7_Catter.Llamo | /Catter/while3.py | 363 | 3.546875 | 4 | #ingresar los sueldos de n trabajadores y calcular su sueldo de acuerdo a las horas trabajadas y la
#tarifa de pago que es 20 soles
n=int(input("ingrese cantidad de trabajadores: "))
for i in range(n):
ht=int(input("ingrese horas trabajadas: "))
if(ht==0):
print("sueldo: 0")
else:
sueldo=ht... |
a4d6ab643e14f8361c9a7271911ba979f216114f | kittttttan/pe | /py/pe/primes.py | 1,792 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
from math import log
class Primes:
def __init__(self, limit=100000):
primes = sieve(limit)
self.max_prime = primes[-1]
self.primes = primes
self.prime_set = set(primes)
def __getitem__(self, index):
... |
a35fdd5087355266dcecca422be14bf4e419bad3 | KimYeong-su/algorithms | /D02/search_seq.py | 504 | 3.703125 | 4 | # a : 배열
# n : 배열의 길이
# key : 찾고자 하는 수
def seqSearch(a,n,key):
i = 0
while i<n and a[i] != key:
i += 1
if i < n: return i
else: return -1
arr = [4,9,11,23,2,19,7]
print(seqSearch(arr,len(arr),2))
print(seqSearch(arr,len(arr),55555))
def seqSearch2(a,n,key):
i = 0
while i<n and a[i]<... |
1bbc2e6a1bc175bbfd484aed4c2fe4bc10937638 | yanasobolieva/Lesson-4-Homework | /FirstTask.py | 830 | 4.3125 | 4 | # First approach with using slice
def reverse_with_slice_function(some_word):
return some_word[::-1]
my_first_result = reverse_with_slice_function("ecnalubma")
print(my_first_result)
# Second approach with using loop
def reverse_with_loop_function(some_string):
reversed_list_from_string = []
index = len... |
a8a666bd5268c1aa59e637c40198b33ecdcb51df | rritec/Trainings | /01 DS ML DL NLP and AI With Python Lab Copy/02 Lab Data/Python/Py29_5_Generators_expression_to_read_items.py | 335 | 4 | 4 | # Create generator object: result
result = (num for num in range(10))
print("***** 01 First 5 values of generator ***** ")
print(next(result))
print(next(result))
print(next(result))
print(next(result))
print(next(result))
print("***** 02 Print the rest of the values using for Loop *****")
for value in result:
pri... |
3a52b136f45cc7066660d8e5e45ef279c7b8f4de | Ursinus-IDS301-S2020/Week9Class | /Iliad.py | 657 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Purpose: Show how to make parallel arrays of the
keys/values in a dictionary and to use armax
on the values to index into the keys
"""
import numpy as np
fin = open("Iliad.txt", "r")
iliad_text = fin.read()
fin.close()
iliad_text = iliad_text.lower()
counts_dict = {} # key is ... |
66db6c2b91e18153ff348177a382a7a5fcd1526e | ajschumacher/generalizedCompiler | /core/global_obj.py | 1,070 | 3.84375 | 4 | class python_list_obj:
def __init__(self,name):
self.name = name
self.obj = []
def append(self,item):
self.obj.append(item)
def sort(self):
self.obj.sort()
def pop(self):
return self.obj.pop()
def remove(self,item):
self.obj.remove(item)
def revers... |
57d76d5b560dea060b4598e23d12a7e00b659d68 | mnw247/Python | /python_stack/python_fundamentals/FunctionsIntermediate1.py | 741 | 3.984375 | 4 | # randInt() returns a random integer between 0 to 100
import random
def randInt():
x = 0
x = int(random.random()*101)
return x
y = randInt()
print (y)
# randInt(max=50) returns a random integer between 0 to 50
import random
def randInt(max=51):
x = 0
x = int(random.random()*max)
return x
y = ra... |
2d258a2dbfdb96b1cdd69cac065765ba83f2b431 | makrandp/python-practice | /LeetCode/Solved/Hard/ConsecutiveNumbersSum.py | 1,285 | 3.78125 | 4 | '''
829. Consecutive Numbers Sum
Given a positive integer N, how many ways can we write it as a sum of consecutive positive integers?
Example 1:
Input: 5
Output: 2
Explanation: 5 = 5 = 2 + 3
Example 2:
Input: 9
Output: 3
Explanation: 9 = 9 = 4 + 5 = 2 + 3 + 4
Example 3:
Input: 15
Output: 4
Explanation: 15 = 15 = 8... |
9bb63bc21df4e4d25e217bdd1f4df3f0f6020f33 | snowbar/atcoder_abc | /python/abc194/abc194_b.py | 1,569 | 3.515625 | 4 | class Employee_A:
def __init__(self, a, b):
self.a = a
self.b = b
def get_sum(self):
return self.a + self.b
def get_a(self):
return self.a
def get_b(self):
return self.b
def __lt__(self, other):
return self.get_a() < other.get_a()
def __gt__(... |
ac1b022e89c37e4375c35edb50ce80381588df14 | chendddong/Udacity | /Technical Interview/quick_sort.py | 788 | 4.0625 | 4 | """Implement quick sort in Python.
Input a list.
Output a sorted list."""
def quicksort(array):
if array == None or len(array) == 0:
return
sort(array, 0, len(array) - 1)
return array
def sort(array, start, end):
left = start
right = end
pivot = array[start + (right - left) / 2]
# print "pivot " + str(pivot... |
8acdf030fbb6e1772312eecf12cdb23d2e6b4b59 | heikoschmidt1187/DailyCodingChallenges | /day14.py | 838 | 4.3125 | 4 | #!/bin/python3
"""
The area of a circle is defined as πr^2. Estimate π to 3 decimal places using a
Monte Carlo method.
Hint: The basic equation of a circle is x^2 + y^2 = r^2.
"""
import random
import math
if __name__ == '__main__':
"""
The idea is to take one quadrant of the unit circle, emit points at rando... |
c1fb2767946e5558a2f53e60da3d03fde6faeed2 | franciscoguemes/python3_examples | /basic/82_lambdas.py | 857 | 4.625 | 5 | #!/usr/bin/python3
# In this example I am going to show how to use lambdas in Python with a very easy example
# If you want to go deeper into lambdas I recommend you the following articles:
# https://realpython.com/python-lambda/#cryptic-style
# https://pythonconquerstheuniverse.wordpress.com/2011/08/29/lambda_tut... |
a12b403af3c586ad62e1b143018206b420f32719 | nemac/fswms | /msconfig/ColorMap.py | 1,640 | 3.734375 | 4 | ###
### ColorMap class for loading color maps from CSV files
### and accessing their values.
###
### Mark Phillips <mphillip@unca.edu>
### Fri Sep 17 16:07:05 2010
###
class ColorMap:
###
### Create a new ColorMap object by loading it from a CSV file
###
def __init__(self, filename):
f = open(fi... |
76b00f281f8001d3d26f18203a1bf7a47d33272f | Conquerk/test | /python/yu/12.py | 207 | 3.734375 | 4 | list=[]
while True:
x=int(input("请输入一个数:"))
if len(list)>9:
break
list+=[x]
list.sort(reverse=False)
print("列表为:",list)
print("排序后的列表为:",list)
|
15b5653f17977b9525a2d1edd4efd15736229192 | pi408637535/Algorithm | /com/study/algorithm/offer/面试题 04.06. 后继者.py | 738 | 3.703125 | 4 | class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def inorderSuccessor(self, root, p):
"""
:type root: TreeNode
:type p: TreeNode
:rtype: TreeNode
"""
if not root:
... |
7a9f5c699c4f842ab4ee068c6f8c5f056b73ab6a | nishthagrover/30DaysOfcodePython | /Day_7_Arrays.py | 355 | 3.515625 | 4 | # Link to the complete Problem Statement: https://www.hackerrank.com/challenges/30-arrays/problem
# Solution
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().rstrip().split()))
arr = arr[::-1]
for a in... |
4c00037be4f4cf3d3d8dc2622a1e9d4f01d0000a | lansichu/guessThatGeo | /game.py | 2,562 | 3.96875 | 4 | from countryinfo import CountryInfo
import random
COUNTRIES = list(CountryInfo().all().keys())
COUNTRY = CountryInfo()
# for c in COUNTRY:
# print(c)
class Game:
def __init__(self):
self.curCountry = ''
self.curCity = ''
self.score = 0
self.guess_city = False
def get_cou... |
01e3a67157d98d5ba95d1681f6c56f09c2a268dd | bpmsilva/My-Journey-into-NLP-with-Deep-Learning | /code/word2vec/word2vec-from-scratch-tutorial/utils/training.py | 2,715 | 3.578125 | 4 | """
Module containing utils functions to train the Word2Vec model
Author: Ivan Chen (https://github.com/ujhuyz0110)
Modified by: Bernardo Silva (https://github.com/bpmsilva)
"""
import numpy as np
import matplotlib.pyplot as plt
from .init_params import initialize_parameters
from .forward_propagation import forward_pr... |
d6c8a447a4f7b81cf853262f16ce610fca90a5cf | RekidiangData-S/Biometrics_NUS_2017 | /AssignmentTwo/Q1.py | 384 | 3.640625 | 4 | #!/usr/bin/python
# -*- coding:utf-8 -*-
'''
Q1 is to convolve 2 matrix and use python to check the answer
A = 1, 3, 2, 4; 2, 2, 3, 1; 3, 2, 4, 5; 4, 2, 0, 1
B(kernel) = 1, 2, 3; 2, 1, 3; 4, 1, 3
'''
import numpy as np
from scipy import signal
A = np.mat('1, 3, 2, 4; 2, 2, 3, 1; 3, 2, 4, 5; 4, 2, 0, 1')
B = np.mat('1,... |
4b8c545e650c7674f803cc9be17bcef67b08643f | chenlei65368/algorithm004-05 | /Week 6/id_545/LeetCode_37_545.py | 1,321 | 3.671875 | 4 | ## 37. 解数独
class Solution:
def __init__(self):
self.empty = []
self.row = [set(range(1,10)) for _ in range(9)]
self.col = [set(range(1,10)) for _ in range(9)]
self.block = [set(range(1,10)) for _ in range(9)]
def backtrack(self, board, iter=0):
if iter == len(self.empty)... |
bd6358e563209ac1951872ac2e9c33397ac47b9c | A-Powell/Intro-Python-II | /src/backupadv.py | 2,957 | 3.75 | 4 | '''while True:
current = newPlayer.room
items = newPlayer.room.roomItems
print(
f"\n****Hello {newPlayer.name}. your current location is {current}****")
print(f"\nItems in the area:")
for i in items:
print(i)
print('-------------------------------------------------------')
ch... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.