blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
b9cfd4f5d867a0cfb538893ec02683a8a0a46678 | maruichen2004/EPI | /Binary Tree/LCANoParent.py | 630 | 3.546875 | 4 | from Util.BinaryTree import TreeNode
from Util.BinaryTree import BinaryTree
class Solution:
# Time: O(n)
# Space: O(h)
def LCANoParent(self, root, a, b):
if root is None: return None
if root == a or root == b: return root
left = self.LCANoParent(root.left, a, b)
right = self.LCANoParen... |
a93ba28ac9f89c54c01673f6d3f2b1c6554d7ec2 | maruichen2004/EPI | /Binary Tree/SumRootToLeafNumber.py | 634 | 3.625 | 4 | from Util.BinaryTree import TreeNode
from Util.BinaryTree import BinaryTree
class Solution:
# Time: O(n)
# Space: O(h)
def sumRootToLeafNumber(self, root):
return self.sumRootToLeafNumberHelper(root, 0)
def sumRootToLeafNumberHelper(self, root, sum):
if root is None: return 0
res = (sum ... |
030336da26250a16ae1338087b754f6ba456d8dc | maruichen2004/EPI | /Stack and Queue/SlidingWindow.py | 986 | 4 | 4 | from collections import deque
class QueueWithMax:
def __init__(self):
self.Q = deque()
self.D = deque()
def enQueue(self, x):
self.Q.append(x)
while self.D and self.D[-1] < x:
self.D.pop()
self.D.append(x)
def deQueue(self):
if self.Q:
val = self.Q.pople... |
8e5450c5ad1df9a6f91c650ae9142e61dc3dd739 | maruichen2004/EPI | /LinkedList/InsertionSortList.py | 886 | 3.96875 | 4 | from Util.LinkedList import ListNode
from Util.LinkedList import LinkedList
class Solution:
# Time: O(n^2)
# Space: O(1)
def insertionSortList(self, head):
if head is None or head.next is None:
return head
dummy = ListNode(0)
dummy.next = head
cur = head
while cur and cu... |
137e607627329a6258e064360bd8ca7a060452e3 | maruichen2004/EPI | /Stack and Queue/QueueFromStacks.py | 539 | 3.796875 | 4 | class QueueFromStacks:
def __init__(self):
self.A = []
self.B = []
# Time: O(1)
def enQueue(self, x):
self.A.append(x)
# Time: O(m) m is elements in queue so far
def deQueue(self):
if len(self.B) == 0:
while self.A:
self.B.append(self.A.pop())
if len(se... |
36d605888109231473b7b392aac5a4e097359f71 | maruichen2004/EPI | /Array/RotateMatrix.py | 449 | 3.546875 | 4 | class Solution:
# Time: O(n^2)
# Space: O(1)
def rotateMatrix(self, A):
n = len(A)
for i in range(n):
for j in range(n-1-i):
A[i][j], A[n-1-j][n-1-i] = A[n-1-j][n-1-i], A[i][j]
for i in range(n/2):
for j in range(n):
A[i][j], A[n-1-i][j] = A[n-1-i][j]... |
08d911af21eabc084ff1d3b3fa5d3e5160f1faba | maruichen2004/EPI | /Hashing/Util/BinaryTree.py | 1,122 | 3.765625 | 4 | class TreeNode:
def __init__(self, value):
self.val = value
self.left = None
self.right = None
self.parent = None
self.next = None
self.size = 0
class BinaryTree:
def __init__(self):
node = [TreeNode(i) for i in range(1, 11)]
node[5].left = node[3]
node[5].ri... |
93225d89dc61ec4098bd77f66a62a71bebc4146f | maruichen2004/EPI | /Binary Search Tree/FindKLargestBST.py | 624 | 3.640625 | 4 | from Util.BinaryTree import TreeNode
from Util.BinaryTree import BinaryTree
class Solution:
# Time: O(n)
# Space: O(h)
def findKLargestBST(self, root, k):
res = []
self.findKLargestBSTHelper(root, k, res)
return res
def findKLargestBSTHelper(self, root, k, res):
if root and len(res... |
5d3f0ff71d83c55bce82304df650b4154df12db1 | maruichen2004/EPI | /Sorting/MergeTwoSortedArray.py | 528 | 3.8125 | 4 | class Solution:
# Time: O(n + m)
# Space: O(1)
def mergeTwoSortedArray(self, A, m, B, n):
i, j = m - 1, n - 1
while i >= 0 and j >= 0:
if A[i] > B[j]:
A[i+j+1] = A[i]
i -= 1
else:
A[i+j+1] = B[j]
j -= 1
while j >= 0:
A... |
d323a70c982e1269cc46d5e9d2561216101d5fd6 | trevor-clarke/Backtracking-Hamiltonian-Circuit | /Graph.py | 1,886 | 3.84375 | 4 | class Graph:
adjacency_matrix = []
totalV = 0
def __init__(self, adjacency_matrix):
self.adjacency_matrix = adjacency_matrix
self.totalV = len(self.adjacency_matrix)
#Given a path to a file, loads an adjacency_matrix space separated, one line per row
@classmethod
def fromFile(self, filename):
... |
6ef692c3413dfce5c0c59988def707f8494c78ce | Toxiang/python-his | /自动化测试/__init__.py | 276 | 3.671875 | 4 | def moveZeroes(nums):
n = len(nums)
left = right = 0
while right < n:
if nums[right] != 0:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right += 1
nums = [0,1,0,3,12]
moveZeroes(nums)
print(nums)
|
519be059ae183042bcd2e3a472582c950cbb9d8e | Strainer2/SI206 | /HW3-StudentCopy/twitterhw3b.py | 1,113 | 3.703125 | 4 | # In this assignment you must do a Twitter search on any term
# of your choice.
# Deliverables:
# 1) Print each tweet
# 2) Print the average subjectivity of the results
# 3) Print the average polarity of the results
# Be prepared to change the search term during demo.
import nltk
import requests
import requests_oauth... |
74cee5b2fbc472d7a18d64f59ba5e73b2664fde5 | laith19-meet/y2s18-python_review | /exercises/conditionals.py | 99 | 3.546875 | 4 | # Write your solution for 1.2 here!
a = 0
for i in range (101):
if i %2 == 0 :
a=a+i
print (a)
|
bcb9a6a66fa28599294e53248a4e3fc55da636e2 | ankawm/NowyProjektSages | /exception_catch_finally.py | 1,415 | 4.46875 | 4 | """
* Assignment: Exception Catch Finally
* Required: yes
* Complexity: easy
* Lines of code: 8 lines
* Time: 8 min
English:
1. Convert value passed to the function as a `degrees: int`
2. If conversion fails, raise exception `TypeError` with message:
'Invalid type, expected int or float'
3. Use `fi... |
df0f55dbf025076992921add59dad3a1fa932695 | ankawm/NowyProjektSages | /type_fset_split.py | 1,558 | 4.0625 | 4 | """
* Assignment: Sequence Frozenset Split
* Required: no
* Complexity: easy
* Lines of code: 1 lines
* Time: 3 min
English:
1. Define `result: frozenset`
2. Split lines and convert result to frozenset
3. Run doctests - all must succeed
Polish:
1. Zdefiniuj `result: frozenset`
2. Podziel linie i p... |
72cd03a29488ec0cae62134473df244739a548f1 | ankawm/NowyProjektSages | /type_int_trueDiv.py | 1,740 | 4.40625 | 4 | """
* Assignment: Type Int Bits
* Required: yes
* Complexity: easy
* Lines of code: 3 lines
* Time: 3 min
English:
1. Calculate altitude in kilometers:
a. Kármán Line Earth: 100_000 m
b. Kármán Line Mars: 80_000 m
c. Kármán Line Venus: 250_000 m
2. In Calculations use floordiv (`//`)
... |
c302570aa4690e3a2d2e028561c2933abe55dadc | ankawm/NowyProjektSages | /exception_custom_exception.py | 1,443 | 3.78125 | 4 | """
* Assignment: Exception Custom Exception
* Required: no
* Complexity: easy
* Lines of code: 4 lines
* Time: 5 min
English:
1. Define custom exception `NegativeKelvinError`
2. Check value passed to a `result` function
3. If value is lower than 0, raise `NegativeKelvinError`
4. Non-functional require... |
bbf8cb979edffa0e12f1d4038aaede1cc4b30fcc | ankawm/NowyProjektSages | /type_int_bits.py | 1,475 | 3.890625 | 4 | """
* Assignment: Type Int Bits
* Required: no
* Complexity: medium
* Lines of code: 4 lines
* Time: 3 min
English:
1. File size is 1337 megabits [Mb]
2. Calculate size in bits [b]
3. Calculate size in kilobits [kb]
4. In Calculations use floordiv (`//`)
5. Run doctests - all must succeed
Polish:
... |
a120f5b981cb8ed1cb5155bcd2a88722e9a68d89 | ankawm/NowyProjektSages | /exception_catch_else.py | 1,275 | 4 | 4 | """
* Assignment: Exception Catch Else
* Required: yes
* Complexity: easy
* Lines of code: 7 lines
* Time: 5 min
English:
1. Convert value passed to the `result` function as a `float`
2. If conversion fails, raise `TypeError`
3. If value is below AGE, raise `PermissionError`
4. Non-functional requireme... |
1c5790befa09be2072c7e663f8abf862eceb4458 | ankawm/NowyProjektSages | /conditional_modulo_operator.py | 1,539 | 4.34375 | 4 | """
* Assignment: Conditional Operator Modulo
* Required: yes
* Complexity: easy
* Lines of code: 3 lines
* Time: 3 min
English:
1. Read a number from user
2. User will input `int` and will not try to input invalid data
3. Define `result: bool` with parity check of input number
4. Number is even, when ... |
2bc3e5f30bb5a8e04b52e707bd7fc060334374de | IgpI/python_learning_000 | /ball_bound.py | 779 | 3.8125 | 4 | from tkinter import *
#物体設定
ball={
"x":350,
"y":300,
"w":30,
"vx":15,
"vy":-15,
}
#GUI
root=Tk()
root.title(u"like Windows")
cv = Canvas(root, width = 1200,height =900)
cv.pack()
def d_o():
cv.delete('all')
cv.create_oval(
ball["x"]-ball["w"],ball["... |
e8bbc492a772bc93107197be4b0452d0fe4e47ed | Anthonymoe/Python-Intro | /hello_world.py | 1,761 | 4.0625 | 4 | def my_function():
print("Hello world")
my_function()
name = "Lucas";
print(name)
name = 0;
print(name);
arr = [0,1,2];
print(arr);
# %%
print('Hello World')
# %%
name = "Anthony"
name = "Nate"
print("name 1:", name)
# this is how variables are declared
# constant variables do not exist
# %%
a = b = c ... |
fdcd80800ea1e954185a1aae44e722920af061b3 | KaterynaT/Tests | /lesson4/static_class.py | 460 | 3.53125 | 4 | class MyClass(object):
def __init__(self, data):
self.data = data
def create(self):
print(self.data)
@staticmethod
def smethod(*arg):
"""
:param arg: any data you'd like to enter
"""
print 'Static:', arg
@classmethod
def cmethod(*arg):
p... |
6f4bfcf5c86d71bb1e7c1d410ec781d421f39a9c | Davit50/Python | /sql/main.py | 2,160 | 3.90625 | 4 | from tkinter import *
import sqlite3
root = Tk()
root.geometry('600x500')
root.title("Registration Form")
Fullname = StringVar()
Email = StringVar()
var = IntVar()
c = StringVar()
var1 = IntVar()
def database():
name1 = Fullname.get()
email = Email.get()
gender = var.get()
country ... |
09f100fe8980a952afa3e606deddf61c5d49b6b1 | MCOfficer/simple-youtube-api | /simple_youtube_api/name_converter.py | 228 | 3.59375 | 4 | import re
def c_to_u(name):
return re.sub(r"(?<!^)(?=[A-Z])", "_", name).lower()
def u_to_c(name):
name = "".join(x.capitalize() or "_" for x in name.split("_"))
name = name[0].lower() + name[1:]
return name
|
20b6ce34f2cc0bcda758ad71b97f73ee045e26e6 | johnny-flynn/Markov-chain-Monte-Carlo | /bayes.py | 4,388 | 3.546875 | 4 | import random as rand
# import matplotlib.pyplot as plt
# CP Tables for every node (A, G are always True, no tables needed)
# Able to get proper index by mapping vals by their truth table
# Ex. B_TABLE:
# - First 4 vals are C=F, Last 4 are C=T
# - This is why we multiply the node C val (0 or 1) by 4 for B_TABLE in... |
7019a7fd8dc43e38d17fb3af32cca6d5ace9b0d4 | gokceeaktug/DSC-GAZI-PG1926 | /Python/Python-Problem_Set_4/app.py | 213 | 3.921875 | 4 | liste = []
adet = int(input('Kaç Sayı Girilecek: '))
for n in range(adet):
sayi = int(input('Sayıyı Gir: '))
liste.append(sayi)
print(liste)
print("Liste İçindeki En Büyük Sayı :", max(liste))
|
fc36f12a14f26c3038266f7e34675877d6fb7ad8 | papousek/spiderpig | /example/wikipedia/commands/intro.py | 363 | 3.546875 | 4 | """
Download and print the first paragraph from Wikipedia for the given keyword.
"""
from general.model import load_html
from html2text import HTML2Text
def execute(text, lang='en'):
h = HTML2Text()
h.ignore_links = True
print(h.handle(load_html('https://en.wikipedia.org/w/index.php?search={}'.format(tex... |
7153c54ba17de88745d3dbb1ccaf83862b2cbf5e | kolarav/Coding-Problems-Arrays | /smaller_than_current_number.py | 1,281 | 3.703125 | 4 | from typing import List
# Time : worst case -> O(N^2) best case O(N) Space : O(N)
# class Solution:
# def smaller_than_current(self, nums: List[int]) -> List[int]:
# smaller = []
# scount = {}
# for num in nums:
# if num in scount:
# smaller.append(scount[num])... |
838eb30ef92ae42c5ac849fc8afb17357816891e | fyangss/questions | /python/hr/algorithms/between_two_sets_easy.py | 1,744 | 3.53125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'getTotalX' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER_ARRAY a
# 2. INTEGER_ARRAY b
#
def getTotalX(a, b):
"""
Brute force, basic math / num... |
fb2bf0e48c512be097b38c7dca0310deec0a41a4 | fyangss/questions | /python/hr/algorithms/big_sorting_alt01_easy.py | 602 | 3.71875 | 4 | class StringAsInt(object):
def __init__(self, obj, *args):
self.obj = obj
def __lt__(self, other):
if len(self.obj) != len(other.obj):
return len(self.obj) < len(other.obj)
else:
return self.obj < other.obj
def __gt__(self, other):
return other < self
... |
6decc945c80ca5720d703dd8f280ced230bce0c2 | fyangss/questions | /python/hr/algorithms/hackerrank_in_a_string_easy.py | 1,165 | 3.828125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
def search(search_string, rem_string):
if len(rem_string) < len(search_string):
return False
elif len(search_string) == 0:
return True
elif len(search_string) == 1:
for i in rem_string:
if i == search_string:
retur... |
3ab7a9b606978f922e5d1c567111aefe22b0de52 | fyangss/questions | /python/hr/algorithms/strong_password_easy.py | 887 | 3.640625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the minimumNumber function below.
def minimumNumber(n, password):
numbers = "0123456789"
lower_case = "abcdefghijklmnopqrstuvwxyz"
upper_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
special_characters = "!@#$%^&*()-+"
reqs = [len(pas... |
f91da8485a2e3470cc9051ae66b5498fe6f1fd7e | fyangss/questions | /python/hr/algorithms/separate_the_numbers_easy.py | 557 | 3.703125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the separateNumbers function below.
def separateNumbers(s):
length = 1
for i in range(length, len(s)):
sequence = s[:i]
cur_num = int(sequence)
first_num = cur_num
while len(sequence) < len(s):
cur_num += 1
... |
7de6a89bbe8a7a138dbfc05054a7588bce17073a | carlos123quirino/Tomadedeciciones | /Teoriavalesperado.py | 1,041 | 3.96875 | 4 | print("INSERTA DATOS DE LA PRIMERA OPCION\n")
r1 = float(input("Ingresa cantidad a Ganar:\t"))
p1 = float(input("Ingresa probabilidad de Ganar:\t"))
r2 = float(input("Ingresa cantidad a Perder:\t"))
p2 = float(input("Ingresa probabilidad de Perder:\t"))
print("\n\nINSERTAR DATOS DE LA SEGUNDA OPCION\n")
r11 = float(inp... |
4bb5b2eafd0eb049ea39e29959bb7453d06dab80 | bsadoski/entra21 | /aula10/foreign.py | 1,076 | 4.0625 | 4 | #sqlite3 já faz parte do python :D
import sqlite3
# isso cria o banco, caso não exista!
conn = sqlite3.connect('super_cliente.db')
# para fazermos nossas operações, sempre precisaremos de um cursor
cursor = conn.cursor()
# criando a tabela (schema)
cursor.executescript("""
CREATE TABLE cidades (
id INTEGER PRIMARY... |
cdcc90778ad83f0ff03db2a8d637c0c3dc466a56 | bsadoski/entra21 | /aula4/poo3.py | 1,039 | 4 | 4 | #parent and child classes
class Animal:
def __init__(self, habitat, classe):
self.habitat = habitat
self.classe = classe
def som(self):
return "???"
class Cachorro(Animal):
def __init__(self, habitat):
super().__init__(habitat, "Mamifero")
def som(self):
return... |
ba13ea5794eb0940acd21f591f84f13514468452 | bsadoski/entra21 | /aula11/create-db.py | 969 | 4.28125 | 4 | #sqlite3 já faz parte do python :D
import sqlite3
# isso cria o banco, caso não exista!
conn = sqlite3.connect('poke.db')
# para fazermos nossas operações, sempre precisaremos de um cursor
cursor = conn.cursor()
# criando a tabela (schema)
cursor.executescript("""
CREATE TABLE treinadores(
id INTEGER NOT NU... |
257d5f22284345460adf2fd8956a8a1ffb2b8e62 | bsadoski/entra21 | /aula9/5-where.py | 384 | 3.625 | 4 | import sqlite3
conn = sqlite3.connect('clientes.db')
cursor = conn.cursor()
cursor.execute("""
SELECT * FROM clientes
WHERE id = ?;
""", (1,))
print(cursor.fetchone())
cursor.execute("""
SELECT * FROM clientes
WHERE idade > ?;
""", (21,))
print(cursor.fetchall())
cursor.execute("""
SELECT * FROM clientes
WHERE ci... |
3ad42196c25d835d69a1d1619aae5934d2923c67 | selex-edinburgh/rampchartest | /testProgramAnswers.py | 4,441 | 3.75 | 4 | #testProgramAnswers.py
'''
This file contains help to answer the exercises in the test programmes.
#testMotors.py cycling option
#Insert this code block at the end of the event key if statements.
'''
if event.key == pygame.K_y: #cycle over speed range
status = "cycling"
... |
c3a0bb618643669a0283ea8c486d37f668a5886c | ProgFuncionalReactivaoct19-feb20/clase04-vysery98 | /ejemplo3.py | 220 | 3.796875 | 4 | """
@vysery98
Ejemplo 3
"""
lista = [(100, 2), (20, 4), (30,1)]
lista2 = ["b", "a", "c"]
# Upper - Mayuscula
f = lambda x: x.upper()
print(list(zip(sorted(lista), sorted(map(f, lista2), reverse = True)))) |
8cc2bcc6aa36aa941b90bb538609c818e6509556 | angelmtenor/AIND-deep-learning | /L3_NLP/B_read_text_files.py | 1,140 | 4.25 | 4 | """Text input functions."""
import os
import glob
def read_file(filename):
"""Read a plain text file and return the contents as a string."""
# Open "filename", read text and return it
with open(filename, 'r') as f:
text = f.read()
return text
def read_files(path):
"""Read all files that ... |
36ad44fdab61c80f92847790e6010fb67f478e2f | DEVESHKUMAR97/Turtle_patterns | /Turtle_pattern2.py | 518 | 3.65625 | 4 | import turtle
turtle.bgcolor("black")
turtle.speed(0)
turtle.penup()
turtle.goto(-50,-50)
turtle.pendown()
turtle.left(36)
turtle.color("blue","skyblue")
turtle.begin_fill()
def multiple_stars(turtle,size):
if size >=10:
for i in range(5):
turtle.forward(size)
multiple_stars(turtle,... |
e3c201cfb4a65055a71a83dc8e570fb6db86ef1c | ebinezh/power-of-number | /power of a number.py | 221 | 4.15625 | 4 | # power of a number
n=float(input("Enter a number:"))
e=int(input("Enter exponent: "))
for i in range(1, e):
x=n**e
print(n, "^", e, "=", x)
# thanks for watching
# like, share & subscribe
# Dream2code
|
b7237c92fd39f8b10bb56057782fa922aaab8928 | Abdulrahman-Ashour/Sea-Level-Predictor | /sea_level_predictor.py | 1,003 | 3.6875 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import linregress
def draw_plot():
# Read data from file
df = pd.read_csv('epa-sea-level.csv')
# Create scatter plot
plt.scatter(df['Year'], df['CSIRO Adjusted Sea Level'])
# Create first line of best fit
... |
03127e4ba95f541d37c22598cace5b927c30f87c | Lavenda/myPythonCastle | /src/myLibs/myThread/threadqueue/test.py | 1,186 | 3.9375 | 4 | #!/usr/bin/env python2.6
#-*- coding: utf-8 -*-
"""
Created on 2013-5-3
@author: lavenda
"""
from time import sleep
class Test(object):
"""
classdocs
"""
num = 0
def __init__(self):
"""
Constructor
"""
pass
def range3(self):
for i in range(3):
... |
078c217b79c1dd19faaca68afdb41e0b0b0db153 | Lavenda/myPythonCastle | /src/myTest/generator/generatorTest.py | 796 | 3.578125 | 4 | #!/usr/bin/env python2.6
#-*- coding: utf-8 -*-
"""
Created on 2013-5-15
@author: lavenda
"""
def echo(value=None):
print "Execution starts when 'next()' is called for the time."
try:
while True:
try:
print type(value)
value = (yield value)
... |
79f4d1464c5dd1967561e0354420b930e77cedc1 | AndreyPikunov/VesiclesInitialization | /vesinit/functions/geometry.py | 1,538 | 3.59375 | 4 | import numpy as np
import math
def length(x1,y1,x2,y2):
return math.sqrt( (x1-x2)**2 + (y1-y2)**2 )
def vector_length(x,y):
return length(x, y, 0.0, 0.0)
def area(x,y): # CAN BE NEGATIVE, IMPORTANT!
x = np.array(x)
y = np.array(y)
return 0.5*(np.dot(y,np.roll(x,1))-np.dot(x,np.roll(y,1)))
... |
40394afc6940cf7ddaf3d10478e279f2b6590881 | bjh83/matt-and-brendan-teaching-stuff | /sum.py | 353 | 3.921875 | 4 | def sum2(numbers):
total = 0
for num in numbers:
total += num
return total
def sum3(numbers):
total = 0
i = 0
print('Got here!')
while i < len(numbers):
print('i = ' + str(i) + ', total = ' + str(total))
total += numbers[i]
i += 1
return total
print('Hello, world!')
print(sum2([1, 2, 3... |
9414f815d96dcbea31a100ce8c005334c0a6afb8 | LeBoot/Practice-Code | /Python/number_divis_by_2_and_or_3.py | 704 | 4.3125 | 4 | #Ask for favorite number.
favnum = int(input("What is your favorite whole number? ").strip())
#Divisible by 2.
if (favnum/2 == int(favnum/2)) and (not(favnum/3 == int(favnum/3))) :
print("Divisible by 2 but not by 3.")
#Divisible by 3.
elif (not(favnum/2 == int(favnum/2))) and (favnum/3 == int(favnum/3)) :
pr... |
705d9deaa4f8bcec1980a6756d2e18cfbf7e955e | LeBoot/Practice-Code | /Python/Udemy-The-Python-Bible/name_program.py | 309 | 4.1875 | 4 | #Ask user for first then last name.
namein = input("What is your full name? ").strip()
#Reverse order to be last, first.
forename = namein[:namein.index(" "):]
surname = namein[namein.index(" ") + 1 ::]
#Create output.
output = "Your name is {}, {}.".format(surname, forename)
#Print output.
print(output)
|
9eb4de9a8d62de2f42c43e01fb20f68eb26648d7 | alikabeel/JetBrains-Python | /Easy Projects/Coffee Machine/Stage5.py | 2,418 | 4.0625 | 4 | money = 550
water = 400
milk = 540
coffee = 120
cups = 9
def buy():
global money,water,milk,coffee,cups
print('What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino:')
choice = input()
if choice == 'back':
return
choice = int(choice)
if cups < 1:
print("Not enough Cup... |
8b209748c88249ec3979756049f92089bd6bb4a9 | yonghyunJay/TIL | /python/basic-example/q_20191219.py | 1,246 | 3.609375 | 4 | '''
# 문제 1.
문자열을 입력받아 문자열의 첫 글자와 마지막 글자를 출력하는 프로그램을 작성하시오.
ex) python py_quest.py 실행 후 나타나는 입력란에
ABCDEFG 입력시
A G 출력
'''
str = input('문자를 입력하세요: ')
# 아래에 코드를 작성해 주세요.
# print(str[0], str[len(str)-1])
print(str[0], str[-1])
'''
문제 2.
자연수 N이 주어졌을 때, 1부터 N까지 한 줄에 하나씩 출력하는 프로그램을 작성하시오.
ex) python py_quest.py 실행 후... |
d214ed0d3d882d25d7e11c50f7ced21b06ff7ddd | LakeEffectRobotics/LakeEffectScoutingApp | /python parsing/AverageImproved (Legacy).py | 11,996 | 3.5 | 4 | import os
class Score:
def __init__(self):
self.success = 0;
self.fail = 0;
self.max = 0;
def __str__(self):
return str(self.success)+","+str(self.fail)
def score(self):
self.success+=1
def miss(self):
self.fail+=1;
d... |
a934ecb0ac833b34048e33f0f7d3df862badc6bc | Priety789/project111 | /code.py | 1,168 | 3.703125 | 4 | import plotly.figure_factory as ff
import plotly.graph_objects as go
import statistics
import random
import pandas as pd
import csv
df = pd.read_csv("medium_data.csv")
data = df["reading_time"].tolist()
fig = ff.create_distplot([data], ["reading_time"], show_hist=False)
fig.show()
mean = statistics.mean(data)... |
054946927d4284778f825ec46e89f8fe24bd75b6 | mingxiao/codeeval | /hard/JuggleFest.py | 3,895 | 3.703125 | 4 | def form_dict(lines):
"""
Given a list of lines, return a dictionary mapping from
circuit/jugg --> [H, E,P]
"""
d = {}
for line in lines:
line = line.strip()
info = line.split(' ')
d[info[1]] = form_list(info[2],info[3],info[4])
return d
def prefs(lines):
d = {... |
2bf0cf89242bca0d2721c26c5da81910016026bd | swuerth/StravaDevChallenge | /strava-club-highlights-gcloud/env/lib/python2.7/site-packages/units/abstract.py | 1,512 | 3.96875 | 4 | """An abstract base class to define the interface for all units."""
from units.compatibility import compatible
from units.exception import IncompatibleUnitsError
from units.quantity import Quantity
class AbstractUnit(object):
"""Parent class/interface for units."""
def __init__(self, is_si):
self... |
d713bc2a5ca7a3402fc87c5f56df53852389e64c | krother/software-engineering-python | /refactoring/solution/03-extract-and-modify/space_game.py | 2,995 | 4.0625 | 4 | """
Space Travel Game
A simple text adventure written for a refactoring tutorial.
"""
from text_en import TEXT
def display_inventory(credits, engines, copilot):
print("-" * 79)
inventory = "\nYou have: "
inventory += "plenty of credits, " if credits else ""
inventory += "a hyperdrive, " if engines ... |
a2f7efd4259a99717283d770a8afbfca64639d67 | krother/software-engineering-python | /refactoring/solution/07-oop-decouple-game-logic/space_game.py | 3,588 | 3.703125 | 4 | """
Space Travel Game
A simple text adventure written for a refactoring tutorial.
"""
from text_en import TEXT
from puzzles import StellarQuiz, BuyEngine, HireCopilot, BlackHole
from puzzles import credits, engines, copilot, game_end
class Planet:
def __init__(self, name, connections, puzzle=None):
sel... |
0e4b85c9bae742de8a9811cdf84914150062c20f | tanishka-yadav/SDP-python | /SDP_Day1.py | 1,759 | 3.828125 | 4 | # Day1 of SDP python
#=============================================Exercise 1===========================================#
#WAP for ADD, MUL, DIV, SUB
a = 10
b = 20
print(a+b) #Addition
x = 40
y = 20
print(x*y) #Multiplication
a = 100
b = 50
print(a/b) #Division
x = 90
y = 40
print(x-y) #Subtratio... |
ccd2debe67b7a35e7d30f076db09b47efef909a1 | potzenhotz/py_euler_project | /7_10001st_prime.py | 741 | 4.09375 | 4 | #!/usr/bin/env python3.4
import math
import pdb
def is_prime(number):
if number>1:
if number in [2,3,5,7]:
return True
if number % 2 == 0:
return False
for divisons_to_test in range(3,int(math.sqrt(number))+1,2):
if number % divisons_to_test == 0:
... |
08e47a829cdab378c8afb8111a084e94fcc779f8 | girishsr25/Python-Internship | /Day 3 Task.py | 871 | 3.703125 | 4 | #1
fruits = {1:"apple",2:"pineapple",3:"mango"}
vegetables = {4:"tomato",5:"potato",6:"onion"}
fruits.update(vegetables)
print(fruits)
#output = {1: 'apple', 2: 'pineapple', 3: 'mango', 4: 'tomato', 5: 'potato', 6: 'onion'}
#2
cars = {1:"BMW",2:"Benz",3:"Audi"}
cars.pop(3)
print(cars)
#output = {1: 'BMW', 2:... |
da68ffc2bd4be39bd4a0e98a64f9ba9a9cd0183e | thomasdziedzic/datamatch | /test_utilities.py | 755 | 3.625 | 4 | import unittest
import utilities
class TestUtilityFunctions(unittest.TestCase):
def test_readCSV(self):
filename = "./test_data/1.csv"
contents = utilities.readCSV(filename)
self.assertEqual(3, len(contents), 'There should be 3 rows in the file')
for row in ... |
413f07009fc542ef32487afabc3084852508904f | satyamnoob/Hangman | /hangman.py | 2,647 | 3.953125 | 4 | import random
def printAList(a_list):
print()
for charecter in a_list:
print(charecter, end="")
print()
def reveals(guess, word, reveal):
c = 0
for alphabet in word:
if guess == alphabet:
reveal[c] = guess
c += 1
def hasLost(reveal, tries, guessed, word):
if t... |
1a095387dbeb3f661dc8016b26691c7c3cd3ea68 | chepkuruipurity/Codewars | /which_are_in.py | 194 | 3.84375 | 4 | def in_array(array1, array2):
# your code
r = []
for a1 in array1:
for a2 in array2:
if a1 in a2 and not a1 in r:
r.append(a1)
r.sort()
return r |
78bd7a731f415d5ef8074170cc51284d4554e331 | gan3i/Python_second | /Data Types/tuple.py | 582 | 3.53125 | 4 | #immutable sequence of orbitrary objects
t=("hey",2,4,5)
print("first="+t[0]+ " Second=" + str(t[1]) +" length=" +str(len(t)))
t+(48,34)
t=t*3
for i in t:
print(str(i))
p=((3,3),4,4)
print(p[0][1])
singletuple=(343,)
emptytuple=()
#tuple unpacking
def return_min_max(item):
return min(item),max(item)
... |
2744b53e3e958cf240e78b162973bd010c62e100 | gan3i/Python_second | /UnitTesting/test_phonebook.py | 1,476 | 3.578125 | 4 | from phonebook import PhoneBook
import unittest
class PhoneBookTest(unittest.TestCase):
def setUp(self) -> None:#called before every test method
self.phonebook =PhoneBook()
def tearDown(self) -> None:#called after every test method
pass
def test_lookup_by_name(self):
self.phonebo... |
3c533ce797628ed823869d022a9a53de61de837c | andromeder/PythonExploits | /first_factorial.py | 137 | 3.6875 | 4 |
def simpleAdding(num):
sum = 0
i = 0
while i <= num:
sum += i
i+=1
return sum
print(simpleAdding(8))
|
cc596f40bc8604a4f83499ae2521c2ebf336b734 | ericachesley/code-challenges | /zero-matrix/zeromatrix.py | 1,293 | 4.25 | 4 | """Given an NxM matrix, if a cell is zero, set entire row and column to zeroes.
A matrix without zeroes doesn't change:
>>> zero_matrix([[1, 2 ,3], [4, 5, 6], [7, 8, 9]])
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
But if there's a zero, zero both that row and column:
>>> zero_matrix([[1, 0, 3], [4, 5, 6], [7, 8,... |
df079daeae2bf16b074ee7dfab3d85083f2f1b60 | djd0723/crime_map | /old/scrape_wloo.py | 5,334 | 3.59375 | 4 | import urllib2
from bs4 import BeautifulSoup
import re
# PDF taken from the Waterloo Police Department's website:
# http://www.waterloopolice.com/images/crpress.PDF
# Create a CSV where we'll save our data.
f = open('csv/todays_crime_data.csv', 'w')
# Add headers
f.write("date" + "," + "times" "," + "crime" + "," + "... |
75bd53a1590dab00a26a3ba57a2932b75c537074 | Galbator1x/18_price_format | /format_price.py | 759 | 3.8125 | 4 | import re
import locale
def format_price(price):
price = str(price).replace(',', '.')
price = re.sub(r'\s', '', price)
try:
price = float(price)
except ValueError:
return 'N/A'
loc = locale.getlocale()
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
price = locale.currency... |
cf353d37d7215a689b7fec728642479155a08c7c | MikeyABedneyJr/CodeGuild | /python_basic_exercises/list_build_new_list_stocks2.py | 843 | 3.6875 | 4 | #GIVEN THE FOLLOWING LIST OF LIST
test_data = [
["2014-06-01", "APPL", 100.11],
["2014-06-02", "APPL", 110.61],
["2014-06-03", "APPL", 120.22],
["2014-06-04", "APPL", 100.54],
["2014-06-01", "MSFT", 20.46],
["2014-06-02", "MSFT", 21.25],
["2014-06-03", "MSFT", 32.53],
["2014-06-04", "MSF... |
2a32fb6338772f353e2432df396221bc027a6838 | MikeyABedneyJr/CodeGuild | /python_basic_exercises/class2(dictionaries).py | 519 | 4.4375 | 4 | dictionary = {'name':'Mikey', 'phone_number': '867-5309'} #python orders in most memory efficient manner so phone # might appear first
print dictionary['name']
dictionary['name'] = 'Mykee' #changed value of name
print dictionary['name']
dictionary['age'] = 32
print dictionary #just added a key named "age" which is 32 {... |
67be13f1994200908a1fda1802e7dde89226ca74 | HubertFraczek/boikwd-laboratoria | /lab12/zad2.py | 563 | 3.5 | 4 | import numpy as np
from scipy.optimize import linear_sum_assignment
cost = np.array([[0.8, 0.8, 0.8, 0.6, 0.6, 0.6],
[2, 2, 2, 1.5, 1.5, 1.5],
[0.7, 0.7, 0.7, 0.6, 0.6, 0.6],
[0.4, 0.4, 0.4, 0.2, 0.2, 0.2],
[0.2, 0.2, 0.2, 0.4, 0.4, 0.4],
[0.3, 0.3, 0.3, 0.5, 0.5, 0.5]])
row_ind, col_ind = linear_sum_assign... |
525d5e3385233720ee65ce41e649f233bf7c7021 | Flo-code/Advent-of-Code-2019 | /day04/pb01.py | 590 | 3.75 | 4 | def count_password(start, end):
nb_password = 0
for number in range(start, end + 1):
increasing = True
double = False
previous = []
for cpt in str(number):
if len(previous) > 0:
if cpt < previous[-1]:
increasing = False
... |
d96ba0aa4380dd84460df22987abfd300dcf0b79 | doug-ecomp/DesafioDivulgaTudo | /controller.py | 3,177 | 3.78125 | 4 | """Módulo responsável pela integração entre as requisições do usuário e os recursos do sistema.
"""
from persistencia import Persistencia
from anuncio import Anuncio
from relatorio import RelatorioAnuncio as RA
class Controller:
"""Controlador das chamadas do sistema.
"""
bd = Persistencia()
def c... |
5f8e38c3c43966d712692ac4fdbe3e35ebe635f2 | m3gan-m/CIDM5310 | /ch01.py | 3,209 | 3.9375 | 4 | print("Chapter 1 Exercises")
print("-------------------")
print("My only comment - The hardest part of this whole assignment was getting everything installed and setup correctly.")
print()
print("Number 2")
print("No it is not. It can appear to be but belong to a different distribution.")
print()
print("Number... |
c63c404892dbef32e15a522c54090654cce22507 | ratularora/python_code | /python/string/min_string.py | 98 | 3.609375 | 4 | str = "abcd";
print "Min character: " + min(str)
str = "xyz";
print "Min character: " + min(str)
|
66d96cfa8467b7cbfffae1c91ada09a63553c2c6 | ratularora/python_code | /python/func & files/readmethod.py | 150 | 3.59375 | 4 | # Open a file
fo = open("foo.txt", "r+") #mention ur existing file
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()
|
4a64c36a54e149f86713b630c24e870635f94965 | pchiuco-seer/python-training3 | /exercise6.py | 506 | 3.953125 | 4 | """def create_fib(input):
fib_array = [1,1]
if input == 0:
return [1]
elif input == 1:
return fib_array
else:
for i in xrange(2,input):
fib_array.append(fib_array[i-1] + fib_array[i-2])
for j in xrange(0,len(fib_array)):
yield fib_array[j]"""
def fib(input):
fib_array = [1,1]
if input == 0 or inp... |
899809cf9b5cdb5323a69f456f97c2d6ff2ccff8 | LISPIER/StartFrom2018-6-24 | /2018-6-24-1.py | 1,361 | 3.703125 | 4 | # 2018-6-24
# 杨辉三角形
# 按q退出,任意键显示下一行
# 不断打印杨辉三角形的每一行直到结束
from typing import List, Any, Union
def main():
historyLines = [] # 用于存储已经打印过的行
currentLine = [] # 当前行
nextLine = [] # 下一行
while True:
command=input()
if command == "q":
break
else: # 主逻辑开始
i... |
1782eea54edbf29bdce406b8f6030c7ce9498e62 | newcaolaing/web_auto | /otherdemo/python高级编程/多线程/6.queue队列限制最大线程数.py | 1,093 | 3.65625 | 4 | import queue
import threading
from time import sleep
def work1(num):
sleep(10)
print("work1:"+num)
def work2():
# 先进先出队列
q=queue.Queue()
q.put(1)
q.put(2)
q.put(3)
print(q.qsize())
print(q.get())
print(q.qsize())
# 先进后出队列
q=queue.LifoQueue()
q.put(1)
q.put(2)... |
4138a45f15bb387b35c77ce259d22ed423be9f38 | newcaolaing/web_auto | /otherdemo/python高级编程/多线程/5.互斥锁.py | 614 | 3.78125 | 4 | import threading
from threading import Thread
from time import sleep
nums = 0
def work1(num):
global nums
for x in range(num):
lock.acquire()
nums+=1
lock.release()
print("work1:"+str(nums))
def work2(num):
global nums
for x in range(num):
lock.acquire()
nu... |
886a85ad8f212c51ac529b98f747da86565a7b4b | ocojeda/computorV1 | /computorV1/core.py | 3,423 | 4.03125 | 4 | from logger import logger
def __sqrt(n):
return n ** (1/2)
def __curt(n):
return -(-n) ** (1 / 3) if n < 0 else n ** (1 / 3)
def solve_constant(a):
"""Solves a constant equation (form: a = 0 <=> ax^0 = 0)
Parameters
----------
a : `float`
Value of the constant term.
Returns
-------
s : `str`
Soluti... |
5d4587555a9eb9b809a34add65df54bd97a592df | KIMSEUNGHYUN-eng/python_lecture | /if_and_or_test_input.py | 236 | 3.96875 | 4 | a =int(input("a를 입력하세요"))
b= int(input("b를 입력하세요"))
if (a % 2==0) and (b% 2 ==0):
print("두 수 모두 짝수입니다.")
if( a%2 ==0) or (b%2 ==0):
print("두 수 중 하나 이상이 짝수입니다.") |
b051ed6d68d79f5e5217085cae1dbe963921b5b1 | narsi423/Python | /file_creation.py | 693 | 3.671875 | 4 | '''
Script Name: file_creation.py
Author: Narasimha
date: 30/06/2017
description: This created a file with a required format and then check for it's availability and then read and print the data in the file.
'''
import os
import datetime
import glob
pattern = 'Info-'
ext = '.txt'
path = "F:/Projects/Python/src/"
d... |
f53664094cb1edd9c8d79ba7fa0a7ffca11c47b6 | narsi423/Python | /Ifstatements.py | 223 | 4.0625 | 4 | value = int(input("Enter a price you want to sell at: "))
if value < 100:
print("You can buy the chair")
elif value == 100:
print("If you really want you can buy it")
else:
print("You no need to buy this chair") |
df0c0f8e79e6a6ea5ea7c9bcea6aceec8dcc22f4 | alexis-martin33/project_euler | /q_14.py | 626 | 3.8125 | 4 | ## Iterate the sequence until you find a number with a known sequence
## Eg. if sequence of 10 is done, sequence of 20 is 20 -> sequence(10)
num = 1000000
collatz_dict = {1:1}
for number in range(2,num+1):
start = number
chain_len = 0
while start not in collatz_dict:
if start % 2 == 0:
... |
32094ffec3b86176f0856be0944f89350d9aad16 | newphycoder/USTC_SSE_Python | /练习/练习场1/练习4.py | 343 | 4.3125 | 4 | from tkinter import * # Import all definitions from tkinter
window = Tk()
label = Label(window , text = "Welcome to Python") # Create a "label
button = Button(window , text = "Click Me") # Create a button
label.pack() # PI ace the "label in the window
button.pack() # Place the button in the window
window.mainloop() ... |
aac6288953cdbc80caf8134621d1309cf7a99666 | Luis-Ariel-SM/Modulo-02-Bootcamp0 | /P05, La recursividad en funciones.py | 1,048 | 4.15625 | 4 | # La recursividad es un paradigma de programacion basado en funciones solo se necesitan a asi mismas y se invocan a si mismas. Su mayor
# problema es que puede ejecutar bucles infinitos ya que no para de llamarse por lo cual su punto mas importante es la condicion de
# parada. Es un codigo original y elegante a nivel d... |
168577bc4d0ba59a9dc1e8dfc19ec2cde1c3c452 | lucifer773/100DaysofPythonCode | /Day4 - Rock Paper and Scissor Game/Rock Paper Scissor/main.py | 1,191 | 4.40625 | 4 | """Using ASCI art for console printing"""
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
... |
dd25473bc2060dad2b70833dd83fa59a3a31ba06 | TRoyer86/DoingMathWithPython | /Median.py | 965 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 3 16:38:12 2017
@author: tater
"""
from scipy import *
from matplotlib import pyplot as plt
'''
Calculating the median
'''
def calculate_median(numbers):
N = len(numbers)
numbers.sort()
# Find the median
if N % 2 == 0:
... |
3823d007312343ba0945144fa6ea4d681dee4372 | messi10hitu/fashion_mnist | /main.py | 6,348 | 4.09375 | 4 | import tensorflow as tf
from tensorflow import keras # keras is an API for tensorflow which allow us to write less code
import numpy as np
import matplotlib.pyplot as plt
"""
1.Import the Dataset
2.Preprocess the Dataset
3.Build the Model
a) input layer
b) hidden layer
c) output layer
4.Compile the Model
... |
dffb35a7281f2700848ad5eae3348dfd934dfd24 | xieQin/python34 | /ex38.py | 547 | 3.75 | 4 | ten_things = "Apple Orange"
print("Wait!There isn't 10 things in the list!Let's fix it.")
stuff = ten_things.split(' ')
more_stuff = ["Day", "Month", "Year", "Red", "Blue", "Green", "Black", "Master", "Exercise", "Python"]
while len(stuff) != 10:
next_one = more_stuff.pop()
print("Adding: ",next_one)
stuff.append... |
f94dcc70797491d99bf643cd5b1f2c40aacde6d1 | teofr/CompProg | /Meli/2018/arg.py | 1,061 | 3.546875 | 4 | # s = 'a'
# cnt = 18
# while cnt:
# cnt -= 1
# t = ''
# for c in s:
# if c == 'a':
# t += ('al')
# if c == 'l':
# t += ('paca')
# if c == 'p':
# t += ('cp')
# if c == 'c':
# t += ('pc')
# # print (t)
# print (s.count('alpaca'), end=', ')
# s = t
'''
(2**cant + 1) / 3 = x (mod m)
2**cant + ... |
5bfa5c7b40fa5469f5454f7edb00d366dc137000 | KyleMcInness/CP1404_Practicals | /prac_02/ascii_table.py | 579 | 4.4375 | 4 | LOWER = 33
UPPER = 127
# 1
character = input("Enter a character: ")
ascii_code = ord(character)
print("The ASCII code for {} is {}".format(character, ascii_code))
# 2
ascii_code = int(input("Enter a number between 33 and 127: "))
while ascii_code < LOWER or ascii_code > UPPER:
print("Enter a number greater than o... |
0865ce79212062970ef2647f3fa6243b55ce8fde | KyleMcInness/CP1404_Practicals | /prac_04/list_exercises.py | 450 | 4.28125 | 4 | numbers = []
for i in range(5):
number = int(input("Number: "))
numbers.append(number)
print("The first number is {}".format(numbers[0]))
print("The last number is {}".format(numbers[-1]))
numbers.sort()
print("The smallest numbers is {}".format(numbers[0]))
print("The largest number is {}".format(numbers[-1]... |
fe1ae86c4f9fb4ba800a0c7d478f617a13df498d | A01029961/TC1001-S | /Python/01_turtle.py | 663 | 4.5625 | 5 | #!/usr/bin/python3
"""
First example of using the turtle graphics library in Python
Drawing the shape of a square of side length 400
Gilberto Echeverria
26/03/2019
"""
# Declare the module to use
import turtle
#Draw a square, around the center
side = 400
# Move right
turtle.forward(side/2)
# Turn to the left
turtle... |
9f682dcc458533a7988dea200aa051ce12bc87c2 | johngaitho05/CohMat | /data_structures/BinaryTree/LinkedBinaryTree.py | 2,577 | 3.578125 | 4 | from collections import deque
class Node:
def __init__(self,value):
self.info = value
self.lchild = None
self.rchild = None
class LInkedBinaryTree:
def __init__(self):
self.root = None
def is_empty(self):
return self.root == None
def display(self):
... |
20ffbeee44d90c6e66af23838ad5d4f9b0799131 | dborncamp/ScienceSaturday | /ScienceSaturday07/candy_analysis.py | 3,730 | 3.6875 | 4 | '''
Code to generate some analysis about the various candy tests.
'''
#Global
import pandas as pd
import matplotlib.pyplot as plt
import argparse
#YES, we will use the xkcd style.
plt.xkcd()
def plot_candy(candy,colors):
'''
This function produces the analysis plots for a candy.
'''
tab = pd.read... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.