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 |
|---|---|---|---|---|---|---|
9719f56e9e6351c1cb37aa7bd80bb1293a99d419 | tuananh200599/Python-Project | /Find_Max.py | 197 | 3.65625 | 4 | import random
n = int(input('Nhap so phan tu : '))
array = random.sample(range(1,99),n)
max = 0
for item in array:
if max < item:
max = item
print(array)
print('Max la: ', max) |
635f901b3928fc44a776f97cc2d5904ef6741c88 | thomasren681/Project-Optimization-Xidian | /Assingment1/ratio.py | 635 | 3.578125 | 4 | import numpy as np
import matplotlib.pyplot as plt
def f(x):
return 3*(x**3)-4*x+2
x = np.linspace(0,2)
y = f(x)
a = 0
b = 2
t = (np.sqrt(5)-1)/2
x1 = a + (1-t)*(b-a)
x2 = a + t*(b-a)
epsilon = 0.2
iteration = 0
cache = []
while (abs(b-a)>epsilon):
if f(x1)-f(x2)>0:
cache.append(x2... |
5df07c5ac176afa6cbce6cb685843867811383e0 | ywwill/LeetCode-Python | /053.maximum-subarray/maximum-subarray.py | 379 | 3.90625 | 4 | # !usr/bin/python
# -*- coding:utf-8 -*-
def maxSubArray(nums):
currentSum = maxSum = nums[0]
for i in xrange(1, len(nums)):
currentSum = max(nums[i], currentSum + nums[i])
maxSum = max(maxSum, currentSum)
return maxSum
def main():
nums = [-2,1,-3,4,-1,2,1,-5,4]
print(m... |
69033fcfbbf141f5eecafa87c99a3a1c0cb6766d | ywwill/LeetCode-Python | /561.array-partition-i/array-partition-i.py | 342 | 3.6875 | 4 | # !usr/bin/python
# -*- coding:utf-8 -*-
def arrayPairSum(nums):
"""
:type nums: List[int]
:rtype: int
"""
# 结果便是排序后第1,3,5,...2n-1数的和
return sum(sorted(nums)[::2])
def main():
nums = [1,4,3,2]
print(arrayPairSum(nums))
if __name__ == '__main__':
main()
|
1c3789d4c1df93bc42c67596cbc3f8392d2964fd | ywwill/LeetCode-Python | /532.k-diff-pairs-in-an-array/k-diff-pairs-in-an-array.py | 463 | 3.75 | 4 | # !usr/bin/python
# -*- coding:utf-8 -*-
import collections
def findPairs(nums, k):
if k>0:
# 返回两个集合的交集
return len(set(nums) & set(n+k for n in nums))
elif k==0:
# 统计出现次数>1的
return sum(v>1 for v in collections.Counter(nums).values())
else:
return 0
def... |
5478815e2624ccf748827a69a76d505a9f0f2fdf | ywwill/LeetCode-Python | /349.intersection-of-two-arrays/intersection-of-two-arrays.py | 801 | 3.984375 | 4 | # !usr/bin/python
# -*- coding:utf-8 -*-
def intersection1(nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
d = {}
ans = []
for num in nums1:
d[num] = d.get(num, 0) + 1
for num in nums2:
if num in d:
... |
f295a73c2fc291a95355b73b3cb03c28148a302b | AdamOtto/Twitterpated | /functions.py | 29,725 | 3.609375 | 4 | import pdb
import queries
import os
CLEAR_SCREEN = 'cls' if os.name == 'nt' else 'clear'
def get_valid_input(length = 20, valids = [], valids_description = None, prompt = '', tries = float('inf')):
"""
Will attempt to grab input from the user and check if it belongs to the
passed list of valids, if not it... |
1f158af20f62ebac9a6b4778ed4929719939ba62 | MDGQC/coffee-machine | /lib/coffee/coffee.py | 306 | 3.921875 | 4 | class Coffee(object):
def __init__(self, name, beans, water, milk):
self.name = name
self.beans = beans
self.water = water
self.milk = milk
def print(self):
print("Name: {}, Beans: {} Water: {} Milk: {}".format(self.name, self.beans, self.water, self.milk)) |
1fa494ba9a17f11ed6a24282be71cb7b63b4eef2 | sumitparw/leetcode_practise | /amazon/array_duplicate_o1_no manipulation.py | 1,057 | 3.5625 | 4 | class Solution:
def findDuplicate_o_n(self, nums):
# Find the intersection point of the two runners.
tortoise = nums[0]
hare = nums[0]
while True:
tortoise = nums[tortoise]
hare = nums[nums[hare]]
if tortoise == hare:
break
... |
7948ec773a7a972c00d91ffd501158c7b9ac327d | sumitparw/leetcode_practise | /array/target_sum.py | 706 | 3.6875 | 4 | def targetsum_set(arr,k):
s =set()
return_list = []
for i in range(len(arr)):
temp = k - arr[i]
if temp in s:
return_list.append((arr[i],k-arr[i]))
s.add(arr[i])
return return_list
def targetsum_sort(arr,k):
arr =sorted(arr)
return_list = []
l = 0
... |
f4a39f00435ae438123b440ffa9ef0b300077902 | Skinz3/CNet | /Pytest/layer_dense.py | 815 | 3.5625 | 4 | import numpy as np
# Dense layer
class Layer_Dense:
# Layer initialization
def __init__(self, n_inputs, n_neurons):
# Initialize weights and biases
self.weights = 0.01 * np.random.randn(n_inputs, n_neurons)
self.biases = np.zeros((1, n_neurons))
# Forward pass
def forward(self... |
0d73e2ed5a5d08a87ba232169ac224dd1c579072 | sscurini/pythonGame | /main_game.py | 3,092 | 3.75 | 4 | from heroes import Heroes
from monsters import Monsters
def getUserName():
username = input()
return username
#Program starting point "Welcome"
print("Please Enter your name: ")
playersUsername = getUserName()
print(" ")
print("Welcome to the super awesome monster battle text based game")
print(" ")
print("He... |
0abe0e63e9cd588267c456a87ea6ce6068e3da15 | Tonyqu123/data-structure-algorithm | /Valid Palindrome.py | 720 | 4.3125 | 4 | # Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
#
# For example,
# "A man, a plan, a canal: Panama" is a palindrome.
# "race a car" is not a palindrome.
#
# Note:
# Have you consider that the string might be empty? This is a good question to ask dur... |
0a4f8e6fdf14660dfab896ebb1b530d3a536d5c3 | zahasky/Neural_network_inversion | /training_data_generation/noise_addition.py | 2,385 | 3.59375 | 4 |
#######
# Here we load the dataset, add gaussian,poisson,speckle
#
# 'gauss' Gaussian-distributed additive noise.
# 'speckle' Multiplicative noise using out = image + n*image,where
# n is uniform noise with specified mean & variance.
#
# We define a function that adds each no... |
ee8ba93c9945a4fb39552ece1e21d471d6f3c394 | ayk-dev/python-basics | /nested-loops/pool_days.py | 507 | 3.625 | 4 | import math
number_of_people = int(input())
entrance_fee = float(input())
price_chair = float(input())
price_umbrella = float(input())
total_entrance_fee = number_of_people * entrance_fee
total_umbrellas = math.ceil(number_of_people / 2)
total_chairs = math.ceil(0.75 * number_of_people)
chairs_cost = total_... |
a771cb64e5073c0a244b142c3db5f92d30f9bb6a | ayk-dev/python-basics | /nested-loops/travel_agency.py | 1,463 | 3.84375 | 4 | town = input() # "Bansko", "Borovets", "Varna" или "Burgas"
packet = input() # "noEquipment", "withEquipment", "noBreakfast" или "withBreakfast"
vip_discount = input() # "yes" или "no"
nights = int(input())
price_per_night = 0
if nights < 1:
print(f'Days must be positive number!')
else:
if town ==... |
52b77796ade318f7fe4775cf1fe30e2911c049c2 | chococigar/Cracking_the_code_interview | /4_Trees_and_graphs/BST.py | 3,970 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Write a function to remove a single occurrence of an integer from a doubly linked list if it is present. You may use any language you like.
"""
class Node(object):
def __init__(self, data, left_child, right_child): #initdata?
self.name = ""
self.data = data
s... |
8c7569bf644859b9a51d0a6b06935c0dcbbfd509 | chococigar/Cracking_the_code_interview | /3_Stacks_and_Queues/queue.py | 598 | 4.1875 | 4 | #alternative method : use lists as stack
class Queue(object) :
def __init__(self):
self.items = []
def isEmpty(self):
return (self.items==[])
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
self.items.pop() #first in first out. last item is first.
... |
ce8339c1289b8a52bc6759af5a80d43588ef3752 | chococigar/Cracking_the_code_interview | /1_Arrays_and_Strings/1_3.py | 331 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
- Time : O(n)
- if in Java, need to use character array, and work from backwords for index consideration)
"""
s_input, n = input()
def replace_space(s):
if n>len(s): #Edge case : need to consider this.
return None
return (s_input[:n].replace(" ", "%20"))
print(replace_space... |
a63340fb1b647ed2a412eccec8e2e4bb9aab7616 | chococigar/Cracking_the_code_interview | /Google_Coding_Interview_Q/sort_two_strings.py | 405 | 3.671875 | 4 | #-*- coding: utf-8 -*-
"""
Given two lowercase strings, S1 and S2, sort S1 in same order as S2.
If a character in S1 doesn't exist in S2, put them at the end.
If S1 is "program" and S2 is "grapo", then return "grrapom".
Link : https://www.glassdoor.com/Interview/Given-two-lowercase-strings-S1-and-S2-sort-S1-in-same-o... |
f15b0f6af19b84b195a5babac154b202621e2c35 | JohnMagnusson/FixMatch-Exploration | /ExpMovingAvg.py | 547 | 3.703125 | 4 | # Obtained from: https://discuss.pytorch.org/t/how-to-apply-exponential-moving-average-decay-for-variables/10856/3
class EMA:
def __init__(self, mu, device):
self.mu = mu
self.shadow = {}
self.device = device
def register(self, name, val):
self.shadow[name] = val.clone()
... |
a9745d428080f28628edd3aab741e72a564cf269 | g-m-ke/num_ditector_py | /main.py | 7,460 | 3.765625 | 4 | import PIL
from PIL import Image , ImageFilter, ImageDraw, ImageFont
import sys
def Blur (imagename):
try:
img = Image.open(imagename)
except IOError:
print("Unable to load image")
sys.exit(1)
blurred = img.filter(ImageFilter.BLUR)
blurred.save(image... |
f36ecd805ab5c6ad1e567d3e4ec36e95aaf75a2d | g-banana/ptas | /codes/smallIDEA.py | 371 | 3.65625 | 4 | # 手动十 - 十六机制转换
def dic_to_ox(num,grad):
rep = []
round = num//grad
decim = num/grad - round
while(round):
newpla = decim*grad
rep.append(newpla)
decim = round / grad - round//grad
round = round//grad
newpla = decim * grad
rep.append(newpla)
rep.reverse()
... |
d79b9bc8fea06c03d0318d89903b137300be58e6 | TerezaMertlova/intenzivnikurz | /main.py | 443 | 3.78125 | 4 | item = {"title": "konvička", "price": 899, "in Stock": True}
item["price"] = 929
print("Název položky je", item["title"])
print("Název položky je "+ str(item["title"]))
print(f"Cena položky je {item['price']}")
print(item)
item["weight"] = 0.5
if "weight" in item:
print(item["weight"])
else:
print("Hmotnost n... |
daed78e3a371606f96deb70099481207484f4e0c | mr-sigma/setback-game | /setback.py | 10,486 | 3.65625 | 4 | # setback script
import random
import time
class SetDeck:
def __init__(self, players = 3):
self.deck = []
self.players = players
self.hands = []
self.community = []
self.tricks = []
self.points = []
self.winning_bid = 0
self.bid_winner = 0 # Will be wi... |
939da2dd5cf9dbc763a9cf7bb022099b25069022 | sahitya-pavurala/dplay | /python/problems99/p8.py | 411 | 3.828125 | 4 | # Eliminate consecutive duplicates in a list
def remove_consecutive_duplicates(lst):
if len(lst) <= 1:
return lst
pre = lst[0]
result = [pre]
for i in range(1, len(lst)):
if lst[i] != pre:
pre = lst[i]
result.append(pre)
return result
if __name__ == "__... |
53e4d517729e0908f437c58280c62727208653b7 | sahitya-pavurala/dplay | /python/problems99/p3.py | 451 | 3.9375 | 4 | # find kth element in a list
# 1,3,5,6,9,23,45 k = 5, 9 should be returned
import sys
def find_kth_element(lst, k):
if len(lst) < k:
print("Invalid input. Cannot find the %dth element"%k)
sys.exit(1)
if len(lst) == len(lst) - k + 1:
return lst[0]
return find_kth_element(lst[1:], ... |
ec7e999baaf6fe87b593ea606eac3298e856d2c9 | matyh/Checkio | /Electronic_Station/time_converter_12h_to_24h.py | 1,425 | 3.984375 | 4 | #!/usr/bin/env checkio --domain=py run time-converter-12h-to-24h
# You are the modern man who prefers the 24-hour time format. But the
# 12-hour format is used in some places. Your task is to convert the time
# from the 12-h format into 24-h by following the next rules: - the output
# format should be 'hh:mm' - if the... |
f99612e4c8329f017bbf7a20f6024f24d2ce2bea | matyh/Checkio | /Electronic_Station/restricted_sum.py | 853 | 3.828125 | 4 | #!/usr/bin/env checkio --domain=py run restricted-sum
# Our new calculator is censored and as such it does not accept certain words. You should try to trick by writing a program to calculate the sum of numbers.
#
# Given a list of numbers, you should find the sum of these numbers. Your solution should not conta... |
d3c8a73094434236fe21143c56663dfb3b4c90f7 | CorradoTorino/BrainTrain | /MyHashTable/MyHashTable.py | 1,804 | 3.765625 | 4 | class MyHashTable:
"""A dummy hash table not intended to replace a dictionary ;)"""
def __init__(self, length = 4):
"""
Parameters
----------
length : str
The number of buckets used for split the key-value.
"""
self.length = length
self.bucke... |
048c95614902b76f1854db0325850aad0447473f | GudniNathan/square_sum | /square_sum_loop.py | 1,496 | 3.609375 | 4 | import threading
import time
from timeit import default_timer as timer
import sys
print("Choose length:")
count = int(input())
start = timer()
li = [i for i in range(count, 0, -1)]
sqnum = list()
for i in range(2, int((count ** 0.5) * 1.5) + 3):
if i ** 2 < count * 2:
sqnum.append(i ** 2)
sqnum.reverse... |
670a3bd0228cb57ce879d7fb605ea0a4a9f3937e | Makeupfor/ctf_ringzer0team | /cryptography/martian_message_part_3/challenge26.py | 577 | 3.75 | 4 | def decrypt(c, k):
''' Decrypt function, XOR each byte with the key '''
p = ''
for i in c:
p = p + chr(ord(i) ^ k)
return p
def main():
# Our encrypted flag
c = 'EOBD.7igq4;1ikb51ibOO0;:41R'
# Find the key
for k in range(0, 255):
p = chr(ord(c[0]) ^ k) + chr(ord(c[1]) ^... |
e3e99c1621c994e586733afdf8e9a64d84bba0fb | nilashan/Python | /oop/Sort.py | 460 | 3.59375 | 4 | class myclassforsort:
'Common base class for all employees'
empCount = 0
def __init__(self, Arr):
self.Arr = Arr
def dosort(self,ddd):
print ddd;
def dosort(self):
l=list(self.Arr)
for i in range(len(l)-1,0,-1):
for j in range(i):
if l[... |
506b4a8816d15c4ef48b7522729289e0e98f7d26 | maniaclogic/mini_games | /hangman.py | 431 | 3.734375 | 4 | import random
words = open('words.txt', 'r').readlines()
words = [word.replace('\n', ' ').replace('\"', ' ').strip() for word in words]
def play_hangman():
hangman_word = words[random.randint(0, len(words) - 1)]
underscore_array = ['_' for i in hangman_word]
game_end = false
while game_end == false:... |
b0f6fe4de44808248373838fab2dce6fe6407f9c | DominusChris/Programming-Problems | /DsAlgo/1/Solution_1.py | 592 | 3.5625 | 4 | def getAbsoluteMinAndMax(array):
if not array: # catch case where n = 0
return (None, None)
lengthArray = len(array)
if lengthArray > 2: # divide and conquer
half = len(array)//2
(leftMin, leftMax) = getAbsoluteMinAndMax(array[:half])
(rightMin, rightMax) = getAbsoluteMinAndMax(array[half:])
return (min(le... |
93b706571c7b3451f5c677cc7d9ddb1dffa67f13 | blkbrd/python_practice | /helloWorld.py | 2,330 | 4.15625 | 4 | print ("hello World")
'''
#print('Yay! Printing.')
#print("I'd much rather you 'not'.")
#print('I "said" do not touch this.')
print ( "counting is fun")
print ("hens", 25 + 30 / 6)
print ("Is it greater?", 5 > -2)
#variables
cars = 100
space_in_a_car = 4
drivers = 30
passengers = 90
cars_not_driven = c... |
9adcde6f7e5dde3406c10a10b95cc23732256437 | ht-evth/computational-mathematics | /lab10/spline.py | 2,723 | 3.734375 | 4 | # Построение сплайна дефекта 1
def interpolation(listX, listY):
# инициализация массива для сплайнов
res = []
for i in range(len(listX)):
res.append([-1, 0, 0, 0, 0])
res[i][0] = listX[i] # задаём значение х
# задаём коэф-т а
for i in range(len(listX)):
res[i][1... |
9b6afb518e9986b9d1b1f9ff4287023da5933f5e | ej2/divided_kingdom | /divided_kingdom/apps/game/helpers/weather.py | 246 | 3.5 | 4 | import random
SEASONS = ("spring", "summer", "fall", "winter")
WEATHER_TYPES = ("sunny", "rainy", "stormy", "foggy", "hot", "cold", "brisk", "clear", "cloudy")
def get_weather():
return "It is {0} out.".format(random.choice(WEATHER_TYPES)) |
f5e6c749824fba7c1682f1ecb4f2aaa8f9409ee9 | Yodeman/social_media_behaviour | /comments/json_txt.py | 710 | 3.796875 | 4 | # COnverts JSON files to text files.
import os
import json
def json_txt(input_file_dir):
"""
converts json file into text file.
"""
file_name = input_file_dir.split('\\')[-1]+"_comments.txt" #get folder name.
txt_output = open(file_name, 'w')
with open(input_file_dir+"\\merged.json", 'r'... |
24b14dc7f772059c4a22772eeddc0a2a1965e0fe | DevGpsalm/Movie-Recommendation | /functions.py | 3,507 | 4.125 | 4 | from pandas.io.formats.format import GenericArrayFormatter
def ratings_ranked_df(data, vote_count = 1000):
global ratings_ranked
'''
This function returns a dataframe rank of movies in descending order for movies with atleast 1000 votes
INPUT
data - the movies dataframe with t... |
64f31b62c4a464b495cf051d73c26b67b37cc8bb | padma67/guvi | /looping/sum_of_first_and_last_digit_of_number.py | 342 | 4.15625 | 4 | # Program to find First Digit and last digit of a Number
def fldigit():
number = int(input("Enter the Number: "))
firstdigit = number
while (firstdigit >= 10):
firstdigit = firstdigit // 10
lastdigit = number % 10
print("sum of first and last digit of number is {0}".format(firstdigit+l... |
21f9224ef481a73485349e2d6775a0b40d3bf75b | padma67/guvi | /Array/compare_two_strings.py | 431 | 3.796875 | 4 | #Given 2 strings S1 and s2, check whether they are case senitively equal without using any predefined function(case sensitive).
#If they are not same print 'no'
def str():
s1,s2=map(str,input().split())
count=0
y="yes"
n="no"
#check two strings are case senitively equal
if(len(s1)==len(s2)):
for i in range(len(... |
df2c4134cb5454aac257dcb270cc651595b3a8c4 | padma67/guvi | /looping/Calculator.py | 865 | 4.1875 | 4 | #Calculator
#get the input value from user
num1=float(input("Enter the number 1:"))
num2=float(input("Enter the number 2:"))
print("1.Add")
print("2.Sub")
print("3.Div")
print("4.Mod")
print("5.Mul")
print("6.Expo")
#get the function operator from uuer
ch=float(input("Enter your choice:"))
c=round(ch)
if(c==1):
pr... |
968edbed9fa5da6b483e3761c2c73ed258b05665 | padma67/guvi | /Basics/Find_GCD_of_given_nmber.py | 326 | 3.71875 | 4 | #Given 2 numbers N,M find the GCD of N and M.If it cannot be found for given number(s) then print -1
def GCD():
gcd=0
g=-1
N, M = map(int, input().split())
i = 1
while(i <= N and i <= M):
if(N % i == 0 and M % i == 0):
gcd = i
i = i + 1
return gcd
res=GCD()
print... |
451744ff93bd4ee503af5d2f28e1bf8d89f16517 | padma67/guvi | /looping/Print_even_numbers_from_1_to_100.py | 264 | 4.1875 | 4 | #To print all even numbers between 1 to 100
def Even():
#declare the list for collect even numbers
even=[]
i=1
while(i<=100):
if(i%2==0):
even.append(i)
i=i+1
print("even numbers between 1 to n",even)
Even()
|
811d94f89f38cf5996a6e0f3d14be2895248956c | don6hao/leetcode | /SameTree.py | 1,705 | 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:
# @param p, a tree node
# @param q, a tree node
# @return a boolean
def isSameTree(self, p, q):
if None == p and None == ... |
2f7c3064c85e472f311411621e1dac4a49a27d05 | don6hao/leetcode | /preOrderTraveral.py | 1,517 | 3.828125 | 4 | # Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param root, a tree node
# @return a list of integers
def preorderTraversal(self, root):
if None == root:
return... |
15e68bba93bd5794e440a0bf5e4532f4b76030dd | peasant98/NBA-Stats-Clustering | /clustering/Cluster.py | 7,430 | 3.625 | 4 | # NBA Stats Clustering
# Copyright Matthew Strong, 2019
# main cluster file
import numpy as np
# reads the csv into dataframe before clustering
import clustering.CreateClusterData
import clustering.DimReduce
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from nba_api.stats.static import play... |
6e135b53bbde0cd65bdf7c36815195dd29e6ec66 | Nitin26-ck/Scripting-Languages-Lab | /Part B/Lab 5/Prg5_file_listcomprehension.py | 2,064 | 4.1875 | 4 | """
Python File Handling & List Comprehension
Write a python program to read contents of a file (filename as argument) and store the number of occurrences of each word in a dictionary.
Display the top 10 words with the most number of occurrences in descending order.
Store the length of each of these words... |
221fdeb75e2f6db401901b5755e991bdffdcee75 | Nitin26-ck/Scripting-Languages-Lab | /Part B/Lab 1/Prg1c_recursion_max.py | 809 | 4.15625 | 4 | """
Introduction to Python : Classes & Objects, Functions
c) Write a recursive python function that has a parameter representing a list of integers
#and returns the maximum stored in the list.
"""
#Hint: The maximum is either the first value in the list or the maximum of the rest of
#the list whichever is larger. If th... |
d9c3195fd763021fc67164bbd0acf5feee3171e5 | MarkNambatac/CSC151 | /Ass_No_2/CSC151_AssNo2/Python Code/students.py | 4,893 | 3.96875 | 4 | """" This program should be able to do the following:
> Be able to access a database
> Update
> Add
> and Delete
"""
import psycopg2
def read():
try:
conn = psycopg2.connect(database="student", user="postgres", password="123456789", host="127.0.0.1",
port="5432")
... |
8fb5102d15d360a799ea6a8405d4eda5547bde7b | raghubgowda/python | /beginer/exceptions.py | 441 | 3.71875 | 4 | try:
yob = int(input('Enter a your year of birth: '))
salary = int(input('Enter you salary: '))
age = 2020 - yob
retirement_benefits = (65 - age) * 20000 / salary
print(f'You are {age} years old and you will get ${retirement_benefits} retire benefits')
except ZeroDivisionError:
print('Salary can... |
09c0d3472a0640b00ad24d62775bbb1406ef55ee | rachitdev/ugMDSCode | /grpDF.py | 447 | 3.765625 | 4 | import pandas as pd
pd.set_option('display.max_columns', 500)
df = pd.read_csv('https://media-doselect.s3.amazonaws.com/generic/wkyk2AWYdJbqgXoRo3Y8w42nX/test.csv')
input_list = [['Pclass','Age'], [3,13]]
cols = input_list[0]#the columns to group the dataframe by
values = input_list[1]# The group to print
#Write your c... |
c7f7ea35a06186a10dbba5023e123255d0838f7d | CaptainJackF/LeetCode | /1.Two Sum.py | 904 | 3.828125 | 4 | # -- coding:utf-8 --
'''
1. Two Sum
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
'''
class Solution:
def twoSum( self, nums, target):
dic = {} #... |
2f181871064fc6bfdc663d7831b2c912b4f6f62b | Geoff10/Group_19 | /HauntedHouse/game.py | 12,093 | 4 | 4 | #!/usr/bin/python3
from items import *
from gameparser import *
from map import rooms
from missions import *
from player import *
import player
def list_of_items(items):
"""This function takes a list of items (see items.py for the definition) and
returns a comma-separated list of item names (as a string)."""... |
901e5ae13f821c2e3da9df9b46d9a1d7e7cc003c | KodingKurriculum/learn-to-code | /beginner/beginner_3.py | 1,789 | 4.78125 | 5 | # -*- coding: utf-8 -*-
"""
Beginner Script 3 - Lists, and Dictionaries
Functions allow you to group blocks of code and assign it a name. Functions
can be called over and over again to perform specific tasks and return values
back to the calling program.
"""
"""
1.) Lists (also known as an Array) are great for storin... |
aab5a20a1ed33cc9ee159f62c25647d44860f7dc | enria/algorithm-problem | /pta/pat_a/1136.py | 450 | 3.890625 | 4 | def isPalindrome(num):
for i in range(0, len(num)//2):
if(num[i] != num[-(i+1)]):
return False
return True
cur = input()
time = 0
while time < 10 and not isPalindrome(cur):
nextNum=int(cur)+int(str(cur[::-1]))
print("%s + %s = %d"%(cur,str(cur[::-1]),nextNum))
cur = str(nextNum)... |
12466267d8740eba108e610b78054f82c24441e4 | enria/algorithm-problem | /pta/pat_a/1065.py | 177 | 3.5625 | 4 | n=int(input())
for i in range(n):
nums=input().split()
nums=[int(ni) for ni in nums]
print("Case #{}: {}".format(i+1,"true" if nums[0]+nums[1]>nums[2] else "false")) |
3c5dbabce2188b2ae5a5208cc79b55df571ab076 | enria/algorithm-problem | /pta/pat_a/1088.py | 1,918 | 3.765625 | 4 | from math import gcd
class Rational:
def __init__(self, _a=0, _b=1):
self.a, self.b = _a, _b
def __add__(self, other):
result = Rational()
lcm = other.b*self.b//gcd(other.b, self.b)
result.b = lcm
result.a = self.a*lcm//self.b+other.a*lcm//other.b
return result... |
af0d5eb1997a59ac0feb35c857b15950ec58683e | fstgerm/advent-of-code | /2017/09/challenge.py | 622 | 3.65625 | 4 | data = open('input.txt').read()
characters = iter(data)
score = depth = garbage_count = 0
garbage = False
for character in characters:
if garbage:
if character == '!':
characters.next()
continue
if character == '>':
garbage = False
continue
ga... |
eb39376f9409be23d2b756a70aafff2a6782b31b | ijuarezb/InterviewBit | /06_TreesDataStructure/zigzag_level_order_traversal_bt.py | 2,617 | 4.0625 | 4 | #!/usr/bin/env python3
import sys
from BST import TreeNode
from BST import insertNode
# ZigZag Level Order Traversal BT
# https://www.interviewbit.com/problems/zigzag-level-order-traversal-bt/
#
# Given a binary tree, return the zigzag level order traversal of its nodes’ values. (ie, from
# left to right, then right... |
504c0c110a149b585f401805e3697bae1a258266 | ijuarezb/InterviewBit | /03_TwoPointers/3_sum.py | 2,155 | 4 | 4 | #!/usr/bin/env python3
import sys
# 3 Sum
# https://www.interviewbit.com/problems/3-sum/
#
# Given an array S of n integers, find three integers in S such that the sum is closest to a
# given number, target. Return the sum of the three integers.
#
# Assume that there will only be one solution
#
# Example:
# given arr... |
6b8f0b7821568c8112bccaca09b5987e13d0eb41 | ijuarezb/InterviewBit | /05_Backtracking/kth_permutation_sequence.py | 5,939 | 4.1875 | 4 | #!/usr/bin/env python3
import sys
# Kth Permutation Sequence
# https://www.interviewbit.com/problems/kth-permutation-sequence/
#
# The set [1,2,3,…,n] contains a total of n! unique permutations.
#
# By listing and labeling all of the permutations in order,
# We get the following sequence (ie, for n = 3 ) :
#
# 1. "123... |
073ac7170fb034c293d8ff3aa828f635742da1ce | ijuarezb/InterviewBit | /08_GraphsDSAndAlgs/word_latterc.py | 4,279 | 3.765625 | 4 | #!/usr/bin/env python3
import sys
from collections import defaultdict
class Solution(object):
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
if endWord not in wordLi... |
cb6c02ed143b1af8db702c153c23da4f09723d49 | ijuarezb/InterviewBit | /02_Arrays/SpiralMatOrderII.py | 1,270 | 3.875 | 4 | import sys
def generateMatrix(A):
if A <= 0:
return 0
Matrix = [[0 for x in range(A)] for y in range(A)]
spiral = []
for i in range(A*A):
spiral.append(i+1)
T = 0
R = A-1
L = 0
B = A-1
direction = 0
items = (B+1)*(R+1)
spiral_pivot = 0
#print(T, B, L, R)
while T<=B and L<=R:
if direction ==... |
284bfa0c623d6bfbfdda6fb4f3672d1ecceb02fa | ijuarezb/InterviewBit | /04_LinkedList/reverse_linked_list_II.py | 3,421 | 3.984375 | 4 | #!/usr/bin/env python3
import sys
from LinkedList import LinkedList
from LinkedList import Node
# Remove Element from Array
# https://www.interviewbit.com/problems/remove-element-from-array/
#
# Remove Element
#
# Given an array and a value, remove all the instances of that value in the array.
# Also return the numb... |
c39769c9474d860fda9ac1a3256a5bddd61d8692 | ijuarezb/InterviewBit | /04_LinkedList/subtract.py | 2,345 | 3.984375 | 4 | #!/usr/bin/env python3
import sys
from LinkedList import LinkedList
from LinkedList import Node
# List Cycle
# https://www.interviewbit.com/problems/list-cycle/
#
# Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
#
# Try solving it using constant additional space.
#
# Ex... |
c5027fb988a4e63929e3222d6d53c28ca3c0897d | ijuarezb/InterviewBit | /03_BinarySearch/rotated_sorted_array_search.py | 1,893 | 4 | 4 | #!/usr/bin/env python3
import sys
# Rotated Sorted Array Search
# https://www.interviewbit.com/problems/rotated-sorted-array-search/
#
# Suppose a sorted array is rotated at some pivot unknown to you beforehand.
#
# (i.e., 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... |
ce307f868fa8861b5d61ab189c361a6cf7d8a286 | ijuarezb/InterviewBit | /02_Math/gridUniquePaths.py | 730 | 3.75 | 4 | #!/usr/bin/env python3
class Solution:
# @param A : integer
# @param B : integer
# @return an integer
def uniquePaths(self, A, B):
if A == 1 or B == 1:
return 1
M = [[0 for j in range(B)] for i in range(A)]
for i in range(A):
M[i][0] = 1
for ... |
c4e134eded186551f1f47090c9b0f217ec850d9a | ijuarezb/InterviewBit | /07_DynamicProgramming/mapDecoding.py | 2,200 | 4 | 4 | #!/usr/bin/env python3
import sys
# A top secret message containing uppercase letters from 'A' to 'Z' has been encoded as numbers
# using the following mapping:
#
# 'A' -> 1
# 'B' -> 2
# ...
# 'Z' -> 26
# You are an FBI agent and you need to determine the total number of ways that the message can be decoded.
#
# Sinc... |
39cf8fcd01c32cbd4e6522665ad16620894149fd | ijuarezb/InterviewBit | /02_Math/rearangeArray.py | 860 | 3.859375 | 4 | #!/usr/bin/env python3
import sys
class Solution:
# @param A : list of integers
# Modify the array A which is passed by reference.
# You do not need to return anything in this case.
def arrange(self, arr):
# The function to rearrange an
# array in-place so that arr[i]
# becomes arr[arr[i]]... |
0f882e8b74773b888de20be38564c13642cd306a | ijuarezb/InterviewBit | /04_LinkedList/K_reverse_linked_list.py | 2,527 | 4.125 | 4 | #!/usr/bin/env python3
import sys
#import LinkedList
# K reverse linked list
# https://www.interviewbit.com/problems/k-reverse-linked-list/
#
# Given a singly linked list and an integer K, reverses the nodes of the
#
# list K at a time and returns modified linked list.
#
# NOTE : The length of the list is divisibl... |
41aff2c6737092010ed79ff48e2c3cf747e6eaac | KhangNLY/Py4E | /Assignment/Course 2 - Python Data Structures/Week 4 - Lists/8.5.py | 362 | 3.953125 | 4 | fname = input("Enter file name: ")
if len(fname) < 1: fname = "mbox-short.txt"
fh = open(fname)
count = 0
for line in fh:
line = line.rstrip()
wrd = line.split()
if len(wrd) < 3 or wrd[0] != 'From':
continue
print(wrd[1])
count = count + 1
print("There were", count, "lines i... |
0e8330781cac465d3bae07379fa9d2435940d03e | Ekimkuznetsov/Lists_operations | /List_split.py | 309 | 4.25 | 4 | # LIsts operations
# For each line, split the line into a list of words using the split() method
fname = input("Enter file name: ")
fh = open(fname)
fst = list()
for line in fh:
x = line.split()
for word in x:
if word not in fst:
fst.append(word)
fst.sort()
print(fst) |
33575e5dc09e6bbf484c2055c3468e5ac04ede9a | whc2/learn_python3 | /argparse2.py | 262 | 3.96875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'Martin Wang'
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('square', type = int, help = 'display a square of a given number')
args = parser.parse_args()
print (args.square**2)
|
bec36156b3853b4e791d88b69fa5083a3c07ea3c | huangyouqi1/python | /class_1.py | 1,314 | 3.796875 | 4 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
class Student(object):
def __init__(self,name):
self.name=name
def __str__(self):
return 'Student object (name:%s)' % self.name
__repr__=__str__
#print Student('Michael')
s=Student('hyq')
print s
class Fib(object):
def __init__(self):
self.a,self.b=0,1
def __... |
2548632ab144493b9a740909990c8614c209a355 | huangyouqi1/python | /functions.py | 5,431 | 4.15625 | 4 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
print abs(-123)
'''比较函数cmp(x, y)就需要两个参数,如果x<y,返回-1,如果x==y,返回0,如果x>y,返回1:'''
print cmp(1,2)
print cmp(2,1)
print cmp(2,2)
#数据类型转换
print int('123')
print int(12.3)
print float('12.3')
print str(12.3)
print unicode(123)
print bool(1)
print bool('')
'''在Python中,定义一个函数要使用def语句... |
997677bdef9a91265ceff47567a73b1e78017f57 | Mifour/Algorithms | /algopro/fibonacci.py | 254 | 3.703125 | 4 | def fib(n):
"""
O(2**n) time and space
"""
if n < 2:
return n
return fib(n-1) + fib(n-2)
def fib(n):
"""
O(n) time
O(1) space
"""
first = 0
second = 1
for i in range(2,n+1):
tmp = first+second
first=second
second = tmp
return second |
d3eb98e311edc55dbaab2c83a34c532afe51fa86 | Mifour/Algorithms | /algoexpert/easy_selection_sort.py | 356 | 3.859375 | 4 | def selection_sort(array):
current_index = 0
while current_index < len(array) - 1:
smallest_index = current_index
for i in range(current_index + 1, len(array)):
if array[smallest_index] > array[i]:
smallest_index =i
array[current_index], array[smallest_index] = array[smallest_index], array[current_index]... |
d0635e1cb5f50f4eec60245e3fcac64762c28499 | Mifour/Algorithms | /others/annagram.py | 702 | 3.890625 | 4 | """
annagram: for a sentence composed of strings, returned every couple of word that are annagram to each other
O(n) time & space
"""
def annagram(sentence):
words = sentence.split()
dico = {}
reversed_dico = {}
for word in words:
letters = "".join(sorted(list(word)))
reversed_dico[letters] = reversed_dico[let... |
d09c0331e0fcda88efbb1e749e0e157d08af8621 | Mifour/Algorithms | /algopro/is_BST_balanced.py | 850 | 3.6875 | 4 | class Tree():
def __init__(self, val, left=None, right=None):
self.value = val
self.left = left
self.right = right
def max_depth(tree):
if not tree:
return 0
depth_rigth=max_depth(tree.right)
depth_left=max_depth(tree.left)
return max(depth_left, depth_rigth)+1
def is_BST_balanced(tree):
return abs(ma... |
11fda23e19ab312f3b2c571ec3120c13f85f45e7 | Mifour/Algorithms | /algopro/merge_linked_lists.py | 678 | 3.84375 | 4 | class Node:
def __init__(self, val, next=None):
self.value = val
self.next = next
def merge_linked_lists(l1, l2):
"""
O(max(len(a), len(b))) time and space
"""
if l1.value < l2.value:
res= Node(l1.value)
l1 = l1.next
else:
res= Node(l2.value)
l2 = l2.next
head = res
while l1.value or l2.value:
if ... |
17367394a883b819225481eae7e259f41f29dce1 | Mifour/Algorithms | /algopro/check_palindrome.py | 726 | 4.0625 | 4 | def check_palindrome(string):
"""
Check if the given string can be rearange as a palidnrome
and if so, give a palidrome
O(n) time for n long string
O(n) space, worst case
"""
dico = {}
for letter in string:
dico[letter] = dico[letter]+1 if letter in dico else 1
palindrome = ''
even = ''
for k,v in di... |
f737db456059b71cbae0c2257a8e14142f19b2b1 | Mifour/Algorithms | /algopro/ransom_note.py | 492 | 3.921875 | 4 | """
is it possible to write a note from a magazine of letter?
O(n) time
O(n) space
"""
def ransom_note(note, magazine):
histo_note = {0 for l in ["abcdefghijklmnopqrstuvwxyz"]}
histo_magazine = {0 for l in ["abcdefghijklmnopqrstuvwxyz"]}
for letter in list(note):
histo_note[letter] +=1
for letter in list(magazin... |
f88e8013f5946f839fd26d64d679baa6f5522b9e | Mifour/Algorithms | /algopro/intersection_liked_lists.py | 481 | 3.75 | 4 | class LinkedList:
def __init__'self, val:
self.val = val
self.next = None
def intersection_liked_lists(a,b):
"""
return the intersection of 2 linked_lists
ex: 1->2->3->4->7
1->2->3->5
return 1->2->3
O(min(len(a),len(b))) time and space
""" s1 = []
s2 = []
while a.val:
s1.append(a.val)
a= a.next
wh... |
21b8a85392434146f2f6ef7bd2a88a50614affeb | jstnhuang/skin_segmentation | /src/skin_segmentation/hand_segmentation.py | 4,501 | 3.65625 | 4 | import cv2
import networks
import numpy as np
import tensorflow as tf
import utils.blob
def _get_image_blob(im, im_depth, pixel_means):
"""Converts an image into a network input.
Arguments:
im (ndarray): a color image in BGR order
Returns:
blob (ndarray): a data blob holding an image pyr... |
6171644644a41a02fd5e42a827e8addaea008a93 | SoutaTanaka/my_pyhton | /rsa/row_input.py | 997 | 3.765625 | 4 | import time
import random
from statistics import mean
def gcd(x, y):
if y == 0:
return x
else:
return gcd(y, x % y)
def f(x, n):
return (x**2 + 1) % n
def is_prime(q):
q = abs(q)
if q == 2: return True
if q < 2 or q&1 == 0: return False
return pow(2, q-1, q) == 1
def nea... |
89cd4afab898463889efed5b18db0c3761948fb7 | Anup-Toggi/python | /prime.py | 133 | 3.953125 | 4 | n=int(input("enter value: "))
c=0
for i in range(1,n+1):
if n%i==0:
c=c+1
if c==2:
print("prime")
else:
print("not prime")
|
8471f0c42f94c1785f93ea7b0c30c408b209a6fa | Anup-Toggi/python | /patterns/Swastika_pattern.py | 385 | 3.640625 | 4 | n=int(input())
for i in range(1,n+1):
if i!=n:
print('*',' '*(n-2),'*'*n if i==1 else '*',sep='')
else:
print('*'*(2*n-1),sep='')
for i in range(2,n+1):
if i==n:
print('*'*n,' '*(n-2),'*',sep='')
else:
print(' '*(n-1),'*',' '*(n-2),'*',sep='')
'''
output-
* *****
* *
* ... |
ab4510e6c21e3f505ee4d3e62ea8e40c86908a70 | Anup-Toggi/python | /OOPS/class and objects.py | 618 | 3.71875 | 4 | class Employee:
#constructor
def __init__(self):
reg_no=None
name=None
salary=None
#function for getting user data
def getdata(self):
self.reg_no=int(input("Enter Reg.No:"))
self.name=input("Enter Name:")
self.salary=int(input("Enter Sala... |
cc0784d7d69cce0b179938a785da4299578a17aa | Anup-Toggi/python | /patterns/10.py | 151 | 3.875 | 4 | n=int(input("enter number of rows: "))
for i in range(1,n+1):
for j in range(1,i+1):
print(j,end='')
print()
'''output
1
12
123
1234
12345
'''
|
cd711f3bb12b64a05d504e0574a61f731d269bd8 | Anup-Toggi/python | /matrix_by_list.py | 692 | 3.859375 | 4 | r,c=map(int,input("enter number of rows and cols: ").split())
m=[]
print("enter matrix elements: ")
for i in range(r):
l=[]
for j in range(c):
l.append(int(input(f"enter m[{i}][{j}]")))
m.append(l)
print(m)
print()
for row in m:
print(row)
print()
for row in m:
for e in row:
print(e,end='\t')
prin... |
cf9fb8e887ea311368d3e404e656b109b73740e0 | Anup-Toggi/python | /threading/thread.py | 238 | 3.578125 | 4 | import time
import threading
def f():
print("hello",10,"class")
time.sleep(5)
t1=time.time()
l=[]
for i in range(5):
l.append(threading.Thread(target=f))
l[-1].start()
for t in l:
t.join()
print(t)
t2=time.time()
print(t2-t1)
|
23e5cde4567028135d95f81a9345b7fe370d5ff4 | kapitsa2811/CS5242-Neural-Network-and-Deep-Learning-Assignments | /assignment2/CS5242_Assignment_2.py | 29,529 | 3.90625 | 4 |
# coding: utf-8
# # Assignment 2 - Building CNNs
#
# **ASSIGNMENT DEADLINE: 19 OCT 2017 (THU) 11.59PM**
#
# In this assignment we will be coding the building blocks for the convolutional neural network and putting them together to train a CNN on the CIFAR2 dataset (taking just 2 classes (airplane and bird) from the... |
0ea5a9036b49c2459f7e5f93d537eb31f44b738a | junwei-zhou/progam | /python-and-http-interface-test-master/4.7/trig2.py | 174 | 3.609375 | 4 | import time
high = int(input("请输入塔高"))
first = time.time()
for line in range(1,high):
print(" "*(high-line)+"*"*(line*2-1))
last = time.time()
print(last-first) |
e6ecd5211b15b6cb201bdd2e716a7b4fec2db726 | markcurtis1970/education_etc | /timestable.py | 1,693 | 4.5 | 4 | # Simple example to show how to calculate a times table grid
# for a given times table for a given length.
#
# Note there's no input validation to check for valid numbers or
# data types etc, just to keep the example as simple. Plus I'm not
# a python developer :-)
# Ask user for multiplier and max range of times tab... |
90487050fec8cbbf9184127c0ce6a076b2f922e2 | param-tech-23/python-basics | /com/paramtech/pythonlearning/basics/features/methods/MyParametersTest.py | 646 | 3.515625 | 4 |
def showDefaultParameter(name="aaa"):
print name
def showDefaultParameter2(age, name="aaa",):
print name
def addNames(name, names=[]):
names.append(name)
return names
def properAddNames(name, names=None):
if names is None:
names = []
names.append(name)
return names
if __name__ == ... |
6415c205f64bee60e5567968cc2903ee68790ade | param-tech-23/python-basics | /com/paramtech/pythonlearning/basics/features/MyPythonFeatures.py | 1,431 | 3.859375 | 4 | '''
Created on Apr 30, 2015
@author: bisdallas
'''
import string
def helloWorld():
print "this is hello world python program"
def showDifferentQuotes():
print 'this is single quote'
print "this is double quotes"
print """this is for multiline\n
statemenst we can right what ever we wanted
this is... |
867bf3fd244e23ab5471171172f3767827692c0e | aviloncho/hangman | /hangman/hangman.py | 2,140 | 3.5 | 4 | import os
import random
from hangman.pics import HANGMAN_PICS
MAX_ATTEMPTS = 7
def clear():
return os.system('cls')
class Hangman:
def __init__(self):
self.remaining_attempts = MAX_ATTEMPTS
self.failed_attempts = 0
self.user_chars = []
self.load_words()
def load_word... |
1a024d3e345afbcc0b8cfa354e14416401f9c565 | dogac00/Python-General | /generators.py | 1,253 | 4.46875 | 4 | def square_numbers(nums):
result = []
for i in nums:
result.append(i*i)
return result
my_nums = square_numbers([1,2,3,4,5])
print(my_nums) # will print the list
# to convert it to a generator
def square_numbers_generator(nums):
for i in nums:
yield i*i
my_nums_generator = square_numbers_gener... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.