blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
ef35e70ab533ad35f5f299aa602eed0bf4d7a403 | Adison25/CS362-inClass4 | /countPytest.py | 467 | 3.625 | 4 | def count(count):
check = 1
#check input
for i in range(len(count)):
if (i+1 < len(count)) and count[i] != " " and count[i+1] == " ":
check = check + 1
return check
def test_palindromeTrue():
assert count("maam") == 1
assert count("hi everyone") == 2
assert count("what up b... |
14082d5fe19213c33b4aee7ad4b6663883007a42 | Pritish0173/Phonebook | /Contact.py | 5,800 | 3.78125 | 4 | import pickle
import pathlib
# Class for contact inputs
class Contact:
def __init__(self, name, phno, email):
self.name = name
if phno.isdigit():
self.phno = phno
else:
self.phno = None
if email.isspace() or email == "":
self.email = None
... |
5a160497703f7ee6efd9cbf8d3216993d7315d6f | tusharmahajan/machine-learning-june-2018 | /Kernel_filteringMatrix.py | 614 | 3.8125 | 4 | import numpy as np
def multiply (big_matrix , small_matrix):
temp1 = np.subtract((big_matrix.shape),(small_matrix.shape))
temp = np.add((temp1),([1,1]))
x , y = small_matrix.shape[0],small_matrix.shape[1]
final_matrix = np.zeros(temp)
for i in range(temp[0]):
for j in ... |
fc01cec9b9acfbad9ed6e8cb1a7ad0ac65fbd0af | RocketDonkey/project_euler | /python/problems/euler_035.py | 594 | 3.5 | 4 | """Project Euler - Problem 35
The number, 197, is called a circular prime because all rotations of the digits:
197, 971, and 719, are themselves prime.
There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71,
73, 79, and 97.
How many circular primes are there below one million?
"""
from primes... |
4d872b88871da0fd909f4cb71954a3f0f8d0f43f | RocketDonkey/project_euler | /python/problems/euler_001.py | 470 | 4.125 | 4 | """Project Euler - Problem 1
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
def Euler001():
num = 1000
r = range(3, num)
for index, i in enumerate(xrange(3, num)):
... |
b6673f4de385c539083d0be484d0caa8a789697b | i-abr/DecentralizedErgodicControl | /d_erg_lib/barrier.py | 1,120 | 3.78125 | 4 | import numpy as np
class Barrier(object):
'''
This class prevents the agent from
going outside the exploration space
'''
def __init__(self, explr_space, pow=2, weight=100):
self.explr_space = explr_space
self.dl = explr_space[1,:] - explr_space[0,:]
self.pow = pow
... |
aa431f95be0baf167285a62987df29142a75557c | nicodaisuki/Stochastic-Process-2018 | /Queue.py | 1,310 | 3.671875 | 4 | #Written by Kalvin Goode 9454554, 4/27/2018
import numpy as np
import matplotlib.pyplot as plt
import math
T=100
record=[0]
customer=[0]
server=[0]
time=0
state=-1
maxi=0
while(time<T):
if(state==-1): #when no customer in line
customer=np.random.exponential(0.5,1)
time+=customer
state+=1 #one more... |
ba8fa01022b4e438af5998b9a991f4809f8a889d | WhiteHair-H/StudyRasberry21 | /Test/test/test01.py | 716 | 3.859375 | 4 | # 변수 기본
n = 1
name = 'Sung'
n = n + 2
value = 1.2 * n
# print('{0} = 1.2 * {1}'.format(value, n))
# print(name)
# 문자(배열) 인덱스 방법
greeting = 'Hello World'
# print(greeting[0]) # H
# print(greeting[2:5]) # llo
# print(greeting[:2]) # l
# print(greeting[-2:]) # ld
# print(greeting * 2)
# List
numbers = [0, 1, 2, 3]... |
dd722b74a09bab091674c315ac8442486fd41eed | mnylen/pygraph | /pygraph/core.py | 4,657 | 3.78125 | 4 | class Node(object):
"""
Represents a node in a graph.
"""
pass
class NamedNode(Node):
"""
Represents a named node in a graph.
"""
name = str
def __init__(self, name):
self.name = name
def __hash__(self):
return hash(self.name)
def __eq__(self, other):
... |
0de97c7d711b39eb109dbe8649918792fd8eedf0 | maria-zdr/softuni | /Python Fundamentals/Exams/Exam 2018-08-11/02. Gladiator Inventory.py | 712 | 3.59375 | 4 | inventory = input().split()
while True:
data = input().split()
if data[0] == 'Fight!':
break
command = data[0]
equipment = data[1].split('-')[0]
if command == 'Buy' and equipment not in inventory:
inventory.append(equipment)
elif command == 'Trash' and equipment in inventory:
... |
cb674d1adb077f2d6b3e97cfe9b8bb69f1925851 | maria-zdr/softuni | /Python Fundamentals/Lists/8. Append Lists.py | 144 | 3.734375 | 4 | data = input().split('|')
data.reverse()
list_result = []
for item in data:
list_result.extend(item.split())
print(' '.join(list_result))
|
e1bdf5cb2bfa3603b68919c32c56d864b0f5475f | maria-zdr/softuni | /Python Fundamentals/Lists Exercise/02. Split by Word Casing.py | 676 | 3.96875 | 4 | list_specials = [',', ';', ':', '.', '!', '(', ')', '\"', '\'', '\\', '/', '[', ']']
list_lower = []
list_mixed = []
list_upper = []
data = input()
for item in list_specials:
data = data.replace(item, ' ')
list_data = data.split(' ')
for item in list_data:
if item != '':
if item == item.upper() and... |
f62cf967c6b3031706c8b5c535b18c9de6a6b5e5 | maria-zdr/softuni | /Python Fundamentals/Regular Expressions/08. Word Encounter.py | 413 | 3.78125 | 4 | import re
search = input()
result = []
sentence_pattern = r'^[A-Z].*[.!?]$'
while True:
data = input()
if data == 'end':
break
if re.match(sentence_pattern, data):
words = re.findall(r'\w+', data)
for item in words:
symbols = re.findall(search[0], item)
if ... |
443bad08b80bb0fee43ee1b71c4917399e058dd2 | saniya-ashrafi/assignment1 | /question5.py | 162 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 24 12:53:56 2020
@author: DELL
"""
n = 2
for i in range(1, 11, 1):
product = n*i
print(product) |
6571413a33535ab3723664c44f542114b4f2f863 | cliuthulu/day4 | /Exercise04/testing.py | 590 | 3.703125 | 4 | def custom_len(input_list):
"""custom_len(input_list) imitates len(input_list)"""
for i in input_list:
count =0
count += i
return count
def custom_insert(input_list, index, value):
"""custom_insert(input_list, index, value) imitates
input_list.insert(index, value)
"""
list_length = custom_len(input_list)
... |
f679fa0e53bcd748e7a52ef58081ab66ec26b0e0 | RichardJ16/Cracking-The-Coding-Interview | /Chapter-1/Q1_6.py | 1,261 | 3.96875 | 4 | # implement an algorithm that performs a string compression
def repeatedCharacter(string):
i = 0
c = 1
retString = ""
while i != len(string):
if i != len(string) - 1 and string[i] == string[i + 1]:
c = c + 1
elif i != len(string) - 1 and strin... |
336411cb85a117b0da2de56b67b33a8186ca541b | deiuch/PPSE | /Assignment10/lab10.py | 6,541 | 3.6875 | 4 | ### Python Programming for Software Engineers
### Assignment 10
### '(Anniversary) Inverse of Assignment 10'
### Eugene Zuev, Tim Fayz
# Here is your story:
# It is 2005. Recently, you've got your dream job offer from one of the
# best "Big Five" tech company. More than that, you've been immediately
# accepted as a ... |
611005f58d797bbd7d3ad69ed33a65d7bf3a94a3 | millarba/python_exercises | /ex18.py | 360 | 3.59375 | 4 | def print_two(*args):
arg1, arg2 = args
print("arg1: %r, arg2: %r" % (arg1, arg2))
def print_two_again(arg1, arg2):
print("arg1: %r, arg2: %r" % (arg1, arg2))
def print_one(arg1):
print("arg1: %r" % arg1)
def print_none():
print("I got nothin'.")
print_two("Ben", "Millar")
print_two_again("Ben",... |
655bbb317e61c21922655f2af31b54f87d55e7d6 | kristiyanto/python_scratchbook- | /.metadata/.plugins/org.eclipse.core.resources/.history/6f/60a63aecb60600161c55dd4c932dba0b | 458 | 3.8125 | 4 | #!/usr/bin/python3.5
def main():
str = "abcde"
result = isUniqueChars(str)
print("Unique") if result else print("Not Unique")
def isUniqueChars(str):
if len(str) > 128:
print(len(str))
return False
else:
charByte = bytearray()
for char in str:
return Fal... |
cca943ffc0b1a91fcdb9e8603a8a2b5fb1483c61 | larteyjoshua/Numerical-Assignments | /Assignment 3/Example64.py | 858 | 3.703125 | 4 | ## module trapezoid
''' Inew = trapezoid(f,a,b,Iold,k).
Recursive trapezoidal rule:
old = Integral of f(x) from x = a to b computed by
trapezoidal rule with 2ˆ(k-1) panels.
Inew = Same integral computed with 2ˆk panels.
'''
import math
def trapezoid(f,a,b,Iold,k):
if k == 1:Inew = (f(a) + f(b))*(b - a)/2.0
else... |
6c2aa82e6ff3db888043ceb17d9ff238c7ba7adb | elizamendibekova/Hello-world | /lesson8_1.py | 326 | 4 | 4 | import csv
def csv_dict_reader(file_obj, delimiter=','):
reader = csv.DictReader(file_obj, delimiter=delimiter)
for line in reader:
print(line)
print("__________")
print(line["first_name"])
print(line["last_name"])
print("__________")
with open("data.csv", "r") as file_obj:
csv_dict_reader(... |
cdf60a273c103d29671403509ad0f86e2498f697 | arikj/Smart-email-client | /gui.py | 530 | 3.625 | 4 | from Tkinter import *
def bind(widget, event):
def decorator(func):
widget.bind(event, func)
return func
return decorator
master = Tk()
listbox = Listbox(master)
listbox.insert(END, "a list entry")
for item in ["one", "two", "three", "four"]:
listbox.insert(END, item... |
d84763b79621f589befd50627021828c3dcbe5d1 | RenatoCPortella/estruturasRepeticao | /ex7.py | 137 | 4.0625 | 4 | maior = 0
for i in range(5):
numero = int(input('Informe um número: '))
if numero > maior:
maior = numero
print(maior)
|
6c2bd58af252864346c4bf4b2abef281dcc00859 | Chaenini/Programing-Python- | /IX. 프로젝트/tictactoe.py | 1,425 | 3.734375 | 4 | class TicTacToe :
def __init__(self) :
self.board = [".", ".", ".",\
".", ".", ".",\
".", ".", "."]
self.current_turn = "X"
def set(self, row, col):
# if self.current_turn == "O" :
# self.current_turn = "X"
# else :
... |
080089fcb0b7c72054d9ae4c6058f08f409ad197 | Chaenini/Programing-Python- | /2314_이채린/choice.py | 2,121 | 3.5 | 4 | from urllib.parse import urlunparse, urlparse
from tutorial import Tutorial
from schoolFileReader import SchoolFileReader
class Choice:
def choice(self) :
name = input("이름을 입력해주세요 : ")
age = input("나이를 입력해주세요 : ")
f = open("data.txt", 'w')
f.write(name + " ")
... |
077812fb91097182d15a3aa0dba8c1bdb6946a03 | Chaenini/Programing-Python- | /Function2.py | 3,423 | 3.828125 | 4 | #107p
import random
def rolling_dice():
n = random.randint(1,6) #1<=n<=6인 랜덤수 random(1,6) = 1~5 randint(1,6) = 1~6
print("6면 주사위를 굴린 결과 : ",n)
#파이썬은 오버로딩이 불가하다
def rolling_dice(pip):
n = random.randint(1,pip) #1<=n<=6인 랜덤수 random(1,6) = 1~5 randint(1,6) = 1~6
print(pip,"면 주사위를 굴린 결과 : ",n)
def rollin... |
a25fd3f691c1205fd09a1f1ad3530e7e12f26d2d | hofvanta/basic_programs | /server_names2.py | 888 | 3.640625 | 4 | def add_some(servers):
"""
- voeg Helsinki toe aan het einde van de lijst
- voeg ~Madrid~ toe tussen ~Tokyo~ en ~Paris~
"""
def get_five_letter_servers(servers):
five_letter_names = ['Paris'] # fixture
'''Doorloop de list servers.
indien de lengte van de servernaam lengte 5 heeft,
... |
9e253fc47680f2d2d74f3a98815eb9517eae936b | MushtaqRossier/Task-Manager | /task_manager_new.py | 18,322 | 4.03125 | 4 | from datetime import date
#------------------------------------------------------------------------------
"""
Creating a function that registers new users whose details are not yet in the
text file.
"""
def reg_user():
user_list = []
with open("user.txt") as f:
incorrect_i... |
54406e46376433c727027b350e1b7b6a6f818181 | kamil-fijalski/python-reborn | /@Main.py | 2,365 | 4.15625 | 4 | # Let's begin this madness
print("Hello Python!")
int1 = 10 + 10j
int2 = 20 + 5j
int3 = int1 * int2
print(int3)
print(5 / 3) # floating
print(5 // 3) # integer
str1 = "Apple"
print(str1[0])
print(str(len(str1)))
print(str1.replace("p", "x") + " " + str1.upper() + " " + str1.lower() + " " + str1.swapcase())
# me... |
07a0371a7d0a0cc437508f6b6b94c27ef212973e | kamil-fijalski/python-reborn | /@Pandas.py | 563 | 3.53125 | 4 | # Loading data
import pandas as pd
xlsx_path = 'test.xlsx'
df = pd.read_excel(xlsx_path) # df -> dataframe
# print(df)
y = df.keys()
print(y)
# creating single dataframe (here: with phone numbers)
z = df[['phone']]
print(z)
a1 = df['postal'].unique() # find unique elements in df
print(a1)
print("Length of A1: " +... |
f1fd7d472442e9889ff367595b2acf09eba013b0 | stephen-engler/numpy | /index_selection.py | 642 | 3.5625 | 4 | import numpy as np
arr = np.arange(0,11)
#indexing similar to lists
print(arr[4])
#same with slicing
print(arr[1:5])
print(arr[5:])
#broadcast
arr[0:5]=100
print(arr)
arr = np.arange(0,11)
#data isn't copied but reference
#if want copy
arr_copy = arr.copy()
arr_copy[:] = 100
print(arr)
print(arr_copy)
arr_2d = np... |
b31b9ae8e5a092fabd066dfe7bf602530ab342ad | sravyasr/find-s | /EnjoySport/enjoySport.py | 1,276 | 3.78125 | 4 | import csv
weather_dataset = []
# Import the data from the CSV file
with open('enjoysport.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for row in csv_reader:
weather_dataset.append(row)
# The attributes that describe the weather
dataset_attributes = ['Sky', 'AirTemp', 'Humidity... |
1db82a8ede171d97c4fb116285464f684e1b8305 | limuxiao/PythonNote_Liy | /week01/TestClass/Base.py | 873 | 3.671875 | 4 | # -*- coding:utf-8 -*-
class Base(object):
def __init__(self):
print('----Base init----')
def get_base(self):
return 'Base'
def test(self):
print('----Base test----')
@classmethod
def test_class_method(cls):
print('----Base class method----')
@staticmethod
... |
30f92614c829fbed5b1a8182b991b2a6c58a906b | limuxiao/PythonNote_Liy | /week04/测试tcp/TcpServer.py | 1,428 | 3.5625 | 4 | # -*- coding:utf-8 -*-
import socket
from threading import Thread
class ServerThread(Thread):
"""
服务端线程类
"""
def __init__(self, sock, c_addr):
super().__init__()
self.__sock = sock
self.__c_addr = c_addr
def run(self):
while True:
ret = self.__sock.... |
742147147bab1046e6a51dda4d2523ee8dde61da | limuxiao/PythonNote_Liy | /week02/测试内建属性及方法、元类/测试集合的交并补差.py | 403 | 3.6875 | 4 | # -*- coding:utf-8 -*-
def f1():
a = [i for i in range(10)]
print(a)
b = a[::2]
print(b)
a = set(a)
b = set(b)
print(type(a))
print(type(b))
b.add(3)
b.add(5)
b.add(10)
print(a & b)
print(a | b)
print(a ^ b)
print(a - b)
print(b ^ a)
print(b - a)
... |
23a77292c1a854f580f9ab3d90d2f108aa5b67c0 | limuxiao/PythonNote_Liy | /week02/TestDongtai/test.py | 883 | 3.65625 | 4 | # -*- coding:utf-8 -*-
import types
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
pass
def test01():
# print(globals())
num = 10
print(locals())
def test02():
p1 = Person('p1', 20)
print(p1.name)
print(p1.age)
p1.addres... |
d19d5cde9dc4b5d71bc1d308a2385fc40b51f9be | limuxiao/PythonNote_Liy | /week03/测试线程/简单的生产者与消费者模式.py | 1,506 | 3.890625 | 4 | # -*- coding:utf-8 -*-
import threading
from threading import Thread
from queue import Queue
import time
class Factory(Thread):
"""
工厂类
"""
def __init__(self, queue):
super().__init__()
self.queue = queue
pass
class Producer(Factory):
"""
生产者类
"""
def run... |
09afa3fca2b02f25714da3d474f3c764c969362a | limuxiao/PythonNote_Liy | /week02/TestBibao.py | 991 | 3.859375 | 4 | # -*- coding:utf-8 -*-
def test01(num1):
print("----test01----")
def test(num2):
return num1 + num2
return test
def test02():
fun1 = test01(100)
fun2 = test01(1)
print(fun1(100))
print(id(fun1))
print(id(fun2))
a = test01
b = test01
print(a == b)
print(a is b... |
bf3ffe57af7faa05f72e2fd499ff3abd6fe4b514 | limuxiao/PythonNote_Liy | /week02/测试装饰器/通用方法装饰器.py | 897 | 3.859375 | 4 | # -*- coding:utf-8 -*-
def decorator(fn):
"""
这是一个通用方法装饰器,可以用来装饰无参无返回值、无参有返回值、有参无返回值、有参有返回值的方法
:param fn:
:return:
"""
def inner(*args, **kwargs):
print('----inner----')
return fn(*args, **kwargs)
return inner
@decorator
def f1():
print('----f1----')
@decorator
... |
52158b57f39a21327a5db258b4f8f6159d83a761 | limuxiao/PythonNote_Liy | /week01/Animal.py | 525 | 3.78125 | 4 | # -*- coding:utf-8 -*-
class Animal:
def __init__(self):
pass
def eat(self):
print('.....eating.....')
class C(Animal):
def __init__(self, name='Haha', age=15):
# Animal.__init__(self)
super().__init__()
pass
def eat(self):
print('=====eating=====')
... |
f04e1a64bf4afb4829576a5a5b0f163b2e7571b0 | limuxiao/PythonNote_Liy | /测试杀死进程/kill.py | 206 | 3.703125 | 4 | # -*- coding:utf-8 -*-
import os
def f1():
while True:
pass
def main():
t = (1, 2, 3)
if t and len(t) % 2 == 0:
print('s')
pass
if __name__ == '__main__':
main()
|
cdd94f94c27e93456937456ab31b03088d0d4d5e | limuxiao/PythonNote_Liy | /week01/TestExtend.py | 585 | 3.703125 | 4 | # -*- coding:utf-8 -*-
class A:
def __init__(self):
self.num = 100
self.__num = 200
def test01(self):
print('----test01----')
def __test02(self):
print('----test02----')
def test03(self):
self.__test02()
class B(A):
def __init__(self):
super().__... |
8bcd20c785d72d4e21a828bb383f894c0c54c40b | limuxiao/PythonNote_Liy | /week02/测试内建属性及方法、元类/用type元类创建类.py | 282 | 3.5 | 4 | # -*- coding:utf-8 -*-
def f1():
"""
这是最简单的用type方法来创建类
:return:
"""
Bird = type('Bird', (), {'name': 'haha'})
bird1 = Bird()
print(Bird.name)
pass
def main():
f1()
pass
if __name__ == '__main__':
main() |
e12b80ac73eea3290d8fa2f58f40a3a4df196730 | cmajorsolo/python-resharper | /three_sum.py | 1,272 | 3.515625 | 4 | class Solution:
def threeSum(self, nums):
result = []
print(float('inf'))
for i in range(0, len(nums)):
for j in range(i+1, len(nums)):
for k in range(j+1, len(nums)):
if nums[i] + nums[j] + nums[k] == 0:
childResult = [... |
01efe6fc3d174b7cf2e200183b3ca5ebea966c57 | cmajorsolo/python-resharper | /reverseNodesInKGroupTest.py | 3,807 | 3.65625 | 4 | import unittest
from ListNode import ListNode
from reverseNodesInKGruop import Solution
class reverseNodeInKGroupTest(unittest.TestCase):
def example_k_is_3_test(self):
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)
node5 = ListNode(5)
... |
5b5df1e0ddd93a652798dc007f4f4649549eee0c | cmajorsolo/python-resharper | /longest_substring.py | 349 | 3.578125 | 4 | from collections import deque
class findLongestSubString:
def longest_string_online(self, s):
curr = deque()
longest = 0
for c in s:
if c in curr:
while curr.popleft() != c: pass
curr.append(c)
longest = max(longest, len(curr))
r... |
5dd93fd8351ea6bbc9baa49d8b8731e052712dc0 | omer-goder/python-skillshare-beginner | /list/slicing_a_list.py | 203 | 4.0625 | 4 | ### 15/04/2020
### Author: Omer Goder
### Slicing a list
names = ['tony','deirdre','senan','carol']
print(names[0:2])
print(names[1:3])
print(names[:3])
print(names[2:])
print(names[-3:])
|
7b2d9aa4ece7d8a777def586cb3af02685eac071 | omer-goder/python-skillshare-beginner | /conditions/not_in_keyword.py | 347 | 4.1875 | 4 | ### 17/04/2020
### Author: Omer Goder
### Checking if a value is not in a list
# Admin users
admin_users = ['tony','frank']
# Ask for username
username = input("Please enter you username?")
# Check if user is an admin user
if username not in admin_users:
print("You do not have access.")
else:
p... |
622772dadf07330ab6e90b5dcb485c2b87d42178 | omer-goder/python-skillshare-beginner | /json/storing_and_reading_user_data.py | 351 | 3.875 | 4 | ### 18/05/2020
### Author: Omer Goder
### Storing and reading user data
import json
filename = 'username.json'
try:
with open(filename) as f1:
username = json.load(f1)
except FileNotFoundError:
username = input("What's your saint nick's name")
with open(filename, 'w') as f2:
json.dump(username, f2)
else:
pri... |
3cbb12303b7788144cde7c943ed8c69be387b426 | omer-goder/python-skillshare-beginner | /super basics/split_test.py | 200 | 3.6875 | 4 | ### 15/05/2020
### Author: Omer Goder
### Testing the split() function
str = 'hello world and welcome to the show'
print(str.split(' ', 4))
for word in range(len(str.split())):
print(str.split()[word]) |
f457e6763c190e10b297912019aa76ad7dc899a4 | omer-goder/python-skillshare-beginner | /dictionary/adding_user_input_to_a_dictionary.py | 997 | 4.375 | 4 | ### 04/05/2020
### Author: Omer Goder
### Adding user input to a dictionary
# Creat an empty dictionary
rental_properties = {}
# Set a flag to indicate we are taking apllications
rental_open = True
while rental_open: # while True
# prompt users for name and address.
username = input("\nWhat is your nam... |
fd1ccd8e94a9a2f7d68ce5caade21b4727a5356e | omer-goder/python-skillshare-beginner | /conditions/or_keyword.py | 418 | 4.21875 | 4 | ### 17/04/2020
### Author: Omer Goder
### Using the OR keyword to check values in a list
# Names registered
registered_names = ['tony','frank','mary','peter']
username = input("Please enter username you would like to use.\n\n").lower()
#Check to see if username is already taken
if username in registered_na... |
c4a68db98e27273aebfcf3499d716bf6b0abe142 | omer-goder/python-skillshare-beginner | /methods/get_method(2).py | 380 | 4.03125 | 4 | ### 21/04/2020
### Author: Omer Goder
### Editing & deleting values in a dictionary
# terms = {'integer' : 'Is a number that contains a decimal place.'}
# terms['integer'] = 'A whole number'
# print(terms.get('integer'))
terms = {'integer' : 'Is a number that contains a decimal place.' , 'string' : 'a seq... |
a673aa5f87153106ae8f45ff660453ff185e5da2 | omer-goder/python-skillshare-beginner | /functions/passing_info_to_function.py | 628 | 3.546875 | 4 | ### 05/05/2020
### Author: Omer Goder
### Passing information to function
def welcome(username):
"""Showing a username"""
print("Hi " + username.title() + ".\n")
# Notice that the name of the argument sent to the function (call)
# doesn't have to be the same as the argument the function accepts
name = 'omer'
welcom... |
34c12dde56d3cb3176565750b4292d6a062105df | omer-goder/python-skillshare-beginner | /list/a_list_of_numbers.py | 552 | 4.25 | 4 | ### 15/04/2020
### Author: Omer Goder
### Creating a list of numbers
# Convert numbers into a list
numbers = list(range(1,6))
print(numbers)
print('\n')
# print("List of even number in the range of 0 to 100:")
even_numbers = list(range(0,102, 2))
print(even_numbers)
print('\n')
print("List of square va... |
97360bd4a55477713e3868b9c9af811143151aca | omer-goder/python-skillshare-beginner | /class/class_as_attribute(2).py | 1,127 | 4.34375 | 4 | ### 11/05/2020
### Author: Omer Goder
### Using a class as an attribute to another class
class Tablet():
"""This will be the class that uses the attribute."""
def __init__(self, thickness, color, battery):
"""Initialize a parameter as a class"""
self.thickness = thickness
self.color = color
self.battery = ... |
c137de8352cecb7bff57b404c8bb64a48732c1a1 | omer-goder/python-skillshare-beginner | /functions/positional+arbitrary(var_args).py | 372 | 3.796875 | 4 | ### 06/05/2020
### Author: Omer Goder
### Using positional and arbitrary arguments together
def assign_seat(seat, *requests):
"""Assign a seat and requests to a passenger"""
print("\nThe passenger in seat %d has made the follwing requests:" % (seat))
for request in requests:
print("- " + request)
assign_seat(5, ... |
c2f5de301a04d61edf9c2cb2aa4887b910b13436 | maclyne/volcano_database | /my_utils.py | 7,453 | 4.21875 | 4 | """Collects data from a column within a dataset
* open_file - opens a comma separated CSV file
* get_column - searches through a data file and finds specific values
relating to an inputted search parameter(s).
* identify_column - Identifies the query columns of interest if entered
... |
2aa556b46db3f7aca4065431d91ccdb460cd1127 | CodeDeemons/Python-Tkinter-Gui-Project | /Email_Sender/main.py | 4,074 | 3.84375 | 4 | from tkinter import *
import smtplib
from tkinter import messagebox
# making tkinter window
root = Tk()
root.geometry('500x500')
root.title('Email Sender @_python.py_')
root.resizable(False, False)
root.config(bg="#fff")
# variable for Entry box
Email = StringVar()
Password = StringVar()
To = StringVar()
Subjec... |
d347210fb0e7008e8cf45df56bf5f5725e0fe324 | saikrishna-427/Python_learning | /Duplicate_bithday.py | 403 | 3.78125 | 4 | #finding duplicate birthdays in lists of python
def has_duplicates(dates):
word_checked = {}
same_date = []
for i in dates:
if i not in word_checked:
word_checked[i] = 1
else:
if word_checked[i] == 1:
same_date.append(i)
word_checked[i] = word_checked[i] + 1
return word_check... |
2b844498e1179dc75c64f18154c693b780f4965b | TRManderson/math4202 | /ride_sharing/models.py | 2,264 | 3.734375 | 4 | from typing import List, Optional
import math
import attr
import pickle
Time = float # type alias
@attr.s(frozen=True)
class Location(object):
"""
The distance between any pair of locations must be known, this is the only
requirement.
A simple way to fulfill this requirement is by generating 2D coo... |
f385856290585e7e625d82c6f1d0b6f5aa171f71 | akram2015/Python | /HW4/SECURITY SCANNER.py | 631 | 4.4375 | 4 | # this program Prompt user for a file name, and read the file, then find and report if file contains a string with a string ("password=") in it.
# file name = read_it.txt
found = True
userinput = input ("Enter the file name: ")
string = input ("Enter the string: ")
myfile = open (userinput) # open the file that might... |
c6ee4574166c0e00e6e7bddad59ca354677ea66a | akram2015/Python | /HW3/BunnyEars.py | 431 | 4.3125 | 4 | # Recursive function that return the number of ears for bunnies
def bunny_ears(n): # n number of bunnies
if n <= 0: # 0 bunny condition
return 0
elif n % 2 == 0: # for even numbers of bunnies
return bunny_ears(n-1) + 2
else: # for odd numbers of bunnies
return bun... |
429776165afb038e33026788881f504f137d629e | kellischeuble/cs-module-project-hash-tables | /applications/markov/markov.py | 474 | 3.5 | 4 | import random
with open("input.txt") as f:
words = f.read()
words = words.split()
word_after = dict()
for i, word in enumerate(words[:-1]):
if word in word_after:
word_after[word].append(words[i+1])
else:
word_after[word] = [words[i+1]]
sentence = "he"
value = sentence
while not sente... |
446deb2d033de690fb358330d3665c53d35a3d55 | DeanTae/sample | /second.py | 512 | 3.8125 | 4 | def determinePrime(number):
if number < 2:
return False
if number == 2:
return True
for i in range(2,number):
if number % i == 0:
return False
return True
def checkPrimeDuplicate(d):
count = 0
for i in range(0,len(d)):
for specific in d[i]:
if determinePrime(specific)==True:
count = count + 1
... |
46df9c3814c9e167351f58cae2a60e7b225921b1 | CodecoolGlobal/lightweight-erp-python-p-a | /sales/sales.py | 17,680 | 3.640625 | 4 | """ Sales module
Data table structure:
* id (string): Unique and random generated identifier
at least 2 special characters (except: ';'), 2 number, 2 lower and 2 upper case letters)
* title (string): Title of the game sold
* price (number): The actual sale price in USD
* month (number): Month o... |
8e2989008f52b56dee43360378533c5b4a757d90 | josego85/livescore-cli | /lib/tt.py | 2,078 | 4.40625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
import re
'''
module to convert the given time in UTC to local device time
_convert() method takes a single time in string and returns the local time
convert() takes a list of time in string format and returns in local time
NOTE: any string not in the format "... |
8a24e0a0f9795f924856420f34c1f57a0034b0e4 | Daniel451/praktikumNN | /PyObjMLP/NeuralNetworkClass.py | 15,969 | 3.703125 | 4 | __author__ = 'daniel'
import numpy
import LayerClass
import sys
class NeuralNetwork:
def __init__(self, in_input, hiddenLayerList, outputLayerLength, out_expected, label="no-name"):
"""
:param in_input: InputLayer -> List of lists which hold input value/data for
... |
18518e9f199ab496543d8ab73e6ba210326effff | zxy987872674/LearnCode | /python/commonPackage/Re/learnGroup.py | 1,251 | 3.59375 | 4 | #coding=utf-8
'''
match和search一旦匹配成功,就是一个match object对象,而match object对象有以下方法:
group() 返回被 RE 匹配的字符串
start() 返回匹配开始的位置
end() 返回匹配结束的位置
span() 返回一个元组包含匹配 (开始,结束) 的位置
group() 返回re整体匹配的字符串,可以一次输入多个组号,对应组号匹配的字符串。
a. group()返回re整体匹配的字符串,
b. group (n,m) 返回组号为n,m所匹配的字符串,如果组号不存在,则返回indexError异常
c.groups()groups() 方法返回一个包含正则表达式中... |
3c865ce1b84c94cb1d888623993f382bf1da0119 | claudiaps/Atividades_Grafos | /frete/frete.py | 551 | 3.640625 | 4 | import graph
def main():
base_input = input().split(' ') # le o input do usuario
numero_cidades = int(base_input[0])
gp = graph.Graph()
for i in range(1, numero_cidades+1):
gp.add_vertex(str(i))
numero_pares = int(base_input[1])
for i in range(numero_pares):
base_input = inpu... |
e35d0410866646f3f604dc8d2a628a67ea19ee6e | sclarke/adventofcode2017 | /d23.py | 2,131 | 3.609375 | 4 | from collections import defaultdict
import math
with open('d23_input.txt') as f:
puzzle_input = [line.strip().split() for line in f.readlines()]
def run_program(instructions, part2_mode=False):
registers = defaultdict(int)
if part2_mode:
registers['a'] = 1
pointer = 0
mul_count = 0
... |
c5730814dc5fe6c882bdd9da2bed29cf57b7c174 | sclarke/adventofcode2017 | /d12.py | 1,460 | 3.625 | 4 |
test_input = """
0 <-> 2
1 <-> 1
2 <-> 0, 3, 4
3 <-> 2, 4
4 <-> 2, 3, 6
5 <-> 6
6 <-> 4, 5""".strip().splitlines()
with open('d12_input.txt') as f:
puzzle_input = f.readlines()
def build_groups(inp):
return dict(parse_line(line) for line in inp)
def parse_line(line):
"""return the index and direct lin... |
e5f6cbd259cc613d9b22f3f92f355a2cf3111bad | JHyuna/BOJ_Algorithm | /1 prob each day/B2-12605.py | 144 | 3.5 | 4 | n = int(input())
for i in range(1,n+1):
string = reversed(input().rstrip().split())
print('Case #' + str(i) + ': ' + ' '.join(string))
|
1cf6a640c2aa811acb14cb9552e2ce0ec035834e | JHyuna/BOJ_Algorithm | /1 prob each day/B3-4153.py | 257 | 3.65625 | 4 | while True:
in_value = input()
if in_value != '0 0 0':
L = sorted(tuple(map(int, in_value.split())))
if L[-1]**2 == (L[0]**2 + L[1]**2):
print('right')
else:
print('wrong')
else:
break
|
17488c10bb60d5145c5f1427f07947ba8d399602 | JHyuna/BOJ_Algorithm | /1 prob each day/B3-1547.py | 235 | 3.609375 | 4 | a = [0,1,2,3] # 인덱스활용을 쉽게 하기 위해 1번 컵의 인덱스를 1로 조정
n = int(input())
for _ in range(n):
i,j = map(int, input().split())
a[i],a[j] = a[j],a[i]
print(a.index(1)) # 1번 컵의 위치를 뽑기 |
9af2b9f10033e86f5d76efc59890853944c074e8 | tdworowy/PythonPlayground | /Playground/Python_Staff/Functions_/recursion.py | 805 | 3.734375 | 4 | def my_sum(l):
print(l)
try:
if not l:
return 0
else:
return l[0] + my_sum(l[1:])
except RecursionError as re:
print(re)
return 0
def my_sum2(l):
try:
first, *rest = l
print(l)
return first if not rest else first + my_sum... |
2fc23ce67186f112699e3f53aa9c30db64eb6969 | tdworowy/PythonPlayground | /Playground/Exercises/exer41_longest_common_prefix.py | 927 | 3.828125 | 4 | from typing import List
def longest_common_prefix(strs: List[str]) -> str:
if not strs:
return ""
shortest = min(strs, key=len)
for i, ch in enumerate(shortest):
for other in strs:
if other[i] != ch:
return shortest[:i]
return shortest
if __name__ == "__ma... |
74bc4222b6e007c9667db92c7e3e83ec23add7fb | tdworowy/PythonPlayground | /Playground/Exercises/exer27_luck_balance.py | 534 | 3.578125 | 4 | contests = [[5, 1], [2, 1], [1, 1], [8, 1], [10, 0], [5, 0]]
k = 3
def luck_balance(k, contests):
max_luck = 0
loose_important = 0
contests.sort(reverse=True)
for contest in contests:
if contest[1] == 0:
max_luck += contest[0]
else:
if loose_important < k:
... |
afd20e690a99e1cc6d1e81d3d9b309c34faaae5c | tdworowy/PythonPlayground | /Playground/Algorithms/search/binary_search.py | 634 | 3.796875 | 4 | from random import randint
from Playground.my_utils.staff.timer3 import timer3
@timer3
def binary_search(list_: list, item):
"""list_ must be sorted"""
first = 0
last = len(list_) - 1
while first <= last:
mind_point = (first + last) // 2
if list_[mind_point] == item:
retu... |
aecb84b02845448af1d14231c361784d1648a4e2 | tdworowy/PythonPlayground | /Playground/Algorithms/graph_theory/searching/depth_first_search.py | 836 | 3.734375 | 4 | import networkx as nx
import matplotlib.pyplot as plt
def depth_first_search(graph: dict, start: str, visited: set = None) -> set:
if visited is None:
visited = set()
visited.add(start)
print(start)
for next_ in graph[start] - visited:
depth_first_search(graph, next_, visited)
retu... |
7cf3e7e2beb6eaf848222ea04aa50f6b98bc613e | tdworowy/PythonPlayground | /Playground/Algorithms/math/chinese_remainder_theorem.py | 496 | 3.65625 | 4 | def extended_gcd(a: int, b: int) -> tuple:
assert a >= 0 and b >= 0 and a + b > 0
if b == 0:
d, x, y = a, 1, 0
else:
(d, p, q) = extended_gcd(b, a % b)
x = q
y = p - q * (a // b)
return d, x, y
def chinese_remainder_theorem(n1, r1, n2, r2):
(_, x, y) = extended_gc... |
3e99c0a7604aab2ba84d72aec599904d2d8c20a5 | tdworowy/PythonPlayground | /Playground/Exercises/exer35_number_format.py | 201 | 3.625 | 4 | def print_formatted(number):
w = len(f'{number:b}')
for n in range(1, number + 1):
print(f'{n:={w}} {n:={w}o} {n:={w}X} {n:={w}b}')
if __name__ == '__main__':
print_formatted(99)
|
2da5f1a682922369aab5671f38cee51472c2cebc | tdworowy/PythonPlayground | /Playground/Python_Staff/OOP/ovrloading/iters1.py | 744 | 3.78125 | 4 | class Squares:
def __init__(self, start, stop):
if self.check(start):
self.value = start - 1
self.stop = stop
else:
self.value = 0
self.stop = 0
def __iter__(self):
return self
def __next__(self):
if self.value == self.stop:
... |
6776d2097a5446cfb1a14a91c9e684114d59053f | tdworowy/PythonPlayground | /Playground/Algorithms/graph_theory/gale_shapley_algoritmh.py | 1,173 | 3.65625 | 4 | def stable_matching(n: int, men_preferences: list, women_preferences) -> list:
unmarried_men = list(range(n))
man_spouse = [None] * n
woman_spouse = [None] * n
next_man_choice = [0] * n
while unmarried_men:
he = unmarried_men[0]
his_preferences = men_preferences[he]
she = h... |
fa886013b6d810ce7f844b42dc2967c14568c619 | tdworowy/PythonPlayground | /Playground/my_utils/staff/random_string.py | 322 | 3.640625 | 4 | import string
from random import choices
def generate_random_string(size):
return "".join(choices(string.ascii_lowercase, k=size))
def generate_random_string_all(size):
return ''.join(choices(string.ascii_letters + string.digits, k=size))
if __name__ == '__main__':
print(generate_random_string_all(12)... |
365dea86fb894b0afd126443b31efe81c301542d | tdworowy/PythonPlayground | /Playground/Python_Staff/Tests/unit_tests2.py | 423 | 3.765625 | 4 | print("I'm : ", __name__)
def min_max(test, *args):
res = args[0]
for arg in args:
if test(arg, res):
res = arg
return res
def less_than(x, y): return x < y
def greater_than(x, y): return x > y
if __name__ == '__main__': # tests , won't run if module is imported
print(min_ma... |
c9c6c0860f6ae331a292e90f1f2aebfb340227f6 | tdworowy/PythonPlayground | /Playground/Python_Staff/metaclasses/meta5_Overloading_call.py | 960 | 3.609375 | 4 | class SuperMeta:
def __call__(self, classname, supers, classdic):
print("in SuperMeta.call: ", classname, supers, classdic, sep='\n')
Class = self.__new__(classname, supers, classdic)
self.__init__(Class,classname, supers, classdic)
return Class
class SubMeta(SuperMeta):
def __... |
65994e9c687f0d2fa7f77765f0e39ff216798fc7 | tdworowy/PythonPlayground | /Playground/Exercises/exer33_count_triplets.py | 980 | 3.734375 | 4 | from itertools import permutations
# performance could by much better
def count_triplets(arr: list, r: int) -> int:
try:
if len(arr) <= 2:
return 0
triplets = [tuple(sorted(per)) for per in permutations(arr, 3)]
count = 0
for triplet in triplets:
if triplet[... |
00b71c3107af4a6423504b0bd808e327b4e9eec8 | Nhlamulomax/Lottery_Project | /lottery.py | 4,725 | 3.78125 | 4 | import random
from datetime import datetime, date
import calendar
import csv
class NationLottery: #
# Function to populate entry ticket
def populate_draw_ticket(self):
x = 0
y = 6
entry_ticket = [] # List to store 6 draw numbers from the user
while... |
66223d5145ced27275b93e64d71f623d6fb99411 | dwaynethebard/djisktra-vs-Astar | /TwoThreeNode.py | 15,573 | 4 | 4 | class TwoThreeNode:
def __init__(self,
parent=None,
count=0,
smallest=None, largest=None,
left=None, middle=None, right=None):
self.parent = parent
self.count = count
self.smallest = smallest
self.largest... |
0c900e9b4ad2f2b3e904ee61661cda39ed458646 | shivraj-thecoder/python_programming | /Swapping/using_tuple.py | 271 | 4.34375 | 4 | def swap_tuple(value_one,value_two):
value_one,value_two=value_two,value_one
return value_one,value_two
X=input("enter value of X :")
Y=input("enter value of Y :")
X, Y=swap_tuple(X,Y)
print('value of X after swapping:', X)
print('value of Y after swapping:', Y) |
3ef0e6ed115ebe2fddc00f41289a9745bcec1299 | KhMassri/for-test-repo | /nicecode.py~ | 811 | 3.875 | 4 | import matplotlib.pyplot as plt
plt.figure
#create data
x_series = [0,1,2,3,4,5]
y_series_1 = [x**2 for x in x_series]
y_series_2 = [x**3 for x in x_series]
#plot data
plt.plot(x_series, y_series_1, label="x^2")
plt.plot(x_series, y_series_2, label="x^3")
#add in labels and title
plt.xlabel("Small X Interval")
pl... |
7af3a6e053f3fec84eaad6efd69f0c69d8d1e797 | inaciofabricio/python | /001 - Python basico/Variaveis.py | 204 | 3.6875 | 4 | # -*- coding: utf-8 -*-
a = 5
b = 10
print(a+b)
print(type(a+b))
print('')
a = 5.0
b = 10.0
print(a+b)
print(type(a+b))
print('')
texto = "Lorem ipsum dolor sit amet."
print(texto)
print(type(texto)) |
b56efda70d65a9dd33277bae1eac032a6d99b083 | Serzol64/mypythonlearntasks1 | /task17.py | 233 | 4 | 4 | def sum_digits(num):
digits = [int(d) for d in str(num)]
return sum(digits)
f = input("Введите целое число:")
print("Результат сложения цифр целого числа:", sum_digits(int(f))) |
522705d07896e40a3b0bffc5f293d826b084b65b | Serzol64/mypythonlearntasks1 | /task5.py | 158 | 3.8125 | 4 | my_dict = {'a':500, 'b':5874, 'c': 560,'d':400, 'e':5874, 'f': 20}
print('Maximal keys:')
print([k for k,v in my_dict.items() if v == max(my_dict.values())]) |
723718ae13d59a4555082a280513070b0766cf1d | danstelian/python_misc | /filter_compress_vs_comprehensions.py | 1,536 | 3.734375 | 4 | from itertools import compress
from random import randint
# filter vs list comprehensions (eg 1)
nums = [randint(-9, 10) for i in range(15)]
positive = [num for num in nums if num > 0]
negative = list(filter(lambda num: num < 0, nums))
print(f'positive: {positive}\nnegative: {negative}', end='\n\n')
... |
c7787f3109f9b87d2bc040dd524b4f1829341546 | danstelian/python_misc | /counter_most_common.py | 2,160 | 3.921875 | 4 | """
Experimenting with Python's Counter data type!
Counter is a container that keeps track of how
many times equivalent values are added.
Just like a dictionary (it's a dict subclass),
except values can be positive/negative integers.
It's an unordered collection where elements are
stored as keys.
"""
from collecti... |
d79e21953263250a7c94461da0d80f57fd290fa7 | danstelian/python_misc | /groupby_vs_defaultdict.py | 1,117 | 3.53125 | 4 | from itertools import groupby
from collections import defaultdict
from operator import itemgetter
rows = [
{'address': '5412 N CLARK', 'date': '07/01/2012'},
{'address': '5148 N CLARK', 'date': '07/04/2012'},
{'address': '5800 E 58TH', 'date': '07/02/2012'},
{'address': '2122 N CLARK', 'date'... |
ad00ddf3a4f192d2017d9bb8fbb5dd4d90d9a065 | Mengeroshi/python-tricks | /3.Classes-and-OOP/4.3.copying_arbitrary_objects.py | 779 | 4.1875 | 4 | import copy
"""Shallow copy of an object """
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f'Point({self.x!r}, {self.y!r})'
a = Point(23, 42)
b = copy.copy(a)
print(a)
print(b)
print(a is b)
class Rectangle:
def __init__(self, topleft, ... |
95bdcf9a12edae1be18cfd5b5c1705967fda44a4 | Mengeroshi/python-tricks | /2.Efective-Functions/3.1decorators.py | 284 | 3.671875 | 4 | """
Decorators: allow you to extend the behaviour of a callable(fun, class, method)
"""
def null_decorator(func):
return func
def greet():
return 'hello'
greet = null_decorator(greet)
print(greet())
@null_decorator
def greeting():
return 'hello!'
print(greeting())
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.