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 |
|---|---|---|---|---|---|---|
e42a943a2c0798d4851a6cd2db0905c2259ae38c | dweepjyoti/automatic_gcp_detection | /modules/lshapedetection.py | 23,654 | 3.515625 | 4 | import json
import os
import cv2
import numpy as np
from matplotlib import pyplot as plt
class LShapeDetector:
"""'ShapeDetector' is a class to detect 'L' shaped marker from a grayscale or binary image. Some notes:
1) Perimeter and area of original marker is used to detect the shape.
2) Length of one pie... |
cc07c2cc984123ee7f37e1082f6f7bb10d410deb | EvanGarber/doubt | /Code/life.py | 572 | 3.78125 | 4 | import random, time
def life(your_life):
for days in your_life:
you_can = int('LIVE',32)/(days+1)
try:
#to not fall apart
#make goals
print('succeed and fail')
except:
#we
pass
#away eventually, try
while you_ca... |
15211b4b13203781da208dedbb87941cf85950fd | madzing/T-Box | /GpsList.py | 5,494 | 3.515625 | 4 | #!/usr/bin/python3
###############################################################
# Script written by Jan Metzing
# Kontakt: janmetzing@gmx.de
###############################################################
import math
import datetime
"""
Objects build by this class are meant to store and manage Gps-Data-Lists.
One... |
f162c58bf76905ede02b0d416da485519bb1adb9 | tonywolf-git/PyHangman | /hangman.py | 1,360 | 3.859375 | 4 | import random
def hangman():
wordlist = ["jurassic", "titanic", "witcher", "moonlight", "castlevania"]
word = wordlist[random.randint(0, len(wordlist)-1)]
wrong = 0
stages = ["",
"________ ",
"| ",
"| | ",
"| 0 ... |
dfaa6b91d8ac82c5c8437ac1c009ec1f61d4bcab | wulfebw/algorithms | /scripts/heaps/heapsort.py | 1,146 | 3.9375 | 4 |
import copy
import heap_operations as heap_ops
def heapsort(arr):
"""
:description: heapsort, version not in place b/c the heap ops don't take heap size parameter. Works by removing largest element and calling max_heapify
:time: O(nlgn) worst case calls max_heapify n times
:space: O(n)
"""
... |
006b52516cffdd65e9830a7920ae472312cd2a5a | wulfebw/algorithms | /scripts/dynamic_programming/expected_rolls.py | 1,585 | 3.984375 | 4 | '''
game involves a 1d board with numbers
you start on the left and end when you get past the last square
each time you roll a die
whatever it lands on
multiply that by the cotents of your current square
and move forward in the array by that amount
question:
what is the expected number of steps it will take to re... |
31ba94e7b9500aa7f081cf25bf87739be3148622 | wulfebw/algorithms | /scripts/recursion/cutting_rectangles.py | 407 | 3.546875 | 4 |
def mygcd(n, m):
while m:
n, m = m, n%m
return n
def find_squares(n, m):
s = mygcd(n, m)
return int(n/s * m/s), s
if __name__ == '__main__':
inputs = [
(7,14),
(9,12),
(2,8),
]
expect = [
(2, 7),
(12,3),
(4,2)
]
for (i,e) i... |
61c9ffb88e669b86595ade35218920e949a50cb3 | wulfebw/algorithms | /scripts/recursion/product_sequence.py | 1,128 | 3.828125 | 4 |
import numpy as np
def compute_prod_seq_term(n):
'''
O(n) ? or O(n^2) ?
how many recursive calls are made? n
how much work per call? n
so O(n^2)
the recurrence is T(n) = T(n-1) + O(n)
which you can't apply the master theorem to
but you can just logic it out
there are n levels to... |
674c9fc9a485a3febe1b3f4d3a2d04204f299263 | wulfebw/algorithms | /scripts/recursion/flip_x_o.py | 3,561 | 3.875 | 4 |
import numpy as np
def flip_x_o(a):
'''
time complexity:
it iterates the entire grid so n * m
for each, it calls recurse, in the worst case, everything is an o
in which case the internal nodes call their neighbors
but this can happen at most 1 time, so I'd say at worst this is
O((n*m)^2... |
bf58ea5fd360e3fdf62d72e00ef0273f8d8b7909 | wulfebw/algorithms | /scripts/sorting/fraud_detection.py | 1,774 | 3.6875 | 4 | '''
The challenge here is to compute the medians in linear time
you can do this using a modified counting sort
by inserting and removing values from the counts
to find the median in the new counts you have to figure out how the
addition / subtraction of indices / values works
I think because it's the median you ca... |
3cee8d7a3042ee3224668dadeda9315a96859b2e | wulfebw/algorithms | /scripts/trees/preorder_to_bst.py | 2,043 | 3.765625 | 4 |
class Node(object):
def __init__(self, v, l=None, r=None):
self.v = v
self.l = l
self.r = r
def preorder(r):
print(r.v)
if r.l:
preorder(r.l)
if r.r:
preorder(r.r)
def preorder2bst(a):
'''
The idea is that you store everything in a stack as you go
... |
619b89ffac0315b310b9fa4dc846ad126f6e9f2e | wulfebw/algorithms | /scripts/getting_started/selection_sort.py | 1,176 | 4.0625 | 4 | """
:keywords: sorting, selection sort
"""
import copy
def selection_sort(lst):
"""
:description: inplace selection sort
:time: O(n^2)
:space: O(1)
"""
if len(lst) <= 1:
return lst
smallest_val = lst[0]
smallest_idx = 0
for insert_idx, val_at_insert in enumerate(lst):
... |
1463a7589563b1c21209fda81290bc07a7f19308 | wulfebw/algorithms | /scripts/graphs/roads_and_libraries.py | 779 | 3.90625 | 4 | '''
for each set of vertices that can be connected, choose the cheapest library to
build and build it
then find the mst for that set of components
how does prims work again?
- it starts with an unconnected graph
- then selects the edge that will connect the mst to a new vertex that also costs the least
+ for th... |
cfb8deeb087124c34afdc1e3bd8877a04a0ec2e2 | wulfebw/algorithms | /scripts/recursion/decode_string.py | 1,106 | 3.53125 | 4 |
def can_parse_int(f):
try:
int(f)
except:
return False
return True
def find_matching_parens(string, start):
onstack = 1
for i, char in enumerate(string[start+1:]):
if char == ']':
onstack -= 1
elif char == '[':
onstack += 1
if onsta... |
131258b6a4ec6684c297a9475b1d04fff45de3fe | wulfebw/algorithms | /scripts/search/backtracking_search.py | 2,313 | 3.84375 | 4 |
import sys
import search_algorithm
class BacktrackingSearch(search_algorithm.SearchAlgorithm):
"""
BacktrackingSearch is a search algorithm that only works
on DAGs (though does work with negative weight edges)
and uses memoization to be somewhat efficient.
runtime is O(|V|^2) because for each v... |
79800893ed9232e754ea1104cddc6c1eef456c0a | wulfebw/algorithms | /scripts/dynamic_programming/coin_change.py | 2,191 | 3.59375 | 4 |
from context_timer import ContextTimer
def find_change_recursive_inefficient(n, vals):
'''
this is a recursive solution that misses the point
run time is
a function of the number of ways that you can form the amount
you instead need to formualte it in terms of the coins and the amount
'''
... |
15e3ed05dc5919e6a86fe26cd62e6fff05e65209 | wulfebw/algorithms | /scripts/probability_statistics/biased_random.py | 2,057 | 4.25 | 4 | """
:keywords: probability, biased, random
"""
import random
def biased_random(p=.1):
"""
:description: returns 1 with p probability and 0 o/w
"""
if random.random() < p:
return 1
return 0
def unbiased_random():
"""
:description: uses a biased random sampling with unknown bias to ... |
b55162530e396b8faf523bb30f3640467b91a2da | wulfebw/algorithms | /scripts/trees/postorder_to_bst.py | 1,208 | 3.5 | 4 |
import sys
class Node(object):
def __init__(self, v, l=None, r=None):
self.v = v
self.l = l
self.r = r
def inorder(r):
if r.l:
inorder(r.l)
sys.stdout.write('{} '.format(r.v))
if r.r:
inorder(r.r)
def postorder(r):
if r.l:
postorder(r.l)
if r... |
1a46dfca76bc17c5be38d7ddbe42a2fff8ab66ff | wulfebw/algorithms | /scripts/selection/weighted_three_median.py | 3,328 | 4.1875 | 4 | """
:question: what is a weighted median? Does the original order of the data matter at all?
"""
from median import randomized_select as select
def weighted_three_median_via_sort(arr):
"""
:description: returns the weighted three median by sorting the array and traversing it. Returns the value and the origina... |
b55d60829b45461d7698af1eba6f1ed35dc4983c | KFarm93/python_exercises2 | /python_exercises2/reverse.py | 111 | 3.6875 | 4 | reversed = "Reversed String"
letters = list(reversed)
letters.reverse()
output = ''.join(letters)
print output
|
7086e77437399634f372ef1fd2050fd04eb60a62 | SakyaSumedh/eulerProblem | /lattice_paths.py | 894 | 3.8125 | 4 | '''
Starting in the top left corner of a 2×2 grid,
and only being able to move to the right and down,
there are exactly 6 routes to the bottom right corner.
How many such routes are there through a 20×20 grid?
'''
def number_of_routes(x_grid, y_grid):
# solution 1
'''
Using matrix form
'''
# grid = [[0 for i in ... |
aeb99c8e03de7cb07c92ce2e2e3b6ef579b9a6b2 | ksang/Voigt-Kampff | /agents/base.py | 1,891 | 3.75 | 4 | class BaseAgent(object):
"""
BaseAgent is the base class abstractions, all other agent implementations
are based on this interface.
Agent is an actor that decoupled from environment, which means this interface
only implements agent internal flows, interactions with environment should be
implemen... |
82e99e5ef946cba072c12431d8b293b3cc4aa3b8 | paulusdevries/python-exercises | /hackerrank/dayOfWeek.py | 334 | 3.625 | 4 | import calendar
def weekDag(datum):
dagen = {
0: "MONDAY",
1: "TUESDAY",
2: "WEDNESDAY",
3: "THURSDAY",
4: "FRIDAY",
5: "SATURDAY",
6: "SUNDAY"
}
maand, dag, jaar = datum.split()
print(dagen[calendar.weekday(int(jaar), int(maand), int(dag))])
we... |
414e06e9ed602099af47f798b3cc02e536fa37e5 | paulusdevries/python-exercises | /hackerrank/permutations.py | 198 | 3.53125 | 4 | from itertools import permutations
def get_perm():
p_string, p_length = input().split()
for _ in sorted(list(permutations(p_string, int(p_length)))):
print(*_, sep="")
get_perm() |
3917d7d4cf9b72f38ddde2302c6f1026650aaad7 | paulusdevries/python-exercises | /hackerrank/lists.py | 636 | 3.8125 | 4 | if __name__ == '__main__':
N = int(input())
command = []
list_ = []
for i in range(N):
command = list(input().split())
if command[0] == "insert":
list_.insert(int(command[1]), int(command[2]))
if command[0] == "reverse":
list_.reverse()
if command[... |
7dfab4a75a72de7bd5594f7756836b77e3340dcf | AdamsEatin/Data_Sci | /correlation-Emissions.py | 2,636 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Author: Adam Eaton - C00179859
This file generates a graph showing the correlation between the chosen countries usage of renewable energies and their
Emissions per year
"""
import pandas as pd
import numpy as np
import plotly
import plotly.plotly as py
import plotly.graph_objs as go
from ... |
c098393b387d2a11865d233ac5ac6a631623f57d | shishir-kr92/DataStructure | /tree/insertion_operation.py | 794 | 4.03125 | 4 | class Node:
def __init__(self, key):
self.left = None
self.right = None
self.key = key
def inorder_transversal(tree):
if not tree:
return
inorder_transversal(tree.left)
print(tree.key, end = " ")
inorder_transversal(tree.right)
def insert(tree, key):
q = [tree]
while(len(q)):
temp = q[0]
q.pop(0)... |
914c9007a4dbf898d7d84bcdf477dc00b5a43d89 | JingYiTeo/Python-Practical-2 | /Q08_top2_scores.py | 567 | 4.15625 | 4 | NStudents = int(input("Please Enter Number of Students: "))
Names = []
Scores = []
for i in range(NStudents):
Name = str(input("Please enter Name: "))
Score = int(input("Please enter Score: "))
Names.append(Name)
Scores.append(Score)
Scores, Names = (list(t) for t in zip(*sorted(zip(Scor... |
f2dfcd0a52380b1c0babf0bf4924d698c6ae83aa | ruku786/Boodl_Assignment | /Problem1.py | 407 | 3.6875 | 4 | # Problem 1 :- Sum to N
class Solution:
def Sum(self, nums, target):
look = {}
for n, x in enumerate(nums):
try:
return(look[x], n)
except KeyError:
look.setdefault(target - x, n)
test= Solution()
a1 = [1, 3, 5]
a2 = [2, 5, 6]
given_num = [2,... |
48434fdacc40da8a8ac702f3d198b4c34b1b2d1a | wellifabio/etec2020 | /tpa/python/exemplos/usuarios.py | 775 | 3.59375 | 4 | numFuncionarios = int(input('Quantos funcionáios você vai cadastrar? '))
arquivo = open('usuario.txt', 'w')
for i in range(0, numFuncionarios):
nome = ''
while (len(nome) == 0) or (len(nome) > 15):
nome = input('Nome ') #recebe o nome do funcionario
if len(nome) == 0:
print('Escreva... |
20be4721df1889e770c934130f541b2fde0e64a0 | jenmccall/CS3612017 | /python/python/exercise9.py | 563 | 4.09375 | 4 | def main():
a = [[1,3], [3,6], [8,10,12]]
print(a)
print(sublist(a))
def sublist(a):
s = []
length = len(a)
for i in range(0, length):
templist = a[i] #when the item is a list, we separate it and make it it's own list.
templength = len(a[i]) #this is the length o... |
1ed80eed3846b059272b9fcd1323701efa76ac61 | Fleford/Multiline_pyMergeChanges | /Better_pyMergeChanges.py | 4,056 | 3.578125 | 4 | # Function Definitions
def find_curly_brackets(input_string):
istart = [] # stack of indices of opening brackets
d = {} # prepared dictionary
skip = False
for i, c in enumerate(input_string):
if skip:
skip = False
continue
if c == '\\': # Ignore character after ... |
a69354ede13d67b01080f98361e9a0df7dcfb6e5 | shivanigambhir11/SeleniumPython | /10ActionsDemo.py | 1,133 | 3.5625 | 4 | from selenium import webdriver
from selenium.webdriver import ActionChains
driver = webdriver.Chrome(executable_path="/Users/shivanigambhir/Downloads/chromedriver 8.51.34 PM")
driver.get("https://www.familysearch.org/en/")
#ActionChains
action = ActionChains(driver) #Advanced classes will be used name as ActionC... |
fefd32983164bb57718f6cde668e2658e77234d6 | yesu14/study | /day01/password.py | 477 | 3.65625 | 4 | # @Author :RG
# @Time :2020-04-08 上午 0:22
# @Note :
import getpass
_username = "tom"
_password = "1234"
username = input("请输入username:")
# password = getpass.getpass("password")
password = input("请输入password:")
print("您输入的用户名为",username,"密码为", password);
if _username == username and _password == password:
... |
c32362f8fd906287b06346f9bfec26c1c7abddb4 | yesu14/study | /day03/画图.py | 857 | 3.59375 | 4 | #-*- coding:utf-8 -*-
# @Author :RG
# @Time :2020-04-23 上午 0:34
# @Note :
# import turtle as t
# t.goto(100,0)
# for i in range(100):
# t.left(80)
# t.fd(100)
# t.left(135)
# t.fd(165)
# t.left(125)
# t.fd(115)
import turtle
import time
# 曲线移动
def curveMove():
for i in range(200... |
a1603adb598e8790573c4bf6fb7c1f8c5a0014ea | daldantas/CursoPython | /exercicios/003.py | 172 | 3.890625 | 4 | print ('====== DESAFIO 03 ====== \n'+'Some dois números:')
n1 = int(input('Primeiro número = '))
n2 = int(input('Segundo número = '))
print ('A soma vale', n1 + n2)
|
f1a292481f75a9e44048d2fa0be0b99523d77e87 | daldantas/CursoPython | /exercicios/001.py | 124 | 3.625 | 4 | print ('====== DESAFIO 01 ======')
nome = input('Qual seu nome? \n')
print ('Olá ' , nome , '! prazer em te conhecer!')
|
fbcd5862a5817a4e1bc584cec1ad9ffa6675847e | daldantas/CursoPython | /exercicios/050.py | 192 | 3.84375 | 4 | #050
s = 0
for c in range(1, 7):
n = int(input("Digite um nº inteiro: "))
if n % 2 == 0:
s += n
print(s)# < refaça esta linha caso o código copiado não funcione.
|
0df33d756725d320808cad3bc95b1c036179e75e | daldantas/CursoPython | /exercicios/022.py | 228 | 3.796875 | 4 | nome = str(input("Seu nome: "))
print(nome.upper())
print(nome.lower())
nomese = nome.replace(' ','')
print("Qte de letras s/ espaços:",len(nomese))
nomepn = nome.split()
print("Qte de letras do 1º nome:",len(nomepn[0])) |
751888590865ed88c97515f8dc89f9af6f0f60a0 | daldantas/CursoPython | /exercicios/033.py | 281 | 3.953125 | 4 | n1 = int(input("Digite o 1º nº: "))
n2 = int(input("Digite o 2º nº: "))
n3 = int(input("Digite o 3º nº: "))
if n1 > n2:
ma = n1
me = n2
else:
ma = n2
me = n1
if n3 > ma:
ma = n3
if n3 < me:
me = n3
print("Maior: ",ma)
print("Menor: ",me) |
63858babace1ddf22ed410afda7529440a2206c9 | daldantas/CursoPython | /exercicios/031.py | 141 | 3.765625 | 4 | dis = float(input("Distância em km: "))
if dis <= 200:
v = dis * .5
else:
v = dis * .45
print("Vai custar R$ {:.2f}".format(v)) |
ebe4921f840c0802afaa43a31645bb8e655d71f1 | Miriam295/Final_Project_Python_DragonQuest | /Dragon_Support.py | 7,630 | 3.84375 | 4 | import time
class Skills:
def __init__(self):
self._skills = 1
def gain_skills(self):
self._skills += 1
def __repr__(self):
return 'Current level of skills: %s' % (self._skills)
def count_skills(self):
return self._skills
class Money:
def __init__(self):
... |
8797fff43e5051ec397c5e5b45e5969dad6a3870 | mattchang0214/practice | /get_k_largest.py | 924 | 3.8125 | 4 | # get the k largest numbers in an array
# runtime: O(k*log(n))
def heapify(arr, size, root):
largest = root
left = 2*root
right = 2*root + 1
if left <= size and arr[left] > arr[largest]:
largest = left
if right <= size and arr[right] > arr[largest]:
largest = right
... |
8d4f20fc421e07b425eb32de3af2399f26a9dd46 | bhupesh17040/K-map-minimization | /gitpart4.py | 8,365 | 3.546875 | 4 | # HOMEWORK ASSIGNMENT 5
# K-MAP MINIMISATION
#USING OOPS CONCEPT
#It involves def __init__ function which includes self as an object
import itertools
#compare two binary strings, check where there is one difference
def compBinary(s1,s2):
c= 0
p= 0
for i in range(len(s1)):
if s1... |
65cf5882a3be9e4efa041a6b661fd17a419e9a9f | Soreasan/Python | /millionaire.py | 7,653 | 3.671875 | 4 | #!/usr/bin/env python3
'''
Kenneth Adair
To run this program type:
python3 millionaire.py
What does this script do?
This program calculates how much money you'll have for retirement if you work for the federal government as a computer scientist in an area
with the lowest cost of living adjustment such as Utah or anot... |
ab7a5601210b13fd049b859d96aa0e25c1f6df0e | Soreasan/Python | /MoreList.py | 1,135 | 4.4375 | 4 | #!/usr/bin/env python3
#We can create a list from a string using the split() method
w = "the quick brown fox jumps over the lazy dog".split()
print(w)
#We can search for a value like this which returns the index it's at
i = w.index('fox')
print(i)
print(w[i])
#w.index('unicorn') #Error
#You can check for membership wi... |
55cd1bbee49e8ce61eac38d8a91c7d49e23f54fb | ebenz99/Math | /algos/threeSum.py | 713 | 3.671875 | 4 | class Solution:
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
overallSols = set()
def twoSum(val,nums):
dic = {}
sols = set()
for num in nums:
if num in dic:
sols... |
1f51943c31e5cd77e963ef306efa5ca677a3787a | ImmortalSnake/AOC | /src/day6.py | 585 | 3.53125 | 4 | def get_children(child, parent):
p = parent.get(child)
if not p:
return []
return [p] + get_children(p, parent)
def part1(tree):
print(sum([len(o) for o in tree.values()]))
def part2(tree):
common = [e for e in tree["YOU"] if e in tree["SAN"]][0]
print(tree["YOU"].index(common) + t... |
6ec6479d88e1d7e21476786ef84cdd7f062948c1 | kamlook/personalFinance | /gui.py | 547 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 15 17:21:36 2020
@author: Kam Look
"""
import tkinter as tk
root = tk.Tk()
alphaLabel = tk.Label(root, text='Alpha: ')
alphaLabel.grid(row=0,column=0)
e = tk.Entry(root)
e.grid(row =0, column =1)
def storeEntry():
alpha = e.get()
#once all fields are working,... |
ee8dca32dacd4580870972a4e4cdb9bd7a67351b | dengguoguo/algorithm | /binary_search.py | 1,056 | 3.75 | 4 | # -*- coding: utf-8 -*-
# @Time : 2018/8/23 10:38
# @Author : dengguo
# @File : binary_search.py
# @Software: PyCharm
# --------------------------------------
# 二分查找也称折半查找(Binary Search),它是一种效率较高的查找方法。但是,
# 折半查找要求线性表必须采用顺序存储结构,而且表中元素按关键字有序排列
# --------------------------------------
def binary_search(tar... |
e6b4587b69e39a7e1bdbeb7befc1cd064ef1cb35 | Ankitpahuja/LearnPython3.6 | /Lab Assignments/Lab06 - Comprehensions,Zip/Q1.py | 886 | 4.75 | 5 | # Create a text file containing lot of numbers in float form. The numbers may be on separate lines and there may be several numbers on same line as well. We have to read this file, and generate a list by comprehension that contains all the float values as elements. After the data has been loaded, display the total numb... |
6486f929c5adccc0980dc26db652e9358c001754 | Ankitpahuja/LearnPython3.6 | /Lab Assignments/Lab05 - RegEX/ppt_assignment.py | 673 | 4.3125 | 4 | '''
Write a function that would validate an enrolment number.
valid=validateEnrolment(eno )
Example enrolment number U101113FCS498
U-1011-13-F-CS-498
13 – is the year of registration, can be between 00 to 99
CS, EC or BT
Last 3 are digits
'''
import re
pattern = re.compile("U1011[0-9][0-9]F(CS|BT)\d\d\d")... |
76e97fc42db60802575bb4b9be80a7499298d26e | Ankitpahuja/LearnPython3.6 | /Tutorials - Examples/GUI - Tkinter/boilerplate.py | 1,170 | 4.4375 | 4 | import tkinter as tk
window = tk.Tk()
window.title("Tkinter's Tutorial")
window.geometry("550x400")
# Label
title = tk.Label(text="Hello World. Welcome to tkinter's tutorial!", font=("Times New Roman",20))
title.grid(column=0,row=0)
#Button1
button1 = tk.Button(text="Click Me!", bg="red")
button1.gri... |
4aabe2d7bcd32c8de942e1cc0f72decbb28f52b9 | mounish9894978881/arithmetic | /arithmetic.py | 115 | 3.75 | 4 | a=10
b=20
print("Addition=",a+b)
print("Subrction=",b-a)
print("multiplication=",a*b)
print("division=",a/b)
|
f5716f83a96b49ba16b8fe7a6f81f5e4f150b52b | kavmuni/python_training_new | /Python_training/current_age_pgm.py | 364 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 19 12:07:11 2018
@author: calydon
"""
import datetime as dt
current_date=dt.datetime.now()
current_year=current_date.year
print("current_year: "+str(current_year))
input_year=input("Please input your birth year: ")
age=current_year - int(input_year) + 10
print... |
0f00057ede12ca0a3321eb113ac01b7331df28ee | kavmuni/python_training_new | /Python_training/range.py | 231 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 19 17:04:41 2018
@author: calydon
"""
some=range(4)
more=range(10,14)
for values in [*some,*more]:
if values > 10:
break
else:
print(values + 10) |
aa9711e7e8face369ecadc78c97b5a3237e8c86c | kavmuni/python_training_new | /Python_training/pythondetails/fibannocci.py | 1,317 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 19 19:47:10 2018
@author: Muniappan
"""
def fibannoci(start_num=0,end_num=10000,n_count=10,for_even=0):
num_01=start_num
num_02=start_num + 1
count=0
#print("starting")
if n_count < 0:
print("Please enter a positive count")
e... |
dfe339423b83149a43710cbf6eef8ad51cb9c1e9 | pavanvittanala/Coding_programs | /uniformity.py | 1,475 | 4.15625 | 4 | ''' ----->>>>> PROBLEM STATEMENT <<<<<----- '''
''' You are given a string that is formed from only three characters ‘a’, ‘b’, ‘c’. You are allowed to change atmost ‘k’ characters in the given string while attempting to optimize the uniformity index.
Note : The uniform... |
6c66dd171c8f4a373b1f61b5728d08237d73d002 | rajeshr428/MITx-6.00.1x | /countbob.py | 177 | 3.71875 | 4 | found=0
cnt=0
for char in s:
if (char == 'b'):
if (s[cnt:cnt+3] == 'bob'):
found += 1
cnt += 1
print ("Number of times bob occurs is:" + str(found))
|
22476e4df3ded45820de0843aaec37c0caf182f3 | oskarolaussen/Fun-side-projects | /ascii_art_generator.py | 798 | 3.609375 | 4 | #This program converts a jpg picture to ASCII art.
from PIL import Image
import numpy as np
import textwrap
ASCII_CHARACTERS=['@', '%', '#', '*', '+', '=', '-', ':', '.']
NEW_WIDTH=150
name_of_picture=input("File name of picture to be converted: ")
img=Image.open(name_of_picture)
img=img.convert('L')
(height, width)=i... |
8b7a6418d8789494c4f389c9168a678ba331e3e5 | mjul/opencvlabpy | /src/sheet_detection.py | 2,862 | 3.53125 | 4 | #!/usr/bin/env python
'''
Code for detecting a sheet of paper in an image.
See http://stackoverflow.com/questions/8667818/opencv-c-obj-c-detecting-a-sheet-of-paper-square-detection
'''
# OpenCV imports
import numpy as np
import cv2
# ----------------------------------------------------------------
def angle_cos(p0,... |
02d823f6749a4bd81a5909ad231801c3cf162c48 | wfeliciano20/pythonBootcamp | /TkinterGUI/icons_images.py | 375 | 3.625 | 4 | from tkinter import Tk, Button, Label
import PIL as pillow
from PIL import ImageTk, Image
root = Tk()
root.title("Icon,Images & exit buttons")
# root.iconbitmap()
quit_button = Button(root, text="Exit Program", command=root.quit)
quit_button.pack()
my_img = ImageTk.PhotoImage(Image.open("mario_PNG57.png"))
my_label ... |
08061d256e8741b714bf13acb5ab9e397f1e83be | wfeliciano20/pythonBootcamp | /IntroToPython/numbers.py | 196 | 3.9375 | 4 | integer_division = 13//5
print(integer_division)
remainder = 13 % 5
print(remainder)
x = 37
remainder = x % 2
print(remainder)
age = 34
print("You are " + str(age))
print(f"You are {age}")
|
1d3c5a9b0279d101f40a947fbeb1bdc6f6ccbd8d | wfeliciano20/pythonBootcamp | /IntroToPython/stringFormatting.py | 337 | 3.984375 | 4 | # name = "William"
# final_greating = "How are you, {}?"
# william_greeting = final_greating.format(name)
# final_greating2 = "How are you, {name}?"
# will_greating = final_greating2.format(name="Will")
# print(will_greating)
# age = input("Enter your age: ")
# age_num = int(age)
# print(f'You have lived for {age_nu... |
1b3bb1ae1928a08a73d4e5018c484f41f2ec79e1 | iamepps/prefix-notation | /src/variables.py | 1,484 | 3.90625 | 4 | import re
from itertools import product
def all_combinations_of_variables(variables: dict) -> list:
"""Find all potential combinations of variable values.
This feels a bit inelegant - I think there is a better way."""
# zip variable name and potential values from range
list_of_variable_val_dicts = [[... |
76c5bbf0406f269be83278fea5898c1ec436ec21 | souvikhaldar/Famous-algorithmic-problems | /first.py | 634 | 4.0625 | 4 | #Given a string, find the length of the longest substring without repeating characters.
def longestsub(s):
start = 0
l = len(s)
maxi = 1
count = 1
visited = []
for end in range(1,l):
if s[start] == s[end] or s[end] in visited:
start = end
count = 1
vis... |
bc9a53894603781b04bc3d0e55d91eb4e50263f2 | farahnorma/Homework4 | /InfiniteFor.py | 256 | 3.640625 | 4 | #Norma
#InfiniteFor.py
#extra credit
import itertools
def infinite():
count =0
for i in itertools.count():
count = count +1
print(count)
return count
def main():
infinite()
print(infinite())
main() |
d57ddeadb444dcae21cd277a28e4208edbaa5dfe | atseng202/ic_problems | /linked_lists/kth_to_last_node/kth_to_last_node.py | 1,714 | 3.84375 | 4 | class LinkedListNode:
def __init__(self, value):
self.value = value
self.next = None
def kth_to_last_node_improved(k, head):
if k < 1:
raise ValueError("K cannot be 0")
fast_walker = head
slow_walker = head
for i in range(1, k):
if not fast_walker.next:
raise ValueError("K cannot be ... |
6d619d4de5e01ff716a69c18c659b6f2f10b58a8 | atseng202/ic_problems | /arrays/is_first_come_first_served/is_first_come_first_served.py | 727 | 3.703125 | 4 | def is_first_come_first_served(take_out_orders, dine_in_orders, served_orders):
take_out_length = len(take_out_orders)
dine_in_length = len(dine_in_orders)
served_length = len(served_orders)
if served_length != (take_out_length + dine_in_length):
return False
take_out_idx = 0
dine_in_idx = 0
for ... |
eccaf13f1f46e435b9547ecffe26c55e63108852 | atseng202/ic_problems | /queues_and_stacks/queue_with_two_stacks/queue_two_stacks.py | 1,371 | 4.125 | 4 | class Stack(object):
def __init__(self):
# """Initialize an empty stack"""
self.items = []
def push(self, item):
# """Push a new item onto the stack"""
self.items.append(item)
def pop(self):
# """Remove and return the last item"""
# If the stack is empty, return None
# (it would also be reasonable to thr... |
a1ad9bb48d43fc6b493db60d3a8ccda8bb51dd44 | atseng202/ic_problems | /trees_and_graphs/graph_coloring/color_graph.py | 1,293 | 3.921875 | 4 | class GraphNode:
def __init__(self, label):
self.label = label
self.neighbors = set()
self.color = None
def color_graph(graph, colors):
# Create a valid coloring for the graph
# Iterate thru the N nodes
# for each node, look at it's nearest neighbors
# the total number of neighbors we would lo... |
5745e50ad2ef97b405906503dfe1b238908d02b8 | mohamed7osama7/Connect-Four-game | /Connect Four game.py | 4,234 | 4 | 4 | """
Assigning values to the grid
The grid will look like this:
0,0 | 0,1 | 0,2 | 0,3 | 0,4 | 0,5 | 0,6
1,0 | 1,1 | 1,2 | 1,3 | 1,4 | 1,5 | 1,6
2,0 | 2,1 | 2,2 | 2,3 | 2,4 | 2,5 | 2,6
3,0 | 3,1 | 3,2 | 3,3 | 3,4 | 3,5 | 3,6
4,0 | 4,1 | 4,2 | 4,3 | 4,4 | 4,5 | 4,6
5,0 | 5,1 | 5,2 | 5,3 | 5,4 | 5,5 |... |
3e8f386ae58263d3a45a9e79706144af5cc6710a | Doxxy1/UniversityProjects | /Programming Internet of Things/A2/RP/validation.py | 1,735 | 3.890625 | 4 | import re
class validateData:
def __init__(self):
pass
#checking the name input against our syntax
def nameValidation(self,nameInput):
if nameInput.isalpha():
fixedName = nameInput.lower().capitalize()
return fixedNa... |
38a1019e9b591d493c0efa3e8699a4ecca4ebcf6 | Juhye-Kim/Boosting-Study | /윤장원/210629/오픈채팅방.py | 712 | 3.6875 | 4 | import collections
def solution(record):
answer = []
hash_table = collections.defaultdict(str)
record = [r.split() for r in record]
# 최종적으로 바뀐 아이디
for r in record:
attr = r[0]
u_id = r[1]
if attr == 'Enter':
hash_table[u_id] = r[2]
elif attr == 'Cha... |
63a9ad33825620de6667c0d694471fbe8e939149 | Garima-sharma814/The-faulty-calculator | /faultycalculator.py | 1,596 | 4.3125 | 4 | # faulty calculator
# Design a calculator which will correctly solve all the problems except the following ones:
# if the combination of number contain 56 and 9 it will give you 77 as the answer no matter what operation your perform
# same for 45 and 3 , 56 and 6
# Your program should take operator and two numbers as i... |
7794a3a3ff17aa0ab5bdfe976474b10ddb90d8b6 | MAD-reasoning/Python-Programming | /Lists/list_14.py | 409 | 4.03125 | 4 | # Write a function that takes a number and returns a list of its digits. So for 2345 it should return [2,3,4,5].
def split_num(num):
i = num
lists = []
while i >= 10:
div = i // 10
rem = i % 10
i = div
lists.append(rem)
else:
lists.append(i)
... |
ce9b53ac17bff836d778e08c55000090e9a3b1c3 | MAD-reasoning/Python-Programming | /Elementry/Elementry_04.py | 324 | 4.28125 | 4 | # Write a program that asks the user for a number and prints the sum of the numbers 1 to number.
try:
num_sum = 0
number = int(input("Enter a natural number: "))
for i in range(1, number+1):
num_sum += i
except ValueError:
print("Enter a valid number")
else:
print("Sum = ", num_su... |
7c15c07c1c2ba68bf6c8ec615907a1c2bf8bc5a8 | MAD-reasoning/Python-Programming | /Lists/list_18.py | 477 | 3.84375 | 4 | # Implement binary search.
def binary_search(lists, num):
begin, end = 0, len(lists)
while begin <= end:
mid = (begin + end) // 2
if lists[mid] == num:
return mid
elif lists[mid] > num:
end = mid - 1
elif lists[mid] < num:
begin =... |
8fecc42af8fc036d5d48fe2807d8ba0a6d8ab68c | evelyn-pardo/tarea3 | /menu.py | 501 | 3.921875 | 4 | menu = 0
while menu<4:
print("Ingresar una opcion")
print("1 para pila")
print("2 para cola")
print("3 para lista")
print("4 para Salir")
menu = float(input())
if menu==1:
print("Aqui se hará la pila")
elif menu==2:
print("Aqui se hará la cola")
elif menu=... |
9135fe874a32ee0f4dcd64aa9d878c937707e0c1 | blackplusy/0801 | /例子-0819-09.多分支判断.py | 300 | 3.6875 | 4 | #coding=utf-8
name=input('请输入您喜欢的主播:')
if name=='张大仙':
print('不慌,吃口药!')
elif name=='55开':
print('难受啊,马飞')
elif name=='大司马':
print('正方形打野')
else:
print('来,关注一波刷个666,火箭走起!')
|
c842e4399979c40650b4fe8e05755e97b827dd40 | blackplusy/0801 | /例子-0820.03.字符串的练习.py | 325 | 3.71875 | 4 | #coding=utf-8
a=input('请输入字符串>>')
'''
if a=='':
print('为空!')
'''
'''
if len(a)==0:
print('为空')
elif a[0]=='A' or a[0]=='E':
print('yes')
else:
pass
'''
if len(a)==0:
print('null')
elif a[0] in 'aeiouAEIOU':
print(a+'ay')
else:
print(a[1:]+a[0]+'ay')
|
19ae22cfbd802b9b0c1c27179a671b8b5e9005d7 | blackplusy/0801 | /例子-0822.08.类的属性的访问特性.py | 440 | 3.6875 | 4 | #coding=utf-8
class test:
a=100 #类的属性
def __init__(self,b):
self.b=b #实例属性
t=test(998) #实例化对象
#1.通过实例化对象访问类的属性
print('t.a=%d'%t.a)
#2.通过类名访问类的属性
print('test.a=%d'% test.a)
#3.通过实例化对象访问实例属性
print('t.b=%d'%t.b)
#通过类名访问实例属性
print('test.b=%d ' %test.b)... |
38d854041bdbda0e2cb2b26cf781b54a1d483fa3 | shivam-tripathi/code | /ds/python/chap4:Recursion/chapterCode/binarySearch.py | 1,212 | 3.953125 | 4 | '''
Binary search uses a sorted array to returns True if present.
Linear search or sequential search uses unsorted list, and iterates over each
element.
'''
def binSearch(arr):
print ('Element to be searched:')
elem = int(input())
l = len(arr)
print(main(arr, elem, 0, l-1))
def main(arr, elem, lower, ... |
92185c6fca2405aeb81e4949c8593ff9331b8120 | shivam-tripathi/code | /ds/python/nextPalin.py | 1,019 | 3.984375 | 4 | # This simple program calculates the next palindrome number after the given
# number.
# It's performance can be improved though.
num = list(input())
numcopy = int(''.join(num))
l = len(num)
bool = True
# Half the elements have to be copied.
lim = l//2
# To remove repeated code, k is used to distinguish between even ... |
8530ec39481c4631fa6abe52bc0eb0419dc4d7ba | nishantchauhan00/ML | /05 Neural Networks/00 practice - simple nn/lib.py | 937 | 3.53125 | 4 | import numpy as np
from operator import sub
from math import exp
class func(object):
def sigmoid(self, z):
return 1.0 / (1.0 + exp(-z))
def Dsigmoid(self, z):
return self.sigmoid(z) / (1.0 - self.sigmoid(z))
class cost(object):
def MSE(self, y, a, n):
"""
Mean Squared Erro... |
078ea09e4ee48438cce3b9711b65b2d25d917cd6 | victorawillis/Python-playbook | /tweetmanager/twitter.py | 1,064 | 4.0625 | 4 | from tweet import *
def menu(list):
user_input = int(input("Tweet Menu\n- - -\n1) Write a Tweet\n2) View Recent Tweets\n3) Search Tweets\n4) Quit\nWhat would you like to do? "))
if (user_input is 1):
name = input("What is your name? ")
user_tweet = input("What would you like to tweet? ")
list.append(twee... |
b85cd5cc82afa2fb6c72d156b9601f3eaa439e40 | 4hlberg/curing | /scripts/db_cleanup.py | 707 | 3.640625 | 4 | import sqlite3
from datetime import datetime, timedelta
''' input average of readings the last 12 hours in to a table and clean up readings older than 7 days '''
db_file = '/home/pi/testscripts/curing'
def create_connection(db_file):
conn = None
try:
conn = sqlite3.connect(db_file)
except Error as... |
f0b213bee5bc4fe59d032d15eadb5bbe7c30eb63 | larstonder/proglab | /p5-keypad/rule.py | 1,006 | 3.90625 | 4 | """Rule module"""
from inspect import isfunction
def match(matcher, value):
"""Checks if the value matches the matcher, matcher can be a function"""
if isfunction(matcher):
return matcher(value)
return value == matcher
class Rule:
"""Rule class"""
def __init__(self, state1, state2, sig... |
d1e624fa33f7f88f8a7cb1603f8ff01916bba585 | larstonder/proglab | /p5-keypad/fsm.py | 855 | 3.578125 | 4 | """Finite State Machine"""
class FSM:
"""Class for finite state machines"""
def __init__(self, start_state, end_states, agent):
self.rules = []
self.start_state = start_state
self.end_states = end_states
self.agent = agent
def add_rule(self, rule):
"""Add a rule t... |
74278b21ab540b3dea2a05663412fbf14f0964fe | idosilverwater/ai-project | /Solver/FormulaTree.py | 7,777 | 3.828125 | 4 | ###########
# Imports #
###########
from magicNums import *
#############
# Constants #
#############
class FormulaTree:
"""
Generates and maneges a tree representing a boolean formula.
"""
def __init__(self, constraints):
"""
:param constraints: A list of constraints objects.
... |
bc3b76e700e81d9bb232b8aa8fe17d0423fd27e9 | idosilverwater/ai-project | /SoftConstraintHeuristics/NameSoftConstraintHeuristic.py | 915 | 3.6875 | 4 | from SoftConstraintHeuristics.BaseSoftConstraintHeuristic import *
from functools import partial
class NameSoftConstraintHeuristic(BaseSoftConstraintsHeuristic):
"""
counts the number of variables. and returns the soft constraint which holds the least amount of variables.
"""
def __init__(self, hard_... |
454c97f3339871d7b76a68b9b4d3c9a63a8b2d4a | Sprinter1999/PythonAdvanced | /Interesting OJs/blackJack-v2.py | 4,205 | 3.859375 | 4 | # 如果手中牌的点数之和小于17点则继续要下一张牌,直到大于等于17点为止
# 如果手里的牌有A,且A的点数当成11点没有超过21点,则此时A要按11点计算,如果超过21点,则A要按1点计算
# 1、设计一个card类,用于保存一张牌;
# 2、设计一个hand类,用于保存一手牌;
# 3、设计一个player类,该类可以基于指定策略完成一次游戏过程。
# 读入前两张牌不输出,从第三张牌开始 如果需要
# 则每次要牌,要先输出Hit,然后读入下一张牌
# 并依次输出该牌的花色及点数(A输出1 11,即它有两个点数)
# 当不再要牌时要先输出Stand,然后在一行内输出这一手牌,牌与牌之间用一个空格分隔。牌输出的顺序为先看牌面,牌面小... |
e3ac66172e50fa45b8f50a2620697bcdf873b71d | Sprinter1999/PythonAdvanced | /keras/Perception.py | 2,198 | 3.734375 | 4 | #@LINK:A hyperplane in Rn is an n-1 dimensional subspace
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']#中文标签
plt.rcParams['axes.unicode_minus']=False#正常显示负号
plt.rcParams['figure.figsize']=(8,6)#figsize
#TODO:Randomly generate 100 points
fig=plt.figure()
#... |
a38327dc4951bcf2ab44a2aa04722b4016379ad1 | rynguyen2018/cs61a | /lab/lab00/lab00/lab00.py | 294 | 3.5625 | 4 | def twenty_seventeen():
"""Come up with the most creative expression that evaluates to 2017,
using only numbers and the +, *, and - operators.
>>> twenty_seventeen()
2017
"""
#alright check me out cuh
return int((2017 -1 +1)/1 *1)
print(int(twenty_seventeen())) |
e376359a4434b559d8b9e7845b1a9aa428429d71 | GuilhermeBiavati/Trabalho-python | /2.py | 389 | 4.1875 | 4 | # Recebe nome e armazena na variavel
nome = input('Informe o nome: ')
# Transforma string para maiusculo, e substitui as vogais pelos caracteres requiridos
retorno = nome.upper().replace('A', '@').replace('E', '&').replace('I',
'!').replace('O', '#').re... |
519e47c1f5b6e8b3f4603a9f8ea251895220bceb | ZhenfeiYu/CS506-Fall2020 | /02-library/cs506/read.py | 644 | 3.90625 | 4 | def read_csv(csv_file_path):
"""
Given a path to a csv file, return a matrix (list of lists)
in row major.
"""
res = []
with open(csv_file_path,"r+") as f:
lines = f.readlines()
for line in lines:
res.append([x for x in line.strip().split(",")])
for i... |
e29ff540a0375f255ae163e88d222460ee72e8d9 | jay-bhamare/Python_for_Everybody_Specialization_University_of_Michigan | /PY4E_Python_Data_Structures/Assignment 8.4.py | 996 | 4.1875 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: jayvant
#
# Created: 08/04/2020
# Copyright: (c) jayvant 2020
# Licence: <your licence>
#-------------------------------------------------------------------------------
... |
6be03d03fa0505d440baa4a07c9726fb6c752644 | TuhinChandra/PythonLearning | /Basics/Shaswata/test2_video8_Variables.py | 889 | 4.53125 | 5 | print('Variables examples are here...')
x = 10
# Anything in python is an Object unlike other languages
print('x=', x, sep='')
print('type of x :', type(x))
print('id of x :', id(x))
y = 15
print('y=', y, sep='')
print('id of y :', id(y))
# Now see the id of y will change to id of x
y = 10
print('# Now see the id of y... |
89d6cc60549a3807b8736670d0b28bd12e298f4f | TuhinChandra/PythonLearning | /Basics/Shaswata/test9_video17_relationalOperator.py | 314 | 4.25 | 4 | print('Relational operator examples are here...')
x = 10
y = 5
print('Type of relational operator results :', type(x > y))
print('x > y (True):', x > y)
print('x < y (False):', x < y)
print('x >= y (True):', x >= y)
print('x <= y (False):', x <= y)
print('x == y (False):', x == y)
print('x != y (True):', x != y)
|
6e1ebc1b1f077968f102c31e157e7d1af37a0e3a | TuhinChandra/PythonLearning | /Basics/Shaswata/test5_video12_intFunc.py | 599 | 4.375 | 4 | print('int function examples are here...')
x = '1100'
print("x =", x)
print("type of x :", type(x))
# int string -> int
print('int string -> int')
y = int(x) # default base is 10
print("y =", y)
print("type of y :", type(y))
# binary string -> int
print('binary string -> int')
z = int(x, 2)
print("z =", z)
# ValueE... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.