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 |
|---|---|---|---|---|---|---|
d04d77f606ee354fc990d98ad52d498af91c44d4 | Unknown-Flyin-Wayfarer/pycodes | /8/calc.py | 740 | 4.09375 | 4 | print("Please select your desired operation")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
ab = int(input("enter your choice"))
a = int(input("Enter first no"))
b = int(input("Enter second no"))
if ab == 1:
print("you've chosen additon")
c = a + b
... |
511fa02ea8117ddecccc953b69673374d5312ac4 | vainya/python-projects | /Collatz conjecture.py | 601 | 3.625 | 4 |
# Mystery computation in Python
# Takes input n and computes output named result
import simplegui
num = 217
def get_next(current):
if current%2 ==0:
return current/2
else:
return current*3+1
#print num
#print get_next(num)
# timer callback
def update():
global nu... |
523a41fe31e29bc3e1e877c17a9c5b1fa59383b4 | burnsjordan/Project-Euler | /26-50/50.py | 484 | 3.625 | 4 | import math
def is_prime(n):
for i in range(2,int(math.sqrt(n))+1):
if(n % i == 0):
return False
else:
return True
primes = []
for i in range(2,1000000):
if(is_prime(i)):
primes.append(i)
i = 600
not_done = True
while i > 90 and not_done:
print(i)
for j in ran... |
7eb9ed956e034839b3b4233b050c58b822047c99 | Abhisheknakka/python | /array2.py | 264 | 3.96875 | 4 | from array import *
from math import *
arr1=array('i',[])
n=int(input("Enter the length of array"))
for i in range (n):
x=int(input("Enter your numbers"))
arr1.append(x)
print(arr1)
arr2=array(arr1.typecode,(x**3 for x in arr1))
print(arr2)
|
fa16985c531d37a2a302f0d7d5a7d088656958d7 | aaroncymor/python-data-structures-and-algorithms | /Search and Sort/sequential_search.py | 298 | 3.796875 | 4 | def seq_search(arr,ele):
"""
Sequential search O(n)
"""
pos = 0 #position
found = False
while pos < len(arr) and not found:
#print pos
if arr[pos] == ele:
found = True
else:
pos += 1
return found
print seq_search([1,2,3,4,5],3)
print seq_search([1,2,3,4,5],2.2) |
4099dc1356c855ae88c54f21b43994b1daa37aa7 | aaroncymor/python-data-structures-and-algorithms | /Recursion/change_making_problem.py | 2,077 | 3.921875 | 4 | def _get_change_making_matrix(set_of_coins,r):
m = [[0 for _ in range(r + 1)] for _ in range(len(set_of_coins) + 1)]
for i in range(r + 1):
m[0][i] = i
return m
def change_making(coins, n):
"""This function assumes that all coins are available infinitely.
n is the number that we need to obtain with ... |
7bfc463f05d5555ea2df2b2ca7d36a5a3e5d1d64 | aaroncymor/python-data-structures-and-algorithms | /Search and Sort/sort_implementation.py | 1,094 | 4.125 | 4 | # Hello World program in Python
def bubblesort(arr):
for i in range(len(arr)-1,0,-1):
for j in range(i):
if arr[j] > arr[j+1]:
temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
return arr
def insertionsort(arr):
for i in range(1... |
ee2a75edd19267ce2f97c7aa89b87dd966729987 | Developerguy3/cool_scripts | /randome picker/randome_picker.py | 357 | 3.84375 | 4 | from random import randint
print( "how many option do you want to enter:-" )
size = int(input())
print("enter the your choices:-")
lists = []
for item in range(size):
x = input(f"enter the {item+1} value:-")
lists.append(x)
genrater = randint(0,size)
for i in range(size):
if genrater == i:
ans = l... |
833e4d739628165a496e59310ae24073b9a69c0e | Pegasids/VehicleRegistrationDatabaseManagementSystem | /Search_Functions.py | 11,864 | 3.984375 | 4 | # Avery Tan, Canopus Tong, Nathan Nguyen
#Project 1 CMPUT291
def Search1(curs, connection):
'''
List the name, licence_no, addr, birthday, driving class, driving_condition,
and the expiring_data of a driver by entering either a licence_no or a given name.
It shall display all the entries if a duplicate n... |
9a68d37bcd367d32831c162185ea0a0030720c22 | CSEA-IITB/WriteUps | /2020/redpwn/crypto/primimity/primimity.py | 858 | 4.0625 | 4 | #!/usr/bin/env python3
from Crypto.Util.number import getRandomNBitInteger, isPrime
def find_next_prime(n):
if n <= 1:
return 2
elif n == 2:
return 3
else:
if n % 2 == 0:
n += 1
else:
n += 2
while not isPrime(n):
n += 2
re... |
cee778ccb7af76d45d2becc80a46ff1901c71394 | dmjz/scrabble_search | /word_search/searchUtils.py | 2,673 | 3.703125 | 4 | import os
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug('Loading dictionary (word_list_2015.txt)...')
with open(os.path.join(os.getcwd(), 'word_search', 'word_list_2015.txt')) as f:
wordList = [line.rstrip() for line in f]
def removeNonAlpha(word):
"""Remove non-alphabetical char... |
a44818a716d223673bb5f3f774fe2b0ad9fa271f | matthewa313/pyEpilepsy | /pyepilepsy/hjorth_parameters.py | 804 | 3.765625 | 4 | def hjorth(sig):
""" Compute Hjorth mobility and complexity of a time series from either two
cases below:
1. X, the time series of type list (default)
Notes
-----
Computed activity, mobility and complexity together to minimize CPU time.
Parameters
----------
sig
... |
e0622163402f580a65518211eb3378994a15bec2 | rajeshpillai/learnpythonhardway | /ex9.py | 717 | 4.1875 | 4 | # Exercise 9: Printing, Printing, Printing
# By now you should realize the pattern for this book is to use more than one
# exercise to teach you something new. I start with code that you might not
# understand, then more exercises explain the concept. If you don't understand something now,
# you will later as you co... |
e4288c0c6d4b3d2decad9a22a96a79fe8b9502b7 | rajeshpillai/learnpythonhardway | /ex31.py | 2,038 | 4.59375 | 5 | # Exercise 32: Loops and Lists
# You should now be able to do some programs that are much more interesting. If you have been keeping up, you should realize that now you can combine all the other things you have learned with if-statements and boolean expressions to make your programs do smart things.
# However, program... |
3e46fd1199ef89e4f3af2e4bb07acdedf5c593d2 | rajeshpillai/learnpythonhardway | /ex40.py | 7,661 | 4.4375 | 4 | # Exercise 40: Modules, Classes, and Objects
# Python is called an "object-oriented programming language." This means there is a construct in Python called a class that lets you structure your software in a particular way. Using classes, you can add consistency to your programs so that they can be used in a cleaner way... |
e3dce1801071735e8d1d7231e0575d60fd277531 | falian0012/fourthHomeworkRepository | /Task_5/task_5.py | 169 | 3.515625 | 4 | from functools import reduce
initial_list = [item for item in range(100, 1002, 2)]
summary = reduce(lambda x, y: x * y, initial_list)
print(f'summary is : {summary}') |
2800672d2484a93ecbd9660f12d8534412994fe7 | mauriceLC92/LeetCode-solutions | /Binary-search/Binary-search.py | 608 | 3.9375 | 4 | def binary_search(inputArr, target):
lowest_position = 0
highest_position = len(inputArr) - 1
while lowest_position <= highest_position:
middle_position = lowest_position + (highest_position - lowest_position) // 2
guess = inputArr[middle_position]
if guess == target:
r... |
1b1c7cec5d9a5b99607fb4fc9fb4d8865adb356b | mauriceLC92/LeetCode-solutions | /Linked-lists/83-Remove-Duplicates-from-Sorted-List.py | 576 | 3.890625 | 4 | """
Given the head of a sorted linked list, delete all duplicates such that each element appears only once.
Return the linked list sorted as well.
"""
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def deleteDuplicates(head: ListNode) -> ListNode:
if he... |
b6350d9fb8134ecb5fa0d840315140af1c905978 | mauriceLC92/LeetCode-solutions | /Arrays/Selection-sort.py | 607 | 4.125 | 4 | def find_smallest(arr):
smallestIndex = 0
smallestValue = arr[smallestIndex]
index = 1
while index < len(arr):
if arr[index] < smallestValue:
smallestValue = arr[index]
smallestIndex = index
index += 1
return smallestIndex
def selection_sort(arr):
so... |
d74cf0e347fcd6b9cb3186575ced2871e776c6a8 | TheSirLancelot/NCWDG | /pyEcho/client.py | 908 | 3.515625 | 4 | #!/usr/bin/python
from sys import *
import socket
msgTo = ""
msgFrom = ""
if len(argv) != 3:
print "Usage: ./client.py [ip] [port]"
else:
try:
socket.inet_aton(argv[1])
ip = argv[1]
except:
print "Not a legitimate IP address"
exit(0)
if (argv[2].isdigit()) and (int(arg... |
bd8c464c493f294ed0bb3fafb9eb4294c7d27369 | Nobody0321/MyCodes | /OJ/LeetCode/20. Valid Parentheses.py | 751 | 3.90625 | 4 | class Solution:
# 核心思想是实现一个栈
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
v = []
start = ['(','[','{']
for i in range(len(s)):
if s[i] in start:
v.append(s[i])
continue
elif s[i] == ')':
... |
3d69fa7767453ed44ee429bb2bb839dbc3be65a1 | Nobody0321/MyCodes | /OJ/剑指Offer/二叉搜索树的后序遍历序列.py | 733 | 3.6875 | 4 | class Solution:
def VerifySquenceOfBST(self, sequence):
# write code here
if not sequence:
return False
root = sequence[-1]
l = len(sequence)-1
i = 0
for i in range(l):
if sequence[i] > root:
break
for j in range(l-1):
... |
a72244ff5bcc1e712588ab48969223d1b9970171 | Nobody0321/MyCodes | /OJ/LeetCode/110. Balanced Binary Tree.py | 845 | 3.8125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
re... |
404daeff50a0cb6ed3f34cc39f96db1216d731cc | Nobody0321/MyCodes | /OJ/剑指Offer/数值的整数次方.py | 452 | 3.8125 | 4 | class Solution:
def Power(self, base, exponent):
ret = 1
flag = exponent > 0 # 有可能有负指数
exponent = abs(exponent)
while exponent > 0:
if exponent % 2 ==1:
ret = ret * base
base *= base # base 用来计算每一位对应的乘子
exponent >>= 1
... |
c1bbaaac57480b47c53ae46ca58fc143acf71e76 | Nobody0321/MyCodes | /OJ/LeetCode/88. Merge Sorted Array.py | 953 | 4 | 4 | # 这题主要是没有看清楚题目要求,要求这个函数没有返回值,直接修改nums1就行
class Solution:
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
temp = []... |
d906c5383125924b3d37a201e647e57cd2fe8172 | Nobody0321/MyCodes | /OJ/LeetCode/27. Remove Element.py | 447 | 3.609375 | 4 | class Solution:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
lenth = len(nums)
j = 0
for i in range(0,lenth):
if nums[i] == val:
continue
nums[j] = nums[i]
... |
44b207461051e2bb180b56db6222979a6902f3d3 | Nobody0321/MyCodes | /OJ/LeetCode/35. Search Insert Position .py | 560 | 3.984375 | 4 | class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if target in nums:
return nums.index(target)
lenth = len(nums)
if target < nums[0]:
return 0
if target > n... |
ff77d83c0081dfb8240ff3bfa138c169b792dddb | Nobody0321/MyCodes | /OJ/剑指Offer/矩阵中的路径.py | 1,390 | 3.65625 | 4 | # 使用一个矩阵记录当前节点是否已访问,然后不断回溯,注意边界条件即可。与小米面试的n sum 类似
class Solution:
def hasPath(self, matrix, rows, cols, path):
# write code here
i = 0
m = []
for _ in range(rows):
m.append(matrix[i:i+cols])
i += cols
matrix = m
self.visited = [[0] * cols for... |
ab78d58a7e5f36c3a79de9035801bcc1b27b3b04 | Nobody0321/MyCodes | /OJ/剑指Offer/不用加减乘除做加法.py | 317 | 3.921875 | 4 | # 两数相加,相当于进位值与非进位值相加
class Solution:
def Add(self, num1, num2):
# write code here
while num2!=0:
num2, num1 = (num1&num2)<<1, num1^num2 # 非进位部分, 进位部分
return num1
if __name__ == "__main__":
print(Solution().Add(5,7)) |
7f2ddcbc21c66ce739f74cf238339e5c1e6cb751 | Nobody0321/MyCodes | /OJ/剑指Offer/构建乘积数组.py | 895 | 3.625 | 4 | class Solution:
# # 解法1 O(N^2)
# def multiply(self, A):
# return [self.mul(i,A) for i in range(len(A)) ]
# def mul(self,i,A):
# s = 1
# for idx, num in enumerate(A):
# if idx == i:
# continue
# s *= num
# return s
# 解法2 每一个B[i]都是A... |
e0d62d872caf998ac66d928dd6f50db5671609dd | Nobody0321/MyCodes | /OJ/sort.py | 4,703 | 3.6875 | 4 | def radix_sort(nums, radix=10):
"""a为整数列表, radix为基数"""
exp = 1
for i in range(1, K+1): # K次循环
bucket = [[] for j in range(radix)] # 不能用 [[]]*radix,否则相当于开了radix个完全相同的list对象
for val in nums:
bucket[val%(radix**i)//(radix**(i-1))].append(val) # 獲得整數第K位數字 (從低到高)
del nums[:]
... |
e64a8783941c734247b4b22b8faa21f6167e1405 | Nobody0321/MyCodes | /OJ/LeetCode/56. Merge Intervals.py | 455 | 3.59375 | 4 | class Solution:
def merge(self, intervals):
ret = []
print(sorted(intervals, key=lambda x:x[0]))
for each in sorted(intervals, key=lambda x:x[0]):
print(each)
if ret and ret[-1][1] >= each[0]:
ret[-1][1] = max(each[1], ret[-1][1])
else:
... |
9651801eac724ee97e018e526ae3ae233c1d9fcb | Nobody0321/MyCodes | /OJ/剑指Offer/替换空格.py | 1,270 | 3.921875 | 4 | # 题目描述
# 请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
# 思路:
# 正向查找替换的话,"%20"是三个字符,替换" "这一个字符就会覆盖后面的两个字符,使用两个字符串的话又会造成额外的空间开销
# 为了尽可能减少开销,我们先计算替换后的总长度,然后倒序替换,这样在替换的过程中也不会覆盖原字符,可以达到in_place的效果
class Solution:
# s 源字符串
def replaceSpace(self, s):
newLen = 0
space... |
eb761ee2c68c1a76d864a55d063c595d1ee2f07a | Nobody0321/MyCodes | /OJ/剑指Offer/包含min函数的栈.py | 496 | 3.53125 | 4 | class Solution:
def __init__(self):
self.stack = []
def push(self, node):
# write code here
if self.stack == []:
self.stack.append((node, node))
else:
m = self.stack[-1][-1]
m = m if m < node else node
self.stack.append((node, m))
... |
f347c982565b50103b0f13e5f12f52f2eb033f3f | Nobody0321/MyCodes | /OJ/剑指Offer/从上往下打印二叉树.py | 751 | 3.9375 | 4 | # class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回从上到下每个节点值列表,例:[1,2,3]
def __init__(self):
import Queue
self.level = Queue.Queue()
self.nodes = []
def PrintFromTopToBottom(self, root):
... |
1e9419c794b9d0e00601479c559d3f95ff10c838 | Nobody0321/MyCodes | /OJ/剑指Offer/滑动窗口的最大值.py | 1,278 | 3.59375 | 4 | # class Solution:
# def maxInWindows(self, num, size):
# sums = []
# if size <= 0:
# return []
# l = len(num)
# for i in range(l-size+1):
# s = max(num[i:i+size])
# sums.append(s)
# return sums
# 解法2,使用一个队列动态保存每个窗口最大值的索引
class Solution:
... |
ec1ff974949d84acfe1277e786b564a0462c7d31 | Nobody0321/MyCodes | /OJ/LeetCode/74. Search a 2D Matrix.py | 712 | 3.78125 | 4 | # 剑指offer出现过
# 矩阵每一行都是左到右递增,每一列都是上到下递增,所以从左下角开始,类似二分查找
class Solution:
def searchMatrix(self, matrix, target):
if matrix == []:
return False
height, width = len(matrix), len(matrix[0])
i, j= height-1, 0
while 0<=i<=height-1 and 0<=j<=width-1:
if 0<=i<=height-1... |
52d11803cb6bfd7e457f25b2a315a75e62e4f56c | prathamesh-collab/python_tutorials-pratham- | /mymodule/moduletest.py | 629 | 3.796875 | 4 | #!/usr/bin/env python3.7
#define some varible
numberone=1
ageofqueen=78
#define some function
def printhello():
print("hello")
def timesfour(input):
print("input * 4")
#define class
class piano:
def __init__(Self):
self.type=input("what type of piano")
self.heigth=input("what height ... |
a11dae4297dd98f1a75943a3a4e5143e8d716922 | prathamesh-collab/python_tutorials-pratham- | /inheritance.py | 603 | 4.21875 | 4 | #!/usr/bin/env python3.7
#for inheritance
class person:
def __init__(myo,fname,lname):
myo.fname=fname
myo.lname=lname
def printname(myo):
print("hello,my name is " + myo.fname,myo.lname)
#child class ,parent is person class
class student(person):
def __init__(self,fname,lname,y... |
6f5e1666083599d3d40180ba5a488f7dc4512c24 | prathamesh-collab/python_tutorials-pratham- | /practice.py/cal_2020-14.py | 961 | 4.125 | 4 | #!/usr/bin/env python3.7
def menu():
print("welcome")
print(" " )
print("1:- addition")
print("2: subtraction")
print("3:- multiplication")
print("4:- division")
print("5:- quit")
print(" " )
return int(input("chose your option "))
def add():
a = int(input("enter 1st value : "... |
4e3ceb1207f19d89801cf69b63d1bdd6daa721af | prathamesh-collab/python_tutorials-pratham- | /practice.py/inheritance.py | 524 | 3.9375 | 4 | #!/usr/bin/env python3
class person:
def __init__(self,fname,lname):
self.firstname=fname
self.lastname=lname
def printname(self):
print(self.firstname,self.lastname)
class student(person):
def __init__(self,fname,lname,year):
person.__init__(self,fname,lname)
... |
d443981908d634206201d17b1a4d7dff4690fb9d | prathamesh-collab/python_tutorials-pratham- | /practice.py/even_odd.py | 137 | 4.25 | 4 | #!/usr/bin/env python3.7
num=int(input("enter a number"))
if (num % 2) ==0:
print("even number")
else:
print("is odd number")
|
a4bf9cdcc3d13be0e354b9b38a777511d9701fc4 | prathamesh-collab/python_tutorials-pratham- | /Matplotlib_module/multiple_points.py | 178 | 3.671875 | 4 | #!/usr/bin/env python3
import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([1,2,6,8])
ypoints = np.array ([3,10,5,23])
plt.plot(xpoints,ypoints)
plt.show()
|
4b6ee2ea9d738f18eef1f6dc6ac056f767592fc5 | prathamesh-collab/python_tutorials-pratham- | /python_mini_project.py/currency_convtor.py | 538 | 3.796875 | 4 | #!/usr/bin/env python3.7
with open('currency_data.py') as f:
lines = f.readlines()
currencyDict = {}
for line in lines:
parsed = line.split("\t")
currencyDict[parsed[0]] = parsed[1]
amount = int(input("enter amount:\n"))
print("enter the name pf currency you want to convert this amount to ? Availa... |
4c5584bd487b3930564facf23ec0539dd2cd87dd | prathamesh-collab/python_tutorials-pratham- | /parent_child.py | 413 | 3.640625 | 4 | #!/usr/bin/env python3.7
class person:
def __init__(self,fname,lname):
self.fname=fname
self.lname=lname
return
def printname(self):
print(self.fname,self.lname)
x=person("prathamesh","sawant")
x.printname()
class student(person):
pass ##use the pass keyword when you ... |
2533b3f8a5461c6d9fc678c7e64b31b94adfe38e | prathamesh-collab/python_tutorials-pratham- | /python_mini_project.py/health_mange.py | 3,143 | 3.78125 | 4 | #!/usr/bin/env python3.7
import datetime
def gettime():
return datetime.datetime.now()
def take(k):
if k==1:
c=int(input("enter 1 for excersise and 2 for food"))
if(c==1):
value=input("type here\n")
with open("harry_ex.txt","a") as op:
op.write(str([str... |
e46dfffed461beb046f27314608745b55fe52764 | prathamesh-collab/python_tutorials-pratham- | /recursion_function.py | 212 | 4.09375 | 4 | #!/usr/bin/env python3.7
def cal_factorial(x):
if x == 1:
return 1
else:
return(x * cal_factorial (x - 1))
num = 4
print("the factorial of ", num , "is" ,cal_factorial( num ))
|
fdee1472dac296a3def971cb99de2f5cbe8025b5 | prathamesh-collab/python_tutorials-pratham- | /csv_module.py/writecsv.py | 583 | 3.71875 | 4 | #!/usr/bin/env python3
import csv #csv module
outfile = open('output-1.csv','w',newline='')
#create outfile variable @ use open and write method to write into (outout-1.csv) file
#create outwrite and use csv.writer method to write
outwrite = csv.writer(outfile)
#adding data into our created fi... |
03078ba0c3286730410583f48d16463571d84bbc | ysf72byk/deneme | /s1.py | 607 | 3.53125 | 4 |
from multiprocessing.dummy import Pool
import requests
pool = Pool(20) # Creates a pool with ten threads; more threads = more concurrency.
# "pool" is a module attribute; you can be sure there will only
# be one of them in your application
# as modules are cached after... |
c6fb497553306801c5ee4c71ef33e19a832dd6f0 | has-g/HR | /fb_1_TestQuestions.py | 1,551 | 4.1875 | 4 | '''
In order to win the prize for most cookies sold, my friend Alice and
I are going to merge our Girl Scout Cookies orders and enter as one unit.
Each order is represented by an "order id" (an integer).
We have our lists of orders sorted numerically already, in lists.
Write a function to merge our lists of orders into... |
138039d7b562114fb49ba8e09ab5cc8e66019a7c | has-g/HR | /ic_BinaryTreeLevelOrderPrint-DONOTUSE.py | 2,629 | 3.9375 | 4 |
'''
5) Print a binary tree
'''
class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class Tree(object):
def __init__(self, value):
self.root = Node(value)
def printTraversal(self, start):
items = []
if not st... |
77a7c85c828f39c8957d02e294a09f2939375ac3 | has-g/HR | /ic_findDictRotationPoint.py | 828 | 3.6875 | 4 | def find_rotation_point(words):
if len(words) == 0: return -1
if len(words) == 1: return 0
l = 0
r = len(words) - 1
mid = (r - l)//2
count = 0
while l <= r:
if count == 20: return -3
print("l=" + str(l) + ', r=' + str(r) + ', mid=' + str(mid))
if words[mid] < words[... |
688730ca2e89acc2ab325c645cdb94177a550f41 | has-g/HR | /testsample-4-io.py | 451 | 4.09375 | 4 | print("what's your name?")
myname = input()
print("and what about your age.... How old are you?")
myage = input()
print("your name is = " + myname + " and you are " + myage + " years old")
print("your name is {0:s} and you are {1:s} years old".format(myname, myage))
print("your name is %s and you are %s years old" %(my... |
ca88da9dd7849f18c48bddd702f86470a799f0ab | has-g/HR | /trial-stock_seller.py | 853 | 3.96875 | 4 | stock_prices = [10, 7, 5, 8, 11, 9]
stock_prices = [10, 7, 8, 11, 5, 9]
stock_prices = [10, 7, 5, 8, 11, 12]
#stock_prices = [10, 7, 5, 8, 11, 9]
#stock_prices = [10, 7, 5, 8, 11, 9]
def get_max_profit(stock_prices):
# Returns 6 (buying for $5 and selling for $11)
lowest_price = stock_prices[0]
max_profit ... |
136d9f62b55f64c14cdd0ff47a72058225ff48b1 | has-g/HR | /qc_jumptolastindex.py | 2,302 | 3.859375 | 4 | '''
8. Given an array of non-negative integers, you are initially positioned at the
first index of the array. Each element in the array represents your maximum jump length
at that position.Determine if you are able to reach the last index.
Example 1:
Input: [2,3,1,1,4] = True
Input: [3,2,1,0,4] = False
Output: true
Exp... |
52d3de71366d395b3a03e4c2f3c2a5ce3115715d | has-g/HR | /fb_10_DFS_Pre_In_Post_OrderPrints.py | 2,205 | 3.828125 | 4 | '''
https://www.youtube.com/watch?v=6oL-0TdVy28
preorder = 1-2-4-5-3-6-7
inorder = 4-2-5-1-6-3-7
postorder = 4-2-5-6-3-7-1
1
/ \
2 3
/ \ / \
4 5 6 7
'''
class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class... |
124722176bb32c10f7b1f1b05a35f1393a011df1 | has-g/HR | /ic_GetHighestProfit.py | 620 | 3.796875 | 4 |
def get_max_profit(stock_prices):
# Returns 6 (buying for $5 and selling for $11)
if len(stock_prices) == 0: return 0
highestProfit = -1000000
# walk through the list
for i, buy in enumerate(stock_prices):
# go to first element and walk right
for sell in stock_prices[i+1:]:
... |
b5baf9ade545a5d6013a1cf17552d17114348d84 | OSUrobotics/me499 | /Week_0_python/f_tutorial_dictionary.py | 7,559 | 4.25 | 4 | #!/usr/bin/env python3
import numpy as np
# What are dictionaries?
#
# Dictionaries are values (pretty much any data structure/variable type you can think of) paired with keys (unique
# identifiers). Common key types are integers and strings. The best mental image for dictionaries are: I have a bunch of
# items t... |
77d6e6cd9187f8c0b5dc63059a37a717873f3717 | OSUrobotics/me499 | /plotting/basic.py | 1,617 | 4.5 | 4 | #!/usr/bin/env python3
# Import the basic plotting package
# plt has all of the plotting commands - all of your plotting will begin with ply.[blah]
# To have this behave more like MatLab, do
# import matplotlib.pyplot
# in which case the plt scoping isn't needed
import matplotlib.pyplot as plt
# Get some thin... |
7f70ac5e1f1268a67aa83b90f4a16191a91285c6 | OSUrobotics/me499 | /web/json-data.py | 3,141 | 4.28125 | 4 | #!/usr/bin/env python3
# The request library lets you grab data from the web
import urllib.request as req
# JSON is a data format that is popular for web-delivered data, and the json module lets you unpack it easily
import json
if __name__ == '__main__':
# This url delivers census data for Los Angeles. Open i... |
b0e51806f4b6691d7ae7ec3d0e08272339713458 | OSUrobotics/me499 | /lab_examples/lab7_minimization.py | 3,490 | 3.734375 | 4 | from scipy.optimize import fmin
from functools import partial
# A generic function that we want to find the minimum of
def my_func(x):
"""A quadratic function
:param x the input x value
:returns f(x)"""
return (x-2)**2 - 3
# A fancier quadratic-y type function (but in 2D)
def elliptic_paraboloid(x, ... |
744b7479288431296863e7d8d2254c0cd58c1ea4 | OSUrobotics/me499 | /files/basics.py | 760 | 4.40625 | 4 | #!/usr/bin/env python3
if __name__ == '__main__':
# Open a file. The second argument means we're opening the file to write to it.
f = open('example_file', 'w')
# Write something to the file. You have to explicitly add the end of lines.
f.write('This is a string\n')
f.write('So is this\n')
... |
2df2fc0891b3da049e0ee8c1eba2642b6bbc1105 | OSUrobotics/me499 | /Week_1_arrays/b_practice_numpy.py | 9,217 | 4.46875 | 4 | #!/usr/bin/env python3
# Anything numpy-ish will start with np.
import numpy as np
# This is a handful of low-level numpy tasks that are, well, silly, but will give you practice with creating, editing
# and accessing numpy arrays.
# -------------------------- Creating numpy arrays -------------------------
# Crea... |
af9772e66678c4ba8b3a189e464ae359df84e2cf | OSUrobotics/me499 | /functions/find_zeroes.py | 5,131 | 4.78125 | 5 | #!/usr/bin/env python3
# Here's an example of a useful use of recursion. The idea is to find the zero-crossing of a function over a given
# interval. The base is is if there's a zero-crossing in the interval, and the interval is small enough. If not,
# divide the interval into two, and throw away the half the does... |
8e8ef500e2a4f1f1f2b23f4180371b48a70bb976 | OSUrobotics/me499 | /Week_1_arrays/HW_1_data_numpy.py | 2,564 | 3.890625 | 4 | #!/usr/bin/env python3
# Make sure numpy is available
# Problem 1: Read data
# Read in both the data file and the file that describes what's *in* the data file.
data = ...
data_description = ...
# Problem 2: Prints stats for each channel
# Notes for problem 2
# Do this with a for loop and with the names from the... |
84eb498c2dc5b63eb5942e3bd057b1d2602c0348 | OSUrobotics/me499 | /control/while_loops.py | 613 | 4.3125 | 4 | #!/usr/bin/env python3
if __name__ == '__main__':
# This is the basic form a while statement. This particular example is better suited to a for loop, though, since
# you know how many times round the loop you're going to go.
n = 0
while n < 5:
print(n)
n += 1
# This is a better e... |
23b5df5c6836f5759b1b820eb7d57fc51d9d70ff | OSUrobotics/me499 | /containers/list_comprehensions.py | 870 | 4.3125 | 4 | #!/usr/bin/env python3
from random import random
if __name__ == '__main__':
# Instead of enumerating all of the items in a list, you can use a for loop to build one. Start with an empty
# list.
a = []
# This will build a list of the first 10 even numbers.
for i in range(10):
a.append(i... |
964f93fa699c548d4a0159148bddcd9e083d3c49 | OSUrobotics/me499 | /Week_0_python/g_practice_dictionary.py | 4,116 | 4.78125 | 5 | #!/usr/bin/env python3
import numpy as np
# ------------------------------------------------------------------------------
# Dictionary creation/accessing/editing practice
#
######## Dictionary as data storage
# One common use for dictionaries is to store related data; in this example, suppose you have a function th... |
7730f652b4b1bb37f4e2b33533317aca526af6c0 | Mksourav/Python-Data-Structures | /stringlibraryfunction.py | 819 | 4.15625 | 4 | greet=input("Enter the string on which you want to perform the operation::")
# zap=greet.lower()
# print("lower case of the inputted value:",zap)
#
# search=input("Enter the substring you want the find:")
# pos=greet.find(search)
# if pos=='-1':
# print("substring not found!")
# else:
# print("substring spotted... |
383fc68d6f94526c9e7bd6e87d24f16e711d7925 | Mksourav/Python-Data-Structures | /assign8-4.py | 355 | 3.78125 | 4 | fname=input("Enter the name: ")
fh=open(fname)
lst=list()
nlst=list()
c=0
for line in fh:
lst=lst+line.split()
print("List items:\n",lst)
print("List length:",len(lst))
lst.sort()
print("Sorted list items:\n", lst)
for nwlst in range(len(lst)):
if lst[nwlst-1]!=lst[nwlst]:
nlst.append(lst[nwlst])
print(... |
5fae299e298ffe8d828e2902bf08697e50286792 | mgireesh05/algorithms | /old/mergesort.py | 856 | 3.890625 | 4 |
def mergesort(arr):
if len(arr) <= 1:
return arr
left = arr[:len(arr)/2]
right = arr[len(arr)/2:]
ret = []
if len(left) == 1 and len(right) == 1:
if left[0] < right[0]:
ret.append(left[0])
ret.append(right[0])
else:
ret.append(right[0])
ret.append(left[0])
return ret
if(len(left) != 0):
... |
787440bb7adf917eab1253a8543d10b196ff696d | twirrim/kattis | /python/romans.py | 261 | 3.5 | 4 | #!/usr/bin/env python3
""" An attempt to solve Roaming Romans on Kattis """
MODERN_MILE_FEET = 5280.0
ROMAN_MILE_IN_FEET = 4854.0
miles = float(input().rstrip())
roman_paces = (1000 * (MODERN_MILE_FEET/ROMAN_MILE_IN_FEET)) * miles
print(round(roman_paces))
|
5cc3fb3345e5a2cb3b8705db50ca51428e92eadb | twirrim/kattis | /python/anothercandies.py | 841 | 3.65625 | 4 | #!/usr/bin/env python
""" An attempt to solve the Another Candies problem on Kattis """
import sys
def confirm_its_possible(test_case):
children = int(test_case[0])
number_of_candies = 0
for i in range(1, children + 1):
number_of_candies += int(test_case[i])
if number_of_candies % children ==... |
42048e7d8a7fab5f2675580132a921b569cacfff | Programacion-Algoritmos-18-2/ejercicios-clases-6-1-edisongaibor | /Binaria/paquete_modelo/modelo.py | 1,184 | 3.71875 | 4 | class Operaciones(object):
#Constructor que recibe un arreglo ordenado .sort
def __init__(self, array):
self.arreglo = array
#Metodo de Busqueda Binaria
def Busqueda(self, item):
pos = -1 #posicion icia en -1
menor = 0
mayor = len(self.arreglo) -1 #mayor tendra el tamanio del arreglo -1
mitad = int((meno... |
c03bf859af58a94e9edb9bd7c1dc5a6c532674bc | iyuandeng/LearningPython | /pycharmprojects/zodiacv2.py | 1,111 | 3.5625 | 4 | # # 根据出生日期判断星座
# (month,day) = (12,6)
# zodiac_day = list(filter(lambda x: x<=(month,day),zodiac_days))
# print(zodiac_day)
# zodiac_len = list(zodiac_day)
# print(list(zodiac_day))
# zodiac_len = len(list(zodiac_day))%12
# print(zodiac_name[zodiac_len])
# a_list = ['456','abc','xyz']
# a_list.append('D')
# # 添加大写字... |
a7fc3141a0928c1d8d7e5c19165d953ddfa16f60 | ChrisBentley/cl-draw | /draw.py | 6,416 | 4.15625 | 4 | #!/usr/bin/env python
"""
Program that creates a canvas of user specified dimensions and provides
functions for the user to draw with.
Author: Chris Bentley
"""
import sys
from canvas import Canvas
def check_user_input(user_input_array):
valid_commands = ['c', 'l', 'r', 'b', 'q', 'h']
if (user_input_arra... |
1927f92464aef76920c420447962d4a4583677ea | hraya/Intro-Python-II | /src/adv.py | 3,790 | 3.625 | 4 | from room import Room
from player import Player
from items import Item
from os import system, name
# A function that clears the console for the user
def clearScr():
if name == "nt":
_ = system('cls')
else:
_ = system('clear')
# Declare all the rooms
room = {
'outside': Room("Outside Cav... |
e5f5fc697a51fd4aa7436c7ffe19f49f67f10d3d | bhyvex/bhsel | /asserts.py | 1,494 | 3.5 | 4 | '''
Nice helper functions for making different kinds of assertions.
'''
def equal(actual, expected, message=None):
'''
Assert that actual equals expected.
'''
assert actual == expected, (
'\nExpected: {}\n'
'Got: {}\n'
'Additional info: {}\n'
''.format(repr(expected), r... |
78345b42e8ff3dc48545a9d4d3bd1aeac5b74eef | HighPriestJonko/Anger-Bird | /Task1.py | 1,366 | 4.15625 | 4 | import math
v = int(input('Enter a velocity in m/s:')) # With which bird was flung
a = int(input('Enter an angle in degrees:')) # With respect to the horizontal
d = int(input('Enter distance to structure in m:'))
h = int(input('Enter a height in m:')) # Height of structure
g = -9.8 # m/s^2
degC = math.pi / 180
ar = a... |
ddbce3912e96838970a7e4ebeac4512a8130f8dd | nedunurisaiamulya/python_exercise | /str_replacement.py | 77 | 3.6875 | 4 | string = input()
r = input()
re_to = input()
print(string.replace(r, re_to))
|
9f545e91c69d756b943e2745e2200c03d8698ed8 | alaypatel07/k-nearest-neighbors | /knn/main.py | 1,733 | 3.515625 | 4 | import csv
import math
import operator
def load_data_set(filename):
with open(filename, newline='') as iris:
data_reader = csv.reader(iris, delimiter=',')
return list(data_reader)
def get_classes(training_set):
return list(set([c[-1] for c in training_set]))
def find_euclidean_distance(sam... |
161966b73a9d813ab2ffa8edf42e0cc5769d8bf5 | jschwarzwalder/python-intermediate | /generators/gensquares.py | 269 | 3.703125 | 4 | def gen_squares(max_base):
for n in range(max_base):
yield n**2
squares = gen_squares(6)
## for square in squares: print(square)
print(next(squares))
print(next(squares))
print(next(squares))
print(next(squares))
print(next(squares))
print(next(squares))
|
8b11e8566191510812c33c50c77a9c4610904130 | ajakaiye33/pythonic_daily_capsules | /apythonicworkout_book/pig_latin.py | 1,814 | 4.21875 | 4 |
def pig_latin():
"""
The program should asks the user to enter an english word. your program should
then print the word, translated into Pig Latin.
If the word begins with a vowel(a,e,i,o,u), then add way to the end of the word e.g
so "air" becomes "airway" eat becomes "eatway"
if the word begi... |
abd0931633a58b587c9f192a5a646e35a6dca3e0 | ajakaiye33/pythonic_daily_capsules | /apythonicworkout_book/iterables.py | 2,450 | 4.0625 | 4 |
def even_odd_sums(lst):
"""
Receives a list or tuple of numbers. Return a two-element list, containing(respectively)
the sum of the even index numbers and the sum of the odd index numbers
"""
even_result = 0
odd_result = 0
final_result = []
for indyx, numbz in enumerate(lst):
i... |
25223ab1874f7cf1e492040faba073faba3881a4 | ajakaiye33/pythonic_daily_capsules | /make_car_drive.py | 469 | 4.125 | 4 |
class Car(object):
"""
make a car that drive
"""
def __init__(self, electric):
"""
receives a madatory argument: electric
"""
self. electric = electric
def drive(self):
if not self.electric:
return "VROOOOM"
else:
return "WH... |
44be8c3c7f6920bdb8329af683afa045634d682e | ajakaiye33/pythonic_daily_capsules | /concatenate_string.py | 602 | 4.34375 | 4 |
def concatenate_string(stringy1, stringy2):
"""
A function that receives two strings and returns a new one containing both
strings cocatenated
"""
return "{} {}".format(stringy1, stringy2)
print(concatenate_string("Hello", "World"))
print(concatenate_string("Hello", ""))
# some other way...
d... |
9eb26cd86ccd257cfa4ad226dcb3328bec728cda | ajakaiye33/pythonic_daily_capsules | /apythonicworkout_book/perimeter_square.py | 959 | 4.0625 | 4 |
# def perimeter(n):
# # your code
# se = 0
# for i in range(n+1):
# se += i
# return se * 4
#
#
# print(perimeter(5))
# The goal of this exercise is to convert a string to a new string where each
# character in the new string is "(" if that character appears only once in
# the original string... |
4a2f10867025d5cb249d1cd599b68d1f845c8cd3 | ajakaiye33/pythonic_daily_capsules | /apythonicworkout_book/string_permutation.py | 352 | 3.890625 | 4 |
from itertools import permutations
def permutation(stry):
"""
permutate the string and return result without duplicate
"""
comp = []
perm_str = permutations(stry)
for i in list(perm_str):
comp.append("".join(i))
return list(set(comp))
print(permutation("a"))
print(permutation("a... |
7ba818effcd4db9905ca6814f4679184224e9d27 | ajakaiye33/pythonic_daily_capsules | /color_mixer.py | 970 | 4.25 | 4 |
def color_mixer(color1, color2):
"""
Receives two colors and returns the color resulting from mixing them in
EITHER ORDER. The colors received are either "red", "blue", or "yellow" and
should return:
"Magenta" if the colors mixed are "red" and "blue"
"Green" if the colors mixed are "blue" and "... |
611d930266a43e3d8a118a958e12d2043073e531 | ajakaiye33/pythonic_daily_capsules | /apythonicworkout_book/calc.py | 1,032 | 3.75 | 4 |
# def calc(expr):
# d = expr.split()
# #f = int(d[0])
# #s = int(d[1])
# #sym = d[2]
# #ge = f"{f}{sym}{s}"
# print(d)
#
# #e = int(expr[0])
# # symbol = int(expr[])
#
#
# print(calc("3 3 *"))
# def anagrams(word, words):
# # your code here
# sey = []
# for i in words:
# ... |
53e27a4f37161f482e3f6544324508b53ce172ed | ajakaiye33/pythonic_daily_capsules | /find_vacant_room.py | 418 | 4 | 4 |
def find_vacant_room(room_status_array):
"""
function returns the index-in a list- of element
that are 'vacant' in the room_status_array
"""
vacant_room_no = []
for room_no, room in enumerate(room_status_array):
if room == 'vacant':
vacant_room_no.append(room_no)
return... |
f0b78c654683f1499bed60f5b514165e6bff8497 | ajakaiye33/pythonic_daily_capsules | /apythonicworkout_book/repeated_words.py | 828 | 4.03125 | 4 |
from collections import Counter
import operator
# def most_repeated_word(wordy):
# """
# receives a sequence of strings and return the string that contains the greatest
# number of repeated letters
# """
# container = []
# new_word = ''.join(wordy)
# return max(new_word)
#
#
# print(most_r... |
917997f03032f5ef961265e09b57ebe971caa4d3 | ajakaiye33/pythonic_daily_capsules | /apythonicworkout_book/sort_array.py | 614 | 3.796875 | 4 |
# def sort_array(lst):
# foo = []
# boo = []
# for i, j in enumerate(lst):
# if j % 2 == 0:
# foo.insert(i, j)
# elif j % 2 != 0:
# boo.append(j)
# sorted(boo)
# boo[::-1]
# return boo + foo
# print(i.sorted())
# correct solution
def sor... |
89de544c2dee3d9c241eccab30c6989d6f697c7c | ajakaiye33/pythonic_daily_capsules | /apythonicworkout_book/dict_alpha.py | 668 | 3.5625 | 4 | # import operator
# people = [{"first": "Reuven", "last": "Lerner", "email": "reuven@Lerner.co.il"},
# {"first": "Donald", "last": "Trump", "email": "president@whitehouse.gov"},
# {"first": "Vladimir", "last": "Putin", "email": "president@kremavax.ru"}]
#
# for person in sorted(people, key=operator.... |
195b3d1288769e60d0aa6d0023f308a6e0675523 | ajakaiye33/pythonic_daily_capsules | /make_number_odd.py | 288 | 4.25 | 4 |
def make_number_odd(num):
"""
Receives a number, adds 1 to that number if it's even and returns the number
if the original number passed is odd, just return it
"""
if num % 2 == 0:
num += 1
return num
print(make_number_odd(2))
print(make_number_odd(5))
|
fbbcc0a04963a96f4447bf0c55d3973a9b85932e | keishon104/RaspberryPi_Resume_Printing | /printer.py | 804 | 3.53125 | 4 | # Author: Keishon Smith
# Date: January 10, 2019
# Purpose: USE CUPS to print a document with a specified path.
def printDocument(printerName,filePath,copies):
import cups
# TEST_DOCUMENT = '/home/pi/Documents/paperfairy/documents/DOC083118-08312018163618.pdf'
# PRINTER_NAME = 'Brother_HL-L3270CDW_series'
... |
9ed30ff3007a54bab9c141fec040e7f206a16d1a | kkufieta/ud_ds_algos_p2 | /problem_2.py | 3,777 | 4.25 | 4 | #%% [markdown]
# # Problem 2: Search in a Rotated Sorted Array
#
# You are given a sorted array which is rotated at some random pivot point.
#
# Example: `[0,1,2,4,5,6,7]` might become `[4,5,6,7,0,1,2]`
#
# You are given a target value to search. If found in the array return its index, otherwise return `-1`.
#
# Yo... |
8556f1f50286be69017711afc8b5da71850ed766 | rbarillec/project_euler | /Euler0003.py | 594 | 3.921875 | 4 | def IsDivisibleBy(value, factors):
for factor in factors:
if value % factor == 0:
return True
return False
def Euler0003(value):
factors = []
factorProduct = 1
candidate = 1
while (factorProduct < value) and (candidate / value < value):
candidate += 1
if... |
d46bd897ee359b69d2f3fc29d7d6803883590c23 | rhydermike/PythonPrimes | /primes.py | 1,641 | 4.40625 | 4 | #Prime number sieve in Python
MAXNUMBER = 1000 #Total number of numbers to test
results = [] #Create list to store the results
for x in range (1,MAXNUMBER): #Begin outer for loop to test all numbers between 1 and MAXNUMBER
isprime = True #Set boolean variable ispri... |
47e61ac95b738a155b4fb56d98042ed42d390f37 | btonasse/Flammepy | /consoleUI.py | 16,306 | 3.6875 | 4 | # Console interface
from main import Course, Player, Rider
from console import fg, bg, fx
import json
from typing import Union
# Make black color readable on console
fg.black = fg.darkgray
class App():
'''
Main class for IO and implementing the game loop
'''
player_colors = ['blue', 'green', 'red', 'p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.