blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
4f2446c6e97c3d5f2cf6b5896e6576fa3f6dbd3f | nicolaemariuta/PythonTutorial | /learnRegularExpressions.py | 3,736 | 4.40625 | 4 | import re
#Basic example 1
"""
str = 'an example word:cat!!'
match = re.search(r'word:\w\w\w', str)
# If-statement after search() tests if it succeeded
if match:
print('found') ## 'found word:cat'
print (match.group())
else:
print('did not find') """
#Basic example 2
## Search for ... |
7e9d5b736d04e4bd7bf933d5b23522c42c51353b | vutsalsinghal/CleanFlow | /cleanflow/assertions.py | 1,169 | 3.625 | 4 | def assert_type_str_or_list(df, variable, name_arg):
"""This function asserts if variable is a string or a list dataType."""
assert isinstance(variable, (str, list)), "Error: %s argument must be a string or a list." % name_arg
def assert_type_int_or_float(df, variable, name_arg):
"""This function asserts ... |
b5263c64df9c817980c470688afe4cfbc632c761 | dawid0planeta/advent_of_code_2018 | /day2/day2.py | 1,677 | 3.8125 | 4 | from collections import Counter
def read_file(filename):
file_data = open(filename)
data = list(map(lambda line: line.strip(), file_data))
return data
def count_letters(line: str) -> Counter:
return Counter(line)
def does_repeat_x_times(line: str, x: int) -> bool:
letter_count = count_letters(... |
e2974d647c5cda397471fe8654e75137e297ea10 | palakgupta889/GPS-Data-Analyser | /extra files/gpxread_mod1_Nikhil.py | 9,555 | 3.6875 | 4 | # -*- coding: utf-8 -*-
# Copyright (c) 2018, Anders Lervik.
# Distributed under the LGPLv2.1+ License. See LICENSE for more info.
"""This module defines methods for reading data from GPX files."""
from xml.dom import minidom
from datetime import datetime
from math import atan, atan2, radians, tan, sin, cos, sqrt
impor... |
e9683267b636a822e2ab4e7e3f11d76614b0273c | joshualxndrs/ALGOPRO-HW-1_Exercise1-2_JOSHUA | /EX2_Ramp angle_Joshua.py | 374 | 4.15625 | 4 | #Input mass, Input Force
#C = 9.8
#Formula for angle --> angle = f/(m*c)
#Asin(angle) --> degrees
import math
m = float(input("Please enter the mass of the cart (unit in kg): "))
f = float(input("Please enter the force acting on the cart (unit in N): "))
c = 9.8
angle = f/(m*c)
A = math.asin(angle)
Final = math.deg... |
e286d1f3a6771e339ce75fd298d8a4b053ab91ef | ceasaro/projecteuler.net | /euler/problem_0003.py | 2,171 | 3.796875 | 4 | from math import sqrt
from core.EulerProblem import EulerProblem
import log
__author__ = 'cvw'
primes = []
prime_factor_number = 600851475143
def increment_prime(number):
if number > 2:
return number + 2
else:
return number + 1
def nextPrime():
lastPrime = primes[-1]
nextPrime = inc... |
0dbc1c88a6c90cbc8b55486ddf3e8f1bdd19599e | 625781186/lgd_spiders | /others/demo/过滤字符串.py | 1,034 | 3.765625 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/10/14 14:45
# @Author : LGD
# @File : 过滤字符串.py
# @功能 : 过滤字符串
def filter_string(string):
temp = ''
str_list = list(string)
del_list = []
if len(str_list) <= 1:
return str_list
for i in range(len(str_list)):
if i < len(str_list) - 1:
... |
c9324fed783bb2ecc1553638e0d5c65305e662d7 | chjfth/trivials | /python/ratelimit/main.py | 732 | 3.65625 | 4 | import time
from datetime import datetime
from ratelimit import ratelimit
g_count = 0
# The decorator @ratelimit(500), will limit actual calling rate of
# print_now_time() to be at most once every 500ms.
@ratelimit(500)
def print_now_time(prefix):
global g_count
g_count += 1
dt = datetime.now()
prin... |
c63a88851182385385794c4d59bd63ce91a7eec5 | mohdtayyab/travis-test | /tests/test_Calc.py | 370 | 3.734375 | 4 | from Calculator import Calculator
# Tests addition method in Calculator
def test_add():
x,y = 1,2
instance = Calculator(x,y)
assert instance.add() == x + y, "Add method doesnt work"
# Tests subtraction method in Calculator
def test_subtract():
x,y=1,2
instance = Calculator(x,y)
assert instance... |
7b34461600fa26f7a09e46064a74400063dc12d8 | dungcau1/CS106B-MartyStepp-PythonRewritten | /LinkedList.py | 1,452 | 3.796875 | 4 | class LinkedNode:
def __init__(self,d=0,n=None):
self.data=d
self.next=n
class LinkedList(LinkedNode):
def __init__(self):
self.front=None
def get(self,ind):
i=0
cur=self.front
while i<ind:
cur=cur.next
i=i+1
return cur.data
... |
3e347898145ea0ead73e21a53034887b1d7312bc | minseunghwang/YouthAcademy-Python-Mysql | /작업폴더/16_파이썬에서의함수/main.py | 3,999 | 3.609375 | 4 | # 매개변수 이름
def test1(a1, a2 ,a3):
print('test1 호출')
print(f'a1 : {a1}')
print(f'a2 : {a2}')
print(f'a3 : {a3}\n')
test1(100, 200, 300)
# 매개변수의 이름을 통해 넘겨줄 값을 지정할 수 있다.
test1(a2=200, a3=300, a1=100)
test1(100, a3=300, a2=200)
# a3에 정해진 값이 이미 있기 때문에 3번째 값을 어떤 매개변수에 넣어야 할 지 판단할 수 없기 때문에 오류 발생
# test1(a3=30... |
f647062c093159a42a7a87f9be25ba636ddb5d4c | minseunghwang/YouthAcademy-Python-Mysql | /작업폴더/09_Set/main.py | 1,755 | 4.125 | 4 | # Set
# 파이썬에서 집합 처리를 위한 요소
# 중복을 허용하지 않고, 순서 혹은 이름으로 기억장소를 관리하지 않는다.
# set 생성
set1 = {}
set2 = set()
print(f'set1 type : {type(set1)}')
print(f'set2 type : {type(set2)}')
print(f'set2 : {set2}')
set3 = {10, 20, 30, 40, 50}
print(f'set3 : {set3}')
print(f'set3 type : {type(set3)}')
# 중복 불가능 (중복제거용도로 사용)
print('중복 No-... |
2e0d21c83b8b7e732a1feac446790d67dde82fc5 | minseunghwang/YouthAcademy-Python-Mysql | /작업폴더/26_name변수/module1.py | 609 | 3.765625 | 4 | # module1.py
print(f'__name__ : {__name__}')
# __name__ 변수 사용 예
# __name__ 변수에는 모듈의 이름이 들어 있지만 현재 모듈을 실행할 때 사용했다면 '__main__'이라는 문자열이 들어있다.
# 이를 이용해 현재 모듈에서 구현한 함수나 클래스 등을 테스트 해보기 위한 코드를 작성한다.
def add(a1,a2):
return a1 + a2
def minus(a1,a2):
return a1 - a2
if __name__ == '__main__':
r1 = add(100,200)
... |
aa721dce793afd84dbf5118496d88760496f95f1 | minseunghwang/YouthAcademy-Python-Mysql | /작업폴더/35_학생관리(저장)/student.py | 414 | 3.546875 | 4 | # student
# 학생 정보를 관리하는 클래스
class StudentClass:
def __init__(self, name, age, kor):
self.name = name
self.age = age
self.kor = kor
def show_student_info(self):
print(f'이름 : {self.name}')
print(f'나이 : {self.age}')
print(f'국어점수 : {self.kor}')
def __str__(self... |
db02681a822fe74b5a61775ec4375cddbe5cb0e0 | codyowl/python-training | /regular-expression/regex_verbose.py | 410 | 3.6875 | 4 | import re
pattern1 = re.compile(r"""\d + # the integral part
\. # the decimal point
\d * # some fractional digits""", re.X)
pattern2 = re.compile(r"\d+\.\d*") # pattern p2 is same as p1
myregex1 = re.findall(pattern1, u"a3.45")
myregex2 = re.findall(pattern2, u"a3.45")
... |
4e69b6366dd2631b46204ea23c40375dca736d81 | i-am-charlie/python_scripts | /pmf.py | 1,007 | 3.9375 | 4 | """ We create an algorithm that will generate draws from a discrete probability
distribution, with a given probability mass function, q.
One way to implement the algorithm, given 'q', is as follows:
"""
import numpy as np
from random import uniform
def sample(q):
a = 0.0
U = uniform(0,1)
for i in rang... |
15164cfb7e24da7cef32adc436d6b013a6116dfa | liyjie00/data_structures_in_python | /linkedlist.py | 2,059 | 4.03125 | 4 | class Linkedlist(object):
def __init__(self):
self.head = None
self.size = 0
def __str__(self):
s = ""
currentNode = self.head
while currentNode is not None:
s = s + str(currentNode.data)
currentNode = currentNode.next
if currentNode i... |
6d0cd3309024a356570ce0448321d4f3fdde5a6f | ritkumar10/EDA | /MissingValueAnalysis/missing.py | 6,000 | 3.90625 | 4 |
import pandas as pd
from autoimpute.imputations import SingleImputer
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import LogisticRegression
from MissingValueAnalysis import knn as knn
class Missing(object):
"""This module performs missing value analysis and imputation in a dataset.... |
56a20341241eddb541b71d12e6056046648a1461 | tborzyszkowski/LogikaProgramowania | /src/lab/lab02/z_7_slownie.py | 491 | 3.71875 | 4 |
def number_to_list(number):
liczba = number
result = []
while liczba > 0:
result.append(liczba % 10)
liczba = liczba // 10
result.reverse()
return result
def number_list_to_names(numb_list):
numbers = ["zero", "jeden", "dwa", "trzy", "cztery", "piec", "szesc", "siedem", "osiem... |
6105aafd9845c4d2ae6cea576ab012ca457d9bb0 | tborzyszkowski/LogikaProgramowania | /src/lab/lab01/z_4_delta.py | 513 | 3.53125 | 4 | from math import sqrt
a = 1
b = 7
c = 12
if a == 0:
if b == 0:
if c == 0:
print('Duzo')
else:
print("Brak")
else:
print('x = ', (-c)/(b*1.0))
else:
d = b * b - 4 * a * c
if d > 0:
dd = sqrt(d)
print('x1 = ', (-b - dd)/(2*a))
print(... |
7d02a569ee859cf94cac4078956d7375d891ec75 | tborzyszkowski/LogikaProgramowania | /src/a06dziel_i_zwyciezaj/bubble_sort.py | 453 | 4 | 4 | from random import randint
counter = 0
def bubble_sort(arr):
global counter
for i in range(0, len(arr)):
for j in range(len(arr) - 1, i, -1):
counter += 1
if arr[j - 1] > arr[j]:
arr[j - 1], arr[j] = arr[j], arr[j - 1]
if __name__ == "__main__":
dane = [ra... |
5681fd8990be835a13b2724b6c0458a30fa86027 | tborzyszkowski/LogikaProgramowania | /zadania/04pliki/wig.py | 598 | 3.5 | 4 | import csv
import statistics
with open('wig_d.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
next(readCSV)
counter = 0
volumen_lista = []
diff_lista = []
for row in readCSV:
volumen = float(row[5])
volumen_lista.append(volumen)
diff = float(row[2]) - floa... |
858453f43d28f982d0c7607901b964934d1f0624 | Yiming992/Data_Structures_And_Algorithms | /Binary_Search.py | 425 | 3.921875 | 4 | """
Binary Search of an ordered list
"""
def binarySearch(alist,item):
first=0
last=len(alist)-1
found=False
while first<=last and not found:
mid=(first+last)//2
if alist[midpoint]==item:
found=True
else:
if item<alist[midpoint]:
... |
9ea495893214e6b528e8ec5c8d1912819d376558 | usrfriendly/eulersolutions | /Problem2.py | 253 | 3.515625 | 4 | i = 0
a = 0
b = 1
c=0
d=0
fib=list()
while c < 4000000:
if i <= 1:
c = i
else:
c = a + b
a = b
b = c
i = i+1
if c % 2 == 0:
d += c
if c < 4000000:
print(c)
print("Sum of evens is:",d)
|
139f83da49a14c7c1ff0857a0f4e6c73a3a3e414 | Banich-AI/homework4 | /myfunctions_answer.py | 1,833 | 3.625 | 4 | def simple_separator():
print('**********')
return simple_separator
simple_separator()
print('Привет всем!')
def long_separator(count):
print('*' * count)
return long_separator
long_separator(10)
def long_separator(simbol, count):
print(simbol * count)
return long_sepa... |
669462f0ab54fbe8e40ee30a2c6bf43f6321b7f4 | ChuangTseu/PlayingWithProjectEuler | /ProjectEuler/OtherLanguages/Python/problem24.py | 1,371 | 3.53125 | 4 | from math import factorial
# 10 first digits means 10! possible combinations
# 10! == 3,628,800
# 9! == 362,880
# For each digit 0..9, we find wich sub slice contains our millionth
# Is it the slice starting with 0? Or with 1? 2? etc.
# When found, we append this digit, remove it from the pool, and start agai... |
fe872eb022170767bdf288b27501aefb72bc346c | aiemanuel/chiffre_cesar | /main.py | 672 | 3.5625 | 4 | from chiffrement import*
from dechiffrement import*
while True:
choix = input ("Souhaitez-vous [c]hiffrer ou [d]échiffrer un message?")
if choix == "c":
msg = input("entrez le message a chiffrer (en lettre capitales, sans espace ni ponctuation):" )
msg_chiffre =chiffrement (msg)
print(f... |
77798e9f0c7291b1869a122807e68933ae19e672 | akadi/fizzbuzz | /test_fizzbuzz.py | 830 | 3.625 | 4 | #Test fizzbuzz function
#See http://content.codersdojo.org/code-kata-catalogue/fizz-buzz
#For lanch test:
#$python test_fizzbuzz.py
import unittest
from fizzbuzz import fizz_buzz
class TestFizzBuzz(unittest.TestCase):
""" Class for test get Fizz Buzz"""
def test_get_romain_numerals(self):
"""
... |
8b04bdbb8b5a65b60b50b4e2ce6bdfba32895a32 | oleksis/pybites | /189/control_flow.py | 598 | 3.5625 | 4 | IGNORE_CHAR = 'b'
QUIT_CHAR = 'q'
MAX_NAMES = 5
def filter_names(names):
def _have_digits(name):
digits = "0123456789"
result = False
for ch in name:
if ch in digits:
result = True
break
return result
count = 0
for ... |
85bab6f059743adc19da83a4a6ef82e52d48108e | sbiauek/ALX_Zadanie_Domowe | /Zadanie 1.7.py | 564 | 3.625 | 4 | # ### Zadanie 1.7 | Liczenie cen (ok. 0,5 godz.)
#
# Przy pomocy `input()` zapytaj użytkownika co chce kupić, jaką ilość towaru chce kupić i
# jaka jest jego cena. Wyświetl odpowiedni komunikat.
#
# Przykład:
# Co chcesz kupić? - ziemniaki
# Podaj cenę towaru - 5
# Podaj ilość towaru - 10
#
# Za ziemniaki, który chcesz... |
291a5cd01a5f93045e04dc043dd92c38a2cf0a25 | sbiauek/ALX_Zadanie_Domowe | /Zadanie 1.5.py | 962 | 3.953125 | 4 | # ### Zadanie 1.5 | Pole trójkąta (ok. 1 godz.)
#
# Program, który odczytuje trzy liczby, sprawdza czy liczby te mogą stanowić boki trójkąta
# (np. z 2, 2 i 5 nie da się ułożyć trójkąta, prawa?), a jeśli mogą, oblicza pole powierzchni trójkąta o takich bokach.
#
# Wykorzystaj trzeci wzór z [listy](https://www.matemaks.... |
b82b69a31fdc4fe870a18ab244a2c8de696d949b | ali3nw4re/Python-Coding-Challenges | /1. 1.py | 1,783 | 3.84375 | 4 | #Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
input_array = [1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 6, 28, 7, 29, 2, 3, 12, 13, 14, 14.5, 14.5]
k = 29
answer = 0
m = 0
checked_array = []
i = 0
... |
e187a587c1cea24fdc0d9c8c05a8f1743be58c6a | rwhite5279/sorting_algorithm_analysis | /comparisons.py | 3,134 | 4.09375 | 4 | #!/usr/bin/env python 3
"""
comparisons.py
This program times, compares, and graphs the performance
of selection_sort(), insertion_sort(), and quicksort().
"""
__author__ = 'Theo Demetriades'
__version__ = '2021-03-18'
from selection_sort import *
from insertion_sort import insertion_sort
from counting_sort import c... |
a0bd50d67021a58212bf6aa28f4b5de3d4546a83 | yohan1152/nuevas-tecnologias-taller-python | /ejercicios-conceptos-basicos/ejercicio8.py | 435 | 3.859375 | 4 | """
Edad ingresada por usuarios es la misma True o False
"""
try:
edad1 = 0
edad2 = 0
edad1 = int(input("Ingresar edad del primer usuario: \n"))
edad2 = int(input("Ingresar edad del segundo usuario: \n"))
if edad1 == edad2:
print("\nLas edades son las mismas: ", True)
else:
... |
d27f7bff8f099b1f4c82f367ca1e2d90e624ccbe | yohan1152/nuevas-tecnologias-taller-python | /ejercicios-basicos/ejercicio2.py | 315 | 3.90625 | 4 | """
2. Se requiere un algoritmo para obtener la suma de diez cantidades mediante la utilización de un
ciclo for.
"""
try:
N = 10
suma = 0
for i in range(N):
suma += float(input("Ingresar valor # %s: \n" %(i+1)))
print("\nSuma total: ", suma)
except ValueError:
print("Error.") |
e10f9d516bb96f9a41f3b72c245726027dddce3f | NamamiShanker/Python-Work | /GuessingGame.py | 449 | 3.984375 | 4 | print("The game starts. Think of a number between 1 and 100")
lower = 1
upper = 100
for i in range(7):
middle = int((lower+upper)/2)
val = input("Where you thinking of "+str(middle))
if val == 'yes':
print("Number found")
break
else:
val = input("Is your number 'bigger' or 'smal... |
5361e96cc0de895a4718cc5f415fe85ec351d5e9 | NamamiShanker/Python-Work | /sumOfDigits.py | 530 | 4.1875 | 4 | # Advanced if else statement - elif ladder
# -----------------------------------------
import time
'''
Banana, Orange, Apple
<=10 w - Banana
>10 and <=20 - Orange
>20 and <=30 - Apple
>30 and <=40 Watermelon
>40 Knife
'''
def main():
money = 5
if money<=10:
print("Banana")
elif money <= 20:
... |
7beea1c54408e43e724dc8879422186385199fa6 | NamamiShanker/Python-Work | /conditional_statements_2.py | 679 | 4.34375 | 4 | # Conditional Statements
# if elif else- statement
# if - elif ladder
color = input("Enter a color in rainbow: ")
if color == 'violet':
print("It is the first color in the rainbow")
elif color == 'indigo':
print("It is the second color in the rainbow")
elif color == 'blue':
print("It is the thrid color i... |
201080568bb74f76c43d76a972f67b9cf12ed9cf | NamamiShanker/Python-Work | /nested_loops.py | 1,433 | 3.578125 | 4 | # Nested Loop - Loop is inside another Loop
'''
b = int(input())
for n in range(1, b):
for i in range(1, 11):
if n%10 == 0:
break
print(n, 'x', i, '=', n*i)
print('---------------')
'''
'''
*
* *
* * *
* * * *
'''
for i in range(4):
for j in range(i+1):
print("*", end =... |
89ea7b81e4e59db4b9097c36b5a27552f27853ce | NamamiShanker/Python-Work | /exception_handling.py | 332 | 3.8125 | 4 | # Exception - These are errors that happen during the execution of program.
# try, except blocks
# Write those lines of code that can cause exception here
try:
n = int(input("Enter a number: ")
except:
print("jbask")
n = int(input("Enter a number: "))
m = int(input("Enter another number: "))
print(n/m)... |
2d0173cbcac6e402a983347745f5f7cb1c8cd957 | btigercl/Hackbright_ex09 | /markov.py | 1,925 | 3.625 | 4 | #!/usr/bin/env python
from sys import argv
def make_chains(corpus):
"""Takes an input text as a string and returns a dictionary of
markov chains."""
markov_dictionary = {}
filename = open(corpus, 'r')
read_file = filename.read()
words = read_file.split()
for word_index in range(0, len(word... |
2d844bf45699fd1bba68b8e0979fe6c2943432ac | WaqarHassan/OO_Python | /pp.py | 2,398 | 3.765625 | 4 | import os
import random
import sys
import pdb
class Animal(object):
__name = ""
__height = 0
__weight = 0
__sound = 0
def __init__(self,name,height,weight,sound):
self.__name = name
self.__height = height
self.__sound = sound
self.__weight = weight
def set_name(self , name):
self.... |
871f7841a060b6684c93ef2735d071ae61c8cb34 | megan-davi/Python-Projects | /morseCode.py | 5,935 | 4.03125 | 4 | """
Prompt: use a binary tree to decode a string of morse code
"""
import re
import itertools
class BinaryTree:
def __init__(self,rootObj):
self.key = rootObj
self.leftChild = None
self.rightChild = None
def insertLeft(self,newNode):
if self.leftChild == None:
... |
8daeb1055024161c82458a30b6851222ed70ccfb | megan-davi/Python-Projects | /ReverseSentences.py | 659 | 3.78125 | 4 | class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
... |
cb334c776e03fc1f69d4c8ab5e120c2d3e44f3b7 | s-killer/practice | /HackerRank/calender.py | 371 | 3.90625 | 4 | # https://www.hackerrank.com/challenges/calendar-module/problem
import calendar
if __name__ =="__main__":
d,m, y = input().split()
l = ["sunday","Monday","tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
print(int(y))
if (int(y) > 2000 and int(y) < 3000):
index = calendar.weekday(int(y... |
34690968d6df9e58e7ace3fec1d625c3875252c8 | tanjina-3ni/Coursera-programming-for-everybody | /courseraweek6.py | 395 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 19 18:24:03 2019
@author: Aspire
"""
def computepay(h,r):
if (h>40):
x = h-40
pay = 40*r+x*r*1.5
return pay
hrs = input("Enter Hours:")
hr=float(hrs);
rate = input("Enter Rate Per Hour:")
rt=float(rate);
p = computepay(hr,rt)
p... |
94cfb6186b0acc1f32769dd9e78e3b1c201e83c0 | realbucksavage/pymycloud | /owncloud_utils/strings.py | 445 | 4.03125 | 4 | import random
import string
def randstr(chars=string.ascii_lowercase + string.digits, len=16) -> str:
"""Generates a random string out of given charactes.
Parameters
----------
chars : type
An array if charaters to generate the string from.
len : type
Length of the string.
Re... |
e68f4e477a43db797eee1872a7af8a56b6cccfea | MohamedELfeky44/Tic-tac-toe | /Tic tac toe/Tic tac toe (1) version1.py | 5,335 | 4.0625 | 4 | #tic tac toe game
class Board():
def __init__(self):
self.cells = [" "," "," "," "," "," "," "," "," "," "] #creat the board
def display(self):
#display the board
print(" %s | %s | %s " %(self.cells[1],self.cells[2],self.cells[3]))
print("---... |
07b8df910e1e5fb2c27c3f64ae90b40992b65f97 | Snothy/Hangman-Game | /Hangman.py | 5,255 | 3.8125 | 4 | import turtle
sonic = turtle.Turtle()
sonic.hideturtle()
lives = 6 #Head, body, 2arms, 2legs.
counter = 0
secret_word = input("Insert word: ").lower()
#Hiding the word from the guesser.
for i in range(1000):
print(" ")
#Drawing the hanging board.
sonic.penup()
sonic.right(90)
sonic.forward(50)
sonic.... |
e704fac5a5ae2263d8d5b88c1b4043d69d63ae45 | t-a-y-l-o-r/Effective_Python | /1_CH/Zip.py | 912 | 4.4375 | 4 | '''
Author: Taylor Cochran
Book: Effective Python
Ch1
Goal:
To learn about zipping iterators
'''
# create a list from another list using list comprehension
names = ['Johnathan', 'Noah', 'Billy']
letters = [len(n) for n in names]
# to iterate over each list in parallel, iterate over the length of the names source ... |
e2ad028efc64ffb5ccae11b78dc0de089c8b6334 | t-a-y-l-o-r/Effective_Python | /2_CH/None.py | 1,119 | 4.28125 | 4 | '''
Author: Taylor Cochran
Book: Effective Python
Ch2
Goal:
To learn why preferring exceptions to returning None is better
'''
# temptation
def divide(a, b):
try:
return a / b
except ZeroDivisionError:
return None
x, y = 1, 2
result = divide(x, y)
if result is None: # breaks down when result is 0
pri... |
8dca1218c21eb1a74baafc12e3fc2b4bef5d1847 | t-a-y-l-o-r/Effective_Python | /3_CH/Interface.py | 2,898 | 4.03125 | 4 | '''
Author: Taylor Cochran
Book: Effective Python
Chapter 3
Goal: Learn to accept functions for simple interfaces instead of classes
'''
from collections import defaultdict
# some api's allow "hook" functions to be passed as arguments
# in the case of the sort function it allows you to determine
# how the sort is in... |
4d39eb2cdeb3728a34ed451572cb7e31c6ef9ab9 | bielamonika/kurs_python | /hackaton/wisielec.py | 1,408 | 3.890625 | 4 | import random
import json
def import_password():
filename = "words_json.json"
with open(filename, "r") as read_file:
data = json.load(read_file)
category = input("Please choose category (Fruits, Animals, Countries): ")
word = str(data[category][random.randint(0,8)]).lower()
return word
def... |
622e893b971238300d4fa4361f929853696f05fb | jonathonjb/Snake | /food.py | 460 | 3.578125 | 4 | from turtle import Turtle
import random
class Food(Turtle):
def __init__(self):
super().__init__()
self.shape('circle')
self.penup()
self.shapesize(stretch_len=0.5, stretch_wid=0.5)
self.color('blue')
self.speed('fastest')
self.spawn()
def spawn(self):
... |
8dbfb1d251cb898f4d1fa2f521f10b1152ae3aff | vkmicro/Person_coding_exercises | /extraTasks/Lecturing.py | 1,802 | 3.796875 | 4 | '''
Author: Vasiliy Ulin
This is a file with test code and explanatory comments which I use to teach my friends basics of programming
'''
import random
"""
block
comment
"""
'''
interchangable
neat eh
'''
'''
var1 = 5
var2 = 2
res = 5/2
print( " res : " + str(res) + "\n hi")
i = 0
for i in range(10):
print... |
4827afd450345404004b38e99bb34dcfe84c7d57 | leeeyj/KMU-2021-CryptAnalysis | /Caesar Cipher/week3_Caesar_Lib.py | 1,938 | 3.859375 | 4 | '''
20192243 이용진
Cryptanalysis Week3-Caesar Cipher Library
'''
# --시저 암호화 함수
def encrypt(msg, key):
upAlphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
lowerAlphabet = "abcdefghijklmnopqrstuvwxyz"
ciphertext_msg = ''
for ch in msg:
if ch in upAlphabet:
idx = upAlphabet.find(ch)
... |
58b544adf907dadd8c7c754cc620ca9eca61f78c | CHONSPQX/opencv | /opencv.py | 7,042 | 3.65625 | 4 | #coding:utf-8
#step1:加载图片,转成灰度图
import numpy as np
import cv2
image=cv2.imread("image.jpg")
cv2.imshow("testimage",image)
cv2.waitKey(0)
gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
cv2.imshow("gray灰化",gray)
#while(cv2.waitKey(0)!='n'):
# pass
cv2.waitKey(0)
cv2.imwrite("process\gray.jpg", gray)
gray = cv2.blur(g... |
3af2e7a94544525039a55ba14a7a8def40999787 | SandeepRDiddi/soccer_analysis | /Soccer.py | 1,892 | 3.65625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 21 17:51:40 2021
@author: sandeepdiddi
"""
#Import Libraries for loading data from SQLITE
import pandas as pd
import sqlite3
#Declare the connection string
#For class purpose i am declaring the exported DB from ER Diagram , however
#Prefere... |
7c7445a20470c42916447bde443580edc5c3cda8 | alexdmoss/python-fiddle | /fiddle/slices.py | 499 | 4.1875 | 4 | numbers = list(range(1, 11))
print(f"Original list: {numbers}")
this_slice = slice(0, 2)
first_two_numbers = numbers[this_slice]
print(f"Slice first two: {first_two_numbers}")
this_slice = slice(0, 3)
first_three_numbers = numbers[this_slice]
print (f"First two: {first_two_numbers} and reslice to first three: {first_... |
3ec129256fdca458c1e74281b91625dbf572a462 | ComeOnDataMining/intro_deep_learning_tensorflow_tutorial | /source_code/cnn.py | 4,293 | 3.5625 | 4 | """
A CNN with Tensorflow.
"""
import tensorflow as tf
import numpy as np
class CNN(object):
def __init__(self, config):
self.config = config
# place holder for input feature vectors and one-hot encoding output
self.X = tf.placeholder("float",
shape=[None,
... |
50b518c6bbc62c1315275fc1cfd1f4098fad9bbf | WillisLiao/10-1_homework | /Q6.py | 99 | 3.609375 | 4 | import math
r, h = map(float, input().split())
mass= math.pi * r**2 *h
print("{:.2f}".format(mass)) |
ebeb8b703bc1e198545eb09581f4d563544762cf | mnjaggah/Day0 | /test_PRIME_NUM.py | 828 | 3.96875 | 4 | import unittest
from prime_num import is_prime
class TestPrimeNumbers(unittest.TestCase):
def test_zero_prime(self):
self.assertFalse(is_prime(0), msg='Zero is not a prime number')
def test_one_prime(self):
self.assertFalse(is_prime(1), msg='One is not a prime number')
def test_two_prime(se... |
6385fc88fc8d40e90dcbf366081cde7a414d3984 | fabianazabala/artificial-intelligence-tasks | /folder/thiefStealing.py | 1,866 | 4.03125 | 4 | from copy import copy
import time
#the procedure starts by creating a variable calles num_items, following by an array of strings
# that represents the items.
num_items = 4
items = ["book",
"vacuum",
"picture",
"statue",
]
values = [10, 100, 70, 80]
weights = [1, 15, 6, 14]
limit = ... |
3e36cfa297e9f1e8d9d724c7492126d260ebaa55 | yangzou/DouBan | /movieCrawler.py | 2,007 | 3.515625 | 4 | # Step 1: Import necessary packages to your application
import requests
import json
import time
import sys
# Create a method that queries all movies from a given year
class DouBanMovieCrawler:
def crawlMovies(self, year, collect_count):
totalNumber = -1
start = 0
interestingMovies = []
... |
ef16af3b9ab2aefb256296be49ec595f1c9457c3 | kimhe5623/alba-web-scrapper | /save.py | 321 | 3.5 | 4 | import csv
def save_to_file(job_details, companyName, isNewLine):
file = open(f"alba/{companyName}.csv", mode = "w" if isNewLine else "a+")
writer = csv.writer(file)
writer.writerow(['place', 'title', 'time', 'pay', 'date'])
for job_detail in job_details:
writer.writerow(list(job_detail.values()))
retur... |
58913c7c081c97dc62e85d36f5516bec52e6e00b | leonardohra/Recommendation-System-1 | /udemy_course/example_base.py | 1,652 | 3.9375 | 4 | # -*- coding: utf-8 -*-
from recommendation import Recommender
# This function generates a csv with the information on a dictionary
def dictionary_to_csv(dict, file_name):
with open(file_name, 'w') as file:
for key, value in dict.items():
for key2, value2 in value.items():
file... |
096d712232a7197380c839ddf1eab6e4ad742a83 | XiongZhouR/python-of-learning | /ch3/hello.py | 240 | 3.84375 | 4 | names = ['Jack', 'Tony', 'Tom', 'Bill']
message1 = ', How are you'
message2 = 'Hello '
print(message2 + names[0] + message1)
print(message2 + names[1] + message1)
print(message2 + names[2] + message1)
print(message2 + names[-1] + message1)
|
ed83359f45b0239ee07355718bf7794904eb10ee | Jaimss/tp-csp-2020-21 | /213_password-strength/multi_factor_jh.py | 813 | 3.671875 | 4 | import multifactorgui as mfg
# create a multi-factor interface to a restircted app
my_auth = mfg.MultiFactorAuth()
# get a username and password
valid = False
while not valid:
try:
username = input("What is your username? ")
password = input("What is your password? ")
my_auth.se... |
9f78d403b505f597600c202dd3c5bb150aaf5e43 | thanhdanh27600/dive-into-code-ml | /pre-ass1.py | 855 | 4.34375 | 4 | print("\n[Problem 1] Create using the exponentiation arithmetic operator")
"""
Code to calculate the thickness when the paper is folded once
"""
THICKNESS = 0.00008
folded_thickness = THICKNESS*(2**43)
print("Thickness: {} meters".format(folded_thickness))
print("\n[Problem 2] Unit Conversion")
# Convert meters to kil... |
10aeaf81a6e15bc43e435a159fe3ce42eeaa65af | DeepakKarishetti/Clamp-control | /grasping/src/inPolygon.py | 5,713 | 3.609375 | 4 | '''
Module containing methods for determining if a point is within a polygon
represented by a vector of points.
'''
import numpy as np
import copy
def isOdd(x):
if (x % 2 == 0):
return False
else:
return True
def rayIntersectsSegment(point_in, segment):
'''
Determines whether a give... |
67708bb7b2f9deb3c4b245b42c9a8f97ffc8abf4 | Chandani1008/hack1008 | /ques.py | 184 | 4.03125 | 4 | name,char=input("Enter name and a character of that name seperated by comma: \n").split(",")
print(f"Length of name is {len(name)}")
print(f"count :{name.lower().count(char.lower())}") |
b08549f4b043708fc05f438f11a673449dcd6423 | Chandani1008/hack1008 | /int_str_float.py | 105 | 3.765625 | 4 | a=float(input("Enter 1st no:\n"))
b=float(input("Enter 2nd no:\n"))
c=a+b
print("C is "+str(c))
|
e6b0114b7c8c906edb4357ae2c2cc2e5dc24c970 | Chandani1008/hack1008 | /rev.py | 166 | 4.3125 | 4 | name=input("Enter your name:")
print("Your reverse name is {}".format(name[::-1])) #python 3
print(f"Your reverse name is {name[::-1]}") #python 3.6 and above |
f6caa9e666ad6682714c7d3298ee6525d552ade1 | liamgowan/AutoPinMap | /mouseNow.py | 687 | 3.546875 | 4 | #==============================================================================
# mouseNow.py
# Purpose: Program to print screen location of cursor, and corresponding
# colour.
#
# Created by Liam Gowan, November 2018.
#==============================================================================
impor... |
ac4a14a402ab1c56136c91a113941ed8feeb7e0f | chucktilbury/whistle-calculator | /dialogs.py | 47,586 | 3.828125 | 4 | from tkinter import messagebox as mbox
from tkinter import ttk
import tkinter
import math
from utility import Logger, debugger
import utility
from data_store import DataStore
help_text = """
Tilbury Woodwinds Company Whistle Calculator
Chuck Tilbury (c) 2019
This software is open source under the MIT and BSD licenses... |
f0dcf08ab9eac3c3353aaaf60b66148701208be6 | doga44/Group-Project-Python | /pythongroupproject.py | 10,349 | 3.765625 | 4 | #In this program, we use yahoo finance. To run yahoo finance,
#you need to install the tool in terminal/command.
#Install fix_yahoo_finance using pip:
# $ pip install fix_yahoo_finance --upgrade --no-cache-dir
import pandas as pd
from pandas_datareader import data as pdr
import fix_yahoo_finance as yf
yf.pdr_override... |
aa7551dc9a626823642e94bf20a673817baab206 | Minnakey/Python | /Pytest 2-4.py | 277 | 3.703125 | 4 | # 2-4 序列成员资格
# 检查用户名和PIN码
database = [
['albert', '1234'],
['dilbert','4242'],
['simth','7542'],
['jones','9843']
]
username = input('User name: ')
pin = input('PIN code:')
if [username,pin] in database : print('Access granted.') |
a436b40193344f9edefb3a9c27c69947cd28da10 | litl/backoff | /backoff/_jitter.py | 782 | 3.53125 | 4 | # coding:utf-8
import random
def random_jitter(value: float) -> float:
"""Jitter the value a random number of milliseconds.
This adds up to 1 second of additional time to the original value.
Prior to backoff version 1.2 this was the default jitter behavior.
Args:
value: The unadulterated ba... |
2fa967d8f48a5e5ecbcbbe05ee37bb3b2b442d64 | Antiner/Homework | /Session 2 - Markovsky Alexander/Task_1_5.py | 231 | 4.09375 | 4 | # Task 1.5
# Write a Python program to print all unique values of all dictionaries in a list.
def task_1_5(array):
list_1 = []
for i in array:
for v in i:
list_1.append(i.get(v))
print(set(list_1))
|
2cb4b32cebeff6e22fc77764ee27f6fb7543bcfe | ROODAY/Genetic-Programming | /misc/geneticPassword.py | 2,695 | 3.6875 | 4 | import random
import operator
def generateWord(length):
i = 0
result = ""
while i < length:
letter = chr(97 + int(26 * random.random()))
result += letter
i += 1
return result
def generateInitialPopulation(sizePopulation, password):
population = []
i = 0
while i < sizePopulation:
populati... |
8348a06de2e8d0f59a5eaae9999c9166c93b18f7 | smithderon/Homework | /Monday/Week_3/examples.py | 236 | 4.15625 | 4 | """
Given an array of elements, remove duplicates
and return an array of only unique elements.
"""
array = ["Banana", "Bonanza", "Banana", "Nani"]
for items in array:
new_array = []
if items not in new_array:
new_array
|
6d707eb62f0f23d7af2794f89aec20fe388fca69 | suraj027/Python | /Practical Submission 05-11-2020/P3.py | 157 | 4.3125 | 4 | #Write a Python program to check a list is empty or not.
list1=[]
if len(list1)==0:
print("List is empty!!!")
else:
print("List is not empty.") |
2cdc0d1f2edd9f8389adb126757170548d855c95 | suraj027/Python | /Practical Submission 03-12-2020/P5.py | 391 | 4.125 | 4 | #Create a user define function to calculate compound interest rate.
def cal(P,r,n,t):
d=(r/100)
a=(n*t)
s=(P*1+d/n*a)
P=int(input("Enter Principle Amount: "))
r=int(input("Enter Interest Rate: "))
n=int(input("Enter the Number of Times that Interest is Compounded per unit 'Time': "))
t=int(input("En... |
b03cc12299a175e1216e278cdcee436ac34e1454 | suraj027/Python | /Practical Submission 19-10-2020/P4.py | 161 | 4.1875 | 4 | #Write a program to take input form the user while the user enters zero.
n=int(input("Enter some numbers: "))
c=0
while n!=0:
n=int(input(" "))
c+=1 |
ed5fd92265b4891cad0e642088849c4c4a594cac | suraj027/Python | /p1.py | 1,072 | 4.09375 | 4 | #An electronic component vendor supplies three products: transistors, resistors and capacitors. The vendor gives discount of 10% on orders for transistors if order is for more than Rs. 1000. On order of more than Rs. 500 for resistors, a discount of 5% id given, and a discount of 10% is given on order for capacitors of... |
b6c426394af42d0b97bc37a7c53893cfa7dec7d0 | suraj027/Python | /Practical Submission 07-12-2020/P4.py | 278 | 4.28125 | 4 | #Write a program in Python to check a given number is even or odd creating user defined function.
def check(n):
oe=n%2
if oe>0:
print("Entered number is odd")
else:
print("Entered number is even")
num=int(input('Enter a number: '))
check(num) |
df7fb4fe999a7c1b06c967602a41e4949dec4a3c | ISE2012/ch3 | /decision_ex2.py | 295 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 22 15:47:38 2020
@author: xyz
"""
def main():
celsius = int(input("What is the Celsius temperature? "))
fahrenheit = 9/5 * celsius + 32
print("The temperature is",fahrenheit,"degrees Fahrenheit.")
main()
|
b85174cd75846994695846b667e277cc86527a6d | coreymyster/sorting-hashing | /bubble-sort.py | 916 | 4.28125 | 4 | # Corey Sokol
# Defines the function to bubble sort
def bubbleSort(alist):
# For loop that creates the passes.
# After the below loop concludes each time, we create another pass and run through
# the below loop again.
for listPass in range(len(alist)-1, 0, -1):
# Passes through the ent... |
10de96a151cfe2b2b173d1dd50a9c4d0d89b52cd | Sudeshna12052000/Python-Bootcamp | /Activity_14.py | 437 | 3.984375 | 4 | def prime_no(n):
for i in (1,n):
if (n%i!=0):
print(n,"is a prime number")
break
elif(n==2):
print(n,"is the only even prime number")
break
elif(n==1):
print(n,"is neither prime nor compposite")
break
... |
bf6f24c4585971f2ff4906a0ab1bed957bef9d4e | Manjutadi/pronic-num.py | /pronic no.py | 186 | 3.515625 | 4 | #pronic no
def pronic(n):
for i in range(1,n):
if n==i*(i+1):
return True
if i*(i+1)>n:
return False
n=int(input())
print(pronic(n))
|
bad7fb8df11654d74bba6a83d4a219eaf4a9e734 | Kuehar/LeetCode | /Sorting the Sentence.py | 756 | 3.5625 | 4 | class Solution:
def sortSentence(self, s: str) -> str:
# 文章を分割する
s = s.split()
hashmap = {}
# HashMapにキーとして数値、アイテムとして単語を格納
for i in range(len(s)):
hashmap[s[i][-1]] = s[i][:-1]
# インデックス0から順番に値を格納し、連結させたものを返り値として返却する
for key, v... |
816021f8553a69b3dee4ac780c31e743b2e134a8 | Kuehar/LeetCode | /Pascal's Triangle.py | 696 | 3.5625 | 4 | class Solution:
def generate(self, numRows: int) -> List[List[int]]:
if numRows == 0:
return []
elif numRows == 1:
return [[1]]
triangle = [[1]]
for i in range(1,numRows):
row = [1]
for j in range(1,i):
... |
36df90b0e6fb72a8c58ac2f39bc5ad772ec35a9e | Kuehar/LeetCode | /Binary Search.py | 944 | 3.578125 | 4 | class Solution:
def search(self, nums: List[int], target: int) -> int:
lo,hi = 0,len(nums)-1
while lo <= hi:
mid = (hi+lo)//2
if target == nums[mid]:
return mid
elif target > nums[mid]:
lo = mid+1
elif target < nums[mid]... |
a7b75719e79466fd3c084a88cdd1cda16f1209d6 | Kuehar/LeetCode | /Keyboard Row.py | 953 | 3.75 | 4 | class Solution:
def findWords(self, words: List[str]) -> List[str]:
first = ["q","w","e","r","t","y","u","i","o","p"]
second = ["a","s","d","f","g","h","j","k","l"]
third = ["z","x","c","v","b","n","m"]
ans = []
for word in words:
first_count = second_count = thir... |
d486c36886d1dc799bd24fee445abfc8bc38fb2e | Kuehar/LeetCode | /Reverse String.py | 1,824 | 4.09375 | 4 | class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
return s.reverse()
# Runtime: 208 ms, faster than 82.72% of Python3 online submissions for Reverse String.
# Memory Usage: 18.3 MB, less than 5.81% of Python3 onl... |
e64bc145785224e0c3ed0bfba8120ad930381220 | Kuehar/LeetCode | /Contains Duplicate.py | 849 | 3.703125 | 4 | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
l = sorted(nums)
for i in range(len(nums)-1):
print(i)
if l[i] == l[i+1]:
return True
return False
# Runtime: 144 ms, faster than 5.87% of Python3 online submissions for Contains Dup... |
1047a35446361ecb94483f3b66017505f9300e24 | Kuehar/LeetCode | /Merge Sorted Array.py | 1,878 | 4 | 4 | class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
# mとnが0になるまでループ。各処理の最後で該当する値をディクリメント。
while m > 0 and n > 0:
if nums1[m - 1] > nums2[n - 1]:
... |
9c80e7d4f3925baefaa861b6a3fc6b8f6a5488b0 | Kuehar/LeetCode | /Replace Elements with Greatest Element on Right Side.py | 528 | 3.609375 | 4 | class Solution:
def replaceElements(self, arr: List[int]) -> List[int]:
m = -1
i = len(arr)-1
while i >= 0:
temp = arr[i]
arr[i] = m
if temp > m:
m = temp
i -=1
return arr
# Runtime: 169 ms, faster than 57.00% of Python3... |
7ea49dba11b3d9234f5b1b6d9ad5b5f574e6bd85 | Kuehar/LeetCode | /Intersection of Two Arrays.py | 265 | 3.640625 | 4 | class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
set1,set2 = set(nums1),set(nums2)
return list(set1&set2)
# Runtime: 56 ms, faster than 44.78% of Python3 online submissions for Intersection of Two Arrays.
|
31c37c6ca985dc5ff46d1af3cad30ae967cdd43c | tuncyureksinan/Learn-Python-The-Hard-Way | /ex14.py | 1,347 | 4.625 | 5 | # Import the argv method from the sys module
from sys import argv
# Assign the arguments in the arguement variable to
# the variables script and user_name respectively
script, user_name = argv
# Assign the character '>' to the prompt variable
prompt = '> '
# Insert the variables user_name and script
# into the stri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.