blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
72bf293798f3a21d789c8e63c79e4d0df37b1323 | neilhan/reinforcement_learning_python | /python/tic_tac_toe/play.py | 4,063 | 3.765625 | 4 | #! python3
import numpy as np
import matplotlib.pyplot as plt
from tic_tac_toe import BOARD_LENGTH
from tic_tac_toe.game_env import Environment
from tic_tac_toe.agent import Agent
from tic_tac_toe.human import Human
def play_game(p1, p2, env: Environment, draw=False) -> None:
# loops until game over
current_... |
a18df08e864b6e31a5fd6c0909f64f40c76d1feb | pikeszfish/LeetCode | /leetcode.py/LengthofLastWord.py | 232 | 3.609375 | 4 | class Solution:
# @param s, a string
# @return an integer
def lengthOfLastWord(self, s):
s = s.strip().split(' ')[-1].strip(',')
return len(s)
a = Solution()
print a.lengthOfLastWord("Hello World") |
159d615b1862a59ba7d4f66938971ae965ec69f9 | hongjl/Python-network-program | /checkStrongPassword.py | 895 | 3.53125 | 4 | #! python3
'''
强口令: 长度不少于8个字符,同时包含大写和小写字符,至少有一个数字
'''
import re
text = ['SLKJDFSLDKF','laksfdlksd','8378373849999','asdf','sdfkjSDLFK','aslkdfj89899','SLKDFJSLDKF89687','asdfkSDKF78799'] # 测试,只有一个符合条件
def checkStrongPassword(pwList):
# castAndNum = re.compile(r'\w*?[0-9A-Z]*[a-z]+\w*')
... |
1307d3e6241c40f19b8f9c9901147a474e9e3e80 | AllanBastos/Atividades-Python | /ESTATÍSTICA APLICADA/Listas/Exercicio 5.py | 103 | 3.640625 | 4 | def is_sorted(t):
return t == sorted(t)
print(is_sorted([1, 2, 2]))
print(is_sorted(['b', 'a'])) |
8f0502272e6f2eb623c2b09a4af1b852978ab318 | K-Vaid/Python | /Basics/pallindromic.py | 633 | 4.25 | 4 | """
Code Challenge
Name:
Pallindromic Integer
Filename:
pallindromic.py
Problem Statement:
You are given a space separated list of integers.
If all the integers are positive and if any integer is a palindromic integer, then you need to print True else print False.
(Take Input from User)
... |
c693f3d36bbb296bae46c9b3b7ecb34128232f97 | VTrifanov/Quadratic-equation | /grafic.py | 2,337 | 3.546875 | 4 | import tkinter as tk
canvas_h = 650
canvas_w = 800
#x_left = -4
#x_right = 4
#y_top = 4
#y_bottom = -4
#dx = canvas_w / (x_right-x_left) #цена пикселя по х
#dy = canvas_h / (y_top-y_bottom) #цена пикселя по y
def main(a=1, b=0, c=0, x_left=-4, x_right=4, y_bottom=-4, y_top=4):
global canvas, list_x_old, l... |
5a8da87ee3ed9b3d7ee966935bcd14eb8e31ef65 | y43560681/y43560681-270201054 | /lab9/example4.py | 169 | 3.96875 | 4 | t = input("Please enter second : ")
def sleep(t, k = t):
k = int(k)
if k == -1:
return
else:
print(k)
return sleep(t, k - 1)
sleep(t) |
b582f4291e063f51bcdec69fbf8feac08b89bf3b | erdi54/Data_Structure_Algorithm_Python | /Array Sequences/unique_characters.py | 665 | 4 | 4 | """
Bir dize verildiğinde, tüm benzersiz karakterlerin karşılaştırıldığından emin olun.
Örneğin, 'abcde' dizgisi tüm benzersiz karakterlere sahiptir ve True döndürmelidir.
'Aabcde' dizgisi yinelenen karakterler içeriyor ve false döndürmeli.
"""
def uni_char(st):
if len(st) > 256:
return False
... |
9f0306ca8dfaf280e846685652a23853116d212f | julielaursen/Homework | /Julie_Laursen_Lab8b.py | 1,539 | 4.25 | 4 |
#define main function
def main():
#create empty list called students
students = []
#call modify_students
modify_students(students)
#define modify_students and pass students to it
def modify_students(students):
counter = 0
while counter < 12:
#take input ... |
ffb5f7ee32419362d014ea123c9b70f47283abdf | chandni-s/NewsFlash | /src/response.py | 2,555 | 3.65625 | 4 | from model import Model
import json
class ClassEncoder(json.JSONEncoder):
"""A custom JSON encoder that defaults to using the __dict__ method for
database Model classes and subclasses. This allows for automatic
conversion to JSON.
"""
def default(self, o):
"""(ClassEncoder, Object) -> Obje... |
f30fd06a8c1b6e2c994148ef0ad7a3415ac8493b | pvanh80/intro-to-programming | /round11/Numerical_integration.py | 1,111 | 3.953125 | 4 | # Intro to programming
# Numerical integration
# Phan Viet Anh
# 256296
# http://mathworld.wolfram.com/RiemannSum.html
def math_function(x):
return -pow(x,2) + 2*x + 4
def approximate_area(math_function, lower_bound_area, upper_bound_area, number_rec):
step = (upper_bound_area-lower_bound_area)/number_rec
... |
f5f4dc58e04991b23e384689db7fff3741d7c1e9 | GeorgeJopson/OCR-A-Level-Coding-Challenges | /15-Pangrams/Pangrams.py | 459 | 4.1875 | 4 | def isPangram(string):
alphabet=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
for letter in string:
try:
del alphabet[alphabet.index(letter.lower())]
except:
pass
if(len(alphabet)==0):
return True
... |
d4f81a35ec2dd689f47680667a248bfbb9065bfd | magezil/magezil.github.io | /battleship.py | 3,115 | 4.375 | 4 | from random import randint
''' Battleship implementation - does not have to be a square board '''
board = [] # displayed board
ships = [] # board with ships are located
types = {} # types of ships and size
nrows = 10 # number of rows on board
ncols = 10 # number of columns on board
# Create board for other player and... |
66e60bf7b0d5ef02153b9ba4bb0b99e405758a45 | Latas2001/python-program | /birthday reminder.py | 721 | 4.375 | 4 | dict={}
while True:
print("_______________Birthday App________________")
print("1.Show Birthday")
print("2.Add to Birthday List")
print("3.Exit")
choice = int(input("Enter the choice: "))
if choice==1:
if len(dict.keys())==0:
print("nothing to show....")
else:
... |
d5ed44cdcaecaaff976e5abbb838f20f50e75347 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/sieve/953f80d71f8840e596e6db2a119b9425.py | 215 | 3.765625 | 4 | def sieve(n):
multiples = set()
sieved = []
for i in range(2, n + 1):
if i not in multiples:
sieved.append(i)
multiples.update(range(i * i, n + 1, i))
return sieved
|
8eb1f4859bc9b3bc6e459026bd2634cfb0c52058 | wesenbergg/hy-data-analysis-with-python-2020 | /part01/part01-e06_triple_square/src/triple_square.py | 340 | 3.953125 | 4 | #!/usr/bin/env python3
def triple(num):
return num*3
def square(num):
return num**2
def main():
for i in range(1, 11):
t=triple(i)
s=square(i)
if t < s:
break
print("triple({:.0f})=={:.0f} square({:.0f})=={:.0f}".format(i, t, i, s))
if __name__ == "__... |
c89309952ac1544725ffb382cdedc72f879f4719 | riya-kostha/PyhtonAssignment | /largest.py | 211 | 4 | 4 | list=[1,2,45,67,89,90,170]
for i in range(len(list)):
list.sort()
print("list is",list)
print("second largest number",list.__getitem__(len(list)-2))
print("second smallest number",list.__getitem__(1)) |
8a89548f36d60ec9efd878b46e99388b004d2917 | juniorsmartins/Aulas-Python | /Aula24.py | 490 | 3.921875 | 4 | # coding: latin-1
for contador in range (5, 0, -1):
print(contador)
print("\n")
for cont in range (1, 6):
print(cont)
print("\n")
lista = {1, 4, 7, 9}
for itens in lista:
print(itens)
print("\n")
arquivo = {1: "Mário", 2: "Pedro", 3: "Alberto", 4: "Francisco"}
for itens in arquivo:
print(itens, arquivo[iten... |
3c1caed099d9f6096f2625604cae2d6491694474 | jiinmoon/Algorithms_Review | /Archives/Leet_Code/Old-Attempts/0142_Linked_List_Cycle_II.py | 579 | 3.5 | 4 | """ 142. Linked List Cycle II
Question:
Given a linked list with a cycle, return the node where cycle begins.
"""
class Solution:
def detectCycle(self, head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fa... |
1e791a16dc783d149d0fd4eaa314d4902db53f43 | jvnabais/Test-Python | /PythonFile.py | 682 | 3.640625 | 4 | correct_answer = "Corret!"
wrong_answer = "Wrong!"
a = 100
b = -100
total = a + b
if total == 0:
print(correct_answer)
else:
print(wrong_answer)
d = 20
s = -20
total1 = d + s
if total1 == 0:
print(correct_answer)
else:
print(wrong_answer)
g = 10
j = 20000
total2 = g + j
if total2 == 1000:
print(co... |
a4cc4ce100623548acfb4a4b07c610199e5b65b2 | robobyn/code-challenges | /fin-nth-fibonacci.py | 961 | 4.34375 | 4 | """Write a function fib() that a takes an integer n and returns the nth
Fibonacci number."""
def find_nth_fibonacci(n):
"""Finds and returns nth Fibonacci number.
Input: Positive integer
Returns: nth number in Fibonacci sequence - assumes series is 0-indexed."""
if n < 0:
raise ValueError("... |
88e32db0dda55d4eb11c3e03c57e1b9be6e813f5 | acarmonag/ST0245-008 | /Talleres/Recursividad/punto5.py | 261 | 3.6875 | 4 | igual, aux = 0, 0
texto = input("Ingrese la palabra: ")
for i in reversed(range(0, len(texto))):
if texto[i] == texto[aux]:
igual += 1
aux += 1
if len(texto) == igual:
print("El texto es palindromo")
else:
print("El texto NO es palindromo") |
2724d9e711f853cf578ad7104c663eea64c367a6 | Vasilic-Maxim/LeetCode-Problems | /problems/1013. Partition Array Into Three Parts With Equal Sum/1 - Accumulate.py | 622 | 3.8125 | 4 | from itertools import accumulate
from typing import List
class Solution:
"""
Time: O(2n) => O(n)
Space: O(n)
"""
def canThreePartsEqualSum(self, nums: List[int]) -> bool:
# do not need to check if 'nums' is empty because
# of the condition [3 <= A.length <= 50000]
nums_su... |
58dfb6132acf6bd75b83feffebd471faf85e5f5b | Hahn9/MyPython | /join.py | 10,701 | 3.734375 | 4 | Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> s = """line1\nline2\nline3\n"""
print s
SyntaxError: multiple statements found while compiling a single statement
>>> s='hello,world'
>>> print s... |
bf22fc065590d309dd2242c26be3585ca16b3c46 | googlewaitme/oneloveonventi | /bd.py | 2,639 | 3.59375 | 4 | """
Вся работа с БД будет тут
"""
import sqlite3
class BD:
def __init__(self, name_bd="mybd.sqlite"):
""" инитиализация курсора и бд"""
self.conn = sqlite3.connect(name_bd)
self.cursor = self.conn.cursor()
def create_tables(self):
""" Creating new base of date"""
self.cursor.execute("""
CREATE TABLE ... |
f9842fc629fd79343b70d8d7ba8fc555d7119cbf | as-segaf/python | /OOP/class-object.py | 1,136 | 4.21875 | 4 | #!/usr/bin/python3
class employee:
'common base class for all employees'
empCount = 0
def __init__(self, name, salary): # read about 'self' in w3schools.com, it's easier to understand
self.nama = name
self.gaji = salary
employee.empCount += 1
def displayCount(tes):
... |
244d3cb9086eee028ea0b2281362d16a849f7024 | AckersonC/CPython | /Elif.py | 357 | 3.875 | 4 | deposit = float(input("Please enter the ammount of your deposit >>> "))
if deposit < 50 :
print ("Hooray, you get a free gift card!")
elif deposit < 100 :
print ("Hooray, you get a free toaster!")
elif deposit < 200 :
print ("Hooray, you get a free TV")
elif deposit > 200 :
print ("Hooray, you get a f... |
93c8cf8204c919afccca1f1fc44d78d5fab0cdcc | niteesh2268/coding-prepation | /leetcode/Problems/36--Valid-Sudoku-Medium.py | 1,103 | 3.546875 | 4 | class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
rows = collections.defaultdict(list)
columns = collections.defaultdict(list)
for i in range(9):
for j in range(9):
if board[i][j] == '.':
continue
else:
... |
0abff1690f093027f7bb8cc9c72b5af324444a1b | Abhi4899/data-structures-and-algorithms | /python practice/factorial.py | 143 | 3.9375 | 4 | def fact(x):
if x==1:
return x
return x*fact(x-1)
n=int(input('Enter a number\n'))
print('{}! = {}'.format(n,fact(n)))
|
a60513be6c7f4ca9c7c450fc0cfaf79e47e7e7fb | Jeandcc/CS50 | /pset6/Credit/credit.py | 786 | 3.6875 | 4 | import cs50
cCardStr = str(cs50.get_int("Number: "))
def checksum(string):
digits = list(map(int, string))
odd_sum = sum(digits[-1::-2])
even_sum = sum([sum(divmod(2 * d, 10)) for d in digits[-2::-2]])
return (odd_sum + even_sum) % 10
def verify(string):
return (checksum(string) == 0)
if not ... |
8f85990e6548c2c520aae2c24be958cee5907a46 | Sam-G-23/Python-class2020 | /string_functions.py | 650 | 4.25 | 4 | """
program: string_functions.py
Sam Goode
sgoode1@dmacc.edu
6/13/2020
The purpose of this program to to calculate a users input so that they can determine their hourly wage
"""
def multiply_string():
"""
:param string_multiplier: represents the string used to multiply as 'message'
:param n: r... |
5fa10bd2d0fd5feeac017c3379b9bb529862427f | obemauricio/Algoritmos_python | /aprox_soluciones.py | 328 | 4.125 | 4 | target = int(input('Choose a number: '))
epsilon = 0.01
step = epsilon**2
answer = 0.0
while abs(answer**2 - target) >= epsilon and answer <= target:
print(answer)
answer += step
if abs(answer**2 - target) >= epsilon:
print(f'{target} square root not found')
else:
print(f'Square root of {target} is {a... |
c59e148abaf79dee76e2c0eef5fc989d1a1db44e | gidandm/checkio | /Median.py | 520 | 3.703125 | 4 | # -*- coding: utf-8 -*-
def checkio(data):
data.sort()
length = len(data)
half = length//2
if (length % 2) != 0:
mediana = data[half]
else:
mediana = (data[(half)-1] + data[(half)])/2
return mediana
# BEST
# off = len(data) // 2
# data.sort()
# med = data[off] + data[-(off + 1)]
... |
b325f39b89b421e5edeb1472b494f471081d1327 | danilocamus/curso-em-video-python | /aula 16/desafio 074.py | 428 | 3.84375 | 4 | from random import randint
num = randint(1, 10), randint(1, 10), randint(1,10), randint(1, 10), randint(1, 10)
print('Os valores spteados foram: ')
for n in num:
print(f'{n} ', end='')
maior = sorted(num)
menor = sorted(num)
print(f'\nO maior número sorteado é {maior[4]}\nO menor número sorteado é {menor[0]}... |
d91936546e575c5b3daa3c20061d2541d379dc3b | AMJefford/Simulation-and-Chemistry-System | /Student File.py | 25,676 | 3.5625 | 4 | from tkinter import *
import tkinter.messagebox as tm
import sqlite3
import array
import string
import DatabaseKey
from cryptography.fernet import Fernet
from Simulation import *
import random
import time
class Login:
def __init__(self, root):
self.__UsernameE = Entry(root)
... |
8f6abfe85a2253d0599fb519ad21ab0c36cfa5f7 | bsakers/Introduction_to_Python | /hashes.py | 1,424 | 4.71875 | 5 | #hashes are referred to as dictionaries
example_hash = {'key1' : 1, 'key2' : 2, 'key3' : 3}
print example_hash["key1"]
print example_hash["key2"]
print example_hash["key3"]
#dictionaries are mutable, meaning they can be changed (mutated) after being created. Here is adding to it
food_cart = {}
food_cart["chicken and ... |
08cbf8cc5b485e299bbc656eafd5c8da792189a6 | CristianGastonUrbina/Curso_Python | /Clase02/diccionario_geringoso.py | 782 | 4.03125 | 4 | #2.14
"""Construí una función que, a partir de una lista de palabras, devuelva un diccionario geringoso.
Las claves del diccionario deben ser las palabras de la lista y los valores deben ser sus traducciones al geringoso
(como en el Ejercicio 1.18). Probá tu función para la lista ['banana', 'manzana', 'mandarina']. ... |
04f0807018faa05e702de4e8e3f96f7245416c72 | akshayparakh25/wikipediaInfoboxExtractorForInformationExtraction | /dump.py | 408 | 3.65625 | 4 | import csv
import pickle
def dump_dictionary(fileName, dictionaryName):
print("dumping "+fileName)
with open(fileName, 'wb') as handle:
pickle.dump(dictionaryName, handle, protocol=pickle.HIGHEST_PROTOCOL)
def dump_dictionary_csv(fileName, dictionaryName):
with open(fileName, "w+") as csv_file:
writer = csv.w... |
c5fbc22eca1b354b09c8f454fb7444be0f7746b2 | HarshGarg1201/Tkinter | /R-L-M_ click.py | 472 | 3.9375 | 4 | import tkinter
window = tkinter.Tk()
window.title("right-left-middle-click")
def left_click(event):
tkinter.Label(window, text = "left ckick").pack()
def middle_click(event):
tkinter.Label(window, text = "middle click").pack()
def right_click(event):
tkinter.Label(window, text = "right click... |
e92a7a601620cddecd70c10faf18edafa0a0e1a0 | aksharjoshi/practice_problem | /leetcode_top100/twoSum.py | 443 | 3.5 | 4 | class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
map = {}
for index, value in enumerate(nums):
remaining = target - value
if(remaining in map):
ret... |
acd52b8aec0dd6ee42229729d03836adc61e9e54 | belozi/Python-Programs | /MITx 6.00.1x/problem_set_2/problem_3b.py | 1,074 | 3.609375 | 4 | balance = 999999
annualInterestRate = .18
lowerBound = balance / 12
upperBound = (balance * ( 1 + .18)) / 12
payment = (upperBound + lowerBound) / 2
def guessPayment(l, u):
lower = l
upper = u
return (lower + upper) / 2
def monthlyStatement(x, y, z):
balance = x
annualInterestRate = y
p... |
96283335dd4499a8f0043f49b066d0063ed9cdd6 | scottstewart1234/Scripts-For-the-M100-ROS-DJI-OSDK | /FlyPath.py | 5,466 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 17 11:09:03 2019
@author: scottstewart
"""
import math
import os
class flight_path: #lets us make a flight path ealsiy
def __init__(self): #initialize a set of latitudes and longitudes
self.lat = list()
self.lon = list()
... |
6f96d7627f70b6c71bfe685fb77a0daf958acf3e | mkhira2/automate-the-boring-stuff | /python-basics/hello.py | 852 | 4.125 | 4 | # This program says hello and asks for my name
# print('Hello world!')
# print('What is your name?') # ask for their name
# myName = input()
# print('It is good to meet you, ' + myName)
# print('The length of your name is: ' )
# print(len(myName))
# print('What is your age?') # ask for their age
# myAge = input()
# ... |
8b8777580c054cf56c15d702ac8db3889a72be24 | henkmollema/spInDP | /spInDP/LegThread.py | 1,804 | 3.5 | 4 | import time
import threading
class LegThread(threading.Thread):
"""Provides a thread for handling leg movements."""
def __init__(self, legId, sequenceController, group=None, target=None, args=(), kwargs=None, verbose=None):
"""Initializes a new instance of the LegThread class."""
super(Leg... |
d3a89dd33f3192def08d13da606dfb5c05ffd4b6 | chenhh/Uva | /uva_11369.py | 544 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Authors: Hung-Hsin Chen <chenhh@par.cse.nsysu.edu.tw>
License: GPL v2
status: AC
difficulty: 1
http://luckycat.kshs.kh.edu.tw/homework/q11369.htm
"""
import math
def main():
T = int(input())
for _ in range(T):
n = int(input())
# sort prices in descending order
... |
e4f76f72072250379d6ca80d35ca0f0565786084 | RevanthR/AI_Assignments | /assignment.py | 2,400 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 11 21:13:06 2019
@author: DELL
"""
#assignment 1
dict={'keys':['shanghai','intanbul','hyderabad'],'value':[17,18,19]}
dict
#assignment 2
answer = 20
guess = int(input('enter the number you have guessed\n'))
difference = answer-guess
if difference < -30:
print("too h... |
d7955d98d231d53b62a821defade3236e23bd990 | Niloy28/Python-programming-exercises | /Solutions/Q78.py | 155 | 3.875 | 4 | # Please write a program to randomly print a integer number between 7 and 15 inclusive.
import random
random.seed()
print(random.randint(7, 15))
|
7f21f2a0314ae83149986c2140b10c1c2e5f670b | skyleh/Data_Visualization | /code/chapter17/test1.py | 389 | 3.96875 | 4 | def hanoi(n,a,b,c):
if n==1:
print(a,'-->',c)
else:
# 将前n-1个盘子从a移动到b上
hanoi(n-1,a,c,b)
# 将最底下的最后一个盘子从a移动到c上
hanoi(1,a,b,c)
# 将b上的n-1个盘子移动到c上
hanoi(n-1,b,a,c)
n=int(input('请输入汉诺塔的层数:'))
print("移动路径为:")
hanoi(n,'a','b','c') |
7790064eb041efbacf849c21ede726fe34db51e5 | jwds123/offer | /二叉搜索树与双向链表36.py | 1,999 | 3.546875 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
'''
定义两个辅助节点listHead(链表头节点)、listNode(链表尾节点)。事实上,二叉树只是换了种形式的链表;
listHead用于记录链表的头节点,用于最后算法的返回;listNode用于定位当前需要更改指向的节点。
'''
def __init__(self):
self.listHead = Non... |
7b8dbc3e5e4358a04ef75c73b3c1e112c96c9138 | Hariharansingaram/training-session | /மாட்டுப் பொங்கல்.py | 967 | 3.703125 | 4 | #question
Sivasamy is a farmer living in the southern part of Tamilnadu. He has ‘N’ bulls on his farm, which he uses to plough his fields. Hence “Mattu Pongal” is a special occasion to celebrate the hard work of all those bulls. So, for every Mattu Pongal, the bulls will be decorated, the horns of the bull are painted.... |
f10fa62a92ee35cd6dbe266c1d8c052d33ac1da0 | ai-se/ActiveConfig_codebase | /PerformanceMetrics/Spread/Spread.py | 3,519 | 3.53125 | 4 | from __future__ import division
def spread_calculator(obtained_front, extreme_point1, extreme_point2):
"""Given a Pareto front `first_front` and the two extreme points of the
optimal Pareto front, this function returns a metric of the diversity
of the front as explained in the original NSGA-II article by K.... |
207b607a416365a704d0d99b15e57d37a61b4f54 | Avani1992/database_pytest | /database/key_test.py | 2,357 | 3.59375 | 4 | """create a DB in which orders and customers tables are there. Using the concept of Primary Key and Foreign Key.
cu_id is a Primary key of table customers and foreignkey of table orders. Fetch data from customers table according to the ordername of orders table.
and compare the fetched data with json file in which i... |
49139b15072d0797fb0c027ab00fd39ed77743be | Baes14/Python-work | /ordinal_numbers.py | 247 | 3.90625 | 4 | numbers=list(range(1,10))
for number in numbers :
if number == 1 :
print("--> "+str(number)+"st")
elif number == 2 :
print("--> "+str(number)+"nd")
elif number == 3 :
print("--> "+str(number)+"rd")
else :
print("--> "+str(number)+"th") |
3af2c34ad27c921dbc7dafd5e01894a43754a562 | dinkoslav/Python | /Programing0-1/Week1/1-IO-Simple-Problems/n_dice_more.py | 252 | 3.640625 | 4 | N = input("Enter sides: ")
from random import randrange
firstRoll = randrange(1,int(N))
secondRoll = randrange(1,int(N))
print ("First roll:")
print (firstRoll)
print ("Second roll:")
print (secondRoll)
print ("Sum is:")
print (firstRoll + secondRoll)
|
ae19d203bc911c1a26e77dcf54de1fb3869959f1 | quekyufei/rl-tictactoe | /rl_ttt/player.py | 1,059 | 3.703125 | 4 | import random
class Player():
def __init__(self, mark):
self.mark = mark
self.num_wins = 0
self.num_losses = 0
self.num_draws = 0
def get_move(self, board):
# returns move object corresponding to move
pass
def game_ended(self, result):
if result == 'win':
self.num_wins += 1
elif result == 'loss... |
5048e0ac6f930a54a21d2a22825ce403cbc389da | jason-azze/learning-py | /testing-aug-assignment-ops.py | 143 | 3.875 | 4 | base = int(input ("What is your base salary?"))
base /= 52
print(base, "is your weekly pay.")
print (input ("Press any key to continue."))
|
330d22c3a6e47c69d51c1cdf1095fba47ed27a19 | priyanka-111-droid/100daysofcode | /Day054/intro-backend-web-dev/Theory/first-class-func-and-decorators/dec1.py | 1,218 | 4.90625 | 5 | ####<<<DECORATORS>>>####
# A decorator is a function that takes another function as an argument,adds some functionality and returns another function
#Recap:first class function
def outer_func(message):
def inner_func():
print("Message :",message)
#no () as we don't want this function to execute
... |
cc0a8388c2d9e807787768ac37186898b1211d86 | winaba/mapScreen | /rotinasDeConfiguracao.py | 2,965 | 3.5625 | 4 | import pyautogui
from arquivoDeConfiguracao import ArquivoDeConfiguracao
class RotinasDeConfiguracao:
def __init__(self):
self.config = ArquivoDeConfiguracao()
self.pos = pyautogui
def configuraArquivoSAT(self):
print("")
print("##################################")
pr... |
ce8dd9aa2a543cfe1ac3dea225460d37393b1cc0 | Sitiestiya/uin_modularization_using_class_and_package | /main.py | 1,906 | 3.90625 | 4 | nama = 'Siti Estiya Pujiningtiyas'
program = 'Hukum Newton 1'
print(f'Program{program} oleh {nama}')
def hitung_HK1_Newton(massa, percepatan) :
HK1_Newton = massa * percepatan
print(f'massa = {massa/1}kg mengalami sebuah percepatan = {percepatan/1} m/s**')
print(f'Sehingga HK1_Newton = {HK1_Newton} N')
... |
850755819618cc51a51ed5716c06db48826ad1bb | john-mcgonigle/random_scripts | /whiteboard/code_exercises/guess_the_number.py | 1,129 | 4.15625 | 4 | from random import randint
def main():
print('Let\'s play a guessing game. I\'ll choose a number between 1 and 10 and you try and guess the correct number!')
number = randint(1,10)
game(number)
def game(number):
game_over = False
guess = input('OK. I\'ve chosen my number. What do you think it is?\... |
ccc5f80ca14477cf28910efcca3d018aa2ecb003 | fl4kee/homework-repository | /homework1/task5.py | 960 | 4.09375 | 4 | """
Given a list of integers numbers "nums".
You need to find a sub-array with length less equal to "k", with maximal sum.
The written function should return the sum of this sub-array.
Examples:
nums = [1, 3, -1, -3, 5, 3, 6, 7], subarray_len = 3
result = 16
"""
from typing import List
def find_maximal_subarr... |
1462a4ef2588709b6e9a02bb1d0d50951ca095f3 | nidhiatwork/Python_Coding_Practice | /Lists/FindMaxIdxDiff.py | 1,070 | 3.5 | 4 | # Given an array arr[], find the maximum j – i such that arr[j] > arr[i].
# Examples :
# Input: {34, 8, 10, 3, 2, 80, 30, 33, 1}
# Output: 6 (j = 7, i = 1)
import collections
def FindMaxIdxDiff(arr):
n = len(arr)
result = 0
maxFromEnd = collections.deque()
val = -float("inf")
for num in reve... |
5a8e7c0f527e794b9e93c220e2f76202f74abbed | bzd111/PythonLearn | /decorator_use/decorator_def_without_args.py | 649 | 3.640625 | 4 | # -*- coding: utf-8 -*-
from functools import wraps
def decorate_test(func):
@wraps(func)
def wrap(*args, **kwargs):
print('This is a decorate')
print('func name {}'.format(func.__name__))
return func(*args, **kwargs)
return wrap
@decorate_test
def say_hello():
return 'say he... |
9a4780f29a49ec8845c3a50567879f4c111cc349 | aakashmathuri/Python | /ex_03_02/ex_03_03.py | 255 | 3.9375 | 4 | score = input("Enter Score: ")
xf = float(score)
if xf >=1:
print("please enter correct score!")
elif xf >= 0.9:
print("A")
elif xf >= 0.8:
print("B")
elif xf >= 0.7:
print("C")
elif xf >= 0.6:
print("D")
elif xf < 0.6:
print("F")
|
32e10602a8582d637224a58e8ebc73243dd07503 | AlexMaraio/CMBBispectrumCalc | /lib/Visualisation.py | 2,854 | 3.515625 | 4 | # Created by Alessandro Maraio on 02/02/2020.
# Copyright (c) 2020 University of Sussex.
# contributor: Alessandro Maraio <am963@sussex.ac.uk>
"""
This file will be where our visualisation tools will be put so that way
we can present the results for the two- and three-point function integrals
in a nice and coherent w... |
0adfb30c50baaaa22ca8fa18ef7ff65ed9cf8989 | Igglyboo/Project-Euler | /1-99/30-39/Problem31.py | 690 | 3.53125 | 4 | from time import clock
def timer(function):
def wrapper(*args, **kwargs):
start = clock()
print(function(*args, **kwargs))
print("Solution took: %f seconds." % (clock() - start))
return wrapper
@timer
def find_answer():
total = 0
for a in range(200, -1, -200):
for b ... |
a6e08f63e78cba25bdfcd901704391277a63e1d5 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2176/60641/250740.py | 476 | 3.671875 | 4 | def main():
string = list(input())
new_string = sorted(set(string))
result = []
for i in new_string:
result = result + find_index(string, i, 0)
print(" ".join(map(str, result)))
def find_index(string, s, start):
result = []
num = string.index(s, start) + 1
try:
result... |
fbe185684b2dd1375f1b800a5daf5b9a7f34d6b8 | martinusso/code_practice | /codingbat/python/warmup_1/front_back.py | 365 | 4 | 4 | #!/usr/bin/python
# coding: utf-8
'''
Given a string, return a new string where the first and last chars have been exchanged.
front_back('code') -> 'eodc'
front_back('a') -> 'a'
front_back('ab') -> 'ba'
'''
def front_back(str):
if not len(str) > 1:
return str
first = str[0]
last = str[-1:]
m... |
7b2306235f97967fd505cba3b567e71ce7064a5e | luliyucoordinate/Leetcode | /src/0129-Sum-Root-to-Leaf-Numbers/0129.py | 1,048 | 3.609375 | 4 | class Solution:
def sumNumbers(self, root):
"""
:type root: TreeNode
:rtype: int
"""
result = 0
if not root:
return result
path = [(0, root)]
while path:
pre, node = path.pop()
if node:
if not node.l... |
4b557e715d52d155d33a4702e9a124e75e0ca4b3 | paulykp/python_practice | /tip_counting_new.py | 949 | 3.96875 | 4 | #imports for currency values
from money.money import Money
from money.currency import Currency
#defines the way that one inputs the currency value 'i.e. no period as it's valued in cents not dollars¢s
def USD(cents):
return Money.from_sub_units(cents, Currency.USD)
#Combines Names list with totals in the record... |
425f002af31ae0ae4dc4592191cc3819018edff1 | RuizhenMai/academic-blog | /leetcode/akuna/3_palindrome_dates.py | 1,170 | 3.984375 | 4 | from calendar import monthrange
def generate_palindrome_date(year):
'''
param:
year (string)
return:
number of palindrome date of the century the year is in(int)
'''
century_start = year // 100 * 100 + 1 # 2001 is the start of 21st century
century_end = century_start + 99
c... |
0ba262e62d69b2b1e43517673148c79bd3759abd | karunaswamy1/Function | /qu2.py | 122 | 3.796875 | 4 | # numbers = [3, 5, 7, 34, 2, 89, 2, 5]
# a=max(numbers)
# print(a)
list = [8, 6, 4, 8, 4, 50, 2, 7]
a=min(list)
print(a)
|
9f373d564388d51b8e870b72808066901a4eff1c | parfeniukir/parfeniuk | /Lesson 6/loop_v5.py | 110 | 3.84375 | 4 | for i in range(5):
print(i)
else:
print('Else block i = ', i)
for i in range("Hello"):
print(i) |
cc62cf27be15a5c13817784790a235c04b6b0b5b | aknkrstozkn/ceng3511 | /p3/knapsack_ga.py | 2,548 | 3.78125 | 4 | # starter code for solving knapsack problem using genetic algorithm
import random
fc = open('./c.txt', 'r')
fw = open('./w.txt', 'r')
fv = open('./v.txt', 'r')
fout = open('./out.txt', 'w')
c = int(fc.readline())
w = []
v = []
for line in fw:
w.append(int(line))
for line in fv:
v.append(int(line))
print('Ca... |
76136aa0005ddbfd37cf3082c4fecccee02bb4da | Sloomey/DigitalNum_RPi | /src/digits.py | 1,802 | 4.375 | 4 | import LEDarea as area
""" This file is used to have each number be displayed through LEDs (every
number 0-9) using a function. The function's parameter takes a number which
is the number that gets displayed with LEDs. """
def digit(num):
if num == 0:
area.MIDDLE_TOP()
area.RIGHT_TOP()
... |
95277ade6069e1fd5b265e749ee18e4314406252 | zarozombie/music-tool | /Theory/chord.py | 994 | 3.84375 | 4 | import notes
# start = input("Enter Starting Note: \n")
# s = start.upper()
# root = notes.con_note(s)
# # print(root)
# root = int(root)
# first = root
# third = root + 4
# fifth = root + 7
# # print(first, third, fifth)
# print (notes.num_to_note(first), notes.num_to_note(third), notes.num_to_note(fifth))
def... |
da995afe233213d8c4ecfb1eb891b6111a9351b4 | hs06146/Python | /1차원 배열/BJ_2562.py | 143 | 3.515625 | 4 | num = 0
index = 0
for i in range(9):
a = int(input())
if(a > num):
num = a
index = i + 1
print('%d\n%d'%(num, index)) |
25bd6cb192d98de533c89d7fe47cd0191f81f1fc | GMwang550146647/network | /3.爬虫/1.request/1.html_text.py | 695 | 3.578125 | 4 | """
1.反爬机制
1.反爬文件:
url/robots.txt
2.UA检查
"""
import os
import requests
urls = {
'sogou': {
'url': 'https://www.sogou.com/web',
'params': {
'query': 'gmwang'
},
'headers': {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleW... |
d9afc2fbf4be2f42b30bc60cc590a63a21343a12 | shoaibrayeen/Programmers-Community | /Data Structure/Array Or Vector/Counting Sort/SolutionByVaishnavi.py | 904 | 3.578125 | 4 | def count_sort(arr):
max_element = int(max(arr))
min_element = int(min(arr))
range_of_elements = max_element - min_element + 1
count_arr = [0 for _ in range(range_of_elements)]
output_arr = [0 for _ in range(len(arr))]
for i in range(0, len(arr)):
count_arr[arr[i]-min_ele... |
04e6f673030f0b48b68580b10fd2d595001cbccf | emapco/Python-Code-Challenges | /count_unique_words.py | 1,486 | 3.796875 | 4 | from collections import Counter
import re
import string
# counts the number of unique words and how often each occurs
def count_unique_words(file_path):
with open(file_path, 'r', encoding='utf8') as file:
# regex matches all characters that are not alphanumeric, ', or -
forbidden_characters = ''.j... |
957c78e36975520f3fdd24371916c5eb0ebbbb1d | AhlemKaabi/holbertonschool-higher_level_programming | /0x0F-python-object_relational_mapping/4-cities_by_state.py | 891 | 3.765625 | 4 | #!/usr/bin/python3
'''script that lists all cities from the
database hbtn_0e_4_usa
'''
if __name__ == "__main__":
import MySQLdb
from sys import argv
# Open database connection
db = MySQLdb.connect(
host="localhost",
user=argv[1],
password=argv[2],
database=argv[3],... |
32edac452bca0b5b977a91084f71d6699fdcd44e | arathym/sentimentprediction | /merge_test_files.py | 885 | 3.609375 | 4 | #----- combining all the text files into the csv and also removing the punctuations------
# This program should be run inside the test folder since we are taking all the global .text files from that folder
import glob
import string
fw = open('test_set.csv','wb') # file to which we are writing all the text file... |
e78afcf31ab5c1038b4e15826dc2833412551d0c | JackoDev/holbertonschool-higher_level_programming | /0x0B-python-input_output/1-number_of_lines.py | 325 | 4.15625 | 4 | #!/usr/bin/python3
"""a new moduke to count the number of lines of a file"""
def number_of_lines(filename=""):
"""function that returns the number of lines of a text file:"""
num_line = 0
with open(filename, encoding='utf-8') as a_file:
for line in a_file:
num_line += 1
return num_... |
29260e64cd500d42ec06a7de941bca45658b3d03 | zhangyanan3/python-Artificial-Intelligence | /代码/第5章深度学习与神经网络/3-激活函数.py | 897 | 4.0625 | 4 |
# 3-激活函数python实现
def sigmoid(z):
""" Reutrns the element wise sigmoid function. """
return 1./(1 + np.exp(-z))
def sigmoid_prime(z):
""" Returns the derivative of the sigmoid function. """
return sigmoid(z)*(1-sigmoid(z))
def ReLU(z):
""" Reutrns the element wise ReLU function. """
return... |
8654a979f5b006a59c05d8304560f5897ec00365 | PhillipLeeHub/python-algorithm-and-data-structure | /leetcode/230_Kth_Smallest_Element_in_a_BST_Medium.py | 547 | 3.5625 | 4 | 230. Kth Smallest Element in a BST Medium
Given the root of a binary search tree, and an integer k, return the kth (1-indexed) smallest element in the tree.
Example 1:
Input: root = [3,1,4,null,2], k = 1
Output: 1
Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3
Output: 3
Constraints:
The number of n... |
9fd5230e59016a9677bc146446fe073bea12ae1b | eanyanwu/mirthful-rcis | /mirthful_rcis/dal/datastore.py | 1,479 | 3.9375 | 4 | from mirthful_rcis import get_db
import sqlite3
import os.path
class DbTransaction:
"""
Simplifies creating a database transaction
A transaction in this sense is any sequence of commands that are executed
before calling `commit`
This is done by using a python context manager to place all t... |
7fc28902c844db88132dad93ac04ca1e7e209d71 | terrifyzhao/leetcode | /other/max_path_sum.py | 774 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def __init__(self):
self.max_path = float("-inf")
def maxPathSum(self, root):
"""
:type roo... |
b3e729e006026c40d1d834c916a8ab36f8030640 | CodeEMP/DCpython | /week2/tues/turtles/shapes.py | 1,968 | 3.75 | 4 | from turtle import *
def circle(size, fill, color):
boo = fill
if boo is True:
fill(True)
fillcolor(color)
color(color)
circle(size)
def square(size, fill, color):
boo = fill
if boo is True:
fill(True)
fillcolor(color)
color(color)
forward(size)
right... |
88dd626d84459c738bcb6918596b6dce66971e9f | rafin007/Machine-Learning | /Assignment - 1/Perceptron.py | 4,102 | 3.90625 | 4 | import numpy as np
from matplotlib import pyplot as plt
#Class for creating a Perceptron
class Perceptron:
#initialize perceptron
def __init__(self, neurons, bias, epochs, data, eta, dimensionality, num_training, num_testing):
self.neurons = neurons #number of input neurons
self.bias = bias #b... |
822b46685f0016d191c8d8116a50004915e74b40 | ArmandoBerlanga/python_playground | /src/python_tutorial/dictionaries.py | 711 | 3.875 | 4 | # Diccionarios, son lo mismo que los HashMaps en Java
digits = {
1 : "uno",
2 : "dos",
3 : "tres",
4 : "cuatro",
5 : "cinco",
6 : "seis",
7 : "siete",
8 : "ocho",
9 : "nueve",
0 : "cero"
}
value = int (input ("Inserte un valor numertico: "))
concat = ""
for c in str(value):
... |
f6f425c706bad902a44e85d3cc61b1bf7b805286 | tomreddle/vip3test | /第二次上课练习.py | 6,150 | 4.40625 | 4 | # 1、打印小猫爱吃鱼,小猫要喝水
class Cat:
def eat(self, food):
print('小猫爱吃{}'.format(food))
def drink(self):
print('小猫要喝水')
catty = Cat()
catty.eat('鱼')
catty.drink()
# 2、小明爱跑步,爱吃东西。——有吃、跑步两种方法
# 1)小明体重75.0公斤 ——人的属性
# 2)每次跑步会减肥0.5公斤 ——跑步的方法,每次减肥0.5公斤
# 3)每次吃东西体重会增加1公斤——吃的方法,每次吃增加1公斤
# 4)小美的体重是45.0公斤—— 小... |
8442e5c6d85955ac9db619036f14ac6dea5d9d42 | hakusama1024/Practice | /Big_Integer.py | 1,493 | 3.71875 | 4 | class BigInteger:
def __init__(self, num):
self.bigInteger = []
self.sign = False
if num < 0:
self.sign = True
num = abs(num)
while num:
self.bigInteger.insert(0, num%10)
num /= 10
if self.sign:
self.bigInteger.insert(0, '-')
def add(self, n):
sign = False
if n < 0:
sign = True
n = ... |
dede3764d57eb9909477a8bd1caa35b77e856178 | hamdi3/Python-Practice | /Generators.py | 2,315 | 4.375 | 4 | #Generators are used when dealing with very long lists since theyre are mem. efficent (Lazy object)
def genraum(n):
for num in range(n):
yield num**3 #using yield instead of return is by generators since the generators only run once and does'nt sotore anything in the memory meaning its significantly efficen... |
dd4160faf7592705626f7e9dee95fa6f55d10a13 | claudey/zoo-assignment | /zoo_class.py | 3,386 | 3.890625 | 4 | class Zoo:
def __init__(self,name,gender,age):
self.name = name
self.gender = gender
self.age = age
def get_injured(self):
pass
##
####class for animals
####and all of its sub classes
##
class Animals(Zoo):
def __init__(self,name,gender,age):
Zoo.__init__(self,na... |
325f782db869edeb8ba40308a8c01002984d00d8 | Asha-Billava/django-rest-calendar | /core/utils.py | 745 | 3.59375 | 4 | # -*- coding: utf-8 -*-
import pytz
# Assume the calendar is for Europeans only (as it currently has only Polish language).
TIMEZONE_CONTINENT = "Europe"
# Assume the application is for Poles mostly (as it currently has only Polish language).
DEFAULT_TIMEZONE = "Europe/Warsaw"
SYSTEM_TIMEZONE = "Europe/Warsaw"
def ... |
fd7abfc15d0b61465243e3092042ff03e7288dd4 | husnejahan/MyLeetcode-practice | /Algorithms and data structures implementation/Graph/boggleSearch.py | 3,144 | 4.03125 | 4 | """You're given a 2D Boggle Board which contains an m x n matrix (2D list) of characters, and a string - word. Write a method - boggle_search that searches the Boggle Board for the presence of the input word. Words on the board can be constructed with sequentially adjacent letters, where adjacent letters are horizontal... |
955291aad2dc60394164db84b47188bad795bbbe | NPozn/Python_Lab_7 | /Task4.py | 368 | 3.71875 | 4 | #Содержит ли согласные буквы
import re
def ContainSymbols(s):
return re.findall(r"[wrtpsdfghjklzxcvbnmцкнтглдшщзхфвпртсчб]", s) != []
exist = ContainSymbols(input("Введите слово"))
if exist == True :
print("Есть согласная буква")
else:
print("Согласной буквы нет") |
773e7ea877e8179e62382ca04408d30eb70c078e | zelanko/MyProjectEulerSolutions | /Project_0005/SmallestMultiple.py | 483 | 3.609375 | 4 | """Smallest multiple
[Problem 5](https://projecteuler.net/problem=5)
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?"""
candidate = 2520
found = False
while ... |
b8d463232b0521f1c5d729c6428b75a7234b242a | RawitSHIE/Algorithms-Training-Python | /Dote.py | 296 | 3.640625 | 4 | """
60070081
Dot_E
"""
def main():
"""dota"""
per = int(input())
if per%2 == 1:
per += 1
team = fac(per)/(fac(per/2)*fac(per/2))
print(int(team))
def fac(num):
"""fac"""
count = 1
for i in range(1, int(num)+1):
count *= i
return count
main()
|
269b476e19b9f54aead730a204f2bb554e1c7c25 | OneCalledSyn/project-euler | /Python Problems/euler12.py | 1,100 | 3.734375 | 4 | # What is the value of the first triangle number to have over five hundred divisors?
#First try (failure)
import math
n = 5
divisors = 1
number = 6
x = 4
while True:
for i in range(2, math.floor(number/2) + 2):
if number % i == 0:
divisors += 1
if divisors = n:
break
number +=... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.