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 |
|---|---|---|---|---|---|---|
ddf570644ae74b247569a0f9a303abf2906f83b9 | Dagim3/MIS3640 | /factor.py | 381 | 4.25 | 4 | your_number = int(input("Pick a number:")) #Enter value
for factor in range( 1, your_number+1): #Range is from 1 to the entered number, +1 is used as the range function stops right before the last value
factors = your_number % factor == 0 #This runs to check that the entered number doesn't have a remainder
if ... |
b5f1597d8471bcc3344a043e289c0fb6004bf211 | Dagim3/MIS3640 | /101917.py | 205 | 3.9375 | 4 | s=[1,2,3,4]
for i in s:
print(s)
print('now we are removing',s.index(i))
s.remove(i)
print('after removing:',s)
for t in enumerate(s):
print('index:',t[0], 'item: ',t)
|
1d080de0156f5acd9f9a4aa5560cd1ff2c7975e0 | Dagim3/MIS3640 | /102417.py | 866 | 3.65625 | 4 | fout = open('output.txt','w')
line1 = 'How many roads must a man walk down\n'
fout.write(line1)
line2 = 'Before you call him a man?\n'
fout.write(line2)
fout.close()
import os
cwd = os.getcwd()
# cwd stands for '
# print (cwd)
print (os.path.abspath('output.txt'))
print (os.path.exists('output.txt'))
def walk(dirname... |
3df59ff6049246c715d31544df192d245fba4da6 | Dagim3/MIS3640 | /BMIcalc.py | 616 | 4.3125 | 4 | def calculate_bmi(Weight, Height):
BMI = 703* (Weight / (Height*Height))
if BMI>= 30:
print ('You are {}'.format(BMI))
print ('Obese')
elif BMI>= 25 and BMI< 29.9:
print ('You are {}'.format(BMI))
print ('Overweight')
elif BMI>= 18.5 and BMI<24.9:
print ('You a... |
bb22f3451916ab1a18e4b0ae7d8ee854e245cab0 | pamela-zhang/MovieLens-Visualization | /matrixfac_method1.py | 7,425 | 3.78125 | 4 | # First method of matrix factorization.
# (basically just the method from HW 5)
import numpy as np
import matplotlib.pyplot as plt
from helper import load_data, get_popular_best_movies
from sklearn.preprocessing import scale
def grad_U(Ui, Yij, Vj, reg, eta):
"""
Takes as input Ui (the ith row of U), a training p... |
69d1287d9328bb83dc8cd52f8a587a90a0614feb | derekdyer0309/interview_question_solutions | /Array Sequences/sentence_reversal.py | 1,416 | 4.40625 | 4 | """
Given a string of words, reverse all the words. For example:
Given:
'This is the best'
Return:
'best the is This'
As part of this exercise you should remove all leading and trailing whitespace. So that inputs such as:
' space here' and 'space here '
both become:
'here space'
###NOTE: DO NOT USE .re... |
4ba8df598a59c5f1ce1bdf81046b1719d447d277 | derekdyer0309/interview_question_solutions | /Strings/countingValleys.py | 964 | 4.21875 | 4 | import math
def countingValleys(steps, path):
#Make sure steps and len(path) are == or greater than zero
if steps == 0:
return 0
if len(path) == 0:
return 0
if steps != len(path):
return 0
#keep track of steps down, up, and valleys
sea_level = 0
steps = 0
valley... |
a6a55cd859f657b950a0c5f843a06af14bfdc123 | derekdyer0309/interview_question_solutions | /Linked Lists/singly_ll_cycle_check.py | 1,038 | 3.984375 | 4 | """
Given a singly linked list, write a function which takes in the
first node in a singly linked list and returns a boolean indicating
if the linked list contains a "cycle".
A cycle is when a node's next point actually points back to a
previous node in the list. This is also sometimes known as a circularly
linked... |
6f33e6f89a749dbcb2120a47497d8d30a155fce9 | TarunSaini063/Coding | /codeforces_python/1326_a.py | 172 | 3.609375 | 4 | t=int(input())
for _ in range(t):
n=int(input())
if n==1:
print(-1)
else:
for _ in range(n-1):
print(5,end="")
if ((n-1)*5+3)%3!=0:
print(3)
else: print(4) |
6002bb5e86333bf66ac79a1587d1963291581a36 | CleverCat07/tickets | /tiket0008.py | 456 | 3.953125 | 4 | def is_number(x):
try:
float(x)
return True
except ValueError:
return False
a = input("Enter a = ")
if not is_number(a):
print("Enter the number")
quit()
x = float(a)
if x < 0:
print("Enter a positive number")
quit()
b = ''
for i in a:
b = i + b
c = x-float(b)
... |
3f47deb9fae877f96c3a789cf39da595002a08c2 | CleverCat07/tickets | /Karina_dz2.py | 404 | 4.0625 | 4 | a = float(input("Введіть ціну морозива: "))
b = float(input("Введіть ціну газованої води: "))
s = a*3 + b*2
m = a*2 + b*3
if s == m:
print("Вони витратили однаково грошей")
else:
if s > m:
print("Стефані витратила більше")
else:
print("Михайло витратив більше") |
486fe9f537586f2ec80ba2390af18dec21edfe4c | CleverCat07/tickets | /Suma2.py | 78 | 3.59375 | 4 | a = int(input("Enter a "))
E=0
for N in range(0, a, 1):
E = E + N
print(E) |
e099d0fb47d76e3857523fc9f00289cb3e9844ee | joebuckley24/chess-2.0 | /screen.py | 3,017 | 3.640625 | 4 | from constants import *
def coord_to_index(coord_str):
coord = list(coord_str)
return (int(coord[1]) - 1, ord(coord[0].lower()) - 97)
def printable_board(board):
printable = ["| " + " | ".join(row) + " |" for row in reversed(board)]
return " " + "--- "*8 + "\n" + ("\n " + "--- "*8 + "\n").join(printab... |
441d01787f8ba1aa0ebb1f061ead886625e54d34 | Az1122/pi-scanner | /src/interface/LineFinder.py | 2,755 | 3.6875 | 4 | #!/usr/bin/python2
"""
This file contains all of the required classes and functions for extracting a laser line
from a given image and processing it into a collection of points.
"""
import cv2
import numpy as np
class Point3:
"""
Stores the XYZ values of a single point within the pointcloud
"""
def __... |
263e68a0b2b8a898b9f1fdd53f8ca930b29c2946 | natb1/coursera-algorithms | /1-1.py | 2,937 | 3.75 | 4 | def test_that_it_multiplies_small_numbers():
assert int(multiply('32', '64')) == 32 * 64
def test_that_it_multiplies_numbers_with_odd_digits():
assert int(multiply('333', '666')) == 333 * 666
def test_that_it_multiplies_numbers_with_1_digit():
assert int(multiply('2', '3')) == 2 * 3
def test_that_it_mult... |
0889a65e75e7f7c9f616da834aa9575320632bc1 | AdityaNarayan001/Learning_Python_Basics | /Python Basics/if_statement.py | 660 | 3.953125 | 4 | print('************IF STATEMENT*************')
is_hot = False
is_cold = False
if is_hot:
print('It is a hot day')
print('Drink plenty of water')
elif is_cold:
print('It is cold day')
print('Dont go out')
else:
print('Its a lovely day')
print('Enjoy Your Day')
print('******************TAS... |
5b08179675bca8d0be53cc754f0e8eaa6bb3d2ac | AdityaNarayan001/Learning_Python_Basics | /Python Basics/weight_converter.py | 440 | 4.125 | 4 | # Weight converter
type = input('To Enter weight in (L)Lbs or (KG)kilogram :- ')
if type.upper() == "L":
weight = int(input('Enter your Weight in Pound : '))
kg_weight = weight / 0.45
print('Your weight in Kg is ' + str(kg_weight) + ' Kg')
elif type.upper() == "KG":
weight = int(input('Enter yo... |
cfec8498e04543cf53aa8dfe146506130ec1b625 | AdityaNarayan001/Learning_Python_Basics | /Python Basics/random_dice.py | 213 | 3.578125 | 4 | import random
class Dice():
def roll(self):
x = (1, 2, 3, 4, 5, 6)
y = (1, 2, 3, 4, 5, 6)
print(f'({random.choice(x)}, {random.choice(y)})')
dice1 = Dice()
dice1.roll()
|
78eeae36c6f6496e4a0b2b0dfba2c1059213eb88 | JacobDreiling/googology | /Googology.py | 4,265 | 3.609375 | 4 | from time import sleep
from console import clear
def step(data,sweep=True,wait=0):
if sweep: clear()
print(data)
if wait: sleep(wait)
else: input()
#the length difference from factoring an expression S is (k-1)(n-1)-3.
#k is the number of occurrences of S and n is the length of S
#simplified Ackermann function: ω... |
acb3c73a5497db189795a56cea70fda0895ed9e5 | msinnema33/code-challenges | /Python/almostIncreasingSequence.py | 2,223 | 4.25 | 4 | def almostIncreasingSequence(sequence):
#Take out the edge cases
if len(sequence) <= 2:
return True
#Set up a new function to see if it's increasing sequence
def IncreasingSequence(test_sequence):
if len(test_sequence) == 2:
if test_sequence[0] < test_sequence[1]:
... |
fe03ae693ace3d4df9804c97dee16ff44f9f3002 | jayceazua/wallbreakers_work | /company/karat.py | 3,650 | 3.828125 | 4 | """
Given a board and an end position for the player,
write a function to determine if it is possible to travel from every open cell on the board to the given end position.
board1 = [
[ 0, 0, 0, 0, -1 ],
[ 0, -1, -1, 0, 0 ],
[ 0, 0, 0, 0, 0 ],
[ 0, -1, 0, 0, 0 ],
[ 0, 0, 0, 0, 0 ],
... |
a4ebbf063577cca9fd2e6f52987b22f708a12753 | jayceazua/wallbreakers_work | /practice_facebook/clone_graph.py | 2,052 | 3.875 | 4 | """
Given a reference of a node in a connected undirected graph,
return a deep copy (clone) of the graph. Each node in the graph
contains a val (int) and a list (List[Node]) of its neighbors.
Example:
Input:
{"$id":"1","neighbors":[{"$id":"2","neighbors":[{"$ref":"1"},
{"$id":"3","neighbors":[{"$ref":"2"},{"$i... |
912158b65cc5521cd32a8768c6176c5cacbb4f7c | jayceazua/wallbreakers_work | /data_structures/hash_table.py | 4,043 | 3.859375 | 4 | class HashEntry:
def __init__(self, key, data):
self.key = key
# data to be stored
self.value = data
# reference to new entry
self.nxt = None
class HashTable:
# Constructor
def __init__(self):
# Size of the HashTable
self.slots = 10
# Current... |
2d28b82586690a2413a9ffce64d460e3638e731f | jayceazua/wallbreakers_work | /company/google.py | 301 | 3.65625 | 4 | # input -> "aaAAFFfbCcgGGddDD"
# output -> "aAFbGdD"
def google(letters):
stack = []
for letter in letters:
if stack and stack[-1].lower() == letter.lower() and stack[-1] != letter:
stack.pop()
continue
stack.append(letter)
return "".join(stack)
google("abBcCcgGGGtTt")
|
ddf8ca44622b5881c833cc82bee07a88f21a4b35 | jayceazua/wallbreakers_work | /data_structures/graph.py | 4,254 | 4.375 | 4 | from linked_list import LinkedList
from queue import Queue
class Graph:
def __init__(self, vertices):
# Total number of vertices
self.vertices = vertices
# Defining a list which can hold multiple LinkedLists equal to the number of vertices in the graph
self.array = []
# Cre... |
96eb009a11129f84ea3bb1c98abbc7fc93c0937e | jayceazua/wallbreakers_work | /week_1/detect_cap.py | 1,407 | 4.4375 | 4 | """
Given a word, you need to judge whether the usage of capitals in it is right or not.
We define the usage of capitals in a word to be right when one of the following cases holds:
All letters in this word are capitals, like "USA".
All letters in this word are not capitals, like "leetcode".
Only the first letter in ... |
aa30e71156a9aa91289332cdf527376deda4eec0 | jayceazua/wallbreakers_work | /company/slack.py | 2,146 | 3.65625 | 4 | # you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(A, K, L):
# write your code in Python 3.6
"""
Test case:
A = [10,19,15]
K = 2
L = 2
Test case:
A = [6, 2, 4, 6, 3, 2, 7, 4]
K = 3;
... |
325c1a34c36080380709be79330a2ded62c4e4fe | jayceazua/wallbreakers_work | /practice_facebook/reverse_linked_list.py | 658 | 4.3125 | 4 | """
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
"""
def reverseList(head):
# if not head or not head.next:
# return head
# ... |
83aa02c1e5f13e596e4858f4d56f50acf6ccc559 | jayceazua/wallbreakers_work | /week_1/reverse_int.py | 1,049 | 4.21875 | 4 | """
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the pu... |
db18748f39f1d17bfbcf5e28daa511b4b49df53b | jayceazua/wallbreakers_work | /week_1/transpose_matrix.py | 1,179 | 4.28125 | 4 | """
Given a matrix A, return the transpose of A.
The transpose of a matrix is the matrix flipped over it's main diagonal, switching the row and column indices of the matrix.
Example 1:
Input:
[
[1,2,3],
[4,5,6],
[7,8,9]
]
Output: [[1,4,7],[2,5,8],[3,6,9]]
Example 2:
Input: [[1,2,3],[4,5,6]]
Output: ... |
74f71eb7050418cf85f9ce9c03ba9681f56f84eb | xuejingao/TechnicalInterviewPrep2020 | /assignments/week1/day5/Daniel_Zabari_PE_3.py | 931 | 3.890625 | 4 | import math
# This algorithm can be even further optimized, especially in the
# generate prime function.
def find_largest_prime(num):
primes = [2]
while num > 1:
# All prime numbers greater than the square root can be arrived at by
# dividing by smaller prime number.
greatest = math.sq... |
856471e7c728453b5626b5413503e7e92810c1fe | xuejingao/TechnicalInterviewPrep2020 | /assignments/week3/day1/Daniel_Zabari_LC_101.py | 531 | 3.71875 | 4 | class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if (root is None):
return True
return self.symmetrees(root.left, root.right)
def symmetrees(self, left: TreeNode, right: TreeNode)-> bool:
if ((left is None) or (right is None)):
return ((left is None... |
8c05cf6c225a14f05bc041485267a6a22bdb3929 | Crick25/First-Project | /First Project ✓.py | 908 | 4.15625 | 4 | #ask if like basketball, if yes display nba heights the same, if no ask if like football,
#if yes display football heights the same, if no to that print you boring cunt
#height from 5ft8 to 6ft5
myString = 'User'
print ("Hello " + myString)
name = input("What is your name?: ")
type(name)
print("Welcome, "... |
8bb2a8e1f22e4884cfebc81177ac66b47d05e6a7 | jmenchacavr/script-tut | /python/j20.arguments.py | 239 | 3.703125 | 4 | #!/usr/bin/python
import sys
print "The arugments passed are:"
for count in reversed(range(1,len(sys.argv))): # range operator to iterate to max arguments
print " item %d: %s" % (count,sys.argv[count]) # print count and 1st argument |
360d55e6897b8af6e5ed1de8b83937290ffc0baa | jmenchacavr/script-tut | /python/c00.arithmetic.py | 269 | 4 | 4 | #!/usr/bin/python
# integer arithmatic
width = 5
length = 6
area = width * length
print "The area of a square(width=%d, length=%d) is %d" % (width, length, area)
# bolean logic
result = True and False or True;
print "The statement (true AND false OR true) is", result |
13a2236ccb9c1568732cde0679f77b3968265128 | dillon-ward/PythonStuff | /Nul Points.py | 4,101 | 4.25 | 4 | # Import the random library so we can generate random integers with randint()
import random
# This function will return a random integer from 1 to 6
def RanNum():
return random.randint(0,5) + 1
# List of player scores
Score = []
# List of player names
Names = []
# Table of number of same value dice to points
Po... |
975e899398e9c026fdfe52d3c806583e6e34ffaf | dillon-ward/PythonStuff | /D_and_D.py | 822 | 3.53125 | 4 | file = open("D_and_D.txt","w")
Name = (input("Input the name of your character:"))
Race = (input("Input their race :"))
Class = (input("Input their class:"))
Age = int(input("Input their age:"))
Alignment = (input("Input their alignment:"))
Animal = (input("Input their animal (optional):"))
Origin = (input("Input thei... |
16e6ec87f118e98ee4d67ec27a2e891348977de2 | dillon-ward/PythonStuff | /email validation 2.py | 2,265 | 4.09375 | 4 | import string
emailok = False
while(not emailok):
email = input("Input your email:")
atcount = 0
for character in email:
if (character == '@'):
atcount += 1
if atcount ==0:
print ("Failed presence check, '@' needs to be included")
continue
elif atcount... |
f41b8dc0c69a15541a9c13636a709cfdeacf77b1 | iconocaust/csci102-wk11-git | /fibonacci.py | 592 | 4.21875 | 4 | # Galen Stevenson
# CSCI 101 - B
# WEEK 1 - LAB 1B
# fibonacci.py
def fib():
fibs = [1, 2]
for i in range(1,9):
'''
implement Fibonacci sequence to calculate the
first 10 Fibonacci numbers, note Fn = Fn-1 + Fn-2
'''
return fibs
def main():
print('OUTPUT', fib())
i... |
0bfd9b86efc1dde15d95e7888132c8b5a132b9bb | BlueJacket98/codesignal-challenges | /challenges/concatenateNumbers/python3/concatenateNumbers.py | 729 | 3.640625 | 4 | def concatenateNumbers(a, b):
return int(str(a) + str(b))
if __name__ == '__main__':
input0 = [23, 962]
input1 = [45, 12345]
expectedOutput = [2345, 96212345]
assert len(input0) == len(expectedOutput), '# input0 = {}, # expectedOutput = {}'.format(len(input0), len(expectedOutput))
assert len(input1) == len(expec... |
b44399613fe14c69a973594fe2c2426100d399c8 | edsilfer/algorithms | /python/util/sorting/merge.py | 1,045 | 4.09375 | 4 | # -*- coding: utf-8 -*-
# **************************************** #
# MERGE SORT ALGORITHM
# ---------------------------------------- #
# Description: sort in crescent order an #
# array of 'n' element; #
# #
# Time complexity: n log n ... |
6d0d0bebb7c3d2e7b1e51fa5f388dc81c63db0be | edsilfer/algorithms | /python/util/search/binary_search.py | 689 | 3.953125 | 4 | import os
import sys
import traceback
INPUT = [0, 1, 3, 5, 8, 15, 23, 32, 54, 100, 101, 102, 150, 200]
def binarySearch (array, target):
middle = len(array)/2
if array[middle] == target: return "yes"
if middle == 0: return "no"
if target > array[middle]:
result = binarySearch(array[middle + 1:], target)
elif... |
9f599e8d07b3c12779f8dca8d328731e26b0d0cf | linvis/leetcode | /dp/139_Word_Break/solu.py | 700 | 3.546875 | 4 |
# 题目:分个一个字符串,查找子串是否在一个列表里
# 思路:DP解,分割字符串 s[0:i] s[i:j],以此判断s[0:j]是否能够被分割
class Solution:
def wordBreak(self, s: str, wordDict):
hash_table = dict([(word, 1) for word in wordDict])
if not s:return True
m = len(s)
dp = [[0] * (m + 1) for _ in range(m + 1)]
dp[0][0] = 1
... |
618e74f04d5163b7c238f92afe87219ca2b8bcbc | linvis/leetcode | /hash/136_Single_Number/solu.py | 818 | 3.640625 | 4 |
# 题目:返回数组中只出现一次的元素
# 思路:hash
# 常规
class Solution:
def singleNumber(self, nums: List[int]) -> int:
hash_tab = {}
for n in nums:
if n not in hash_tab:
hash_tab[n] = 1
else:
hash_tab[n] += 1
for key, val in hash_tab... |
7620dee31cb11d76e6f94b8a375962aebd9324bc | linvis/leetcode | /tree/236_Lowest_Common_Ancestor_of_a_Binary_Tree/solu.py | 1,437 | 3.765625 | 4 |
# 题目:查找一个二叉树中,任意两个节点的最近公共祖先(LCA, the lowest common ancestor)
# 思路:DFS遍历找出两个节点,比较 O(N)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def dfs(self, root, p, q):
nu... |
b17fc8f9b983fc0d506a6d971085a4550ab6395a | linvis/leetcode | /linked_list/23_Merge_k_Sorted_Lists/solu.py | 1,656 | 3.65625 | 4 |
# 假设k个list,每个list长度为N
# 几种思路,
# 第一种,遍历所有list上的数据,然后排序,时间复杂度O(NlogN)
# 第二种,每次遍历k个list的head,合并,O(Nk),平均每个head要比较k次
# 第三种, divide and conquer,O(Nlogk)
# 很奇怪,我用的第三种,也是复杂度最低的,但是跑出来时间复杂度打败26%
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.nex... |
af625e1e79060f6fab4bb0036d73ed6f6c88425d | zedium/project-euler | /0003.py | 387 | 3.734375 | 4 | import math
original_number =600851475143
number = int(math.sqrt(original_number))
primes = []
def is_prime(number):
for i in range(2,int(math.sqrt(number))-1):
if(number % i == 0):
return False
return True
for i in range(2,number):
if(is_prime(i)):
primes.append(i)
for prime in reversed(primes):
... |
9d5c5b165cb48853763c47504c2765ef9dc8d3f6 | wchengsir/Python | /15_List.py | 546 | 3.984375 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
t = ['a','b','c','d','e']
print t[1:3]
print t[:4]
print t[3:]
print t[:]
print
list = [ 'runoob', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print list # 输出完整列表
print list[0] # 输出列表的第一个元素
print list[1:3] # 输出第二个至第三个元素
print... |
3523d9fe4c3b68ee5d7ca66de6efb38806eaa0fc | thaugdahl/eit-neural-network | /plotting.py | 4,938 | 3.734375 | 4 | import matplotlib.pyplot as plt
import numpy as np
from math import isnan
from sklearn.metrics import mean_squared_error
from settings import *
import scipy.stats as stats
def plot_prediction_accuracy(test_data, predictions, num_vars, title, labels=None):
"""
Plots a figure with graphs for the predicted data... |
5f0d3e5837cd98a06f4e0234d896f430ad4dc4e3 | houdinii/datacamp-data-engineering | /data-engineering/streamlined-data-ingestion-with-pandas/importing-data-from-flat-files.py | 1,550 | 4.25 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
def get_data_from_csvs():
"""
Get data from CSVs
In this exercise, you'll create a data frame from a CSV file. The United States makes available CSV files containing tax data by
ZIP or postal code, allowing us to analyze income ... |
5528635a9ca69d7430bf738da76c8ba178f8498b | houdinii/datacamp-data-engineering | /python/object-oriented-programming-in-python/integrating-with-standard-python.py | 4,624 | 4.3125 | 4 | """
In this chapter, you'll learn how to make sure that objects that store the same data are considered equal, how to define and
customize string representations of objects, and even how to create new error types. Through interactive exercises, you’ll learn
how to further customize your classes to make them work more l... |
b6ef68b3e4d01f1113ce7bcce9413c1ff82940fa | nadineo/python | /exam2017.py | 6,924 | 3.796875 | 4 | #! python3
# Exam.py - xxxxxx
'''
Brief structure:
- Read text from file1
- Build histogram of the words from file1
- Read text from file2
- Analyze the text from file2
'''
import os
import pprint
# Characters we would like to strip off, like dots and commas
stripCharacters = '.,'
#################... |
6c9d3112c9f2fea8cd126af6efd6480d282e6fb5 | daoos/Introduction-to-Mobile-Robotics-Solutions | /Sampling, Motion Models/Sampling_MotionModel.py | 3,776 | 3.9375 | 4 | '''
Exercise 1 : Implement three functions in Python which generate samples of a normal distri-
bution N (μ, σ 2 ). The input parameters of these functions should be the mean μ
and the variance σ 2 of the normal distribution. As only source of randomness, use
samples of a uniform distribution.
• In the first function, ... |
7e3a87ff13ae52a80c4491cc4a420b2df2ed2ac8 | kwahome/ud120-projects | /regression/finance_regression.py | 2,719 | 3.609375 | 4 | #!/usr/bin/python
"""
Starter code for the regression mini-project.
Loads up/formats a modified version of the dataset
(why modified? we've removed some trouble points
that you'll find yourself in the outliers mini-project).
Draws a little scatterplot of the training/testing data
You fi... |
343bd2eebf80463be77d126ba695151f09397ec8 | hualuojingye/TrajSeg | /Trajlib2/SegmentationAlgorithms/GRASP_UTS/old_code/prepare.py | 1,269 | 4 | 4 | import random
def randomize_array(ar):
"""
Randomizes the contents of an array
:param ar: Array to randomize
:return: A array with the values scrambled
"""
random.seed(a=1, version=2)
random_ar = []
while len(ar)>0:
index = random.randint(0,len(ar)-1)
random_ar.append(ar... |
3aa87d5b4ee2575422843502cb33036b6534b179 | shivansh19200/Binary-Tree | /binaryTree_test.py | 1,109 | 4.03125 | 4 | class Node:
def __init__(self,key):
self.left = None
self.right = None
self.val = key
def traversePreOrder(self):
print(self.val, end=" ")
if self.left:
self.left.traversePreOrder()
if self.right:
self.right.traversePreOrder()
... |
285bb28f78cf44e0157a274695eb0fd320bf059c | Ruixz/python-study | /crack-code/ch4.py | 2,691 | 4.03125 | 4 | #!/usr/bin/python
import sys
def check_height(root):
if root is None:
return 0
left_height = check_height(root.left)
if left_height == -1:
return -1
right_height = check_height(root.right)
if right_height == -1:
return -1
height_diff = left_height - right_height
if abs(height_diff) > 1:
... |
d03bf56d92b902fdd9c3e3d8158901b679343a73 | JiajiaLi04/Leetcode | /33. Search in Rotated Sorted Array.py | 841 | 3.828125 | 4 | class Solution:
def search(self, nums, target: int) -> int:
left = 0
right = len(nums) -1
while left<=right:
# middle = left + (right-left)//2
middle = (left + right) // 2
if nums[middle]==target:
return middle
if nums[middle]... |
19ade83a1573e416750af3e58168046cdc97d7ef | JiajiaLi04/Leetcode | /322. Coin Change.py | 1,950 | 3.6875 | 4 | # ## Dynamic programming
# ## the method of recursive
# # leetcode超出时间限制
# class Solution:
# def coinChange(self, coins, amount: int) -> int:
# def dp(amount):
# if amount==0:
# return 0
# if amount<0:
# return -1
# res= float("inf")
# ... |
8d0c1f7c331fda7b1cd3a6a54b8c4bf055ca2cd9 | JiajiaLi04/Leetcode | /preOrder_inOrder_postOrder.py | 3,552 | 3.578125 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
## stack:
class Solution:
# 先序打印二叉树(递归). preOrderTraverse前序遍历:根节点->左子树->右子树
# 1245367
def preOrderTraverse(self, node):
def pre(node):
if not node:
ret... |
4cb6ced5de1ffb717fb617b881d655510f508cd9 | Muneshyne/Python-Projects | /Abstractionassignment.py | 1,157 | 4.375 | 4 |
from abc import ABC, abstractmethod
class Mortgage(ABC):
def pay(self, amount):
print("Your savings account balance is: ",amount)
#this function is telling us to pass in an argument.
@abstractmethod
def payment(self, amount):
pass
class HomePayment(Mortga... |
592c24b9439f5fffd870dd5334f9f7452f4e18ad | Muneshyne/Python-Projects | /tutorials/Parentchildassignment.py | 687 | 3.875 | 4 |
class User:
name = "No Name Provided"
email = " "
password = "password123"
reciept_number = 10
class Customer(User):
area = "Retail", "Diner"
phone_reward = " "
class Employee(User):
address = " "
pay_rate = 15.00
"""
class Math:
def __init__(self, x, y... |
a817267dddf31260f35dd96ffaaa5dd25e71b8e4 | Martin-sys1983/git_practice | /games_of_chance.py | 5,702 | 4.03125 | 4 | import random
money = 100
def coin_flip(guess,bet):
global money
#intro
print("_________________________________")
print("You are playing 'Heads and Tails' ")
print("_________________________________")
#code is checking if bet is less than You have in your pool
if bet > money:
... |
99f1e3993878efb4d7b0b653eabe4d42c559e5eb | RanyellHenrique/exerciciosCourseraPython02 | /Lista de exercicios05/exercicio03.py | 288 | 3.953125 | 4 | def insertion_sort(lista):
ordenacao = False
while not ordenacao:
ordenacao = True
for i in range(len(lista) - 1):
if lista[i] > lista[i+1]:
lista[i], lista[i+1] = lista[i+1], lista[i]
ordenacao = False
return lista
|
7b3aad907476ee8d33d40650e6484c5432bc2810 | daianasousa/POO | /LISTA DE EXERCÍCIOS/Semana_02_postagem_extra_Q02.py | 2,178 | 3.84375 | 4 | class Bicicleta:
#atributos
peso = None
altura = None
veloc_atual = 0
cor = None
aro = None
altura_cela = 0
calibragem_pneus = 0
#métodos
def pedalar(self):
veloc_max = 15
self.veloc_atual += 1
if self.veloc_atual > veloc_max:
print('Você pass... |
a28b8f083f4a59f13d7c792640b2285dd8590166 | MrLW/python | /chapter_09/demo05.py | 400 | 3.515625 | 4 | class Rectangle:
def __init__(self):
self.width = 0
self.height = 0
def __setattr__(self, key, value):
if key == 'size':
self.width ,self.height = value
else:
self.__dict__[key] = value
def __getattr__(self, key):
if key == 'size':
... |
91b1fd429f58ed0ffa50f6cc3053512e28cc2f95 | MrLW/python | /chapter_09/demo08_推导试.py | 893 | 3.828125 | 4 | # 这个前面已经学习过,列表推导
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
b = [x ** 2 for x in a if x % 2 == 0]
print(b)
# 生成器推导
g = ((i + 2) ** 2 for i in range(2, 27))
next(g) # 16
it = iter([1, 2, 3, 4, 5])
# 循环:
while True:
try:
x = next(it)
print(x)
except StopIteration:
# 遇到StopIteration就退出循环
... |
e8d6ed121049b551a3c8ecce3d7d64358317c7ed | MrLW/python | /chapter_07/demo08_abstractclass.py | 298 | 3.53125 | 4 | # 抽象基类
from abc import ABC,abstractmethod
class Talker(ABC):
# 使用@abstractmethod装饰talk,表明是一个抽象方法
@abstractmethod
def talk(selfs):
pass
# 派生子类
class Knigget(Talker):
def talk(selfs):
print('Hi')
class Herring :
pass ;
|
bc0ffff09955ac29454d2193c38de89025afe25c | MrLW/python | /chapter_05/demo02.py | 215 | 4.25 | 4 | name = input('what is your name ?')
if name.endswith('Bob'):
print("Hello Mr.Bob")
else:
print("Hello LiWen")
# python的三目运算符
status = 'friend' if name.endswith("Bob") else "liwen"
print(status)
|
142202f5d32c173e10a49758ea120aad07bfc5a5 | b-junkoo/Misc-Work | /MIT edX Lecture Exercises/NumberGuessingGame.py | 906 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 15 12:40:38 2020
Asks user for number between 0 and 100
Program then uses bisection search to guess their number
Program has an infinite number of tries
@author: Jun
"""
low = 0
high = 100
ans = round((high + low)/2)
print("Please think of a number between 0... |
f33b852c38cc2e3cf9d0d93b555bcbda6198dac4 | b-junkoo/Misc-Work | /MIT edX Lecture Exercises/polysum.py | 294 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 18 19:33:10 2020
sums the perimeter squared and area of any regular polygon
@author: Jun
"""
import math
def polysum(n,s):
area = (0.25*n*s**2)/(math.tan(math.pi/n))
peri = (n*s)**2
sum = round(area + peri, 4)
return sum |
3753f5084c98875e56b404e01c857cb83db4147c | davidmokken/dataprocessing | /Homework/Week_4/converter.py | 658 | 3.84375 | 4 | # Name: David Mokken
# Student Number: 10770798
# Purpose of the file: Converts the csv data into json
import csv
import pandas as pd
import json
def load_data(filename):
"""
Load csv data into pandas
"""
# Load the necessary columns from the csv into pandas
data = pd.read_csv(filename, usecols =... |
e4734a8d93a06bac311d4d017fc4cef649c24b71 | AshwiniR97/ECE6258---Pokemon-Classification | /binary_threshold.py | 4,630 | 3.59375 | 4 | """
ECE 6258
Digital Image Processing
Final Project
Stephanie Sagun, Ashwini Rajasekhar, Dominick Freeman
This file includes functions to perform binary thresholding on each of
the images and store them in the binary_data directory... |
bdeea3aab675d4ca5b2821a0564b6cb85b49bb47 | jnell01/JamesRepo- | /sudoku.py | 6,041 | 3.875 | 4 | "Author: James Hakan Nell"
"This is a sudoku solver program"
def read_sudoku(file): #reads in sudoku problem from notepad text file.
stream = open(file)
data = stream.readlines()
stream.close()
return eval("".join(data))
def convertToSets(problem): #returns a list of the problems, but as a list contai... |
aba32b45b8c281046f638e0ec63f9cab6aa25de2 | shubhkamble26/HackerRank-Solutions | /HackerRank-10-Days-Statistics/Day 0/Day_0_Mean_Median_and_Mode.py | 464 | 3.859375 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
num_of_elements=int(input())
lst=list(map(int,input().split()))
#Mean
mean= sum(lst)/num_of_elements
print(mean)
#Median
if(num_of_elements%2==1):
median=sorted(lst)[int(num_of_elements/2)]
else:
median=(sorted(lst)[int(num_of_e... |
bfbecbfb8d479481aa63aa57433d8eef926ee6d3 | thijsdijkwel/small-practice | /baby-name-generator.py | 2,425 | 4.0625 | 4 | import string
# print (help(string)) if you want to see what it does
print(string.ascii_letters)
print(string.ascii_lowercase)
import random
#print(random.choice('pull a letter from here'))
#print(random.choice(string.ascii_lowercase))
def generator():
letter1 = random.choice(string.ascii_lowercase)
letter2 = rando... |
f790462502c51790a3bdf100851f077b2d86c223 | Dudu-Lucky/2019SummerLeetcode | /Yifan/week-1/5.longest-palindromic-substring.py | 747 | 3.578125 | 4 | #
# @lc app=leetcode id=5 lang=python3
#
# [5] Longest Palindromic Substring
#
class Solution:
def longestPalindrome(self, s: str) -> str:
if not s:
return s
result = s[0]
for i in range(len(s)):
idx = s[i:].rfind(s[i])
while idx>=0:
... |
e7919b67ca8e10731507bcc661024a9248e9b1a8 | Dudu-Lucky/2019SummerLeetcode | /Yifan/week-1/17.letter-combinations-of-a-phone-number.py | 812 | 3.625 | 4 | #
# @lc app=leetcode id=17 lang=python3
#
# [17] Letter Combinations of a Phone Number
#
class Solution:
def letterCombinations(self, digits: str):
map_dict = {
'2': ['a', 'b', 'c'],
'3': ['d', 'e', 'f'],
'4': ['g', 'h', 'i'],
'5': ['j', 'k', 'l'],
... |
72b4954bb2953b608d71c2592e22c8193cda1a51 | archanagottipaty/JAVA | /Documents/python_stack/my_environments/py3Env/Users.py | 2,945 | 4.0625 | 4 | class User: # here's what we have so far
def __init__(self, name, email):
self.name = name
self.email = email
self.account_balance = 0
# adding the deposit method
def make_deposit(self, amount): # takes an argument that is the amount of the deposit
self.account_balance += amoun... |
e7951a9a5c2e97910fac894db299a5077ebc9976 | archanagottipaty/JAVA | /Documents/python_stack/flask/flask_fundamentals/hello_flask/python2.py | 112 | 3.671875 | 4 | myarr = []
mytext='35'
print(mytext)
print(int(mytext))
for i in range(5):
print(i)
#myarr[i]=5
|
90dec954a5752d9fa1bfb3dd6f208c5e4dbb29fd | XuKaze/NYCdatascience | /hw6/hw6.py | 9,956 | 3.5625 | 4 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from sklearn.datasets.samples_generator import make_blobs
from numpy.random import shuffle
from random import choice
# Create the training data
np.random.seed(2)
X, y = make_blobs(n_samples=300,cluster_std=.25, centers=np.array([(-3,1),(0,2),... |
693690e529f8b87705226813946fce53b7bc85f7 | joescathbert/GUVIhiya | /roman.py | 561 | 3.765625 | 4 | a = input().upper()
if a == "I":
print(1)
elif a == "II":
print(2)
elif a == "III":
print(3)
elif a == "IV":
print(4)
elif a == "V":
print(5)
elif a == "VI":
print(6)
elif a == "VII":
print(7)
elif a == "VIII":
print(8)
elif a == "IX":
print(9)
elif a == "X":
print(10)
elif a == "XI":
print(11)
elif a == "XI... |
5bb919b2fe31c029127e305edfe2b839b63763e3 | Kanika-Mittal15/RecursionProblems | /product of no.s in array.py | 306 | 3.71875 | 4 | def product(arr):
if len(arr)==0:
return 0
elif len(arr)==1:
return arr[0]
else:
return arr[len(arr)-1]*product(arr[:len(arr)-1])
# number of elemetns as input
n = int(input("Enter number of elements : "))
arr = list(map(int,input().split()))[:n]
print(product(arr)) |
42c2708eb906649570682fee8f46a5e05b5788de | ramonlimaramos/python_design_patterns | /State/orcamento.py | 4,480 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding=utf-8 -*-
from abc import ABCMeta, abstractmethod
class Estado_Orcamento(object):
__metaclass__ = ABCMeta
def __init__(self):
self.desconto_aplicado = False
@abstractmethod
def aplica_desconto_extra(self, orcamento): pass
@abstr... |
9af398edef71bcbbc273708ef99f7e100edd76c2 | WallNutss/funProject | /Project ATM/customer.py | 476 | 3.546875 | 4 | class customerList:
def __init__(self, name, defPIN, defBalance, randomCustomerCard):
self.name = name
self.defPIN = defPIN
self.defBalance = defBalance
self.randomCustomerCard = randomCustomerCard
def searching(numberdata,dataCard, dataPIN):
for i, j in enumerate(nu... |
ead067f829c2c212b3711c6a7af34dbda6b47f24 | vahric/pythoncodeexamples | /logging/logger_test1.py | 648 | 3.59375 | 4 |
# Instead of print to log something use python powerfull logging module
# Load the module
import logging
#basicConfig help us describe log level , log format , log file name
# set file name , file mode append and show only INFO, WARNING, ERROR or CRITICAL message not DEBUGed ones.
# if no any basicConfig described t... |
7eb969c50bcb0c462c0711f044891b0a6f4bfe58 | mgardiner1354/CIS470 | /exam1_Q21.py | 911 | 4.21875 | 4 | import pandas as pd
#Without using pandas, write a for loop that calculates the average salary of 2020 Public Safety per division of workers in the Cambridge Data Set#
import csv #adding csv library
total_salary = 0 #defining total salary across all employees
emp_count = 0 #defining how many employees work at ... |
3038118b1bff47bbec1967bdb6c96ea990d2ec00 | unknown095/Random-codes | /next line functino after every sign.py | 1,104 | 3.625 | 4 | #using pycharm with input and output file in pycharm
import os #import OS module
text_to_find=str("-") #search string
text_to_replace=str("\n-") #replace string
sourcepath=os.listdir('InputFiles/') #source path
for file in sourcepa... |
0c80b79f09cd6432d4741ba8f9ad7fdfacc339ac | firstlord15/Python | /Уроки/Asik.py | 159 | 4.0625 | 4 | def factorial(n):
if n == 1:
return 1
else:
return factorial(n-1)*n
Chislo = int(input("Введите значение n: "))
print(factorial(Chislo)) |
2364b5b39d859264a501a8ec240075ea48238fad | Tainted-Fool/Portfolio | /Python/flow_book.py | 2,067 | 4.03125 | 4 | # CODE FROM BOOK:
counter = 1
while counter <= 5:
print("Hello, world")
counter = counter + 1 # you can use counter += 1 like java/C++
## NOTE you should always use 4 spaces to indent or set up your editor to insert
## 4 spaces when you type a tab, pyCharm has this a default
# you can use complex boolean exp... |
1726208b866936a90a8d105a22029006818a35b2 | Tainted-Fool/Portfolio | /Python/dict.py | 1,288 | 3.890625 | 4 | # dictionary (the dict type)
# { key1: value1, key2: value2, etc }
color_values = {'red': (1.0, 0.0, 0.0),
'green': (0.0, 1.0, 0.0), # you extend a statement to
'blue': (0.0, 0.0, 1.0), # multiple lines
'black': (0.0, 0.0, 0.0), # in many cases
'whi... |
7e88bd2df676007770ac42a7b42570a4a637f24c | saarku/fig-explorer | /pre-processing/utils.py | 3,722 | 3.71875 | 4 | """Different utilities for processing textual data"""
import re
def read_lines_from_file(input_dir):
"""Read text file and put its lines in a list.
Args:
input_dir: (string) input directory.
Returns:
(list). The file lines.
"""
lines = []
with open(input_dir, 'r') as input_file:
... |
b81058f2ed307ab8e277e6500150e8006924191f | binchoo/NER-RESEARCH | /preprocess/replacement.py | 151 | 3.625 | 4 | import re
def replace_digit(text, to='0'):
return re.sub("\d", to, text)
def replace_alphabet(text, to='a'):
return re.sub("[a-Z]", to, text) |
b3388de73565d60531f4105d819436891be370d4 | N02734910/ELSpring2015 | /code/logTemperature.py | 740 | 3.734375 | 4 | #!/usr/bin/python
import os
import time
import sqlite3
import sys
""" Log Current Time, Temperature in Celsius and Fahrenheit
Returns a list [time, tempC, tempF] """
def readTemp():
tempfile = open("/sys/bus/w1/devices/28-000006979949/w1_slave")
tempfile_text = tempfile.read()
currentTime=time.strftime('%x %X %Z')... |
953c78369d09930d78e25b1e0ba4b9512b63a2e8 | nnnazek/ICT | /lab2/10.py | 114 | 3.765625 | 4 | n=int(input())
print("All the squares in the given range are:")
print([i**2 for i in range(1,n+1) if i**2 <= n]) |
fc1420286dbd736c64480320baf128f9570f2175 | nnnazek/ICT | /lab2/12.py | 74 | 3.53125 | 4 | n = int(input())
i = 1
while n >= 2**i:
i += 1
print(2**(i-1)) |
64b1d6d12972612ed4ecac23863ed732fd5c237f | agony30/HW-Python-1 | /lesson02/home_work/hw02_normal.py | 3,429 | 3.71875 | 4 | # Задача-1:
# Дан список, заполненный произвольными целыми числами, получите новый список,
# элементами которого будут квадратные корни элементов исходного списка,
# но только если результаты извлечения корня не имеют десятичной части и
# если такой корень вообще можно извлечь
# Пример: Дано: [2, -5, 8, 9, -25, 25, 4] ... |
e33a5ff956be5a20c8d98300f96f1b6a7bf4b0e7 | heldersepu/hs-scripts | /Python/sumOfMultiples.py | 321 | 3.53125 | 4 | def solutionL(N):
s = 0
for i in range(N+1):
if (i % 3 == 0) or (i % 5 == 0):
s += i
return s
def solutionC(N):
def fsum(N, F):
n = (N // F) * F
return (n + F) * (n//F)//2
return fsum(N, 3) + fsum(N, 5) - fsum(N, 15)
print(solutionL(151))
print(solutionC(151))... |
7b399ee9e97c795082f93f5e6f83eb6f9c20acce | heldersepu/hs-scripts | /Python/tkinter/canvas.py | 925 | 3.671875 | 4 | from tkinter import Tk, Frame, Button, Canvas
class MyCanvas:
def __init__(self):
window = Tk()
window.title("Canvas")
self.canvas = Canvas(window, width = 200, height = 100, bg = "white")
self.canvas.pack()
frame = Frame(window)
frame.pack()
btRectangle = ... |
8842eedd9e63a03c1c13af02f1474107bf87f545 | ananyajana/Google_Code_Jam | /inconstant_ordering_2021.py | 6,551 | 3.71875 | 4 | from collections import OrderedDict
T = int(input())
n_list =[]
num_list =[]
for t in range(T):
x = int(input())
n_list.append(x)
y = input().split()
y = [int(y[i]) for i in range(len(y))]
num_list.append(y)
''' find the alphabetically first valid string '''
# alphabetically first valid string mea... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.