blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
47bf18c5a0393c0a77786640deb2adb25e3acde8 | 874795937/Leetcode | /leetcode_101.py | 2,316 | 4 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution(object):
def isSymmetric(self, root):
if not root:
return True
def dfs(left, righ... |
8c9ab9827f679383d7beab50a70669f9341f8b40 | 874795937/Leetcode | /01.01.py | 357 | 3.53125 | 4 | # hashset 方法
class Solution(object):
def isUnique(self, astr):
"""
:type astr: str
:rtype: bool
"""
seen = set()
for elm in astr:
if elm in seen:
return True
else:
seen.add(elm)
return False
S = Solution... |
9781a6ce1f70d6d7c256e85a422bf9af6325ca92 | 874795937/Leetcode | /leetcode_125.py | 665 | 3.8125 | 4 | # item.isalnum()--->判断是否是数字或字母
# item.lower()--->转化成小写
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
if s == "":
return True
goodStr = ""
for item in s:
if item.isalnum():
goodStr ... |
d600afbaca5d2f6249e7b5653cee9c791e7b7eb7 | PrakamyaKhare/Machine-Learning | /SimplePrediction.py | 619 | 3.8125 | 4 |
def pow(n,r):
if r == 1:
return n
elif r == 0:
return 1
elif r < 0:
res = 0
n1 = n
i = -1
while i > r:
res = n*n1
n1 = res
i -= 1
return (1/res)
else:
res = 0
n1 = n
for i in range(r):
res = n*n1
n1 = res
return res
def sigmoid(w_sum):
e = 2.71828183
output = 1/(1+(pow(e,-... |
13b28b5c77a4f979218e7dd1d7215c47a444bb46 | G-K-R-git/PY111-German | /Tasks/g0_bubble_sort.py | 643 | 4.125 | 4 | from typing import List
import random
def sort(container: List[int]) -> List[int]:
"""
Sort input container with bubble sort
:param container: container of elements to be sorted
:return: container sorted in ascending order
"""
suffix = 0
for i in range(len(container)-1-suffix):
fo... |
9921187618323358e9cc3af47d55b63393454d65 | G-K-R-git/PY111-German | /Tasks/e1_depth_first_search.py | 693 | 3.546875 | 4 | from typing import Hashable, List
import networkx as nx
import matplotlib.pyplot as plt
def dfs(g: nx.Graph, start_node: Hashable) -> List[Hashable]:
"""
Do an depth-first search and returns list of nodes in the visited order
:param g: input graph
:param start_node: starting node of search
:retur... |
49bafa780196a3559794bef2247c5e6923ac4b36 | Guestman360/Tech-Interview-Mastery-Course-Code | /Trees & Graphs/Invert_Binary_Tree.py | 705 | 3.96875 | 4 | import collections
# Recursive Solution
def invertTree(root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root:
return None
res = TreeNode(root.val)
if root.right:
res.left = invertTree(root.right)
else:
res.left = None
if root.left:
... |
33da802c9b56b85035b23d72bd78365062c5ddd7 | Guestman360/Tech-Interview-Mastery-Course-Code | /Trees & Graphs/Last_Common_Ancestor.py | 660 | 3.78125 | 4 | import Tree
def findLCA(root, n1, n2):
# Base Case
if root is None:
return None
# If node matches either of our targets, return root
if root.data == n1 or root.data == n2:
return root
# Look for keys in left and right subtrees
left_lca = findLCA(root.left, n1... |
10fb8661e8ca01dc76ee5b4f2fa5a2463887c0ff | samlopezv/Practicar | /assignments/Dinero cumpleaños/src/exercise.py | 221 | 3.625 | 4 | def main():
n = int(input('Ingresa la edad a la que se comenzará a dar $10: '))
d =10
while d < 1000 :
n = n+1
d = d*2
print(str(n) + ' ' + str(d))
if __name__=='__main__':
main()
|
c637329caaf214bf7ee6b5d3f5be920e6c86c0a6 | deogakofi/cron_interpreter | /Solution/lyst.py | 5,545 | 3.875 | 4 | from datetime import datetime
import argparse
def open_files(txtfile: str):
"""Open files with scheduler data input
Args:
txtfile => File containing scheduler data
Returns:
mylines => Scheduler data in list format for analysis
"""
mylines = [] # Declare ... |
600b1577655a55e545db415b031f237b419098f0 | vitorshaft/roboMovel | /plan/rota.py | 1,155 | 3.65625 | 4 | import math
class plan:
def __init__(self):
pass
def traj(self,xo,yo,xr,yr): #retorna angulo e distancia para deslocamento em linha reta
self.dx = float(xo-xr)
self.dy = float(yo-yr)
try:
self.tg = self.dy/self.dx
except:
self.tg = self.dy/(self.dx+0.0000000000001)
self.h = math.hypot(self.dx,self.... |
3aad277bfa4efd3b36ddaef399243005e09a69a3 | slimshreydy/advent-of-code | /submissions/day02.py | 885 | 3.71875 | 4 | import re
from advent import AdventProblem
def preprocess(line):
match = list(re.match(r'(\d+)-(\d+) ([a-z]): (\w+)', line.strip()).groups())
match[0] = int(match[0])
match[1] = int(match[1])
return tuple(match)
def part_1(passwords):
valid = 0
for (min_occur, max_occur, key_letter, passwor... |
ad211d5899ea28285cc9d76e18c60543b6e2d5c0 | shriramkv/MachineLearning | /LinearRegression.py | 1,431 | 3.71875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[21]:
# We need numpy and pandas. We have imported the same.
import pandas as pd
import numpy as np
# The next step is to make sure the pandas print decmial values. We have chosen 5 digit precision.
np.set_printoptions(precision=5, linewidth=120)
# Let us create a datafr... |
dd31e821d5e047a8eb82c9d6a9ad5ba08591486d | appacademy-starters/python-tic-tac-toe | /tic_tac_toe.py | 4,487 | 4.25 | 4 | import random
# This function must be completed
def space_value(board, index):
"""
Get the value for a space in the board.
Returns the value in the board at the given index, if not a string that
contains a space. Otherwise, it returns the index as a string.
Arguments: board: An array of nine str... |
43a510f678cea4083e67b5204e907c6f7b4b9200 | Kaushiksekar/SDE_Prepration | /Python_Specifics/Inheritance/Static_Methods.py | 328 | 3.59375 | 4 | class Robot:
__counter = 0
def __init__(self):
type(self).__counter += 1 # can also be Robot.self
@staticmethod
def RobotInstances():
return Robot.__counter
print(Robot.RobotInstances())
x = Robot()
print(x.RobotInstances())
y = Robot()
print(x.RobotInstances())
print(Robot.RobotInsta... |
f0c8f6a5640db84fd84b47d057101ca7b41316d0 | Kaushiksekar/SDE_Prepration | /Python_Specifics/OOP_Jeff_Knupp/call_by_object_reference.py | 172 | 3.609375 | 4 | def list_add(b):
b.append(5)
def string_add(a):
a += "xcxc"
a = [1,2,3,4]
print(a)
list_add(a)
print(a)
b = "asdasds" #immutable
print(b)
string_add(b)
print(b)
|
be0e01b550660da009ded73849458cb2d0de4d7d | yixiu868/algorithm_learn | /search/fibonacci_search.py | 1,430 | 4.21875 | 4 | # 斐波那契查找算法
def fibonacci_search(lists, key):
"""
参考:https://www.cnblogs.com/lsqin/p/9342929.html
https://www.cnblogs.com/maybe2030/p/4715035.html#_label2
主题:属于二分查找优化算法,性能比二分查找快
:param lists:
:param key:
:return:
"""
F = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,
233, 377, ... |
46c8dd2ca2c7b59aac88689a2d640a8fd8cd321f | yixiu868/algorithm_learn | /search/insertSearch.py | 1,282 | 3.9375 | 4 |
# 插值查找算法
def insert_search(lists, key):
"""
基本思想:基于二分查找算法,将查找点的选择改进为自适应选择,可以提高查找效率,插值插值也属于有序查找
注意:对于表长较大,而关键字分布又比较均匀的查找表来说,插值查找算法的平均性能比折半查找要好的多,反之,数组中如果分布非常不均匀,那么插值查找未必
是很合适的选择
复杂度分析:查找成功或者失败的时间复杂度均为O(log2(log2n))
:param lists:
:param key:
:return:
"""
low = 0
high = len... |
b5f2bba1103904def7d570251d1084b332cf0d62 | yashika0810/test | /assign.py | 491 | 3.671875 | 4 | import random as r
FName = input("Enter your first Name")
LName = input("Enter your last Name")
x = r.randint(1,20)
print("The OTP is",x)
count = 0
while (count < 4):
UNum = int(input("Enter your OTP"))
if UNum > 20 or UNum < 1:
print("Wrong Input, Try Again!!")
break
else:
if UNum == x:
print("... |
def7f295ee3ea7cd16b7ab12c4b74271250c7feb | PaulinaOsypanka/LekcjePythona | /im bored/i'm.bored(poddd).py | 366 | 3.6875 | 4 | i_lista = []
for i in range(5):
i_lista.append(input('Daj imie ' + str(i+1) + ' '))
print(i_lista)
sorting = input('Czy chcesz posortować swoją listę imion? (wpisz \'tak\' lub \'nie\')')
sorting.lower()
if sorting == 'tak'
i_lista.sort()
print(i_lista)
elif sorting == 'nie'
print('Ugh, czemu nie? \... |
9aef9ddda87732e44cedb785d4f783b9eaf1563a | dwyong/chapter10 | /division.py | 694 | 3.90625 | 4 | # 异常处置 使用 try-except结构处理异常
try:
print(5 / 0)
except ZeroDivisionError:
print("除数不能为0")
# 演示两个数的除法
print("给我两个数,我将运行除法运算\n")
while True:
first_number = float(input("请输入第一个数:\n"))
if first_number == 'q':
break
second_number = float(input("请输入第二个数:\n"))
answer = first_number / second_numbe... |
9b1b1c038772ff234f176698f75be74d9e0aa5c6 | osmarllq/python-assignments | /6002x_rollDice.py | 2,024 | 4.09375 | 4 | import random
def rollDie():
return random.choice([1,2,3,4,5,6])
def rollN(n):
result = ''
for i in range(n):
result = result + str(rollDie())
return result
print rollN(5)
def getTarget(goal):
numTries = 0
numRolls = len(goal)
while True:
numTries += 1
result = ro... |
9df24917ba37c207aaf44715f98122ea9f71b3aa | osmarllq/python-assignments | /6002x_randomWalks-segment0.py | 3,991 | 4.4375 | 4 | '''
Here we are going to simulate a random walk. Particuarly, we are going to simulate
the movements of a drunk in a field that moves either nort, south, east or west
in each step. We want to know the position of the drunk, and how far he'll end up
after, say, 1000 steps. Our hypothesis is that he's going to end up far... |
ddcb0ec5782325c7afb369b6fa09f07fb0c83d82 | osmarllq/python-assignments | /6002x_hashing1.py | 4,657 | 4.375 | 4 | ### Hash Tables
'''
Hash tables are the way dictionaries are implemented in Python.
Here we will create a dictionary and provide a way to manage collisions.
A simple way to deal with collisions consists in assigning the colliding keys
to the same bucket.
Then a dictionary can be represented as a list of buckets, whe... |
c2c868a239845c42cb47bdfc7fe96035e2bdfcbc | aryanjais/My-Python- | /pattern3.py | 136 | 3.96875 | 4 | n=int(input("Enter Size Of Square : "))
for i in range (1,n+1):
if i==1 or i==n :
print('* '*n)
else:
print('* '+' '*(n-2)+'*')
|
b08408cc32bf3ea89e8a994a3fd622a031d1e9d9 | BurakAkten/GTUCourses | /CSE321-Intro.-To-Algorithm-Design/HW5/theft_141044045.py | 3,012 | 3.984375 | 4 | #****************************************************#
# #
# CSE 321 - Introduction to Algorithm Design #
# HW05 - Question 2 #
# Burak AKTEN #
# 141044045 #
# 2017 #
# #
#***********************************************... |
8d5186a2152b418f377679f3746dfd87b93054a3 | Wanghongw/whwFrame | /utils/webData.py | 839 | 3.640625 | 4 | # -*- coding:utf-8 -*-
# 创建表,插入数据
def createtable():
import pymysql
conn = pymysql.connect(
host='127.0.0.1',
port=3306,
user='root',
password='123',
# 需要在自己的MySQl数据库中创建一个名为auth的库
database='auth',
charset='utf8'
)
cursor = conn.cursor(pymysql.curs... |
ed695dd783226c926995aa1a74dd6256a691a8e8 | swathyamudhan/python-programs | /basic/Registration.py | 1,831 | 4 | 4 | #Registration
import os
from os import path
# Get name
# Name should have minimum of 2 characters and maximum of 256 characters
print('Please,Enter your name')
name = input()
nLen = len(name)
while nLen < 2 or nLen > 256 or name.isnumeric():
print('Invalid name,pls enter again')
name = input()
nLen = len(na... |
101383efaf0730ed4486050c7b9ef0d616ace74e | RafsanRifat/Python-beginning | /part-9/working_with_csv_file.py | 1,045 | 3.703125 | 4 | import csv
# file = open("data.csv", "w") # we cannot use path class here. so we open a csv file in write mode
# file.close() #close kore dite hobe , othoba nicher moto kore korle close korar dorkar hobena.
with open("data.csv", "w") as file:
writer = csv.writer(file) # csv writer create er j... |
96a26bf375400e5ea760883c50f7b51a4e4702c2 | RafsanRifat/Python-beginning | /part-5/accessing-list-items.py | 922 | 4.46875 | 4 | letters = ["a", "b", "c", "d"]
letters[0] = "A" # we can change a list item in this way
print(letters[0]) # This will return the first item of the list
print(letters[-1]) # This will return the last item of the list
print(letters[0:3]) # This will print the first three items of the... |
eb677e6e2230aeb96b8776e93c919909a0447b4d | RafsanRifat/Python-beginning | /part-9/generating_random_values.py | 2,151 | 4.125 | 4 | import random
import string
print(random.random()) # this random module has a method call random, that generate a float type random value
print(random.randint(1, 10)) # It generate a integer random value between two numbers
print(random.choice([1, 2, 10, 4])) # It will randomly pi... |
3f80a393d86940e5ebee7f9b75b6ea3ba8745da6 | RafsanRifat/Python-beginning | /part-9/working_with_time_deltas.py | 578 | 3.5625 | 4 | from datetime import timedelta # 2 ta time er moddhe parthokko repressent korte eita use kora hoy
from datetime import datetime
dt = datetime(2018, 1, 1)
dt2 = datetime.now()
time_duration = dt2 - dt
print(time_duration)
# this timedelta method has some methods =====>>>
print("days", time_duration.days)
print("sec... |
f10890c85f6f8b8e01dd0d59b44bd5da8daf2868 | RafsanRifat/Python-beginning | /part-5/dictionary.py | 1,718 | 3.921875 | 4 | # In python dictionary is a collection of key value ,
# for example : phonebook.. Name ---> number. eikhane name holo key r value holo number.
point = {"x": 1, "y": 2} # eita dictionary define er ekta way. eikhane x r y hocche key r 1,2 hocche value.
# dict function use koreo dictionary define kora jay, tokhon r... |
e0cbaa93021667a7fa964b4b5e7eaa4d33928a86 | RafsanRifat/Python-beginning | /part-5/adding-removing-items.py | 513 | 4.125 | 4 | letters = ["a", "b", "c", "d"]
# Add items
letters.append("e") # to add an item at the end of the list
print(letters)
letters.insert(0, "--") # to add an item at the specifique position of the list.
print(letters)
# Remove items
letters.pop(1) # to remove specifique index number item
print(letters)
letters.rem... |
9c6cd3f578f0f3de96c9ee5cab266765143be004 | RafsanRifat/Python-beginning | /part-3/for-loops.py | 79 | 3.546875 | 4 | for number in range(3):
print("Attempt", number + 1, (number + 1) * "*")
|
e0a6f65a2b55556b4692d03f81b299eb02815593 | vivekworks/learning-to-code | /4. Discovering Computer Science/Python/Chapter 3 - Visualizing Abstraction/Exercises 3/exercise331.py | 1,010 | 3.625 | 4 | import turtle
import random
def bloom(tortoise,fcolor, length, petals):
tortoise.pencolor('red')
tortoise.fillcolor(fcolor)
tortoise.begin_fill()
for segment in range(petals):
tortoise.forward(length)
tortoise.left(1080//petals)
tortoise.end_fill()
def stem(tortoise, length):
tortoise.pencolor('green')
... |
a987f9a6b53b545f015fa9156817b6cb37afa7e9 | vivekworks/learning-to-code | /4. Discovering Computer Science/Python/Chapter 5 - Forks in the road/Exercises 4/exercise549.py | 310 | 3.890625 | 4 | """
Purpose : Grade Remarks
Author : Vivek T S
Date : 16/11/2018
"""
def gradeRemark():
grade = int(input('Grade : '))
if grade >= 96:
return 'Outstanding'
if grade >= 90:
return 'Exceeds expectations'
if grade >= 80:
return 'Acceptable'
return 'Trollish'
def main():
print(gradeRemark())
main() |
dd4399b31eda1c4c4104a2d836369d85662ab4cd | vivekworks/learning-to-code | /4. Discovering Computer Science/Python/Chapter 5 - Forks in the road/Exercises 3/exercise532.py | 278 | 3.71875 | 4 | """
Purpose : Uniform value using random
Author : Vivek T S
Date : 15/11/2018
"""
import random
def uniform(a,b):
#Returns a number in interval [a,b)
result = random.random() * b
if result <= a:
result = result+a
return result
def main():
print(uniform(1,10))
main()
|
8c99457c28e1ea456004295905278feda1edee40 | vivekworks/learning-to-code | /4. Discovering Computer Science/Python/Chapter 4 - Growth And Decay/Exercises 1/exercise4122.py | 258 | 3.921875 | 4 | """
Purpose : Calculate the population each day
Author : Vivek T S
Date : 31/10/2018
"""
def growth2(totalDays):
population = 0
for day in range(0,totalDays):
population = population+3-(day%2)
print(day+1, population)
def main():
growth2(10)
main() |
dc6e73c8ee8d642878cb37d854f826d8a490308c | vivekworks/learning-to-code | /4. Discovering Computer Science/Python/Chapter 4 - Growth And Decay/populationplot.py | 619 | 3.984375 | 4 | """
Purpose : Population plot
Author : Vivek T S
Date : 01/11/2018
"""
import matplotlib.pyplot as pyplot
def pond(years, initialPopulation, harvest):
population = initialPopulation
populationList = []
populationList.append(population)
for year in range(years):
population = population * 1.08 - harvest
popu... |
3eeb8ef84f14b327a9a6ced6bb6c9ed3fdfd8182 | vivekworks/learning-to-code | /4. Discovering Computer Science/Python/Chapter 4 - Growth And Decay/Exercises 1/exercise414.py | 449 | 4.09375 | 4 | """
Purpose : Print integers from 0 to 100
Author : Vivek T S
Date : 29/10/2018
DCS, Python introduction
"""
def print50():
"""
Description:
Print integers from 0 to 100
Parameters:
None
Return value:
None
"""
for integer in range(-50, 51):
print(integer)
def main():
"""
Description:... |
be3b97344e9085c0e59b83132aac22ec213b0f1a | vivekworks/learning-to-code | /4. Discovering Computer Science/Python/Chapter 3 - Visualizing Abstraction/Exercises 5/exercise3512.py | 557 | 4.0625 | 4 | """
Purpose : Calculate Grade Point
Author : Vivek T S
Date : 28/10/2018
"""
def gradePoint(score):
"""
Description : Calculate grade point with the score
Parameters : score - course grade
Return value : Gradepoint
"""
return max(score//10 - 5,0)
def main():
... |
48e7ffe8ea2df280e791376a822f726c27046117 | vivekworks/learning-to-code | /4. Discovering Computer Science/Python/Chapter 4 - Growth And Decay/Exercises 6/exercise463.py | 668 | 4.25 | 4 | """
Purpose : To plot the linear, quadratic and exponential growth graph
Author : Vivek T S
Date : 06/11/2018
"""
import matplotlib.pyplot as pyplot
def growthGraph(n):
sum1 = 1
sum2 = 1
sum3 = 1
sum1List=[sum1]
sum2List=[sum2]
sum3List=[sum3]
for index in range(1,n):
sum1 = sum1+6
sum2 = sum2+index
... |
5d970fb58c3beef5976bbb3455b49cbf66a6d928 | vivekworks/learning-to-code | /4. Discovering Computer Science/Python/Chapter 5 - Forks in the road/Exercises 2/exercise521.py | 474 | 3.734375 | 4 | """
Purpose : Test the quality of random number generator
Author : Vivek T S
Date : 15/11/2018
"""
import turtle
import random
def testRandom(n):
tortoise = turtle.Turtle()
screen = tortoise.getscreen()
screen.setworldcoordinates(0,0,1,1)
screen.tracer(100)
tortoise.speed(0)
for rand in range(n):
#rand = ... |
6dac8058f5105d0179698779db3ee37b64cc8a68 | vivekworks/learning-to-code | /4. Discovering Computer Science/Python/Chapter 3 - Visualizing Abstraction/Exercises 5/exercise354.py | 922 | 4.34375 | 4 | """
Purpose : Calculate the distance between two points
Author : Vivek T S
Date : 28/10/2018
"""
import math #Importing math module
def distance(x1, x2, y1, y2):
"""
Description : Calculate distance between the points
Parameter Value : x1, x2 - x-axis coordinate of the points
y1, y2 - y-a... |
ed9b23abe8721d3f910bcb193ade1b611f0cfac7 | vivekworks/learning-to-code | /4. Discovering Computer Science/Python/Chapter 4 - Growth And Decay/Exercises 1/exercise4135.py | 234 | 3.65625 | 4 | """
Purpose : Calculate investment amount
Author : Vivek T S
Date : 01/11/2018
"""
def invest(investment, rate, years):
amount = investment*((1+(rate/12))**(12*years))
return amount
def main():
print(invest(2000,12,12))
main()
|
0201ff75184426a1d1c671cd9b25bf2c62b2da56 | vivekworks/learning-to-code | /4. Discovering Computer Science/Python/Chapter 6 - Text, Documents & DNA/concordance.py | 728 | 3.640625 | 4 | """
Purpose - A concordance
Author - Vivek T S
Date - 12/12/2018
"""
def find(text, target):
for index in range(len(text)-len(target)+1):
if text[index:index+len(target)]==target:
return index
return -1
def concordanceEntry(target):
textFile = open('Mobydick.txt','r',encoding='utf-8')
lineNumber=1
for l... |
fed58b29e4ce5da68b06919041e4813e736e7095 | vivekworks/learning-to-code | /4. Discovering Computer Science/Python/Chapter 5 - Forks in the road/Exercises 5/exercises557.py | 2,563 | 4.40625 | 4 | """
Purpose : Guessing Game - Monte Carlo Simulation
Author : Vivek T S
Date : 18/11/2018
"""
import random
import matplotlib.pyplot as pyplot
def guessingGame(maxNumber,strategy):
"""Plays a guessing game. The human player tries to guess
the computer's number from 1 to 100.
Parameter:
ma... |
812dfd8a553d433d23ca5656af3a6beebd33269d | vivekworks/learning-to-code | /4. Discovering Computer Science/Python/Chapter 4 - Growth And Decay/Exercises 1/exercise418.py | 426 | 4.4375 | 4 | """
Purpose : Print multiples of n
Author : Vivek T S
Date : 29/10/2018
DCS, Python introduction
"""
def multiples(n):
"""
Description:
Print multiples of n
Parameters:
None
Return value:
None
"""
for mul in range(0,101,n*1):
print(mul)
def main():
"""
Description:
Print multi... |
b7e46007aac02beeebfb3b398d1887c3d2d9092b | vivekworks/learning-to-code | /4. Discovering Computer Science/Python/Chapter 5 - Forks in the road/Exercises 2/exercise522.py | 564 | 3.859375 | 4 | """
Purpose : Lehmer Pseudo Random Number Generator
Author : Vivek T S
Date : 15/11/2018
"""
import turtle
def lehmer(a, r, m):
return ((a * r)% m)
def randomSequence(length, seed):
r = seed
a = 2 ** 31 - 1
m = 16807
tortoise = turtle.Turtle()
screen = tortoise.getscreen()
tortoise.speed(0)
screen.... |
bd868322be040a2df69c23690a0304ae50fb144e | vivekworks/learning-to-code | /4. Discovering Computer Science/Python/Chapter 5 - Forks in the road/Exercises 4/exercise546.py | 230 | 3.859375 | 4 | """
Purpose : Computer purchase
Author : Vivek T S
Date : 16/11/2018
"""
def cost(quantity):
if quantity > 20:
return quantity * 1500 * 0.95
return quantity * 1500
def main():
print(cost(int(input('Quantity : '))))
main()
|
5650c55b6e18efcfc4c7c920060b29cc3fd584e0 | vivekworks/learning-to-code | /4. Discovering Computer Science/Python/Chapter 3 - Visualizing Abstraction/Exercises 5/exercise351.py | 563 | 3.875 | 4 | """
Purpose : Sum of two numbers
Author : Vivek T S
Date : 28/10/2018
DCS, Python introduction
"""
def sum(number1, number2):
"""
Adds the two numbers
Parameter Value : number1 - Any numeral value
number2 - Any numeral value
Return value : sum of the numbers given
"""
return number1+number2
def ma... |
5d1769466444e35ec5499d68b4bf9a3841efbcfc | vivekworks/learning-to-code | /4. Discovering Computer Science/Python/Chapter 5 - Forks in the road/Exercises 5/exercises554.py | 828 | 3.75 | 4 | """
Purpose : Rock-Paper-Scissors-Lizard-Spock
Author : Vivek T S
Date : 18/11/2018
"""
def rockPaperScissorsLizardSpock(player1, player2):
"""
1. Rock
2. Paper
3. Scissors
4. Lizard
5. Spock
"""
diff = abs((player2 - player1))%5
print(diff)
... |
933d72cf75ee55884350afd654b39b42963523af | vivekworks/learning-to-code | /4. Discovering Computer Science/Python/Chapter 6 - Text, Documents & DNA/Exercises 3/exercise632.py | 215 | 3.6875 | 4 | """
Purpose - Print the username in the lastname_firstinitial format
Author - Vivek T S
Date - 09/12/2018
"""
def username(first, last):
return last+'_'+first[0]
def main():
print(username('Vivek','TS'))
main() |
a60cc9b4f71c51354440b4bcba1f1de792748e77 | vivekworks/learning-to-code | /4. Discovering Computer Science/Python/Chapter 4 - Growth And Decay/Exercises 3/exercise431.py | 188 | 3.5 | 4 | """
Purpose : Find out when you get $1200
Author : Vivek T S
Date : 02/11/2018
"""
money = 1000
rate = 3
year = 0
while money < 1200:
money = money*1.03
year = year+1
print(year,money)
|
6ff56a8957d2870ea0f8254191fc1dc145479560 | vivekworks/learning-to-code | /4. Discovering Computer Science/Python/Chapter 4 - Growth And Decay/Exercises 2/exercise423.py | 627 | 4.3125 | 4 | """
Purpose : Plot the population each day
Author : Vivek T S
Date : 02/11/2018
"""
import matplotlib.pyplot as pyplot
def growth1(totalDays):
population = 0
populationList = []
populationList.append(population)
for day in range(1,totalDays+1):
population = population+3
populationList.append(population)
p... |
23d721fdee0ba610d4c747e5b99786a83fb2007f | vivekworks/learning-to-code | /4. Discovering Computer Science/Python/Chapter 4 - Growth And Decay/Exercises 1/exercise4114.py | 1,274 | 3.984375 | 4 | """
Purpose : Prints a table of profits from a show based on ticket price.
Author : Vivek T S
Date : 30/10/2018
DCS, Python introduction
"""
#imports
import turtle
#functions
def plotTurtle(maxPrice,concert,screen):
"""
Description :
Prints a table of profits from a show based on ticket price.
... |
ea2c2f1e550cd2c469a105c04fedac5dbcd75594 | vivekworks/learning-to-code | /4. Discovering Computer Science/Python/Chapter 6 - Text, Documents & DNA/Exercises 3/exercise636-7.py | 724 | 4.25 | 4 | """
Purpose - Encode as even + odd indexed characters for a given string
Author - Vivek T S
Date - 09/12/2018
"""
def encode(word):
even=''
odd=''
count=0
for char in word:
if count%2 ==0:
even=even+char
else:
odd=odd+char
count=count+1
print('Encoded form -',even+odd)
return even+odd
def decode(... |
31cce1016db52f400291180dfeb1728e9bc1d783 | akashvshroff/Path_Finding_Visualisation | /bi_dijkstra.py | 4,989 | 3.75 | 4 | import heapq
class BiDijkstraAlgorithm:
def __init__(self, adj, cost, s, t):
"""
Initialises the data structures needed for the bi-dijkstra algorithm
as well as calls upon method to find the reverse graph.
A _r suffix indicates a data structure used in the backward direction.
... |
12848f28945b05314b213d7c7a4cc785a09754dc | zcb7/UA-Computer-Sim-of-PCR | /Utils.py | 2,145 | 3.578125 | 4 | from random import randrange
from typing import List, Tuple
from GenBank import Sequence
def generate_fall_off_rate(d=200, e=50):
"""Generate a random integer fall-off rate for Taq Polymerase
Args:
d (int, optional): The constant pivot. Defaults to 200.
e (int, optional): The maximum / minim... |
5aac61c0ea4622ae3eb96dfadb0d71019f243821 | Leventi/PY41HW7 | /main.py | 1,273 | 3.65625 | 4 |
class Stack:
def __init__(self):
self.sequence_string = []
def isEmpty(self):
return self.sequence_string == 0
def push(self, item):
self.sequence_string.append(item)
def pop(self):
return self.sequence_string.pop()
def peek(self):
return self.sequence_s... |
1b28580af961b51c7db8f2c530420d853a6ce7c1 | shriphani/cancer_data | /terms_stats.py | 826 | 3.53125 | 4 | '''
Generates plots of terms.
'''
import argparse
import json
import matplotlib.pyplot as plt
import operator
def plot_text_freq_histogram(text_freq_dict):
'''
Args:
- text_freq_dict : { term : frequency }
'''
sorted_text = sorted(text_freq_dict.iteritems(), key = operator.itemgetter(1))
plt.bar(
[x for x in... |
519498f2aacecc3ba7b24d4a2e8d5b7664fe1ab8 | QizaiMing/python-experiments | /repeated_elements.py | 146 | 3.65625 | 4 | import collections
array_input = [4, 3, 2, 7, 8, 2, 3, 1]
print([item for item, count in collections.Counter(array_input).items() if count > 1])
|
af234b88a48ad9dd2ce5c94a376b35ed432229de | FahimFBA/Python-Data-Structures-by-University-of-Michigan | /Manipulating List/2.py | 146 | 3.53125 | 4 | N = [2, 6, 86, 25, 215, 36, 4, 9, 27, 39]
Output = N[:5] # from the beginning (index 0) and upto index 5 but not including index 5
print(Output)
|
bc86a45c14cf269be0c1dab65a80d0251ee99504 | FahimFBA/Python-Data-Structures-by-University-of-Michigan | /Dictionary/main3.py | 415 | 3.875 | 4 | # To get Method for Dictionaries
# The pattern of checking to see if a key is already
# in a dictionary and assuming a default value if the key
# is not there is so commojn that there is a method called get()
# that does this for us
# Default value if key does not exist (and no Traceback)
if name in counts:
x =... |
e240dc6b3b4ae42aea5c22cf5453dc2a61090ccb | FahimFBA/Python-Data-Structures-by-University-of-Michigan | /Lists in Order/a.py | 328 | 4.0625 | 4 | # A list can hold many items and keeps those items in the order until we do something to change the order.
customer = ['Alice' , 'Orca' , 'Sansa' ,'Joffry' , 'Rumel']
customer.sort()
print(customer)
print(customer[2])
# A list can be sorted (i.e., change its order)
# The sort method (unlike in strings) means "sort y... |
9917e3bec1005fef35e749adf2863e5ebec92bc8 | FahimFBA/Python-Data-Structures-by-University-of-Michigan | /Dictionary/main2.py | 485 | 3.90625 | 4 | # When we see a new name
# When we encounter a new name, we need to add a new entry in the dictionary
# and if this the second or later time we have seen the name,
# we simply add one to the count in the dictionary under that name
counts = dict()
names = ['csev' , 'cwen' , 'csev' , 'zaian' , 'cwen']
for name in name... |
2a837318f3b5ee5d8afaed99c883f7b8fc3732ef | FahimFBA/Python-Data-Structures-by-University-of-Michigan | /Dictionary/DIctionary_Literals.py | 254 | 3.578125 | 4 | # Dictionary Literals(Constants)
# Dictionary literals use curly braces and have a list of key : value pairs
# You can make an empty dictionary using empty curly braces
jjj = { 'chuck' : 1 , 'fred' : 42 , 'jan' : 100 }
print(jjj)
ooo = { }
print(ooo) |
7bce968341fe07625b3e4b99c562d3e682e37e86 | FahimFBA/Python-Data-Structures-by-University-of-Michigan | /Tuples/7.py | 398 | 4.4375 | 4 | # Sorting Lists of Tuples
# We can take advantage of the ability to sort a list of tuples to get a sorted version of a dictionary
# First we sort the dictionary by the key using the items() method and sorted() function
d = {'a' : 10, 'b' : 1, 'c' : 22}
print(d.items())
# Output: dict_items([('a', 10), ('b', 1), ('c... |
e2a774705ff6a0fda67139a25655ba990a4ac6ca | aschn/picolo | /src/picolo/config/coord.py | 2,971 | 3.65625 | 4 | """
@package coord
@author Anna Schneider
@version 0.1
@brief Contains class for Coord
"""
# import from standard library
import math
# import external packages
import numpy as np
class Coord(object):
""" Cartesian and polar coordinates for given (x,y) pair.
theta is in range (-pi, pi), degrees is in ran... |
8bb92833f30281ced56fa088cee24cf1a83308fe | bittdy/STLabstract | /rrt_trans.py | 19,693 | 3.640625 | 4 | """
Path planning Sample Code with Randomized Rapidly-Exploring Random Trees (RRT)
author: tdy
"""
import math
import random
import time
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
show_animation = True
from transducer import Once
class RRT:
... |
c92517bf0d32e4a7c23ba463c794a57e01aa59e5 | lvinuezav/Practica1 | /practica2.py | 407 | 3.90625 | 4 | print("--------- TIPOS DE DATOS ---------")
#Tipos de datos
print(type (10))
print(type(5.5))
print(type(1+5j))
print(2+5)
print(2+4)
print(8**3)
print((1+5j)+(1+8j))
print("esto es una cadena")
print ('esto es una cdena con comillas simples')
print("""
linea1
linea2
linea3
""")
print(type("esto es una cadena"))
pr... |
3cb692d56ea52eacd37bbb9053b0bfa187435c3d | WilliamPLamb/pomona-electronics-2020 | /libraries/AccelerometerSensorlib.py | 5,096 | 3.640625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Wrapper library to help make connecting to and reading data from MMA8451 accelerometer easy. Intended function/example can be seen at bottom of file
@author William Lamb
@date 1/23/2020
@email wpl12014@mymail.pomona.edu
@version 0.0.1
"""
import board
import... |
7823ab25e13c4b52575840989d731d5f65f81336 | jbuchan12/FileOperations | /src/Services/FileService.py | 2,906 | 3.65625 | 4 | import glob
import os
from shutil import copyfile
from typing import List
#Get all the files in a given directory
def getFiles(path : str) -> List[str]:
dirs = glob.glob(path + "*.*")
return dirs
#Get only the directories in a given directory
def getDirs(path : str) -> List[str]:
dirs = glob.glob(path + "... |
95a42812005a060a43a7f7a0ce68554fec08501d | Jiaguli/python200805 | /Day 3-6.py | 1,286 | 3.75 | 4 | book={}
BOOK={}
n=0
while int(n)!=6:
print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
print('Please choose one service')
print('1.建立詞彙')
print('2.列出所有單字')
print('3.英翻中')
print('4.中翻英')
print('5.測驗')
print('6.離開')
num=input("Your ans:")
n=int(num)
if n==1:
wor... |
3a06d0af2ffe0ed4442ca26dd435f0cf7a90b15e | Copenhagen-EdTech/Discere | /william-question-generation/npy_data_saver.py | 1,260 | 3.515625 | 4 | '''
Module for preparing data from json-format into a numpy array format (npy).
'''
import json
import numpy as np
def to_npy(data_att, from_path, to_path):
'''
Reads content of a json file and saves it in npy format.
param data_att: The name of the attribute holding the data in
the json file
par... |
e7ff5bfaadac788f1c80e476d918e9a2f9bd0f51 | xiaohuwu/Python-camp | /learningPython/src/Bunoob/test03.py | 447 | 4.21875 | 4 | thistuple = ("apple", "banana", "cherry") # note the double round-brackets
print(type(thistuple))
array = ["apple", "banana", "cherry", "banana"]
thisset = set(array)
print(type(thisset)) # 判断数据类型
print(set(array)) # set 无序且不重复的集合
if 'apple' in thisset:
print("Yes apple is a friut!")
thisset.remove("apple")
if 'a... |
6b49bcb3314013c871578d8ead5eb4cc742818bc | xiaohuwu/Python-camp | /learningPython/src/day06/test01.py | 215 | 3.5625 | 4 | """
输入M和N计算C(M,N)
"""
def funci(n):
result = 1
for n in range(1, n + 1):
result *= n
return result
m = int(input('m = '))
n = int(input('n = '))
print(funci(m) // funci(n)//funci(m-n))
|
273f99418f99b89ba30cb2a1af6af49af81ded4b | xiaohuwu/Python-camp | /learningPython/src/day09/test07.py | 471 | 3.609375 | 4 | pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
while 'cat' in pets:
index = pets.index('cat')
pets.pop(index)
print(pets)
response = {}
polling_active = True
while polling_active:
name = input("\n what is you name: ")
mountain = input("\n mountain you like: ")
response[name] = mountain
polling_... |
97b28065ef55489d17ba757518b6ad3dcfd2dd6f | xiaohuwu/Python-camp | /learningPython/src/Bunoob/test05.py | 258 | 3.546875 | 4 | #! python3
# mapIt.py - Launches a map in the browser using an address from the
# command line or clipboard.
import webbrowser, sys
if len(sys.argv) > 1:
print(sys.argv)
webbrowser.open("https://cn.bing.com/search?q=" + sys.argv[1])
else:
print("error")
|
322292817924ce0438f8424e172230439271d51b | xiaohuwu/Python-camp | /learningPython/src/day06/test02.py | 362 | 3.9375 | 4 | from random import randint
# 设定参数的默认值
def roll_dice(n=2):
total = 0
for _ in range(n):
total += randint(1,6)
return total
# 可变参数
def add(*args):
total = 0
for val in args:
total += val
return total
print("总点数为:",roll_dice())
print("总点数为:",roll_dice(3))
print(add())
print(add(4,5,6... |
15853ff426a38848e44966dc4cb9b36367708bee | xiaohuwu/Python-camp | /learningPython/CircleArea.py | 148 | 3.921875 | 4 | #!/usr/bin/env python3
import math
r = int(input("this is Pai"))
print(type(r))
area = math.pi * math.pow(r, 2)
print("Area is {:.4f}".format(area)) |
0eff51e3d47bf559640f2247b92eb5cc7f4e72d1 | jdanray/blog-code | /dp/lis.py | 389 | 3.609375 | 4 | # given a sequence of integers,
# finds the longest increasing subsequence
def lis(seq):
memo = []
for i, s in enumerate(seq):
longest = []
for j in range(i):
if seq[j] <= s and len(memo[j]) > len(longest):
longest = memo[j]
memo.append(longest + [s])
return max(memo, key=len)
s = [10,20,1,30,40,2,50,3... |
f4e8c42835fa2377493b1f7aee2c94efeb46a2d1 | jdanray/blog-code | /sort/heapsort.py | 200 | 3.671875 | 4 | import heapq
import testsort
def heapsort(nums):
heapq.heapify(nums)
for i in range(len(nums) - 1, 0, -1):
nums[0], nums[i] = nums[i], nums[0]
nums.sort()
return nums
testsort.test(heapsort)
|
6ed52cd13baadc8f0a77e9118f58d2a0adbc3204 | jdanray/blog-code | /dp/top_down_mis.py | 1,706 | 4.0625 | 4 | # an independent set of a graph is a set of vertices s.t.
# no vertex is adjacent to any other vertex in the set
# a maximum independent set contains the largest possible number of such vertices
# max_independent_set(tree, root) finds a maximum independent set of a tree, given the tree and its root
# memoize, because ... |
f88c271f0422f65bfb4cfa2f2b11e8d01b305359 | jdanray/blog-code | /graph_week/graph_size_bfs.py | 955 | 3.65625 | 4 | # https://www.reddit.com/r/dailyprogrammer/comments/4iut1x/20160511_challenge_266_intermediate_graph_radius/
import build_graph as bg
INFINITY = 100000
def eccentricities(graph, vertices):
ecc = [eccentricity(graph, vertices, u) for u in vertices]
return [e for e in ecc if e != None]
def eccentricity(graph, verti... |
b8eaf878ee7f7249af886685dd0a9e3414ef57dd | pstatkiewicz/lista-5 | /Zadanie 3.py | 293 | 4.125 | 4 | def Fibonacci_recursion(n):
if n<0:
return False
elif n<1:
return 0
elif n<3:
return 1
else:
return Fibonacci_recursion(n-1)+Fibonacci_recursion(n-2)
n=int(input("Podaj ilość liczb: "))
for i in range(1,n+1):
print(Fibonacci_recursion(i))
|
296dbe745db0c2414136f479486e62e28c96d958 | rtsfred3/PythonExamples | /1 - Python/16 - DList.py | 1,836 | 3.9375 | 4 | class Node:
def __init__(self, value):
self.before = None
self.value = value
self.next = None
class DList:
def __init__(self, value):
node = Node(value)
self.head = node
def addNode(self, value):
node = Node(value)
r = self.head
while(r.n... |
ef3c631776613bb0cf11b5e0ff8ad91e8b04148c | rtsfred3/PythonExamples | /1 - Python/15 - SList.py | 1,113 | 3.796875 | 4 | class Node:
def __init__(self, value):
self.value = value
self.next = None
class SList:
def __init__(self, value):
node = Node(value)
self.head = node
def addNode(self, value):
node = Node(value)
r = self.head
while(r.next != None):
r... |
7e3d4e12a2cdbce4c500e7e3d70629ae147377d0 | OmerKaan2061/Python_Assignments | /Armstrong_numbers.py | 559 | 4.03125 | 4 | number = input("Please enter a positive number :")
strong = len(number)
i = 0
summon = 0
if not number.isdigit() :
print("It is an invalid entry. Don't use non-numeric, float, or negative values!")
elif float(number) < 0:
print("It is an invalid entry. Don't use non-numeric, float, or negative values!")
else:
... |
050bd34173e1a70b7edba4f3fc9944ac9b19b54c | hanjj01/hanjj-homework | /animal_cat.py | 365 | 3.515625 | 4 | from homework.animal import Animal
class Cat(Animal):
def __init__(self):
hair = "短毛"
super().__init__("短耳猫", "黄色", "3", "女")
def zhuols(self):
print("会捉老鼠")
def sing(self):
super().sing()
print("喵喵叫")
if __name__ == '__main__':
eg2 = Cat()
eg2.sing()
... |
c104119c36e6d3fc9f9e60a8b33613d27d570d0a | apoorv-kumar/udacity-machine-learning | /tutorial_snippets/Encoding/encoder_basic.py | 1,486 | 3.640625 | 4 | from sklearn import preprocessing
import pandas as pd
sample_data = {
'name' : ['Ray', 'Adam', 'Jason', 'Varun'],
'health' : ['fit', 'slim', 'obese', 'fit']
}
data = pd.DataFrame(sample_data)
print(data)
label_encoder = preprocessing.LabelEncoder()
label_encoder.fit(data['health'])
# we could do multiple... |
08283d05e099d1d9db345b9a4e105cac2f87d0c8 | mx60s/CSCE420 | /Homework 1/h1pr1.py | 1,577 | 3.546875 | 4 | # Maggie von Ebers
# 525001114
# CSCE 420
# Due: 1/31/2019
# h1pr1.py
from collections import deque, namedtuple
Node = namedtuple('Node', ['parent', 'action', 'state', 'path'])
class Problem:
def __init__(self, initial_state):
self.initial_state = initial_state
def result(self, state, action):
... |
20d789cc7dbf7cac9d6bdca9610ea3356bc92db9 | Niyuhang2/some-algorithm | /tree.py | 4,245 | 3.828125 | 4 | # This Python file uses the following encoding: utf-8
#二叉树,二叉树的每个节点都有两个分叉,左和右
#定义节点,节点的元素为-1
class Node(object):
def __init__(self, elem=-1, lchild=None, rchild=None):
self.elem = elem
self.lchild = lchild
self.rchild = rchild
def __repr__(self):
return '<elem:%s,lchild:%s,rchil... |
81fc110babc951707c6f4fd0c5e40673f4b39979 | Niyuhang2/some-algorithm | /test/get_the_line.py | 3,451 | 3.59375 | 4 | # This Python file uses the following encoding: utf-8
# for i in range(1, 4):
#创建下一个方向
def get_next_dirction(dirc, index1, index2,grid): #作用得到最后位置的坐标
next_index = {'up': (index1-1, index2), 'left': (index1, index2-1),
'down': (index1+1, index2), 'right': (index1, index2+1)}
#获得下一个方向... |
2d0913d5f6ecb6b7afc300425079dd2ee44c9e7b | kuramu1108/Coursera_python | /Programming for Everybody (Python)/input.py | 359 | 4 | 4 | print "Hello World!"
user = raw_input("What's your name? ")
print "Hello", user
try:
hrs = raw_input("Enter Hours:")
hrs = float(hrs)
rate = raw_input("Enter Rate:")
rate = float(rate)
except:
print "Error, please enter a number"
quit()
if hrs > 40:
pay = 40 * rate + (hrs - 40) * rate * 1.... |
3cef014cb136ac2dc19593a625b30391ddb93a03 | PradeepKumarDwivedi/DeepLearning-LogisticRegressionForMNISTDataSet | /Logistic_Regression_Implementation.py | 7,931 | 3.5 | 4 | import numpy as np
from sklearn.datasets import fetch_mldata
# % matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
mnist = fetch_mldata('MNIST original')
mnist
X, y = mnist["data"], mnist["target"]
X.shape
y.shape
# To know how many digits we have we can run this simple code
total = 0
# for i i... |
8b00a14c5fe3b6d7ffd89bf1db6bd3e4eabdf8b8 | dinosaurz/ProjectEuler | /id041.py | 996 | 3.71875 | 4 | #!/usr/bin/python
''' Project Euler problem #41 Solution'''
def is_prime(num):
'''Test num for a prime trait'''
if num % 2 == 0:
return False
for i in range(3, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
def is_ndigital(num, n):
'''
Return whe... |
4f3019a7fee6cbe3590c61566891c7d3fcfd340c | dinosaurz/ProjectEuler | /id029.py | 245 | 3.578125 | 4 | from time import clock
def main():
start = clock()
terms = len(set([a ** b for a in range(2, 101) for b in range(2, 101)]))
print "%s found in %s seconds" % (terms, clock() - start)
if __name__ == '__main__':
main()
|
b11e32468dda515133231e952e90b28aaebde646 | dinosaurz/ProjectEuler | /id015.py | 358 | 3.71875 | 4 | from math import factorial
import time
# Using the combination formula the answer is easy to find
# C(n, r) = n! / (r! * (n - r)!)
def main():
start = time.time()
n, r = 40, 20
print (factorial(n) / (factorial(r) * factorial(n - r))),
print "found in %s seconds" % (time.time() - start)
if... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.