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 |
|---|---|---|---|---|---|---|
0259eaba23840a8ab74c6f38f47c2805a02abff9 | Greens-Theorem/Green-Pastures | /TipCalculator.py | 1,543 | 3.828125 | 4 | #author Cowen Hames January 2021
from tkinter import *
window = Tk() # TK method that creates a windows objective
window.title("Tip Calculator")
def bad_service():
with_tip.set((float(without_tip.get()) * .10 + float(without_tip.get())))
def average_service():
with_tip.set((float(without_tip.get()) ... |
be8450d8e7bd73004d0e181703dc1175e1309139 | nebkor/lpthw | /ex32.py | 870 | 4.59375 | 5 | the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'appricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in the_count:
print "This is the count %d" % number
# same as above
for fruit in fruits:
print "A fruit of type: ... |
9ceec7eae46ff248dbcdcfa1146738bea6b517cc | nebkor/lpthw | /ex20.py | 2,230 | 4.25 | 4 | # import sys.argv into the global namespace as argv
from sys import argv
# assign script to the 0th entry in the argv array and input_file
# to the 1th entry in the argv array
script, input_file = argv
# Define the function "print_all()" which takes an argument as f
def print_all(f):
print f.read() # print... |
ad25f8423417bd2f9de0ea80ae9c97bc53635969 | nebkor/lpthw | /joe/ex15.py | 1,594 | 4.625 | 5 | # import sys.argv into the global namespace as argv
from sys import argv
# assign to the 'script' variable the value of argv[0],
# assign to the 'filename' variable the value of argv[1]
script, filename = argv
# assign to the 'txt' variable the value returned by the
# function "open()", which was called with the vari... |
0e9ae3f227b7afe949a05bc038bdfb5b9bcd5bef | nebkor/lpthw | /1-100.py | 339 | 4.03125 | 4 | # count up to 100 from 1, printing each number, if divisible by 3 - print richard, if divisible by 7
# print is, if divisible by 21 print awesome
for i in xrange(1, 101):
if i % 21 == 0:
print "Awesome"
elif i % 7 == 0:
print "Is"
elif i % 3 == 0:
print "Richard"
else:... |
756c1221f733e20004f9acc85228addc7f524028 | robbyvan/- | /木/94_Binary Tree Inorder Traversal.py | 748 | 3.609375 | 4 | # 94_Binary Tree Inorder Traversal
# 递归算法: 中序遍历 = 左中右
# 非递归算法: 从根出发, 向左移动, 经过节点进栈, 直到null后pop访问栈顶node, 修改下一个节点为node.
class Solution:
def inorderTraversal(self, root):
res = []
self.helper(root, res)
return res
def helper(self, root, res):
if root is None:
return
self.helper(root.left)
... |
fd77aeda9a0635ebb63902a466a845eefaf775ee | robbyvan/- | /木/101_Symmetric Tree.py | 584 | 3.859375 | 4 | # 101_Symmetric Tree
# 检查左右镜像:
# 都不存在 => true
# 存在不对称 => false
# 都存在:
# 根相同 => 左左 == 右右 and 左右 == 右左
# 根不同 => false
class Solution:
def isSymmetric(self, root):
if not root:
return True
return self.isMirror(root.left, root.right)
def isMirror(self, left, right):
if not left and not right:
... |
e4873e452e1bb943832f1b0828407c2cc2f9c38d | robbyvan/- | /配列/59_Spiral Matrix II.py | 698 | 3.71875 | 4 | # 59_Spiral Matrix II
# 按定义, 四个边界walk. while top <= bot and left <= right
class Solution:
def generateMatrix(self, n):
res = [[0 for _ in range(n) ] for _ in range(n)]
top, bot, left, right = 0, n - 1, 0, n - 1
num = 1
while top <= bot and left <= right:
for j in range(left, right + 1):
... |
893e762e9a23acc43b2c99324eb4b0dae42b71d2 | robbyvan/- | /文字列/71_Simplify Path.py | 549 | 3.65625 | 4 | # 71_Simplify Path
# 按照定义即可.先按照"/+"split, 然后遍历
# "" & "."不管
# ".." 在非空时pop()
# 其他直接append()
import re
class Solution:
def simplifyPath(self, path):
paths = re.split('/+', path)
stack = []
for ch in paths:
if ch == '' or ch == '.':
continue
elif ch == '..':
if len(stack) > 0:
... |
845234bf10eb395c723555727f16f7a3b96b91ef | robbyvan/- | /木/236_Lowest Common Ancestor of a Binary Tree.py | 1,470 | 3.796875 | 4 | # 236_Lowest Common Ancestor of a Binary Tree
# 递归. 如果根是p或q, 返回根
# 否则查看左右子树, 相同的返回规则, 所以LCA出现在left and right的情况(左右各一)
# 如果left, right有一个空, 那么p, q同时出现在了一棵子树, 对那个子树递归查找
class Solution:
def lowestCommonAncestor(self, root, p, q):
if not root:
return None
if root == p or root == q:
return root
le... |
d0de25f3cd0d91a0841f49e24815d6d3f7a23c20 | robbyvan/- | /文字列/49_Group Anagrams.py | 736 | 3.59375 | 4 | # 49_Group Anagrams
# 排序各项, 利用hash表, 保存变形前的单词.
class Solution:
def groupAnagrams(self, strs):
d = {}
for w in sorted(strs):
key = tuple(sorted(w))
d[key] = d.get(key, []) + [w]
return d.values()
# import collections
# class Solution:
# def groupAnagrams(self, strs):
# res = []
# d ... |
5ff56ae397abd3824f7cf70f8985d9dbbb93d2d7 | robbyvan/- | /動的計画法/309_Best Time to Buy and Sell Stock with Cooldown.py | 508 | 3.6875 | 4 | # 309_Best Time to Buy and Sell Stock with Cooldown
# 三种状态, buy, rest, sell.
# 代表在day之前所有的以buy, rest, sell结束的序列的最大profit
class Solution:
def maxProfit(self, prices):
if len(prices) < 2:
return 0
buy, sell, rest = -prices[0], 0, 0
for i in range(1, len(prices)):
prevBuy, prevSell = buy, sell
... |
9ab8535a3a6795080867324245eab7f3b5f38e14 | robbyvan/- | /配列/26_Remove Duplicates from Sorted Array.py | 423 | 3.578125 | 4 | # 26.Remove Duplicates from Sorted Array
# 双指针, 一个遍历, 一个空位
# 如果遍历处是第一个 或者不是重复, 那么就移动到空位, 更新空位
# 否则跳过这个点, 这个点将成为空位.
class Solution:
def removeDuplicates(self, nums):
if not nums:
return 0
i = 0
for num in nums:
if i == 0 or num > nums[i - 1]:
nums[i] = num
i += 1
return i |
8799db9c864051ff63fd6c3d207f7720ba5c9ad9 | robbyvan/- | /配列/189_Rotate Array.py | 234 | 3.65625 | 4 | # 189_Rotate Array
# 注意k比n大的情况, 求余.
# 然后两部分拼起来就好了
class Solution(object):
def rotate(self, nums, k):
n = len(nums)
k = k % n
index = n - k
nums[:] = nums[index:] + nums[:index] |
9cdd458ecba0e05615115efdd3b8bf5dbb6b80d4 | robbyvan/- | /配列/442_Find All Duplicates in an Array.py | 456 | 3.671875 | 4 | # 442_Find All Duplicates in an Array
# 1 ≤ a[i] ≤ n (n = size of array)
# 每个内容都在1~n, 那么内容作为index, 每次翻转index处内容的正负, 然后如果遇到了第二次, 准备翻转时一定是负内容, 则添加到res中.
class Solution:
def findDuplicates(self, nums):
res = []
for num in nums:
if nums[abs(num) - 1] < 0:
res.append(abs(num))
else:
num... |
95256fbf9a851778689a9b580fe6b18da4db6be2 | robbyvan/- | /文字列/165_Compare Version Numbers.py | 919 | 3.5 | 4 | # 165_Compare Version Numbers
# 1) 利用split分开"." => 两个字符数组
# 2) 删掉无用的后缀0.使用int()强转
# 3) 首先比较公共长度部分, int()比较, 返回-1或者1
# 4) 继续比较长度, 长的大, 短的小
class Solution(object):
def compareVersion(self, v1, v2):
version1 = self.trimRightZero(list(map(lambda x: int(x), v1.split('.'))))
version2 = self.trimRightZero(list(map(... |
7c0eb4878ee3719591dc8d888c5fa345f495f9e1 | robbyvan/- | /配列/80_Remove Duplicates from Sorted Array II.py | 350 | 3.65625 | 4 | # 80_Remove Duplicates from Sorted Array II
# 类似26, 只用把交换条件改成2个的情况, 如果小于2, 或者等于前1(2)个
class Solution:
def removeDuplicates(self, nums):
tail = 0
for num in nums:
if tail < 2 or num != nums[tail - 1] or num != nums[tail - 2]:
nums[tail] = num
tail += 1
return tail
|
ac9600fe9bd66e99e75aa8842b5a26979032e365 | robbyvan/- | /木/515_Find Largest Value in Each Tree Row.py | 312 | 3.578125 | 4 | # 515_Find Largest Value in Each Tree Row
# 还是BFS...
class Solution:
def largestValues(self, root):
if not root:
return []
q, res = [root], []
while q:
res.append(max(node.val for node in q))
q = [leaf for node in q for leaf in (node.left, node.right) if leaf]
return res |
093a51c84aa65eb02db29d506d29bd49027f5b6d | robbyvan/- | /配列/119_Pascal's Triangle II.py | 496 | 3.75 | 4 | # 119_Pascal's Triangle II
# 同理path.append(last[i] + last[i - 1])
class Solution:
def getRow(self, rowIndex):
if rowIndex < 0:
return []
if rowIndex == 0:
return [1]
if rowIndex == 1:
return [1, 1]
last = [1]
for row in range(2, rowIndex + 2):
path = []
for i in range... |
3d67d5ed2b7d402bb6fd8cfa2f92be7c9d069118 | robbyvan/- | /配列/268_Missing Number.py | 224 | 3.515625 | 4 | # 268_Missing Number
# 求和公式相减; 异或; 排序 + 二分查找
class Solution:
def missingNumber(self, nums):
res = len(nums)
for i in range(len(nums)):
res ^= i
res ^= nums[i]
return res |
cdff65beddee99af483069c3d2b0d2972c3beb26 | andrewvuong123/Wallbreakers | /Week1/twoSum.py | 778 | 3.5 | 4 | class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# General Idea: Append each num - target to a set and then check to see if the original nums are in the set and append the index to the resulting ... |
e6e3ac71835d53f0d93da2b812033e2a526c215c | andrewvuong123/Wallbreakers | /Week2/intersectionTwoArrays.py | 564 | 3.859375 | 4 | class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
# General Idea: Intersection <=> Appears in both arrays. Can append nums1 to a set and compare with nums2 to see if numbers in nums2 ar... |
9fffbd180f5bc2fa35369e070f704d3597f6571a | andrewvuong123/Wallbreakers | /Week2/wordPattern.py | 925 | 3.96875 | 4 | class Solution(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
# General Idea: Map each letter in the pattern to the word value in the string in a dictionary. Check for three cases, if the letter is in the dictionar... |
6155ad984900d77f58f79cc7224ce70f62032287 | andrewvuong123/Wallbreakers | /Week3/binarySearch.py | 691 | 4.03125 | 4 | class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
# General Idea: Use binary search to split list in half, check on upper/lower half of list based on if median is larger/smaller than target. Keep search... |
9d980f080d34cf99b3bf385402d98724c29edb85 | andrewvuong123/Wallbreakers | /Week1/sortArrayByParity.py | 447 | 3.765625 | 4 | class Solution(object):
def sortArrayByParity(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
# General Idea: Create two separate lists of even/odd ints and then concatenate together
even = []
odd = []
for num in A:
if num % 2 == 0:
... |
b2e707fa9c609f86bd0269ecc349be0696526c85 | andrewvuong123/Wallbreakers | /Week3/editDistanceDynamic.py | 1,072 | 3.578125 | 4 | class Solution(object):
def minDistance(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
# General Idea: Can use the dynamic edit distance algorithm to solve, create a 2d table to sovle.
m = len(word1)
n = len(word2)
E... |
a0c86cd8e8c0c91cddfc25865c123c71cbfc8c4f | tomdos/python-learning | /prefix-tree.py | 5,639 | 3.6875 | 4 | #!/usr/bin/env python3
import sys
class PrefixTree:
def __init__(self):
self._root = self.Node()
def __str__(self):
return self._root.__str__()
def add(self, word, description):
'''
Add new word to the tree. The last node (representing the word itself)
contains ... |
e23e2a0d93aed122f7112df484b0c55a66086940 | kunalgupta777/Neural-Networks | /Program8.py | 2,799 | 3.953125 | 4 | ## 8.) Implement Adaline Network
## An Adaline is a Neural Network that has a single Linear Activation Unit
## The network architecture is like McCulloch Pitts Model with the difference of the learning rule
## The Adaline employs the Widrow-Hoff rule for learning
'''
w_i(new) = w_i(old) + alpha*(t - yin)x_i
... |
89b61180312486b98d1e7f94396977e1a7d87d90 | kunalgupta777/Neural-Networks | /Program10.py | 1,112 | 4.03125 | 4 | ## 10.) Implement Auto Associative Neural Networks
## Auto associative neural nets are a special type of nets which store pattern associations
## Here, the output vector is identical to the input vector
## Both, the input layer and the output layer have 'n' neurons
## Hebbian Learning Rule can be applied to find th... |
eae7bba3d1e968ea877b88106e7839cca99cd386 | libyal/dtformats | /dtformats/output_writers.py | 912 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""Output writer."""
import abc
class OutputWriter(object):
"""Output writer."""
@abc.abstractmethod
def Close(self):
"""Closes the output writer object.
Raises:
IOError: if the output writer cannot be closed.
"""
@abc.abstractmethod
def Open(self):
"""Opens... |
92e055683f9e3ca7e3a8d8342ed7a66deb2e48b3 | MallikarjunH4/python-training | /day 3.py | 376 | 3.65625 | 4 | # age
n=int(input())
print('current age of the person is:',2021-n-1)
#calculator
n,m=map(int,input().split())
print('ADD is:'+str(m+n),'SUB is:'+str(n-m),'MULTI is :'+str(n*m),'FLOORDIV is :'+str(n//m),'DIV is :'+str(n/m),'REM is:'+str(n%m),'POWER is :'+str(n**m),sep='\n')
#count
n=input()
print(n.count('y'))
#even... |
41387ede2b083f443e2d8d625e14c99c364ae11c | Ponkiruthika112/codeset6 | /smal_lex.py | 103 | 3.546875 | 4 | n=int(input())
l=[]
for i in range(0,n):
s=input()
l.append(s)
l.sort()
print(l[0])
#lexically small
|
6042e8e6eb96b44d7b3cd118c9f6059ab6ce888d | Ponkiruthika112/codeset6 | /code2.py | 109 | 3.578125 | 4 | #thud
s=input()
c=0
for i in s:
if i=="1" or i=="0":
c=c+1
if c==len(s):
print("yes")
else:
print("no")
|
a3fe3b1aa3a6f97e8e34d8341a2d07d925215e51 | Ponkiruthika112/codeset6 | /sum_3_7.py | 220 | 3.90625 | 4 | # your code goes here
n=int(input())
if n%3==0 or n%7==0:
print("yes")
else:
k=n%3
y=n-k
i=0
while i<y:
s=y-3
if s+7==n:
print("yes")
break
else:
y=s
i=i+1
else:
print("no")
#for sum of 3 and 7
|
c24e833b69a665dfb8f999fe8d13209eb99d9916 | Ponkiruthika112/codeset6 | /balance.py | 121 | 3.6875 | 4 | s=input()
c=0
for i in s:
if i=="(":
c=c+1
else:
c=c-1
if c==0:
print("yes")
else:
print("no")
#balanced or not
|
8022eb55132290ed86ff7c4e87fb016c2bfe7f3b | Ponkiruthika112/codeset6 | /points.py | 400 | 3.96875 | 4 | import math
def colinear(x1,y1,x2,y2):
s=((y2-y1)*(y2-y1))+((x2-x1)*(x2-x1))
return math.sqrt(s)
x1,y1=map(int,input().split())
x2,y2=map(int,input().split())
x3,y3=map(int,input().split())
p1=colinear(x1,y1,x2,y2)
p2=colinear(x2,y2,x3,y3)
p3=colinear(x3,y3,x1,y1)
if p3==p1+p2 or p1==p2+p3 or p2==p1+p3:
pri... |
d663d4b6db392831b09a3ef70be9c8d5f70e911e | TrakJohnson/esopy | /brainfuck/text_to_bf.py | 1,264 | 3.828125 | 4 | """
Converts text to a bf program that will output it
Very inefficient for now.
"""
import math
class Converter:
def __init__(self, str_in):
self.all_codes = [ord(c) for c in str_in]
self.result_code = ''
def convert(self):
min_char_code = min(self.all_codes)
while True:
... |
48c5c3c58c9236ceb57266a85c6311fb513fbf6f | LyaisanN/Homework_Figure | /src/Square.py | 1,094 | 3.84375 | 4 | from src.Figure import Figure
from src.Rectangle import Rectangle
from src.Circle import Circle
from src.Triangle import Triangle
class Square(Figure):
name = 'Square'
def __init__(self, height):
self.height = height
# self.width = width
super().__init__(name='Square', area=None, peri... |
ef355f0cb0dd4cab75572a9469e24db09d6f9c2d | Edgarlv/Tarea_04 | /IMC.py | 716 | 3.8125 | 4 | #encoding: UTF-8
#author: Edgar Eduardo Alvarado Duran
#Problema 5
def calcularIMC(masa,estatura):
IMC= float(masa/(estatura**2))
return IMC
def calcularEstado(a):
if a>=0 and a<18.5:
print ("Tienes bajo peso")
else:
if a>=18.5 and a<25:
print ("Tu peso es normal")
... |
f808457728180b21ffdc105d654ae3260e092838 | Bobert127/python_and_postgresql | /ownerlern/test.py | 422 | 3.78125 | 4 | class Car:
def __init__(self, color='white', initial_speed=0):
self.color = color
self.speed = initial_speed
self.gear = 0
if self.speed > 0:
self.gear = 1
# def create_car():
# pass
car_dict = {}
car_dict['speed'] = 1
print(car_dict['speed'])
car = Car(initial_spe... |
39f8f6a9e4a1a8f6a890fefb296a0adc3631b2d4 | Bobert127/python_and_postgresql | /ownerlern/exercise1.py | 563 | 3.6875 | 4 | class Calculator:
def __init__(self):
self.history = []
def add(self, num1, num2):
result = num1 + num2
self.history.append(f'added {num1} to {num2} got {result}')
return result
def multiplay(self, num1, num2):
result = num1 * num2
self.history.append(f'add... |
35219159e8a0d2646a5f29db9b96ed3f57b4e59c | Bobert127/python_and_postgresql | /ownerlern/circle.py | 541 | 3.8125 | 4 | import math
class Circle:
def __init__(self, radius):
self._radius = radius
self.area = math.pi * radius ** 2
self.circumference = 2 * math.pi * radius
def get_radius(self):
return self._radius
@property
def radius(self):
return self.get_radius()
@radius.... |
c1c2e63c24774a8ba68a56de24d027690073805d | utevo/ProjectEuler-solutions | /Problem 030/script.py | 531 | 3.796875 | 4 | POWER = 5
def is_good(number):
number_as_str = str(number)
sum_of_fifth_powers_of_digits = 0
for digit in number_as_str:
digit = int(digit)
sum_of_fifth_powers_of_digits += digit ** POWER
if sum_of_fifth_powers_of_digits == number:
return True
return False
def main():
... |
a4016569d9bb15934d21c207ce5573500e69ae9f | utevo/ProjectEuler-solutions | /Problem 015/script.py | 856 | 3.671875 | 4 | import numpy as np
const = 21
def main():
# In this array we write down the number of possible routes for a given
# point.
howManyDifferentPathsTo = np.zeros((const, const), int)
howManyDifferentPathsTo[(0, 0)] = 1 #we know it
for index, value in np.ndenumerate(howManyDifferentPathsTo):
... |
329eb5d391bc355566b7f0bb0c12bf951be3afc8 | Billchatch/numerical-python-part3 | /xercise-3curve.py | 462 | 3.71875 | 4 | ##
## EXERCISE -> change th 3rd order polynomial for the curve fit
##
# use the same data from above
x = np.linspace(-3*np.pi,3*np.pi,20)
noise = (np.random.random(20)*2 - 10) * 200
y = x**3-6*x**2 + noise
# must provide a model function, with independent variable as the first parameter
def m(x,a,b,c,d):
return a... |
c2bf42e044e632a98b9951333a3e977ad5d03b5d | owentopre/orbits | /Particle.py | 5,063 | 3.75 | 4 | import math
import numpy as np
import copy
import scipy.constants as const
class Particle:
'''
A class representing a particle. Use the methods to update the particle's initial conditions over time or to find out the particle's current conditions
Inputs
------
position : array
... |
4be68a159d2dd7b9e794c328d2988681b8fd5075 | joshp123/COMP1036 | /Assignment 2/mathstest.py | 1,045 | 3.765625 | 4 | # mathstest.py
# Random sum thing but catches non-ints and repeats 10 times and keeps score
# Author: J Palmer
# Created on: 2012-03-05
# Version: 1.2 made it slightly more elegant - instead of using global variables and incrementing them, the askrand() function returns a value and it works with that
import r... |
2bc922df729d31110bf077b62f31758575509bdd | theksenia/hm3 | /4.py | 175 | 4 | 4 | a = int(input("Ввод a: "))
b = int(input("Ввод b: "))
if a<b:
for i in range(a, b + 1):
print(i)
else :
for i in range(a, b-1, -1):
print(i)
|
d3c0d07b650d0e0ccc020d054dd0431686304f5c | EllaChen103/Cipher | /CaesarCypher.py | 420 | 3.890625 | 4 | def shift(message, key):
answer = []
for element in message:
element = ord(element)
if 97 <= element < 123:
element = element + key
while element >= 123:
element = element - 26
element = chr(element)
answer.append(element)
ret... |
38c856f461814cb54fb2fbc27026e4a99148d20c | MathBatistela/8-puzzle-solver | /puzzle.py | 5,844 | 3.8125 | 4 | import sys
import heapq
class Puzzle:
LENGTH = 3
goal_state = [1,2,3,4,5,6,7,8,0]
def __init__(self, state, depth = 0, cost_type = None):
self.state = state
self.depth = depth
self.expansion_order = 0
if cost_type:
self.set_cost(cost_type)
... |
f677741f8639896523239b875d6ab547b8be28fe | perdue/ema | /persist/filepersist.py | 678 | 3.515625 | 4 | import os
import io
import gzip
import builder
"""Local file access"""
class LocalDrive:
def __init__(self, persist_dir):
self._dir = persist_dir
builder.mkdirs(self._dir)
def outdir(self):
return self._dir
def gzip_exists(self, filename):
file_exists = False
for ... |
322ce4e648cea68f3af02ae42960ca3d50d42822 | bd3young/pygame | /jet.py | 1,689 | 3.65625 | 4 | import pygame
from pygame.sprite import Sprite
class Jet(Sprite):
"""A class to manage the Jet."""
def __init__(self, ai_game):
"""Initialize the Jet and set its starting position."""
super().__init__()
self.screen = ai_game.screen
self.settings = ai_game.settings
self.s... |
34e49482ae790c414dc139c7a69259fcfd7deaab | AIESECer/CS-1101---Programming-Fundamentals---Python | /Unit 8/sort_fruits.py | 446 | 3.734375 | 4 | print ("The program just started")
#Input and output files
f_in = open("/home/elemelons/unsorted_fruits.txt", "r")
f_out = open("/home/elemelons/sorted_fruits.txt", "w")
#Read the input file
fruits = f_in.readlines()
#Sort the list
fruits.sort()
#Write the sorted file
for fruit in fruits:
if False == str.isspac... |
111885e22ac586006c1ca360a63ca46371f91ddc | kmsiergiej/pdsnd_github | /bikeshare.py | 10,568 | 3.609375 | 4 | import time
import pandas as pd
import numpy as np
import datetime
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
DATETIME_LISTS = {
'months': ['january', 'february', 'march', 'april', 'may', 'june'],
'days': ['Monday',
... |
27cd9e22855d403476fcbe4d8b0e70c6ea480d37 | mrtonks/PythonCourses | /Python Programming/Chapter 6/Exercise1.py | 158 | 3.578125 | 4 | #Sample program with statements outside the loop
ei = 7
while ei != 0:
print ei
ei -= 1
print "Wow, ei now equals", ei
print "This ends everything."
|
0696a1eb1b199494d64f5336db4eb68bf2cfa217 | mrtonks/PythonCourses | /Python Programming/Chapter 6/Exercise2.py | 170 | 4.25 | 4 | #Sample for loop program
#First create a list
this_list = [45, 14, 65, 42, 34]
#Create the for loop
for content in this_list:
print content
print "It's the end."
|
86555752f784eec78689d6fd691753ed4a9f8cb9 | yoavbargad/self.py-course-python | /Unit 4/unit 4 - 4.2.4.py | 219 | 4.21875 | 4 | # Python Course - unit 4
# 4.2.4
import calendar
day_list = list(calendar.day_name)
date = input('Enter a date (dd/mm/yyyy):\t')
day = calendar.weekday(int(date[6:]), int(date[3:5]), int(date[:2]))
print(day_list[day]) |
cb693bbce6fe370e7269d142b14e144639b8a9d4 | yoavbargad/self.py-course-python | /Unit 1/unit1.py | 602 | 4.03125 | 4 | # unit 1 - python course
blocks_num = int(input('\nEnter three digits: '))
num1 = int(blocks_num / 100)
num2 = int((blocks_num / 10) % 10)
num3 = blocks_num % 10
combined = num1 + num2 + num3
print('\n', num1, num2, num3)
print('\n', combined)
print('\n', int(combined / 3))
print('\n', combined % 3 == 0)
flag = True
w... |
a19ba415230227ac3af2a131b60f6de39b02569f | maggieaschneider/ACTUALHACK | /color_quiz.py | 3,757 | 3.71875 | 4 | from tkinter import *
class color(Frame):
def __init__(self, master):
super(color, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
Label(self, text = "Which Color Represents Your Personality?").grid(row = 0, column = 2, columnspan = 2)
... |
0407633b66aa87c0cdb95396ade86513c6e8b5b5 | maggieaschneider/ACTUALHACK | /spiritAnimal.py | 3,405 | 3.671875 | 4 | from tkinter import *
class spiritAnimal(Frame):
def __init__(self, master):
super(spiritAnimal, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
Label(self, text = "Answer these questions to see what your spirit animal is!").grid(row = 0, co... |
f9b2153959aca19d42899c149d5e0d38d7b1c5e1 | ivanfilimonov/python | /main/hw3/employee.py | 2,737 | 3.609375 | 4 | class Employee:
def __init__(self, first_name, last_name, salary):
self.first_name = first_name.title()
self.last_name = last_name.title()
self.salary = self.getValidatedSalary(salary)
self.full_name = (first_name + ", " + last_name).title()
self.email = self.getEmail(first_... |
26a10367441863dea8098af6fba3de324c6b8c58 | rawrgulmuffins/language_projects | /lets_build_a_interpreter/pascal_interpreter/pascal_interpreter.py | 9,385 | 3.96875 | 4 | """This program is an interpreter for a subset of the PASCAL programming
language. It's' based off of the Let's Build A Simple Interpreter tutorial
found at https://ruslanspivak.com/lsbasi-part1/
This code base was build and tested in Python3.5.
"""
# NOTE: So when I made this I made the mistake of switching the token... |
90cf13572f8b29dc692a7f1f19b654cb021f96d6 | JustAlexOne/try_python | /loops_example.py | 516 | 3.875 | 4 | import random
for x in range(0, 10):
print(x, ' ', end="")
num_list = [[1, 2, 3], [10, 20, 30], [100, 200, 300], [1000, 2000, 30000]]
for x in range(0, 4):
for y in range(0, 3):
print(num_list[x][y])
random_num = random.randrange(0, 10)
while(not(random_num == 5)):
# while(random_num != 15):
pri... |
86529b863485e268b782755f9a98164cc7cf9786 | JustAlexOne/try_python | /functions_example.py | 226 | 3.53125 | 4 | def addNumber(num1, num2):
sumNum = num1 + num2
return sumNum
print(addNumber(1, 4))
def printB():
print('I am B')
def printA():
print('I am A')
options = {
1 : printA,
2 : printB
}
options[2]() |
2a9394b044f7496f6c0bc586bcd1e2883a8970de | Dylan-Lebedin/Computer-Science-1 | /Labs/scenery.py | 7,184 | 4.28125 | 4 | """
Create a scene that includes two houses and a tree
file: scenery.py
author: Dylan Lebedin
Partners: Banyan Batts, Gunnar Bachmann, Jaylan Sanford, Phuong Nguyen
"""
# imports the math module for using the square root function
import turtle
import math
# definitions of functions and procedures
def ... |
4272bcf4fdcdee3dfeada312f6e5325d6bc70760 | Dylan-Lebedin/Computer-Science-1 | /Homework/test_debug2.py | 2,868 | 4.1875 | 4 | """
This program includes a function to find and return
the length of a longest common consecutive substring
shared by two strings.
If the strings have nothing in common, the longest
common consecutive substring has length 0.
For example, if string1 = "established", and
string2 = "ballistic", the function re... |
f73581df48bcdc074777d9c4291586ea518b3e7a | Dylan-Lebedin/Computer-Science-1 | /Labs/mobiles.py | 9,597 | 3.984375 | 4 | """
file: mobiles.py
language: python3
author: CS.RIT.EDU
author: Dylan Lebedin
description: Build mobiles using a tree data structure.
date: 10/2015, 11/2019
purpose: starter code for the tree mobiles lab
"""
############################################################
# ... |
4c0f75df39bf555a5362a2b42eead03647a29944 | heckenna/ev3dev-curriculum | /libs/robot_controller.py | 7,484 | 3.71875 | 4 | """
Library of EV3 robot functions that are useful in many different applications. For example things
like arm_up, arm_down, driving around, or doing things with the Pixy camera.
Add commands as needed to support the features you'd like to implement. For organizational
purposes try to only write methods into ... |
be4cc3328a4b17f6d796f4c1ceffed8f7b10ec80 | MilesBDyson/HMC8553L | /reading.py | 279 | 3.671875 | 4 | #!/usr/bin/env python
import hmc5883l
compass = hmc5883l.hmc5883l(gauss = 4.7, declination = (-2,5))
test1 = compass.heading()
test2 = compass.axes()
test3 = compass.degrees(compass.heading())
print "deg " + str(test1)
print "axes " + str(test2)
print "deg/min " + str(test3) |
383b0751cf84577400f4be06206162096685507e | FelipeTerrana/evolutionary-computation | /ppa/individual.py | 644 | 3.765625 | 4 | import random
# TODO Mudar (talvez) representação de vetor de inteiros pra um único inteiro em binário
class Individual:
def __init__(self, paramId, size):
self.size = size
self.id = paramId
self.prey = [0] * self.size
self.survival_value = 0.0
def generate_random_prey(self)... |
22306deb7ddb860523d651641fd9006361766a52 | sarana-25/Pocket | /Shell Sort.py | 384 | 3.78125 | 4 | def shell_sort(lst):
gap=len(lst)//2
while gap>0:
for i in range(gap,len(lst)):
anchor=lst[i]
j=i
while j>=gap and lst[j-gap]>anchor:
lst[j]=lst[j-gap]
j-=gap
lst[j]=anchor
gap=gap//2
n=int(input())
lst=[]
for _ in r... |
453923dc2195b9d717e66e9d95ef2ed91162272b | sarana-25/Pocket | /Reversing any input.py | 163 | 4 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[3]:
a= (input("Enter your string"))
count=0
for letters in a:
count+=1
print(a[len(a)-count])
# In[ ]:
|
8ce8df3507506a53afae3be0c5ae92dc87fdc68f | AdamDzierzko/CS50 | /w6-sentimental, dna/readability.py | 845 | 3.703125 | 4 | import cs50
grade = 0
letters = words = sentences = L = S = index = 0.0
text = cs50.get_string("Text: ")
def count_letters(t):
a = 0
for i in range(len(t)):
if (t[i].isalpha()):
a += 1
return a
def count_words(t):
a = 1
for i in range(len(t)):
if (t[i] == ' '):
... |
a4700c842bb0f0b3dedb3370d836e3afb0f491d1 | si-medbif/FastFASTQTransfer | /Experiments/Pilot_Compression/Huffman-Coding/HuffmanTree.py | 2,041 | 3.734375 | 4 | from HuffmanNode import HuffmanNode
import heapq
from collections import Counter
class HuffmanTree(object):
def __init__(self, root=None):
self.root = root
self.heap = []
self.CODES = {}
self.enc_tree = bytearray()
def char_frequency(self, txt):
'''
txt(str) -> char frequency (dict)
This Funct... |
86ac33ad740f0ac6b4a2e2f964f85bc855257fc6 | BassP97/CTCI | /Med/divisionAlg.py | 899 | 4.0625 | 4 | """
Given two integers dividend and divisor, divide two integers without using
multiplication, division and mod operator.
Return the quotient after dividing dividend(x) by divisor(y).
The integer division should truncate toward zero.
"""
#returning x/y
def divide(x, y):
if x<0 or y<0:
x = abs(x)
... |
9956f0ea9beb16499bd04955fef4a03c471577e9 | BassP97/CTCI | /Hard/surroundedRegions.py | 1,912 | 4.15625 | 4 | """
Given a 2D board containing 'X' and 'O' (the letter O), capture all regions
surrounded by 'X'.
A region is captured by flipping all 'O's into 'X's in that surrounded region.
Example:
X X X X
X O O X
X X O X
X O X X
After running your function, the board should be:
X X X X
X X X X
X X X X
X O X X
"""
#searches ... |
870fc22c0db78eec6a5b92ed407ef42dd600556b | BassP97/CTCI | /2021 prep/findMinRotArrRedux.py | 1,423 | 3.5 | 4 | def minRotArrInner(nums, l, r, returnIndex):
if nums[l] <= nums[r]:
if returnIndex:
return l
return nums[l]
mid = l+((r-l)//2)
if nums[mid] >= nums[l]:
return minRotArrInner(nums, mid+1, r, returnIndex)
return minRotArrInner(nums, l, mid, returnIndex)
def minRotArr(... |
87a7fea85665c6937299d627e8f48b742e35e359 | BassP97/CTCI | /Med/mergeTimes.py | 1,123 | 4.21875 | 4 | """
Write a function merge_ranges() that takes a list of multiple meeting
time ranges and returns a list of condensed ranges.
For example, given:
[(0, 1), (3, 5), (4, 8), (10, 12), (9, 10)]
your function would return:
[(0, 1), (3, 8), (9, 12)]
Do not assume the meetings are in order. The meeting times are c... |
3c1c6570665855076d207469a330015673fff06b | BassP97/CTCI | /Med/pacificAtlantic.py | 2,657 | 3.828125 | 4 | """
Given an m x n matrix of non-negative integers representing the height of each
unit cell in a continent, the "Pacific ocean" touches the left and top edges of
the matrix and the "Atlantic ocean" touches the right and bottom edges.
Water can only flow in four directions (up, down, left, or right) from a cell to
ano... |
8540ce965a48bf247324f3507c52909712245d29 | BassP97/CTCI | /Med/kClosestPoints.py | 1,175 | 3.71875 | 4 | """
We have a list of points on the plane. Find the K closest points to the origin (0, 0).
(Here, the distance between two points on a plane is the Euclidean distance.)
You may return the answer in any order. The answer is guaranteed to be unique
(except for the order that it is in.)
"""
import math
import heapq
... |
a6da9200233585dbd137a92244c13fcf8277b8be | BassP97/CTCI | /Hard/trappingRain.py | 1,298 | 3.921875 | 4 | """
Given n non-negative integers representing an elevation map where
the width of each bar is 1, compute how much water it is able to
trap after raining.
"""
def main(topography):
interStart = 0
interEnd = 0
intervalList = []
i = 0
#step one - get all the intervals that will be filled with water
... |
3fea6250bae84bb55bd9c9a3b9d98878c38e1743 | BassP97/CTCI | /2021 prep/linkedListAdd.py | 1,390 | 3.859375 | 4 | """
You are given two non-empty linked lists representing two non-negative integers.
The digits are stored in reverse order, and each of their nodes contains a single
digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0
i... |
d6181901165881a52d73d399e7939c1300118b1f | BassP97/CTCI | /Med/reverseLLInplace.py | 456 | 4.25 | 4 | """
Write a function for reversing a linked list. Do it in place.
Your function will have one input: the head of the list.
Your function should return the new head of the list.
Here's a sample linked list node class:
"""
def revLL(head):
if head.next is None:
return head
curr = head.next
prev =... |
456ce46ae8dc21ebcac5d4c1c0551e792487ad25 | BassP97/CTCI | /Easy/sumZero.py | 470 | 3.640625 | 4 | """
Given an integer n, return any array containing n unique integers such that they add up to 0.
"""
def sumZero(k):
arr = []
if k%2==0:
for i in range(0,len(k)/2):
arr.append(i)
for i in range(0,len(k)/2):
arr.append(0-i)
else:
arr.append(0)
temp = ... |
3c63a2a1081d683c8c455b8bdd818b38739d0831 | BassP97/CTCI | /Easy/majorityElement.py | 610 | 4.0625 | 4 | """
Given an array of size n, find the majority element. The majority element is the element that
appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
"""
def... |
838b2e05a36c9c8df569a7c01e631711e6dba849 | BassP97/CTCI | /Med/shortEncoding.py | 716 | 4.40625 | 4 | """
Given a list of words, we may encode it by writing a reference string S and a list of indexes A.
For example, if the list of words is ["time", "me", "bell"], we can write it as S = "time#bell#"
and indexes = [0, 2, 5].
Then for each index, we will recover the word by reading from the reference string from that i... |
9e710a8c59dde38dca12f3f509b8596f0d42cdf2 | BassP97/CTCI | /Med/constructBSTFromArr.py | 659 | 4.0625 | 4 | """
Given an array where elements are sorted in ascending order, convert it to a
height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in
which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted array: [-10,-3,0,5,9],
One possib... |
f42be0825f831246d8fb0dae883522ca8281bbba | BassP97/CTCI | /2021 prep/zigZagOrder.py | 1,165 | 4.125 | 4 | """
Given a binary tree, return the zigzag level order traversal
of its nodes' values. (ie, from left to right, then right to
left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
... |
e645a0c57baa560ff297c37c7e9ded16d96c5234 | BassP97/CTCI | /Med/courseSchedule.py | 941 | 4.03125 | 4 | """
There are a total of numCourses prerequisites you have to take, labeled from 0 to numCourses-1.
Some prerequisites may have prerequisites, for example to take course 0 you have to
first take course 1, which is expressed as a pair: [0,1]
Given the total number of prerequisites and a list of prerequisite pairs, is ... |
ac57620920a1630805da46b6ddb5541a754a70c0 | BassP97/CTCI | /Med/keysAndRooms.py | 1,770 | 4.03125 | 4 | """
There are N rooms and you start in room 0. Each room has a distinct number in 0, 1, 2, ..., N-1,
and each room may have some keys to access the next room.
Formally, each room i has a list of keys rooms[i], and each key rooms[i][j] is an
integer in [0, 1, ..., N-1] where N = rooms.length. A key rooms[i][j] = v op... |
0ac46c87a68903e6340ed8545dc1c7fe6cbf10f3 | BassP97/CTCI | /2021 prep/searchRotatedArray.py | 1,926 | 3.90625 | 4 | """
You are given an integer array nums sorted in
ascending order (with distinct values), and an integer target.
Suppose that nums is rotated at some pivot unknown
to you beforehand (i.e., [0,1,2,4,5,6,7] might become
[5,6,7,0,1,2,4]).
If target is found in the array return its index, otherwise, return -1.
"""
impo... |
61039645bddbc9099af7f71213142a6afed5e81d | BassP97/CTCI | /Hard/minWindowSubstring.py | 3,209 | 3.921875 | 4 | """
Given a string S and a string T, find the minimum window in S which will contain
all the characters in T in complexity O(n).
Example:
Input: S = "ADOBECODEBANC", T = "ABC"
Output: "BANC"
"""
"""
#failed attempt
def minWindowSubstr(inputStr,toFind):
inputSet = {}
findSet = {}
for i in inputStr:
... |
26c13d5967797a8dbd118c174099395213d62b03 | BassP97/CTCI | /Easy/diameterOfBinaryTree.py | 636 | 4.15625 | 4 | """
Given a binary tree, you need to compute the length of the diameter of the tree.
The diameter of a binary tree is the length of the longest path between any two
nodes in a tree. This path may or may not pass through the root.
Note - too lazy to implement a real tree so logic will have to do
"""
class Solution(ob... |
c4fe608066ffe7caf64b458ad12c462164dadf35 | BassP97/CTCI | /Med/singleNum.py | 813 | 4.03125 | 4 | """
Given a non-empty array of integers, every element appears
twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity.
Could you implement it without using extra memory?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Outpu... |
721a58fcb536b1692f35c9337676f6855200c61e | BassP97/CTCI | /Med/validateBST.py | 1,034 | 4.15625 | 4 | """
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and righ... |
78cfee5429a1de9c87a75552a61ff45fb6490980 | BassP97/CTCI | /Easy/stocks.py | 866 | 3.71875 | 4 | """
Say you have an array for which the ith element is the price of a given stock on
day i.
If you were only permitted to complete at most one transaction (i.e., buy one
and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot sell a stock before you buy one.
"""
def mai... |
52da1aa788a000c4cf46022b97a18689904143b1 | BassP97/CTCI | /Med/startIndexAna.py | 963 | 3.65625 | 4 | """
Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.
Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
The order of output does not matter.
"""
from collections import Counter
def startAna(string, ana):
... |
f2c2334452be3317ad5527108a7fc8450430eec4 | BassP97/CTCI | /2021 prep/wordSearch.py | 2,747 | 3.90625 | 4 | """
Given an m x n board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells,
where "adjacent" cells are horizontally or vertically neighboring.
The same letter cell may not be used more than once.
"""
from collections import deque
def neighbors(i,... |
feeb3d229b5d34a73c2e4d98e818fb42442c7317 | SlavaGolovatskyu/Program-for-learning-english-words | /database/connect.py | 1,313 | 3.890625 | 4 | # imported "sqlite3" as a DataBase
# imported library "random" for the generation random number
import sqlite3
import random
class ManageDataBase:
def __init__(self): # def Initialization
# Connect to DB
self.db = sqlite3.connect('./database/sqlite.db')
# Take a cursor
self.s = self.db.cursor()
#... |
7eeb6216d5fb56ed73fe6667de37e05fb95379b3 | raghus100/Algorithm-Implementation | /String_Algorithms.py | 1,215 | 3.5625 | 4 | class Solution:
res = []
def permutate(self, soFar, rest):
if (len(rest) <=0):
print(soFar+rest)
self.res.append((soFar+rest))
return
else:
for i in range(len(rest)):
rest_string = rest[0:i]+rest[i+1:len(rest)]
self.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.