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 |
|---|---|---|---|---|---|---|
6ca33abac0bc98a5ba66085dff9f8b1186b400ec | tanchao/algo | /interviews/indeed/comprehensible_ints.py | 779 | 3.640625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'tanchao'
# @param {integer[]} nums
# @return {string}
def comprehensible_ints(nums):
len_ = len(nums)
if len_ == 0:
return ''
if len_ == 1:
return str(nums[0])
i, res, flag = 0, '', False
for j in range(1, len_): # check... |
72e93d6dda36f93473602236a3c6c3a503f709af | tanchao/algo | /interviews/indeed/linked_list.py | 1,336 | 3.9375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'tanchao'
"""
Implement a linked array, where each node of a list contains a fixed size array.
"""
class FixedArray:
def __init__(self, s=10):
self.size = s
self.array = [None] * self.size
class Node:
def __init__(self, value=None,... |
22011a5ad6b6561b7027ef35c7abf1fa106b0626 | tanchao/algo | /interviews/plaid/transactions.py | 3,337 | 3.75 | 4 | """
Part 1
Minimum 3 transactions are required to consider it as a recurring transaction
Same company, same amount, same number of days apart - recurring transactions
Input: Company, Amount, Timestamp (Day of the transaction)
Output: An array of companies who made recurring transactions
Part 2
The amounts and timest... |
850d37364146466183f67ada043d8fac9766cf31 | tanchao/algo | /interviews/zenefits/string_chain2.py | 1,645 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'tanchao'
def word_ladder(start, end_len, dic):
word_queue, cur_word = [], start
word_queue.append(start)
while word_queue:
cur_word = word_queue.pop(0) # FIFO check words
if len(cur_word) == end_len:
if cur_word in d... |
f21823c7a97d5b635bdf10b6c8151792313c1150 | tanchao/algo | /interviews/indeed/lru_cache.py | 1,165 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'tanchao'
class LRUCache:
# @param capacity, an integer
def __init__(self, capacity):
self.capacity = capacity
self.caches = dict()
self.orders = []
# @return an integer
def get(self, key):
if key in self.or... |
9fce10ee9c7917b99472a2a42bfed805bf80ea97 | tanchao/algo | /archive/codeeval/py/shortest_repetition.py | 781 | 3.703125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'tanchao'
import sys
def shortest_repetition(line_):
width_, len_ = 1, len(line_) # max 80 chars
head_ = line_[0]
while True:
pattern_ = line_[:width_]
count_ = line_.count(pattern_)
if line_ == pattern_ * count_:
... |
8822adfd5f0a1d8732e8fa92f0834af2de2764e2 | shaheenery/udacity_ds_and_a_project2 | /problem_5.py | 2,548 | 4.375 | 4 | # Blockchain
# A Blockchain is a sequential chain of records, similar to a linked list. Each
# block contains some information and how it is connected related to the other
# blocks in the chain. Each block contains a cryptographic hash of the previous
# block, a timestamp, and transaction data. For our blockchain we w... |
e6d117be1d4c95a95859e9072d950d79d195920c | 2ntik/ProjectEuler | /#6.py | 255 | 3.625 | 4 | # Найдите разность между суммой квадратов и квадратом суммы первых ста натуральных чисел.
sk, ks = 0, 0
for i in range(1,101):
sk += i**2
ks += i
print(ks**2 - sk)
|
4a25b8344a82cb2c7d9fd948e1174d28fbac0a5a | gstqtfr/MNISTDigitSequence | /imagetransformutils.py | 3,366 | 3.53125 | 4 | #-*- coding: utf-8 -*-
import numpy as np
import cv2
# import matplotlib.pyplot as plt
# import matplotlib.pylab as pylab
from skimage import io, transform, util
def downscale_by_mean(img, cval=0.0):
"""
Down-samples image by local averaging.
:param img: image to downsample
:param cval: value to use f... |
ebf9daedf56c1601b4e79dd015012f0d174e7647 | maddyxplore/sortingz | /merge_sort.py | 533 | 3.96875 | 4 | def merge(left,right):
res = []
i,j = 0,0
while (i < len(left) and j < len(right)):
if left[i] < right[j]:
res.append(left[i])
i+=1
else:
res.append(right[j])
j+=1
res += left[i:]
res += right[j:]
return res
def mergesort(arr):
... |
efce9bd907d2493ea03807cd09ef298ac5facf58 | zoecahill1/pands-problem-set | /collatz.py | 1,060 | 4.34375 | 4 | # Zoe Cahill - Question 4 Solution
# Imports a function from PCInput which was created to handle user input
from PCInput import getPosInt
def collatz1():
# Calls the function imported above
# This function will check that the number entered is a positive integer only
num = getPosInt("Please enter a posit... |
ab7508fadaed1abf28047e9b03d29cde13f7490f | Atlanm/Python-mapsa | /Mojtaba-SemiRedis-project.py | 9,359 | 3.53125 | 4 | import os
from abc import ABC, abstractmethod
import hashlib
import pickle
open('password.txt', 'a+')
class Account(ABC): # abstract class to define concepts of an account
@abstractmethod
def signup(self):
pass
@abstractmethod
def login(self):
pass
class UserInterf... |
af26b65a925d494c7d486b21f5d014ee2aad2d46 | angelvv/HackerRankSolution | /10 Days of Statistics/Day1.Quartiles.py | 592 | 3.859375 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
N0 = int(input())
X = [int(x) for x in input().split(' ')]
def median(array):
N = len(array)
if N % 2 == 0:
med = (array[int(N/2-1)] + array[int(N/2)]) / 2
else:
med = array[int((N-1)/2)]
return med
sortedArray = so... |
a9f3fef226a7e9357100fd4944f873caf4381a21 | angelvv/HackerRankSolution | /10 Days of Statistics/Day5.PoissonDistributionII.py | 485 | 3.6875 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import math
meanA, meanB = [float(x) for x in input().split(" ")]
#E(C) = E(160+40X**2)
# = 160+40*E(X**2)
# = 160+40*(Var(X) + E(X)**2)
# = 160+40*(meanA + meanA**2)
costA = 160 + 40*(meanA + meanA**2)
costB = 128 + 40*(meanB + meanB**2)... |
7468590d8977af15c77c95cc04eff00af7c7b12c | angelvv/HackerRankSolution | /Algorithms/Warmup/10.TimeConversion.py | 781 | 3.75 | 4 | #!/bin/python3
import os
import sys
#
# Complete the timeConversion function below.
#
def timeConversion(s):
#
# Write your code here.
hh, mm, ss = map(int, s[:-2].split(':'))
pm = s[-2:]
h = hh%12 + (pm == 'PM') * 12
return(('%02d:%02d:%02d') % (h, mm, ss))
"""Alternatively: not... |
c57dc40df70eada89f74827f6ec191b79156182b | angelvv/HackerRankSolution | /Algorithms/Implementation/12.AppleAndOrange.py | 1,279 | 3.71875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the countApplesAndOranges function below.
def countApplesAndOranges(s, t, a, b, apples, oranges):
print(sum(s <= (a + x) <= t for x in apples))
print(sum(s <= (b + x) <= t for x in oranges))
""" For unknown reason, this on... |
0d471005c92412c4d365b4dc946c0498ccf0efb6 | angelvv/HackerRankSolution | /10 Days of Statistics/Day7.PearsonCorrelationCoefficientI.py | 503 | 3.828125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import math
N = int(input())
X = [float(x) for x in input().split()]
Y = [float(x) for x in input().split()]
def meanstd(list):
N = len(list)
mean = sum(list)/N
std = (sum([(i - mean)**2 for i in list]) / N)**0.5
return mean, std
m... |
3eb30ff9efa5fc0c3d3f12fd5af4bdeafac6be55 | angelvv/HackerRankSolution | /10 Days of Statistics/Day0.WeightedMean.py | 313 | 3.671875 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
N = int(input())
X = [float(x) for x in input().split(' ')]
W = [float(x) for x in input().split(' ')]
WeightedSum = 0
for i, elem in enumerate(X):
WeightedSum += elem * W[i]
WeightedMean = round(WeightedSum/sum(W),1)
print(WeightedMean)
|
f5a1217cc20985992e2364b7b89ebaf70cc2cc50 | Mkurtz424/n00bc0d3r | /Projects/CodingBat/String-1/String-1 without_end Mike.py | 115 | 3.6875 | 4 | def without_end(str):
if len(str) == 2:
return ""
else:
answer = str[1:(len(str)-1)]
return answer
|
1ed73112228aac056a60ddb30e0737addef9b920 | Mkurtz424/n00bc0d3r | /Projects/Labouseur/Project1Python.py | 847 | 3.921875 | 4 | print 'Please enter the number of US cents you would like to make coins for: '
number = input('>> ')
quarters = 25
dimes = 10
nickles = 5
pennies = 1
num_quarters = 0
num_dimes = 0
num_nickles = 0
num_pennies = 0
if (number/quarters) >= 1:
num_quarters = number/quarters
number = number - (quarters*(number/quarters)... |
f9efae5ed9d953399ac2e1c6107937c300b06cb0 | CompBiochBiophLab/pycbbl | /pycbbl/calculations/local.py | 4,935 | 3.59375 | 4 | import os
def parallel(jobs, cpus=6, script_name='commands'):
"""
Generates scripts to run jobs simultaneously in N Cpus in a local computer,
i.e. without a job manager. The input jobs must be a list representing each
job to execute as a string.
Two different scripts are written to execute the job... |
a698d8b8796efcb9a68b09330e323609d7438b6e | Alexkuzevich/Hangman_game | /hangman.py | 1,765 | 3.90625 | 4 | import random
import string
from words import words
# генерация случайного слова
def valid_word(words):
word = random.choice(words)
while ' ' in word or '-' in word:
word = random.choice(words)
return word.upper()
def hangman():
word = valid_word(words)
word_letters = set(word)
alpha... |
34105d79b2e516cf439bfe5a415bf50ea46b3e07 | codeshef/SummerInternship | /Day2_3/tableTuple.py | 213 | 3.6875 | 4 | # Print tables of number using
tp = tuple(input("Input numbers"))
#print(type(tp))
#print(tp)
for i in tp:
print(i + " table ")
for j in range(1, 11):
result = int(i)*j
print(result)
|
f9dfbf8b29d1a1673076aa512e2d89653af38b6a | codeshef/SummerInternship | /Day5/classesPython.py | 483 | 4.125 | 4 |
# <------- Day 8 work ------->
# classes in python
class User:
def __init__(self):
print("Hello!! I am constructor of class user")
def setUserName(self, fn, ln):
print("I am inside setUserNameFunc")
self.firstName = fn
self.lastName = ln
def printData(self):
p... |
fea195cffaec7a2b8b1bbad980a88578262f37cd | richygregwaa/CodeWars | /09_Categorize_Member.py | 927 | 3.71875 | 4 |
# My Solution
def openOrSenior(data):
categoryOut=[]
for member in data:
if member[0] >= 55 and member[1] > 7:
categoryOut.append("Senior")
else:
categoryOut.append("Open")
return categoryOut
# * * * * * * * * * * * *
# Alternative solution1 - I came close to this ... |
ddf1046d8432d6a192c4d5987c64a86c8d51a224 | richygregwaa/CodeWars | /07_Unique_in_Order.py | 2,580 | 3.796875 | 4 |
# My solution
def unique_in_order(iterable):
iterablelist = list(iterable)
it_count = 0
it_len = len(iterablelist) - 1
while it_count < it_len:
if iterablelist[it_count] == iterablelist[it_count+1]:
del iterablelist[it_count:it_count+1]
it_count -= 1
it_len... |
929e8572801b3fcabfa2bacaaa258d0528c8fb8c | SeanSyue/PythonReferences | /python_system/files/write_files.py | 589 | 3.5625 | 4 | # https://www.youtube.com/watch?v=Uh2ebFW8OYM
# Use seek() method to set the beginning point of file writing.
with open ('file_to_write.txt', 'w') as f:
f.write("Test")
f.seek(0)
f.write("R")
# Copy a file:
with open('text_file.txt', 'r')as rf, open('text_file_copy.txt', 'w') as wf:
for line in rf:
... |
ad21bcf5562f0cf3645526d21c1d9c808fba455b | SeanSyue/PythonReferences | /re_ref/re_ref.py | 1,998 | 3.875 | 4 | # https://github.com/CoreyMSchafer/code_snippets/tree/master/Python-Regular-Expressions
import re
text_to_search = '''
abcdefghijklmnopqurtuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
1234567890
Ha HaHa
MetaCharacters (Need to be escaped):
. ^ $ * + ? { } [ ] \ | ( )
coreyms.com
321-555-4321
123.555.1234
123*555*1234
800-555-123... |
78dd32d1d1aceeaf29a02574f732a580c99ebc71 | SeanSyue/PythonReferences | /python_system/make_dir/make_dir.py | 884 | 4.09375 | 4 | # https://stackoverflow.com/questions/273192/how-can-i-create-a-directory-if-it-does-not-exist
import os
import errno
# Not recommend this one:
# if not os.path.exists(directory):
# os.makedirs(directory)
try:
os.makedirs("D:/tim")
except OSError as e:
if e.errno != errno.EEXIST:
raise... |
b177e88573dc606d14c0efdda3ddeb329d362639 | SeanSyue/PythonReferences | /iterations/enumerate.py | 240 | 4.03125 | 4 | seasons = ['Spring', 'Summer', 'Fall', 'Winter']
enum = enumerate(seasons)
print(enum)
print(type(enum))
print(list(enum))
my_list = ['apple', 'banana', 'grapes', 'pear']
for c, value in enumerate(my_list, 1):
print(c, value)
|
222bf8c4c02e585e9ad4128d4dd14b3f39ec5c23 | SeanSyue/PythonReferences | /OOP_concepts/show_namespace_of_classes.py | 860 | 3.859375 | 4 | # https://github.com/CoreyMSchafer/code_snippets/blob/master/Object-Oriented/2-Class-Instance-Variables/oop.py
class Employee:
"""
Class object of employee information.
"""
# Class variable:
raise_amt = 1.05
def __init__(self, first, last, pay):
self.first = first
self.last =... |
c2de3681dc4accb3d9f8c10c67423b0f3e90ff66 | Ogrodniczek/HGpython | /random_even.py | 241 | 3.640625 | 4 | import random
found_even = []
while True:
current = random.randint(0,100)
if not current % 2:
if current not in found_even:
found_even.append(current)
if len(found_even) == 51:
break
print(found_even)
|
d1b60e896349c16a5f23f2aff64a26c8ae155c2e | rakshitraj/coursera-dsa | /Algorithmic Toolbox/Greedy Algorithms/Money Change/money_change.py | 344 | 3.96875 | 4 | # python3
def money_change(money):
assert 0 <= money <= 10 ** 3
coins = 0
for denomination in [10, 5, 1] :
new_coins = int(money/denomination)
money = money % denomination
coins += new_coins
return coins
if __name__ == '__main__':
input_money = int(input())
print(mon... |
5d57431b0e9ab9de7382fd0e263cb6a94814dfa9 | Neocrumm/code-snippets | /make-a-pie-chart.py | 3,766 | 3.53125 | 4 | import turtle
screen = turtle.Screen()
myPen = turtle.Turtle()
myPen.speed(0)
myPen.shape('turtle')
myPen.width(1)
myPen.pencolor("black")
myPen.degrees(360)
myPen.penup()
def drawPieChart(percentage1, percentage2, percentage3, percentage4, percentage5):
# Title of the Pie Chart
myPen.goto(0,-170)
myPen.left(90... |
7a7c97d0de64c7e0f492d6ea8a7a2597bb38a9ef | adityamagarde/MachineLearning_A-Z | /6_Decision_Tree_Regression.py | 1,232 | 3.578125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 9 21:42:36 2018
@author: adityamagarde
"""
##THIS IS FOR A SINGLE DIMESION
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#IMPORTING DATASET
dataset = pd.read_csv('dataset.csv')
X = dataset.iloc[:, 1:2].values
y = datase... |
48716f83e87439eb8e91f295df377435f68fdb25 | PAVAN123-G/PyProjects | /HEALTH MANAGEMENT SYSTEM.py | 1,347 | 3.96875 | 4 | import datetime
print('****** WELCOME TO HEALTH MANAGEMENT SYSTEM ******')
def harry():
F=input(f'enter the code a for food and b for exercise\n')
if F=='a':
file = open('harryfood.txt', 'r')
print(file.read())
return datetime.datetime.now()
elif F=='b':
file = open... |
cab9101d35e2cb4a4ae724d3758f5497045dc18b | won-cp/data-structures | /python/stack.py | 940 | 4 | 4 | class Stack:
# write your __init__ method here that should store a 'total' value which is the total number of elements in the Stack and a 'stack' value which is an array of stored values in the Stack
def __init__(self):
self.total = 0
self.stack = []
def push(self, data):
# write yo... |
4e77bb95897d9c566d5e7275333240f1670c5a77 | SemenkinaOlga/raspberry | /examples/5 - function.py | 581 | 3.546875 | 4 | import RPi.GPIO as GPIO
def isPressed(btn, led):
if GPIO.input(btn) == False:
GPIO.output(led, GPIO.HIGH)
else:
GPIO.output(led, GPIO.LOW)
button1 = 3
button2 = 4
led1 = 14
led2 = 15
GPIO.setmode(GPIO.BCM)
GPIO.setup(button1, GPIO.IN)
GPIO.setup(button2, GPIO.IN)
GPIO.setup(led1, GPIO.... |
1b19b82099f741ffa613a2f6099a8d521f4ceb2c | Carolineqyau/Data-Structures | /recursiveFunctions/findLargest.py | 216 | 3.875 | 4 | def findLargest(list):
if len(list) == 1:
return list[0]
else:
if list[0] <= list[1]:
return findLargest(list[1:])
else:
return findLargest([list[0]]+list[2:])
|
57fce95ec38ac3a32542a888fd7817086f9c5815 | atrace/advent_of_code | /day1/day1_script.py | 496 | 3.515625 | 4 | filename = "day1/day1_input.txt"
changes = open(filename,"r")
freq = [int(0)]
for line in changes:
new_freq = freq[-1] + int(line)
# result for part 2
if new_freq in freq:
print("First reoccuring frequency: "+str(new_freq))
break
freq.append(new_freq)
# result for part 1
print("Final... |
f327c8fe4c3d5c77a52f8769200e106790d9963b | Guilgalick/Trabalho-AV2 | /Trabalho.py | 12,203 | 3.71875 | 4 | import tkinter as tk
import tkinter.ttk as ttk
from tkinter import *
import sqlite3
import tkinter.messagebox as msg
app=Tk()
app.title("Sistema de reconhecimento de aluno")
width=700
height=400
app.config(bg="#6666ff")
sc_width = app.winfo_screenmmwidth()
sc_height =app.winfo_screenheight()
x = (sc_width/2) - (width/... |
522faa36406762bc5a943fb73a4e45f29f853bff | luxmafra/algorithmic-toolbox | /last_digit_fibonacci.py | 570 | 3.859375 | 4 | # Naive Solution:
def last_digit_of_fibonacci_number_naive(n):
assert 0 <= n <= 10 ** 7
if n <= 1:
return n
return (last_digit_of_fibonacci_number_naive(n - 1) + last_digit_of_fibonacci_number_naive(n - 2)) % 10
# Efficient Solution:
def last_digit_of_fibonacci_number(n):
assert 0 <= n <= 10... |
a1a40ad4d265d512f86157052e5a8b1332ddf976 | kingfischer16/pandex | /pandex/explore.py | 318 | 3.65625 | 4 | import pandas as pd
import numpy as np
def my_func(s):
"""
Prints the string 's' with a description of what it's doing.
Args:
s (string): The input string.
Returns:
None
"""
print(f"The test string passed to the function was: {s}")
return None
|
e5045b390c7b7dd520d4d0e49ad7c7c507437d4c | djoshuac/recursive-tic-tac-toe | /python/prototype.py | 1,893 | 3.859375 | 4 | from collections import namedtuple
from random import randint
### Index of each small game ###
# 7 8 9 tl tm tr
# 4 5 6 => ml mm mr
# 1 2 3 bl bm br
# 0th is who has won the box
### Players ###
# 1 is player 1
# 2 is player 2
# 0 is noone
class Board:
def __init__(self, size):
self.s... |
3346320c1327552ad55942ab22766aeec5866af7 | kcrum/oscillation-plots | /tricubic_interp_test.py | 1,452 | 3.53125 | 4 | import numpy as np
import matplotlib.pyplot as plt
def cubic_int(x, pmin1, p0, p1, p2):
xsq, xcb = x**2, x**3
# print 'xsq: %s xcb: %s' % (xsq, xcb)
xvect = np.array([(-xcb + 2*xsq - x), (3.*xcb - 5.*xsq + 2), (-3.*xcb + 4.*xsq + x), (xcb - xsq)])
# print 'xvect: %s' % xvect
pvect = np.... |
49e5cb4151d6df24b29d5f4d9c336e21b32ce436 | ameriel/nlp-assignments | /min-edit-distance/distance.py | 2,816 | 3.625 | 4 | #!/usr/bin/python
#Amerie Lommen & Dominic Pearson
#CS 404 Group Assignment 1 - Question 2: Minimum Edit Distance
#January 16, 2016
import sys
#Get argument values
args = sys.argv
if len(args) < 3:
print "Usage: python distance.py source target [n=1]"
exit()
else:
source = args[1]
target = args[2]
if len(args) ... |
8bbcda7b16e8e0a44850c18151f2ea9bdbd008d0 | dergaj79/python-learning-campus | /unit6_list/unit_6_exercise_6_3_1.py | 559 | 3.796875 | 4 | def list_exercise631():
list_1 = [0.6, 1, 2, 3]
list_2 = [3, 2, 0.6, 1]
list_3 = [9, 0, 5, 10.5]
list_1.sort()
list_2.sort()
list_3.sort()
print(list_1)
print(list_2)
print(list_3)
result_1 = are_lists_equal(first_list=list_1, second_list=list_2)
result_2 = are_lists_equal(fi... |
bc502be94ca45d1750cce48ca3c39f0eb9dd389c | dergaj79/python-learning-campus | /unit5_function/test.py | 959 | 4.125 | 4 | # animal = "rabbit"
#
# def water():
# animal = "goldfish"
# print(animal)
#
# water()
# print(animal)
# a = 0
#
#
# def my_function() :
# a = 3
# print(a)
#
#
# my_function()
# print(a)
# a=1
# def foo1():
# print(a)
# foo1()
# print(a)
# def amount_of_oranges(small_cups=20, large_cups=10):
# ... |
93851be736b94c138b938c718ae9e38d6c215c74 | eduardocodigo0/Login-por-reconhecimento-facial | /cria_banco.py | 493 | 3.75 | 4 | import sqlite3
from tkinter import messagebox
def criarBanco():
conn = sqlite3.connect('banco.db')
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE faces (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
nome TEXT NOT NULL,
foto TEXT... |
9f8220cbed18b0e05822ae99a652b649c682b08f | sandeeppal1991/D08 | /mimsmind0.py | 2,527 | 4.5625 | 5 | """In this version, the program generates a random number with number of digits
equal to length. If the command line argument length is not provided, the
default value is 1. Then, the program prompts the user to type in a guess,
informing the user of the number of digits expected. The program will then
read the user in... |
fbfdb5edfc00f5290bec15729991c28d2015696f | pulkin/curious | /tests/functions/2_2d_divergence.py | 157 | 3.890625 | 4 | #!/usr/bin/env python3
import sys
import math
x = float(sys.argv[1])
y = float(sys.argv[2])
if x == 0 or y == 0:
print("nan")
else:
print(1/x + 1/y)
|
93cc6fd2e9a28ca312253ed592a2c571dd8ad519 | Nitheesh1305/Innomatics_Internship_APR_21 | /Task - 1 (Python Programming)/4.py | 513 | 3.984375 | 4 | #Questuon 4 - Division
#Task
#The provided code stub reads two integers, and , from STDIN.
#Add logic to print two lines. The first line should contain the result of integer division, // .
# The second line should contain the result of float division, / .
#No rounding or formatting is necessary
a = int(in... |
f0dd89d467efc7181fbd27c0e9eb6e2410dcca15 | Endiexe/uas | /lematization.py | 347 | 3.6875 | 4 | import nltk
from nltk.stem import WordNetLemmatizer
wordnet_lemmatizer = WordNetLemmatizer()
sentence =input("Type the Sentence : ")
sentence_words = nltk.word_tokenize(sentence)
print("{0:20}{1:20}".format("Word","Lemma"))
for word in sentence_words:
print ("{0:20}{1:20}".format(word,wordnet_lemmatizer.... |
3adcd38f83d45e722077960cf50aaf3c435572ea | kncalderong/codeBackUp | /python/Rosalind_programming/stronghold/dna_as_rna.py | 305 | 4.3125 | 4 | dna=input('please enter your DNA sequence: ')
rna=list()
#!string to print a list as a string after..
string=""
for nt in dna:
if nt == 'T':
rna.append('U')
else:
rna.append(nt)
print('dna:',dna)
#!with .join() I can print a list as a string:
print('rna:', string.join(rna))
|
4f9ad362ac8ff8c1362a5aac5983e588694e9bc5 | kncalderong/codeBackUp | /python/Rosalind_programming/stronghold/grahps.py | 1,359 | 3.546875 | 4 | ###! open file and read the FASTA
name = input('Please enter the name of FASTA file: ')
if len(name) < 1: name = "graphs_sample.fasta"
try:
with open(name, "r") as data:
d = data.read().splitlines()
except:
print('sorry, name of FASTA not found')
quit()
def getfastas(self):
name_seq = ""
... |
2c9bdf688c48466aec65d9c3b61a9d5518bf0387 | DoerteMitHut/distancemeasureofembeddedgraphs | /graph_distance.py | 32,971 | 3.515625 | 4 |
class Vertex():
def __init__(self,index,x,y):
self.index = index
self.coords = (x,y)
self.incidentEdges = set()
self.placements = set()
self.containingPlacements = dict()
self.marked = False
self.visited = False
self.placementCount = 0;
self.l... |
d042af6038b6d7817281d8b9344f3029701bfae0 | Sagar3195/AirQualityIndex-Project | /DecisionTreeRegressor.py | 5,387 | 3.8125 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
##Loading dataset
df = pd.read_csv("Data/Real_Data/Real_combine.csv")
print(df.head())
print(df.shape)
##Check null values in dataset
print(df.isnull().sum())
... |
a7bea01157a295e99b32bafba582d983f5a40705 | KratosOmega/BTB | /_archived/feel.py | 4,280 | 3.703125 | 4 |
from random import *
from math import *
import time
import numpy as np
import copy
"""
1. feeling clock is rotating, all features has specific time of staying,
corresponding feature will be giving more time of staying. While staying,
a random.uniform(0, 1) will be adding values to the corresponding feature
pool.... |
ea4f5f5baba0d6b594c0163d957d543482dee1f0 | apsommer/data_structures | /problem_3.py | 10,671 | 4.125 | 4 | import sys
# node for an unsorted binary tree
class Node:
# each node has a key:value pair, and a left and right child
def __init__(self, key, value):
self.key = key
self.value = value
self.left = None
self.right = None
# unsorted binary tree (BT)
class BinaryTree:
# all... |
e863c16b104a02cd12872b6aa984b1ae84c46c56 | yangwooseong/eulerproject | /pro46.py | 701 | 3.859375 | 4 | from __future__ import print_function
import math,time
def is_prime(number):
if number > 1:
if number == 2:
return True
if number % 2 == 0:
return False
for current in range(3, int(number**0.5) + 1, 2):
if number % current == 0:
return F... |
aa4372a519e20bd1a879de45646bf4f73254fd21 | yangwooseong/eulerproject | /pro15_study.py | 686 | 3.609375 | 4 | # Lattice paths from (0,0) to (n,n) but do not pass below the diagonal
from __future__ import print_function
def routes(n):
dp = []
for i in range(n):
dp.append([])
for j in range(n):
if j <= i:
dp[i].append(0)
for i in range(n)[::-1]:
for j in range(len... |
46888f48af85aa51067e50b537e670510dad01c8 | asuddenwhim/DM | /own_text.py | 776 | 4.125 | 4 |
from nltk import word_tokenize, sent_tokenize
text = "Generally, data mining (sometimes called data or knowledge discovery) is the process of analyzing data from different perspectives and summarizing it into useful information - information that can be used to increase revenue, cuts costs, or both. Data mining softwa... |
dd05eaabd62c1bdf283ae2a313b4e638b0be5a9a | 2illlogic/misc | /linkedlist.py | 829 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 19 14:30:05 2019
@author: bob
"""
def make_linked_list(l):
"""Input list object l, return dict object ll that is a linked list"""
n = len(l)
ll = {}
ll[l[0]] = (l[0], l[1])
ll[l[n-1]] = (l[n-2],l[n-1])
for i in range(1, n-1):... |
ae2f7610e8d7426f2d9d678a2a483e57e0225469 | zhao8445/leetcode | /Solution/56.merge.py | 1,123 | 4.09375 | 4 | from typing import List
def merge(intervals: List[List[int]]) -> List[List[int]]:
"""合并区间"""
intervals.sort(key=lambda x: x[0])
print(intervals)
merged = []
for interval in intervals:
# 如果列表为空,或者当前区间与上一区间不重合(上一个区间的右端值 < 下一个区间的左端值,直接添加
if not merged or merged[-1][1] < interval[0]:... |
14e78f997eff1cd6eac034583938255a5101ed27 | hfboyce/PPDS_book | /_build/jupyter_execute/modules/module1/module1_03.py | 5,299 | 3.90625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # What is Pandas?
#
# :::{admonition} Watch it
# See the accompanied youtube video at <a href="https://www.youtube.com/embed/W88f5DAl9hk?start=120&end=371" target="_blank">the link here.</a>
# :::
#
# Pandas is an add-on library to Python.
#
#
# <center>
#
# <img src='../im... |
dd4e7f41cbcadbfd64f77532515ec47655bc0ffa | hfboyce/PPDS_book | /_build/jupyter_execute/modules/module2/module2_25__.py | 18,051 | 3.671875 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Grouping and aggregating
#
# :::{admonition} Watch it
# See the accompanied youtube video at <a href="https://www.youtube.com/embed/WCWi1R2CQsY?start=1740&end=2104" target="_blank">the link here.</a>
# :::
#
#
# <br>
#
# ---
#
# *_Which manufacturer has the highest mean s... |
dde51eb3f188fbe9d8937aa58d68bafb7e0ce98b | hfboyce/PPDS_book | /_build/jupyter_execute/modules/module1/module1_20__.py | 8,210 | 4.21875 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Slicing and selecting using .iloc\[\]
#
# :::{admonition} Watch it
# See the accompanied youtube video at <a href="https://www.youtube.com/embed/W88f5DAl9hk?start=1011&end=1456" target="_blank">the link here.</a>
# :::
#
# Up until point, we have been manipulating our datafr... |
086bfb9d3bc7cccfce20481d7a86ea55294b8bee | RenanMarshall/Algoritms-in-python | /Dados, Variáveis e Entrada e Saída/EX02.py | 459 | 3.90625 | 4 | # Desenvolva um algoritmo que solicite ao usuário uma quantidade de dias, de horas, de minutos e de segundos. Calcule o total de segundos resultante e imprima na tela para o usuário.
# Main
dias = int(input('Digite a quantidade de dias:'))
horas = int(input('As horas:'))
min = int(input('Os minutos:'))
seg = int(inpu... |
66f0e81e3fbfb846264255e4c5908af69a83907b | RenanMarshall/Algoritms-in-python | /Trabalhos/EX_01.py | 1,304 | 4.0625 | 4 | # Main Program
print('Inicio do programa!')
while True:
# Uso do try para lidar com as excessões em geral.
try:
x = input('Deseja inserir dados?\t[S/N]')
if x.lower() in 'n':
break
if x.lower() not in 's':
print('Digite S para continuar. Ou N para encerrar o programa!')
continue
no... |
a6bae6f6c4ea505d810fba91dcdecb9b5ed6c2db | RenanMarshall/Algoritms-in-python | /Estrutura de Dados/EX08.py | 535 | 3.96875 | 4 | def max_value(list):
max_num = 0
for i in list:
if i > max_num:
max_num = i
return max_num
def sum_of_list(list):
sum_of_list = 0
count = 0
for nota in notas:
sum_of_list += nota
count += 1
return sum_of_list / count
# Main
notas = [9,7,7,10,3,9,6,6,2]
... |
cf2e12e4f3fbaf46917d4270e006cf957aade033 | RenanMarshall/Algoritms-in-python | /Estrutura de Dados/EX11.py | 809 | 4 | 4 | def cal_average(num):
sum_num = 0
for t in num:
sum_num = sum_num + t
avg = sum_num // len(num)
return 2021 - avg
cadastro = {'nome':[],'sexo':[],'ano':[]}
total = 0
i = 0
while True:
terminar = input('Deseja realizar mais um cadastro ? [S/N]:')
if terminar.upper() in 'N':
bre... |
0e439e1738b39b522519e979bf6f5d7685abe53f | RenanMarshall/Algoritms-in-python | /Algoritmos Iterativos, Estruturas de repetição/EX06.py | 763 | 3.984375 | 4 | # Escreva um algoritmo que repetidamente pergunte ao usuário qual sua idade e seu sexo (M ou F).
# Para cada resposta o programa deve responder imprimir a mensagem: “Boa noite, Senhor.
# Sua idade é <IDADE>” no caso gênero de masculino e “Boa noite, Senhora. Sua idade é <IDADE>” no caso de gênero feminino.
# O programa... |
f342b5ab149c9678fba615fc9723e8eaa6890c4e | Galymbekov/WebDev-Python | /hackerrank/3.py | 93 | 3.578125 | 4 | n = int(input())
m = int(input())
sum = n + m
dif = n - m
prod = n * m
print(sum, dif, prod) |
1e7db90033a0f66814ddd3eada5fbaf26424755d | rashedrahat/wee-py-proj | /hangman.py | 1,407 | 4.25 | 4 | # a program about guessing the correct word.
import random
i = random.randint(0, 10)
list = [["H*ng*a*", "Hangman"], ["B*n**a", "Banana"], ["*wk*ar*", "Awkward"], ["B*n**", "Banjo"], ["Ba*pi*e*", "Bagpipes"], ["H*p**n", "Hyphen"], ["J*k*b*x", "Jukebox"], ["O*y**n", "Oxygen"], ["Num*sk*l*", "Numbskull"], ["P*j*m*... |
8cb892b68de3aedf9e1eac75ebe3a099b60ae9d4 | AgungPramono/belajar-python | /src/tipe-data.py | 1,073 | 3.796875 | 4 |
#tipe data bilangan bulat
a = 5
print(a)
#tipe data float / pecahan
a = 2.0
print(a)
#tipe data complex
a = 1+2j
print(a)
#deret fibonaci
x = [0] * 10005 #inisialisasi array sebanyak 10005
x[1] = 1
for j in range(2,10001):
x[j]=x[j-1]+x[j-2]
print(x[10000])
b = 0.1234567890123456789
print(b)
b = 1234567... |
beb5885d0a6564b90a8104061220db9910f68824 | loma373/Divide-and-Conquer | /binarySearch.py | 642 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 15 11:10:52 2021
@author: Amol
"""
def binarySearch(arr, low, high, x):
while low <= high:
mid = low + (high - low) // 2;
if arr[mid] == x:
return mid
elif arr[mid] < x:
low = mid + 1
e... |
767e0cf0f1702d35488725404b3cdb893c15fb4c | KenCoder/ThreeDunc | /three.py | 7,088 | 3.953125 | 4 | RIGHT = 0
LEFT = 1
DOWN = 2
UP = 3
from random import *
from copy import *
def generatePackage(random_function, largest_value = 0):
if random_function(2) != 0 or largest_value == 0:
new_package = ThreePackage(default_package)
print default_package
else:
all_below = range(1, largest_val... |
4789f3064dbf6db56231c689c2ec706f934264ac | gitHirsi/PythonNotes02 | /day08-多任务-协程/03-迭代器_斐波那契数列.py | 1,092 | 4.09375 | 4 | """
@Author : Hirsi
@ Time : 2020/7/5
"""
"""
自定义迭代器得到斐波那契数列
1)a保存第一列数据 b保存第二列数据
2)a=b b=a+b
3) 取a的值,获得斐波那契数列
"""
import time
class Fibnacci(object):
def __init__(self, num):
self.num = num
# 记录下标位置的实例属性
self.current_index = 0
# 定义变量保存斐波那契数列的第一列和第二列
self.a ... |
61e8e1a6e36b6ab16d3e91bece74a75d943abe4c | gitHirsi/PythonNotes02 | /day06-多任务-线程/05-守护线程.py | 453 | 3.609375 | 4 | """
@Author : Hirsi
@ Time : 2020/6/30
"""
"""
线程守护 : 子线程守护主线程 setDaemon(True)
"""
import time
import threading
def work1():
for i in range(10):
print('正在执行work1...',i)
time.sleep(0.5)
if __name__ == '__main__':
thread_work1 = threading.Thread(target=work1)
# 线程守护
thread_work1.setDae... |
4daecceedc08944fa40f549a7de360d4a8f2c5c2 | gitHirsi/PythonNotes02 | /day06-多任务-线程/10-死锁.py | 763 | 3.6875 | 4 | """
@Author : Hirsi
@ Time : 2020/7/1
"""
import threading
# 创建锁
lock = threading.Lock()
# 定义获取列表值得函数,参数为索引值
def get_value(index):
# 定义列表
data_list = [1, 3, 5, 7, 9]
# 上锁
lock.acquire()
# 输出内容
if index >= len(data_list):
print("下标 %d 越界" % index)
""" ***要在return 之前解锁,否则剩下的线程... |
5000cc452996c5c9dd1178cbf3f9b04e95a4fcdd | VolodymyrSlav/Codewars | /who_likes_it.py | 521 | 3.9375 | 4 | def likes(names):
if not names:
return 'no one likes this'
elif len(names) == 1:
first = ''
second = names[0]
elif len(names) == 2:
first = names[0]
second = names[1]
elif len(names) == 3:
first = ', '.join(names[:2])
second = names[-1]
else:
... |
d46ec2cdd661faa6e8fdcff5ee945c17a044cb26 | jmockbee/reviewquiz1 | /problems.py | 356 | 3.890625 | 4 | bill = 47.28
tip = bill * 0.15
total = bill + tip
share = (total/5)
print("Each person needs to pay:" + str(share))
numerator = 10
denominator = 10
result = numerator / denominator
print(result)
word1 = "How"
word2 = "do"
word3 = "you"
word4 = "like"
word5 = "Python"
word6 = "so"
word7 = "far?"
print(word1, word2... |
a60c2e8e395157a1b1598cfdbdf0634a8306ba8e | projeto-de-algoritmos/Grafos1_WarFGA | /sources/main.py | 433 | 3.515625 | 4 | import sys
from classes import Game
# create the game object
g = Game.Game()
# how many players have
if len(sys.argv) <= 3 or len(sys.argv) > 7:
print ("Número inválido de jogadores.")
g.quit()
g.count = 0
g.start_game(sys.argv)
g.players = len(sys.argv) -1
while True:
g.arrange()
g.play1()
g.play2()
g.p... |
8d7413d0f464592e588b34843ceca4ff679e8935 | Radu-Raicea/Blockchain-PoC | /pow.py | 830 | 3.671875 | 4 |
import hashlib
def generate_new_proof(previous_proof):
"""
Finds the next proof that, when concatenated to and hashed with the previous_proof, returns a hash with 4 leading zeroes.
:param int previous_proof: Proof of the previous block
:return int: Proof of the next block
"""
proof = 0
... |
dbb0bec40f7c0832c643b66d1e58241d373cd38c | davudduran/CodecraftCS50 | /hafta6/task7-vigenere.py | 2,629 | 3.9375 | 4 | # kütüphaneleri çağır
import sys
from cs50 import get_string
def main():
# Girdi kontrolü ve anahtar kontrolü için
# validate_key fonksiyonunu çağırıyoruz
key = validate_key()
# kullanıcıdan girdi istiyoruz ve bu girdiyi
# şifrelemek üzere encrypt fonksiyonuna gönderiyoruz
plaintext = get_stri... |
3e956e0312bd905a9f9cd602c3a302ad3578a02a | jslee6091/python_basic | /mycode/10_pythonic_code/split_join.py | 1,136 | 3.953125 | 4 | my_str = 'java python kotlin'
my_list = my_str.split()
print(type(my_list), my_list)
my_str2 = ''.join(my_list)
print(my_str2)
my_str3 = 'java,python,kotlin'
my_list2 = my_str3.split(',')
print(type(my_list2), my_list2)
my_str4 = '/'.join(my_list2)
print(my_str4)
# for + append
result = []
for i in range(10):
re... |
4bff8680660c91f0f35849c54a797a9691b6a8de | jslee6091/python_basic | /mycode/3_string/str_test.py | 1,331 | 4.03125 | 4 | greet = 'hello' * 4 + ' people' + '\n'
end = 'gogogo'
en2 = 'my name is \'jae sung lee\' thank you'
print(greet + end + '\n' + en2)
# string offset (or index)
value1 = 'hello world'
print('string length is', len(value1))
print('format : string length is {} and first index is {}'.format(len(value1),value1[10]))
# after... |
6a2aad8c018ac579ba11c1ac1d7405e03950bf16 | jslee6091/python_basic | /exercise/age_student.py | 348 | 4.21875 | 4 | # age = now year - born year +1
from datetime import datetime as dt
current = dt.today().year
print(current)
my_year = int(input())
print(type(my_year))
age = current - my_year + 1
if 17 <= age < 20:
print('you are high school student!')
elif 20 <= age <= 27:
print('you are university student!')
else:
pr... |
9e90f67ac9ec876585f388825be70c62f279dbaf | R6Doc/AirBnB_clone | /tests/test_models/test_amenity.py | 713 | 3.71875 | 4 | #!/usr/bin/python3
""" Test amenity """
import unittest
import models
from models.amenity import Amenity
from models.base_model import BaseModel
class amenity_tests(unittest.TestCase):
""" Test for amenity file """
def test_amenity(self):
""" Test the subclass amenity """
inst = Amenity()
... |
3cf72ac998bf8816ad00f2b43232642cb7d9539a | Dania-sl/KOL_2 | /51.py | 533 | 3.8125 | 4 | '''
Дан одновимірний масив а. Сформувати новий масив, який складається
тільки з тих елементів масиву а, які перевищують свій номер на 10. Якщо таких
елементів немає, то видати повідомлення.
'''
import numpy as np
A = np.random.randint(0, 20, 15)
A_2 = np.array([])
for i in range(len(A)):
if A[i]-10 > i:
... |
ff08b97e377453c7699241690163156e0202d0bd | Dania-sl/KOL_2 | /45.py | 423 | 4.09375 | 4 | '''
Перетин даху має форму півкола з радіусом R м.
Сформувати таблицю, яка містить довжини опор, які встановлюються через кожні R / 5 м.
'''
import math
R = int(input('Enter radius: '))
l = R / 5
x = 0
i = 0
while x < 2 * R - l:
x += l
i += 1
print(f'{i} = {math.sqrt(x * (2 * R - x)): .2f}')
... |
fcb2113777ea6cb29e9c632315f5842e00351677 | Dania-sl/KOL_2 | /38.py | 680 | 3.75 | 4 | '''
Дані про направлення вітру (північний, південний, східний, західний) і
силі вітру за декаду листопада зберігаються в масиві. Визначити, скільки днів дув
південний вітер з силою, що перевищує 8 м / с.
'''
import numpy as np
from random import choice
from random import randint
l = ["Північний ", "Південний"... |
591355c8d8a0156b1677292bd09e5a86b72a5257 | Dania-sl/KOL_2 | /31.py | 406 | 3.625 | 4 | '''
Обчислити середнє арифметичне значення тих елементів одновимірного
масиву, які потрапляють в інтервал від -2 до 10.
'''
import numpy as np
A = np.random.randint(-8, 20, 15)
A_2 = np.array([])
for i in A:
if -2 < i < 10:
A_2 = np.append(A-2, i)
print(A)
print(f'{np.mean(A_2):.2f}')
|
f8eb8786c09942b47be45f3f4f978ab4bd3b063d | Dania-sl/KOL_2 | /35.py | 443 | 3.5625 | 4 | '''
Дан лінійний масив цілих чисел. Перевірте, чи є він упорядкованим по
спаданню.
'''
import numpy as np
A = np.zeros(10)
for i in range(len(A)):
A[i] = int(input('Enter element: '))
c = True
l = len(A)
for i in range(l - 1):
min = i
for j in range(i + 1, l):
if A[j] < A[min]:
... |
4d25b7b2cfbeb53436a83f46bc105d77e57ffd4c | Dania-sl/KOL_2 | /32.py | 341 | 3.71875 | 4 | '''
Змінній t привласнити значення істина, якщо в одновимірному масиві є
хоча б одне від’ємне і парне число.
'''
import numpy as np
A = np.random.randint(-8, 20, 15)
for i in A:
if i < 0 and i % 2 == 0:
t = True
print(A)
print(t)
|
38b854f8c076bf8f901e973856d48bc75780e54a | Dania-sl/KOL_2 | /6.py | 438 | 3.765625 | 4 | '''
Створіть масив А [1..8] за допомогою генератора випадкових чисел з
елементами від -10 до 10 і виведіть його на екран. Підрахуйте кількість від’ємних
елементів масиву.
'''
import numpy as np
X = np.random.randint(-10, 10, 8)
print(X)
c = 0
for i in X:
if i < 0:
c += 1
print(c)
|
35e150fede1e5d5d248ca555579946971c5810ba | PMurph/OnlineProblems | /Project Euler/Problem 4/palindrome.py | 561 | 3.90625 | 4 | import math
def isPalindrome(num):
num_str = str(num)
digits = len(num_str)
if digits == 1:
return True
else:
return num_str[:int(math.floor(digits/2.0))] == num_str[-int(math.floor(digits/2.0)):][::-1]
max = 0
# assumes that the biggest palindromic number that is the product of two 3... |
8fe49f33d844a8da056321e24aeb2adeba87f5b3 | erikac613/PythonCrashCourse | /3-9.py | 151 | 3.65625 | 4 | guests = ['geddy lee', 'john cleese', 'st. vincent', 'john lennon', 'kate bush', 'patrick stewart']
print("There will be a total of " + str(len(guests))) + " guests at dinner."
|
f7126ccfad5822a0b5c4fc6ef22308d30df36ce2 | erikac613/PythonCrashCourse | /employee.py | 323 | 3.6875 | 4 | class Employee(object):
"""Records name and annual salary of a given employee."""
def __init__(first_name, last_name, salary):
self.first_name = first_name
self.last_name = last_name
self.salary = salary
def give_raise(self, raise_amount=5000):
raise = self.give_rais... |
cc791a5329a6bae96291a049ec343cbb2a5cf3f0 | erikac613/PythonCrashCourse | /7-10.py | 481 | 3.953125 | 4 | places = {}
polling_active = True
while polling_active:
name = raw_input("\nWhat is your name? ")
place = raw_input("If you could take a vacation anywhere, where would you go? ")
places[name] = place
repeat = raw_input("\nWould you like to let someone else reply? yes/no ")
if repeat =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.