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 |
|---|---|---|---|---|---|---|
2336f58dbaff1a95e37c67451628847f0132ff98 | Liamplussquared/binarysearch | /generate-primes.py | 539 | 3.53125 | 4 | # https://binarysearch.com/problems/Generate-Primes
class Solution:
def solve(self, n):
# using Sieve of Eratosthenes
if n < 2:
return []
elif n == 2:
return [2]
A = [True] * (n+1)
res = []
for i in range(2, int(sqrt(n))+1):
if A[... |
a9d413ce0fda1ec9d81b28ec7ccb208260e799dc | Liamplussquared/binarysearch | /tranpose-of-matrix-notes.py | 257 | 3.75 | 4 | # https://binarysearch.com/problems/Transpose-of-a-Matrix
"""
*, ** -> unpacking operators
zip() -> maps index of iterables together
"""
class Solution:
def solve(self, matrix):
zipped = zip(*matrix)
return [list(col) for col in zipped]
|
c57b3d10b9c0520a1e109106e058d6c4d87430eb | Liamplussquared/binarysearch | /three-six-nine.py | 307 | 3.703125 | 4 | # https://binarysearch.com/problems/3-6-9
class Solution:
def solve(self, n):
res = []
for i in range(1, n+1):
if i % 3 == 0 or any(t in str(i) for t in ['3','6','9']):
res.append("clap")
else:
res.append(str(i))
return res |
e1291fa6699b98059197264af64e21efc358e037 | Liamplussquared/binarysearch | /rotation-another-string.py | 157 | 3.703125 | 4 | # https://binarysearch.com/problems/Rotation-of-Another-String
class Solution:
def solve(self, s0, s1):
return s0 in (s1+s1) and len(s0)==len(s1) |
2e3c0d2a13d290cbed6788df8c110f512a2286b9 | Liamplussquared/binarysearch | /reverse-words.py | 164 | 4.03125 | 4 | # Reverse-Words
def reverse_words(sentence):
words = sentence.split()
res = ""
for word in words[::-1]:
res += word + " "
return res.strip() |
655bc88f8ff10a0500a31049f027a29da33610a9 | Jniosco/Python-Connect-Four-w-AI | /connect_four_pygame.py | 5,604 | 3.765625 | 4 | # np.zeros(x,y) creates a board for you using zeroes
import numpy as np
ROW_COUNT = 0
COLUMN_COUNT = 0
while ROW_COUNT * COLUMN_COUNT < 16:
while ROW_COUNT < 4:
ROW_COUNT = int(
input("Please select the size of the rows (Must be greater or equal to 4): "))
if type(ROW_COUNT) != "int... |
2a734e755b0490ff31318c7e8288e3c781473e07 | rongkeke/test-two | /test1.py | 393 | 3.71875 | 4 | #!/usr/bin/env python
# _*_ coding: utf-8 _*_
_metaclass_ = type
class Person:
def setName(self, name):
self.name = name
def getName(self):
return self.name
def greet(self):
return "Hello world! I'm %s." % self.name
foo = Person()
bar = Person()
foo.setName('rongkeke')
bar.setName(... |
4fdf8c3fe7b3cc5ae732f45ace058f2a499c2d22 | KaappoRaivio/wordamentcrack | /dfs.py | 598 | 3.578125 | 4 | """
vector<pair<int,int>> adjacents[4][4];
bool visited[4][4];
void dfs(int x, int y) {
if (visited[x][y]) return;
visited[x][y] = 1;
// handle the case
for (auto adjacent : adjacents[x][y]) {
dfs(adjacent.first, adjacent.second);
}
visited[x][y] = 0;
}
"""
from typing import List, Tu... |
73181a76e6fbd8fc4e6bdce4bc5f54e1ec945127 | iglesiasfacu/AlgoritmosED_2020 | /TP1_Recursividad/Funciones_Recursivas.py | 6,172 | 3.9375 | 4 | # EJ 1
def fibonacci(n):
'''Sucesion de fibonacci'''
if n == 0 or n == 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
# EJ 2
def suma(n):
'''Sumatoria entre 0 y un numero dado'''
if n == 0:
return n
else:
return n + suma(n-1)
# EJ 3
def prod(n1, n2):... |
49d78753e0932b2deb04ee1edc7fbada7274839d | jaysoza/LPTHW | /ex3.py | 1,891 | 4.09375 | 4 | print "I will now count my chickens:" # This shows text after the 'print' command in powershell
print "Hens", 25 + 30 / 6 # This is a math equation labeled 'Hens'. The output will compute the math equation
print "Roosters", 100 - 25 * 3 % 4 # This is a math equation labeled 'Roosters'. The output will compute the mat... |
5f79d469738f9c413508d9d17146efefdd771aa7 | JaredCorker/ProjectEuler | /problem_03.py | 603 | 3.671875 | 4 | #The prime factors of 13195 are 5, 7, 13 and 29.
#What is the largest prime factor of the number 600851475143 ?
import math
def get_factors(n):
factors = []
for x in range(1, int(math.sqrt(n) + 1)):
if n % x == 0:
factors.append(x)
factors.append(n // x)
return factors
de... |
c249952a75d9ee0be2a63c1e77040d41e5caa7c9 | qiutaoding/QD_nanoKit_py3 | /fosmid/parseFa.py | 1,033 | 3.953125 | 4 | # -*- coding: utf-8 -*-
#define FASTA file
#1st argment is designed for extracted read name. 2nd is for the sequence in FASTA file
#this readFa function is designed for single fasta sequence parsing
def readFa(readName,readFile):
filename=str(readFile)+".fa"
headerInfo="" #sequence header information to retur... |
d2d68d63813ccd34f7519e24c3dc42b6e4a5b6cd | pdxgitit/python_class | /teaching/solutions/11.py | 419 | 3.78125 | 4 | # You will be provided with an initial list (the first argument
# in the destroyer function), followed by one or more arguments.
# Remove all elements from the initial array that are of the same
# value as these arguments.
def destroyer(first, *argv):
for item in argv:
while item in first:
firs... |
caf06f7e43c1059ff4037920ecbde22319fa2c1d | pdxgitit/python_class | /test.py | 173 | 3.8125 | 4 | unknown = "1234567890111213359439058709587350975309"
if len(unknown) % 2 == 1:
print("It's odd!")
elif len(unknown) % 2 == 0:
print("It's even")
else:
print("whaaa??")
|
e1ca0db7edd3217c8bf9774097aa9e8f125b45cb | chengyiz/CSC411-Machine-Learning | /A2/code/q2_2.py | 5,926 | 3.59375 | 4 | '''
Question 2.2 Skeleton Code
Here you should implement and evaluate the Conditional Gaussian classifier.
'''
import data
import numpy as np
# Import pyplot - plt.imshow is useful!
import matplotlib.pyplot as plt
def compute_mean_mles(train_data, train_labels):
'''
Compute the mean estimate for each digit c... |
70e4720947beec724b84aa84bd1e807dffa03832 | Indie-Jones/Advent-Of-Code | /Day_01/main.py | 722 | 3.78125 | 4 | def sum_by_two(input):
for i, x in enumerate(input):
for y in input[i:]:
if x + y == sum:
return str(x * y)
def sum_by_three(input):
for i, x in enumerate(input):
for j, y in enumerate(input[i:]):
for z in input[j:]:
if x + y +... |
0c09fd17dede62fc00c93f453edf12c91190bdb2 | sarahclarke-skc/week_02-day_2_bus_stop_lab | /src/bus.py | 1,313 | 3.609375 | 4 | from src.bus_stop import BusStop
class Bus:
def __init__(self, route_number, destination, price, capacity):
self.route_number = route_number
self.capacity = capacity
self.destination = destination
self.price = price
self.passengers =[]
self.takings = 0
def driv... |
bec558eefaf2a8d0d9f1fb4647187dfd17e7c261 | k-savage/test_201910_cookiecutter | /{{cookiecutter.repo_name}}/{{cookiecutter.project_slug}}/parquet.py | 1,045 | 3.75 | 4 | import pandas as pd
from .atomic_writer import (
atomic_write
)
def convert_excel_to_parquet(data_source):
"""Converts an excel file to an equivalent parquet file that gets saved
:param data_source: path to input excel file
:return: the path to the newly created parquet file
"""
# read excel fil... |
abbc2a7333f1dd05659bd5e1d10ff1fa9434c66f | ktyagi12/LeetCode | /30DaysOfLeetcoding/CountingElements.py | 562 | 3.640625 | 4 | # Problem available at: https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/528/week-1/3289/
# Question:
'''
Given an integer array arr, count element x such that x + 1 is also in arr.
If there're duplicates in arr, count them seperately.
'''
class Solution:
def countElements(self, arr: List[... |
8d2af5f2d59fa4fd20d7b5cad2e7f00bd6811916 | ktyagi12/LeetCode | /Create_Target_From_Index_Num.py | 558 | 3.703125 | 4 | #Problem available at: https://leetcode.com/problems/create-target-array-in-the-given-order/submissions/
class Solution:
def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:
if not nums or not index:
return
target = [] # Creating target array... |
7621a972820399a4b22d5e5c579d73c78ceaa57a | ktyagi12/LeetCode | /RansomNote.py | 1,050 | 3.828125 | 4 | # Problem available at: https://leetcode.com/explore/challenge/card/may-leetcoding-challenge/534/week-1-may-1st-may-7th/3318/
# Question:
'''
Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructe... |
0c27e8e746a688c6c3976775f59839021cbe591d | ktyagi12/LeetCode | /KeyboardRow.py | 718 | 3.5625 | 4 | #Problem available at: https://leetcode.com/problems/keyboard-row/submissions/
class Solution:
def findWords(self, words: List[str]) -> List[str]:
if not words:
return
my_dict = {
'Q':1,'W':1,'E':1,'R':1,'T':1,'Y':1,'U':1,'I':1,'O':1,'P':1,
'A':2... |
248ba7d0cbbeafe220049594832365f9e829038a | ktyagi12/LeetCode | /RemoveElement.py | 761 | 3.578125 | 4 | # Problem available at: https://leetcode.com/explore/learn/card/fun-with-arrays/526/deleting-items-from-an-array/3247/
# Question available at:
'''
Given an array nums and a value val, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this... |
8602f66c66d3a8b994f9906e73e0d9bfa2199522 | ktyagi12/LeetCode | /MaxContigousSubArray.py | 246 | 3.75 | 4 | #Problem :
## Given an array of N integers. Find the contiguous sub array with maximum sum.
num = [1,2,3,-2,5]
max_ = 0
sum_ = 0
for i in range(len(num)):
sum_ += num[i]
if sum_ < 0:
sum_ = 0
elif sum_ > max_:
max_ = sum_
print(max_) |
807104ae927f6b53095547ccb44de4a4a0698ef4 | ktyagi12/LeetCode | /ReverseWordsInAString.py | 547 | 3.734375 | 4 | #Problem available at: https://leetcode.com/problems/reverse-words-in-a-string-iii/submissions/
class Solution:
def reverseWords(self, s: str) -> str:
if not s:
return s
if s == '':
return s
#print('Original s', s)
words = s.split(' ')
... |
6f87361689310c21fa8d5283f004bf0a676e993c | ktyagi12/LeetCode | /H_Index_II.py | 809 | 3.90625 | 4 | # Problem available at: https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/541/week-3-june-15th-june-21st/3364/
# Question:
'''
Given an array of citations sorted in ascending order (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.
Acc... |
a3cc8ae613f30ff48a9f1a127b34e9884c2b17fd | ktyagi12/LeetCode | /MinDepth.py | 746 | 3.796875 | 4 | #Problem available at: https://leetcode.com/problems/minimum-depth-of-binary-tree/submissions/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def getHeight(self,root):
if root ... |
efcc01331a06eb6a1106fbe5aeee179e4e994cba | ktyagi12/LeetCode | /IsSubsequence.py | 876 | 3.609375 | 4 | # Problem available at: https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/540/week-2-june-8th-june-14th/3355/
# Question:
'''
Given a string s and a string t, check if s is subsequence of t.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be... |
b33531c5d553f0eb1aca00ef3b0b1f88a7c274be | ktyagi12/LeetCode | /QueueReconstructByHeight.py | 707 | 3.71875 | 4 | # Problem available at: https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/539/week-1-june-1st-june-7th/3352/
# Question:
'''
Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number o... |
64d022dbdf3959de0ccb762ed6a0461e2263be64 | ktyagi12/LeetCode | /CountPrime.py | 908 | 3.578125 | 4 | #Problem available at: https://leetcode.com/problems/count-primes/submissions/
class Solution:
def countPrimes(self, n: int) -> int:
prime = [True]*n
if n<2:
return 0
else:
prime[1] = prime[0] = False
for i in range(2,n):
... |
87edd66d09940150ae15d9051af97313f7b88433 | ktyagi12/LeetCode | /ValidPerfectSquare.py | 786 | 3.625 | 4 | # Problem available at: https://leetcode.com/explore/challenge/card/may-leetcoding-challenge/535/week-2-may-8th-may-14th/3324/
# Question: Given a positive integer num, write a function which returns True if num is a perfect square else False.
class Solution:
def isPerfectSquare(self, num: int) -> bool:
... |
c504d833444528f389c54a8e9a0b91203c702fe1 | aspcodenet/Facit | /if2.py | 474 | 3.59375 | 4 | # Be användaren att mata in hur många paket mjölk som finns kvar. Är det mindre än
# 10 skriv- Beställ 30 paket. Är det mellan 10 och 20 skriv- Beställ 20 paket. Annars
# skriv-Du behöver inte beställa någon mjölk.
tal = input("Mata in hut många paket mjölk du har:")
tal = int(tal)
if tal < 10:
print("Beställ 30 ... |
d24b8f4642b30162945efa092e67f877db2c30b2 | aspcodenet/Facit | /objektDemo.py | 1,135 | 3.78125 | 4 | class Person: # RITNING
def __init__(self, name, age, team):
self.name = name
self.age = age
self.team = team
self.dogs = []
def FindInList(listOfPlayers, partOfName):
for player in listOfPlayers:
if partOfName in player.name:
return player
return None
... |
a93f7b1814d275eb09923ec87611a64930454198 | aspcodenet/Facit | /operators5.py | 351 | 3.890625 | 4 | tal1 = int(input("Mata in tal 1"))
tal2 = int(input("Mata in tal 2"))
resultat = tal1 ** tal2
print(resultat)
resultat = tal1 * tal2
print(resultat)
resultat = tal1 / tal2
print(resultat)
resultat = tal1 + tal2
print(resultat)
resultat = tal1 - tal2
print(resultat)
resultat = tal1 % tal2
print(resultat)
resultat... |
e1e3f60083a4aa4babc89a450561325e6a347af7 | AmanDaVinci/pyloader | /pyloader.py | 1,145 | 3.703125 | 4 | #!/usr/bin/env python
"""Quick & easy recipe for downloading a file or a sequence of files
USAGE: $/.pyloader.py [url] [start] [end] [path/to/downloaded/file]
"""
__author__ = "Aman <aman@amandavinci.me>"
__version__ = "Revision: 0.0.1"
__date__ = "Date: 09/05/2017"
import os
import sys
import urllib.request, url... |
7001a71dff6f2975f69f35d78dd3f4c0466094db | surya-ra/LeetCode_practice | /linked_list_sum copy.py | 2,848 | 3.859375 | 4 | """
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Ex... |
4eaaa5956b096686ef7d6adf201bd9437fc69efd | Celnet-hub/Network-Automation | /python35.py | 1,190 | 3.578125 | 4 | import getpass
import telnetlib # importing the telnet library
HOST = "Local Host Device"
user = input("Enter your remote telnet username: ")
password = getpass.getpass() # requesting for a password
f = open('myswitches')
for ip in f:
ip = ip.strip()
print('connecting to network device ' + (ip))
HOST =... |
eaae9cb476302b7de484c2ba376b44f8ef1cbd96 | noserider/school_files | /Python-Next-steps/Python Next steps/L1 The basics/password.py | 391 | 4.09375 | 4 | # SECTION 1
correctPassword = "pa55word"
guesses = 0
guess = ""
# SECTION 2
while guess != correctPassword:
guess = input("Try to guess the password: ")
guesses = guesses + 1
print("Password guessed correctly")
# SECTION 3
if guesses == 1:
print("That took you 1 guess.")
else:
print("That took you ... |
ec37f8c52a802e42c2e4fe1dbb1fb25a7bf19577 | noserider/school_files | /Python-Next-steps/Python Next steps/L6 Assessment/password.py | 745 | 4 | 4 | correctPassword = "letMeIn"
attempts = 0
guess = ""
goAgain = True
while goAgain: # Repeat as long as goAgain is True
guess = input("Enter the password: ") # Ask for a password
if guess == correctPassword: # If correct, print message and stop looping
... |
cf6db1cfb7ba5ebff8bf62f9d55eb93071f03e5f | noserider/school_files | /speed2.py | 539 | 4.125 | 4 | #speed program
speed = int(input("Enter speed: "))
#if is always the first statement
if speed >= 100:
print ("You are driving dangerously and will be banned")
elif speed >= 90:
print ("way too fast: £250 fine + 6 Points")
elif speed >= 80:
print ("too fast: £125 + 3 Points")
elif speed >= 70:
prin... |
8dcdef576c7fb51962fc4c2537742c92f51976f5 | noserider/school_files | /sleep.py | 580 | 4.125 | 4 | #int = interger
#we have two variable defined hourspernight & hoursperweek
hourspernight = input("How many hours per night do you sleep? ")
hoursperweek = int(hourspernight) * 7
print ("You sleep",hoursperweek,"hours per week")
#round gives a whole number answer or a specific number of decimal points
hourspermo... |
a3b6246985aa7ea86a440da73a96cefdd4eb6dc3 | noserider/school_files | /sleep1.py | 291 | 4.1875 | 4 | hourspernight = input("How many hours per night do you sleep? ")
hoursperweek = int(hourspernight) * 7
print ("You sleep",hoursperweek,"hours per week")
hourspermonth = float(hoursperweek) * 4.35
hourspermonth = round(hourspermonth)
print ("You sleep",hourspermonth,"hours per month")
|
9accecd15ef09f80e6b090345afa22d90c8c1f75 | AaronOS0/codewars | /fundamental/Your-order-please.py | 533 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding : utf-8 -*-
def order(sentence):
# Transform str to list, split by space
word_list = sentence.split(" ")
# Extract the number of each word and make tuple, then Sort it
sorted_list = sorted([(character, word) for word in word_list for character in word if character.is... |
c31f995444df53b97ba59b8bf3f21bacef803df4 | AaronOS0/codewars | /fundamental/Product-of-consecutive-Fib-numbers.py | 246 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding : utf-8 -*-
def productFib(prod):
a, b = 0, 1
while a * b < prod:
a, b = b, a + b
return [a, b, a * b == prod]
if __name__ == '__main__':
result = productFib(5895)
print(result)
|
5eb181fe28e6cf509893eea601e08c197ec00391 | OmkarPathak/algorithms-in-C-Cplusplus-Java-Python-JavaScript | /searching/Python/BinarySearch.py | 377 | 3.78125 | 4 | def binarySearch(alist, item):
2 if len(alist) == 0:
3 return False
4 else:
5 midpoint = len(alist)//2
6 if alist[midpoint]==item:
7 return True
8 else:
9 if item<alist[midpoint]:
10 return binarySearch(alist[:midpoint],item)
11 else:
12 ... |
f4e9244ea6521f814fef857840e57da481cbd758 | pinvolha/Algorithms-and-Data-Structures-in-Python | /les_7_task_2.py | 1,151 | 4.03125 | 4 | # Отсортируйте по возрастанию методом слияния одномерный вещественный массив,
# заданный случайными числами на промежутке [0; 50). Выведите на экран исходный и отсортированный массивы.
import random
def merge_sort(a):
if len(a) > 1:
mid = len(a) // 2
left = a[:mid]
right = a[mid:]... |
176166ccdd167e86ec74cff272615589968773b3 | pinvolha/Algorithms-and-Data-Structures-in-Python | /les_4_task_2.py | 2,907 | 3.53125 | 4 | # 2. Написать два алгоритма нахождения i-го по счёту простого числа.
# Функция нахождения простого числа должна принимать на вход натуральное и возвращать соответствующее простое число.
# Проанализировать скорость и сложность алгоритмов.
import cProfile
def eratosthenes_sieve(n):
count = 1
start = 3
... |
c4b79bd354369af6c738be39b07cf241031e00ac | pinvolha/Algorithms-and-Data-Structures-in-Python | /les_1_task_5.py | 317 | 3.96875 | 4 | # Пользователь вводит номер буквы в алфавите. Определить, какая это буква.
n = int(input("Введите номер буквы в алфавите: "))
alf = 'abcdefghijklmnopqrstuvwxyz'
letter = alf[n - 1]
print("Это буква", letter.upper())
|
99d347780e81ca24c4537231f538cec5cbef1175 | Arcus71/GC50-files | /UserInput.py | 224 | 4.15625 | 4 | #Set up two numbers
a = int(input("Enter your first number: "))
b = int(input("Enter your second number: "))
#Output manipulations
print("Sum: " + str(a + b))
print("Product: " + str(a * b))
print("Quotient: " + str(a / b)) |
7a3e91087f4979abc44b990e93757267b8bec6d8 | suyashsachdeva/Artificial_Intelligence | /sklearn/iris.py | 528 | 3.734375 | 4 | # Classification
from sklearn import datasets
from sklearn.model_selection import train_test_split
import numpy as np
iris = datasets.load_iris()
# Spliting features for the target values
x = iris.data
y = iris.target
print(x.shape, y.shape)
# Splilting our data in two parts 80% for training and the rest for testi... |
93759474ce14c13d14c7596a711d3f5a024a5c06 | helectron/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/9-print_last_digit.py | 139 | 4.0625 | 4 | #!/usr/bin/python3
def print_last_digit(number):
last_digit = int(str(number)[-1])
print(last_digit, end="")
return last_digit
|
9b4c1af08c692c76d842037238abcb60a2b8d63a | helectron/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/square.py | 2,234 | 4.03125 | 4 | #!/usr/bin/python3
'''
module square
Class
Square
'''
from models.rectangle import Rectangle
class Square(Rectangle):
'''
Creates a Square object
Properties:
size (int): represent width and height
from Rectangle class
x (int): x coordenate
y (int): y coordenate
... |
eefe35654b600067442c6d663ae8c49b05a48acd | helectron/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/3-say_my_name.py | 505 | 3.9375 | 4 | #!/usr/bin/python3
'''
This module supplies the function say_my_name().
Test it running: python3 -m doctest -v ./tests/3-say_my_name.txt
'''
def say_my_name(first_name, last_name=""):
'''The function prints a string and two arguments'''
if not isinstance(first_name, str):
raise TypeError("first_name m... |
1fb48b796d55cd2988bfb74060178f327b6b549e | helectron/holbertonschool-higher_level_programming | /0x0B-python-input_output/2-append_write.py | 282 | 4.28125 | 4 | #!/usr/bin/python3
'''module 2-append_write
Function:
append_write(filename="", text="")
'''
def append_write(filename="", text=""):
'''Function to append a text in a file'''
with open(filename, mode="a", encoding="utf-8") as myFile:
return myFile.write(text)
|
94d9717c17681634351f3c23acf432b6031ecdb3 | garcam/Machine-Learning-Nano | /ejemplo_conteo_siguiente_palabras_texto.py | 5,000 | 3.78125 | 4 | sample_memo = '''
Milt, we're gonna need to go ahead and move you downstairs into storage B. We have some new people coming in, and we need all the space we can get. So if you could just go ahead and pack up your stuff and move it down there, that would be terrific, OK?
Oh, and remember: next Friday... is Hawaiian shir... |
4b70a77d63f19610062476bae34dd794536b0694 | garcam/Machine-Learning-Nano | /gradient_descent.py | 10,483 | 4.09375 | 4 | import numpy as np
def sigmoid(x):
"""
Calculate sigmoid
"""
return 1/(1+np.exp(-x))
def sigmoid_prime(x):
"""
# Derivative of the sigmoid function
"""
return sigmoid(x) * (1 - sigmoid(x))
learnrate = 0.5
x = np.array([1, 2. 3, 4])
y = np.array(0.5)
# Initial weights
w = np.array([0.... |
d6d411edb24da070e976285992efbf3c5748f3cd | alexangupe/clasesCiclo1 | /P61/Clase5/solucionRequerimientoEjemplo.py | 1,937 | 3.84375 | 4 | #Objetivo: detectar mayores de edad
#para realizar el informe correspondiente
#al requerimiento.
#Algoritmo pseudocódigo general
# 1) Recoger 4 edades y almacenarlas.
# 2) Recoger la edad vigente como mayoría
# de edad.
# 3) Verificar quiénes son mayores de edad
# y contarlos (acumulador).
# 4) Si hay por lo menos do... |
e85febfe1079f48fac3e990073f76067e4902b6f | alexangupe/clasesCiclo1 | /P45/Clase8/requerimientoFor.py | 1,852 | 4.1875 | 4 | #Requerimiento: escribir una función que valide que un correo electrónico
#ingresado, solamente tenga una arroba, mostrar en pantalla la posición de las
#arrobas que estén sobrando
#Objetivo -> Número válido de arrobas den un correo (única arroba)
# #Algoritmo (Pseudocódigo)
# 1) Ingresa el correo electrónico
# 2) I... |
38a1e43eba523c79ca82d7d1016c3c1ebedb3c51 | alexangupe/clasesCiclo1 | /P45/Clase6/gregorianoHarbey.py | 1,049 | 3.890625 | 4 | def saludo():
print('---------------------------')
print('Conoce que año es bisiesto')
print('---------------------------')
return
def datos():
year = int(input('Introduzca el año que desea consultar: '))
return year
def algBisiesto(year):
if year/4 == int(year/4):
if year/100 == i... |
5164b5b3e2f3ae914f6bf84c993c93f322448863 | alexangupe/clasesCiclo1 | /P45/Clase1/primerAlgoritmo.py | 365 | 3.71875 | 4 | variable_1 = 15
print(type(variable_1))
print("El primer conteido es:",variable_1)
variable_2 = 50
resultado = variable_1 + variable_2
print("El resultado de la suma es: ",resultado)
variable_1 = 14.67
print(type(variable_1))
print("El nuevo contenido es:",variable_1)
variable_1 = "hola"
print(type(variable_1))
print("... |
4af0fd7561ec8fca9e253c2d35070f32a8426f5d | alexangupe/clasesCiclo1 | /P45/Clase2/areaCirculo.py | 477 | 3.578125 | 4 | #Algoritmo
#Entradas: radio
#Proceso: cálculo pi*r*r
#Reportar la salida
# def areaCirculo(radio):
# pi = 3.1416
# radioCuadrado = radio**2
# area = pi * radioCuadrado
# return area
#print("Mostrando el valor de pi:", pi)
from libreriaGeometricas import areaCirculo
#& hallar el area de un circulo
r... |
01e304a59420f8fa1646b5f27824293885a9f1e3 | alexangupe/clasesCiclo1 | /P45/Clase11/recorriendoDiccionarios.py | 3,004 | 3.875 | 4 | #Nómina -> Lista grande (primel nivel)
#Empleado -> Lista con 2 o 3 valores: Nombre(s), Impustos (en tal caso), Salario
import pprint as pp #pretty print
nomina = [
['Ana',14000],
['María Fernanda',3000000],
['María Camila',3000000],
['Luis',700]
]
nominaLD = [
{ 'nombre':'Ana' , 'salario': 14000}... |
ce7665d2642ec48330e6912c8978d52775c6fa3e | alexangupe/clasesCiclo1 | /P45/Clase4/scriptImpuestos.py | 1,915 | 3.828125 | 4 | #Objetivo -> Precio final de venta de productos cargados
#sin IVA
#Algoritmo:
# 1) Cargar el precio sin IVA de cada producto.
# 2) Cargar el valor del IVA (porcentaje, float)
# 3) Inicializamos un acumulador para el impuesto de cada
# producto
# 4) Calcular el IVA del primer producto y sumarlo al
# acumulador
# 5) C... |
cfce75d6341ffb4909d73964c2907398b1623dcd | alexangupe/clasesCiclo1 | /P45/Clase2/distanciaPuntos2D.py | 1,341 | 4.0625 | 4 | #Programa que calcula la distancia de dos coordenadas en el plano cartesiano
#Objetivo => Usar la formula euclidiana para hallar la distancia entre dos coordenadas en el plano cartesiano
""" Pasos para solucionarlo
1.Definir y almacenar el valor de X1
2.Definir y almacenar el valor de Y1
3.Definir y almacenar el val... |
d7f7f10778c02b615a8dce116d374363d78946ab | alexangupe/clasesCiclo1 | /P45/Clase2/areaTriangulo.py | 617 | 4.03125 | 4 | #Objetivo: calcular el área de un triángulo
#Algoritmo (pseudocódigo)
#1. Obtener la altura del triángulo y almacenarla en una variable
#2. Obtener la base del triángulo y almacenarla en una variable
#3. Realizar el cálculo (base*altura)/2 y guardarlo
#4. Reportar el resultado almacenado
# def areaTriangulo(base,altu... |
5ed73417ace4a52390c8f79fd0e776ebded432b7 | oyyarko/100-days-of-ds-code | /product-subarray-9-6.py | 262 | 3.921875 | 4 | #product of all subarrays from array
def subarray_product(arr, n):
product = 1
for i in range(0, n):
for j in range(i, n):
for k in range(i, j+1):
product *= arr[j]
print(product)
arr = [2, 5, 4]
#arr = [10, 3, 7]
subarray_product(arr, len(arr))
|
e07bb186683eed3752f800e0c83082822d7be94c | DLukeNelson/Rubiks_Cube_Solver | /Rubiks_Cube_Solver-GUI/RubicksCubeGUI.py | 5,034 | 3.75 | 4 | from tkinter import*
import sys
COLORS = ['white', 'yellow', 'orange', 'red', 'green', 'blue']
class Application(Frame):
"""A GUI application with three buttons"""
def __init__(self, master):
""" Initialize the Frame """
Frame.__init__(self,master)
self.grid()
self.resetClick =... |
89f6aaf3951880cbacbf717942940359860c5cc7 | bdsh-14/Leetcode | /max_sum_subarray.py | 615 | 4.21875 | 4 | '''
Given an array of positive numbers and a positive number ‘k,’ find the maximum sum of any contiguous subarray of size ‘k’
Input: [2, 1, 5, 1, 3, 2], k=3
Output: 9
Explanation: Subarray with maximum sum is [5, 1, 3]
educative.io
'''
def max_sum(k, nums):
windowStart = 0
windowSum = 0
max_sum = 0
... |
218705f91f61608fbc6fb18707c6f9e79277d988 | bdsh-14/Leetcode | /wordLadder_LC127.py | 1,531 | 4 | 4 | """
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
Only one letter can be changed at a time.
Each transformed word must exist in the word list.
Note:
Return 0 if there is no such transformation sequence.
... |
24cbb5b9b020dfa0c9547a74b4ec2f77a26a027d | bdsh-14/Leetcode | /Queue_Intro.gyp | 1,170 | 4.15625 | 4 | #Linear queue
class Queue:
def __init__(self):
self.queueList = []
def is_empty(self):
return len(self.queueList) == 0
def front(self):
if self.is_empty():
return None
return self.queueList[0]
def back(self):
if self.is_empty():
return ... |
f04b7e296e532b0ca64542248938e90ce789cb64 | TonyKeepCoding/little_exers | /bubblesort.py | 210 | 3.71875 | 4 | def bubblesort(L):
for i in range(len(L)-1):
for j in range(len(L)-i-1):
if L[j] > L[j+1]:
L[j],L[j+1] = L[j+1],L[j]
return L
L = [1,85,6,5,95]
print(bubblesort(L)) |
5f7a995750ac6e51c5bc2e6c48d346d92d3525ca | alphaomegos/pylesson3 | /Task 01.py | 655 | 4.09375 | 4 | # Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление.
# Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль.
def Div_Func():
Divisible = int(input("Введите делимое >>> "))
Divisor = int(input("Введите делитель >>> "))
try:
... |
f3d18d4856cbb75bea1fb40a1f32041f97849cbb | caihedongorder/PythonEx | /PythonApplication1/PythonApplication1/Person.py | 493 | 3.9375 | 4 |
class Person(object):
"""description of class"""
def __init__(self,inName,inAge):
self.__name = inName
self.__age = inAge
def getInfo(self):
#return "Name:{Name},Age:{Age}".format(Name = self.__name,Age = self.__age)
return {"Name":self.__name,"Age":self.__age}
def __s... |
a944988dec54b61c9344b54fdacea0fb6b79844c | JohnZeroOne/Small_Python_Projects | /hangman_unfinished/hangman.py | 2,543 | 4.09375 | 4 | # notes
# 2h
# wordlist uses a lot of words with uppercase first letter:
# having to use string.lower() method to make words match
#
# wordlist is long and makes the program slow to load first time
# randomly pick a word
import random
# read the word list online
import urllib2
def _init():
# open th... |
4d31e99dd4c78ab8f25bd0de0662b39a1fe7e739 | vazquezs123/EULER | /euler19.py | 1,613 | 4.15625 | 4 | #!/usr/bin/env python
class Month(object):
def __init__(self, month, days):
"""Return a month object with current month, and total days in month """
self.month = month
jan = Month('January', 31)
feb = Month('February', 28)
mar = Month('March', 31)
apr = Month('April', 30)
may = Month('May', 31)
... |
5004a56adfc58f70d504047c995b675c8501c3fe | YasmminClaudino/lab2018.2 | /biblioteca/pilha.py | 1,316 | 3.53125 | 4 | class No():
def __init__(self,dado):
self.dado = dado
self.prox = None
def getDado(self):
return self.dado
def getProx(self):
return self.prox
def setProx(self,novoNo):
self.prox = novoNo
class Pilha():
def __init__(self):
self._inicio = None
... |
40ecf91e9a720f7e1a31e009e82a40f995514db6 | YasmminClaudino/lab2018.2 | /Extra/amigoSecreto.py | 636 | 3.890625 | 4 | import random
def sorteia(random,nomes):
pessoa = random.choice(nomes)
return pessoa
def guardaNome(nomes,qtd):
for x in range(qtd):
nome = input("Digite o nome de quem vai participar, incluindo seu nome: ")
nomes.append(nome)
def amigoSecreto(pessoa,nomes):
print("Seu inimigo secreto... |
cb18e0b24212ead9ced445d54ddcf4b1597854a7 | YasmminClaudino/lab2018.2 | /24-polonesa.py | 1,855 | 3.59375 | 4 | #Notação Polonesa \\Henrique Cesar
class Nor:
def __init__(self, dados):
self.dados = dados
self.proximoNor = None
def inserirProximo(self, novoNor):
self.proximoNor = novoNor
def obterDados(self):
return self.dados
def obterProx(self):
return self.proximoNor... |
bda1e1644e09c7304e8050be5ded20f4c32dc524 | JotaCampagnolo/calcnum | /chapter4/simpson2.py | 493 | 3.859375 | 4 | # Imports:
from lib import *
# Function:
def simpson2(ll, ul, n):
# Calculate the h value:
h = (ul - ll) / n
# Calculates the integral:
result = f(ll) + f(ul)
i = 0
for i in range(1, INTERVALS):
if i % 3 == 0:
result += 2 * f(ll + i * h)
else:
result += 3... |
f1956f0af0eef443912e320360767557f85a6fb3 | mpashby/schoolModel | /school.py | 5,705 | 3.546875 | 4 | #school model with
import random
import sys
class School:
def __init__(self, name):
self.schoolName = name
self.students = [] #list of student IDs
self.teachers = []
self.classList = []
self.programs = []
self.enrollment = 0
self.staffCount = 0
... |
4e7eb0cf1dceb318fc617ffc2dfb3e310df7f2d3 | sitayebsofiane/jeu_pendu_en_python | /fonctions.py | 2,393 | 3.609375 | 4 | class Player:
def __init__(self,name,score):
self.name=name
self.score=score
def add_score(self,new_score):
self.score+=new_score;
return self.score
def getName(self):
return self.name
def getScore(self):
return self.score
#fonction to check name
def name(... |
aeb8cc5bfbe2d5ce4c5df3bee3deab3313ecf8e8 | M1sterDonut/Exercises_Python-Crash-Course_Eric-Matthes | /famous_quote.py | 980 | 4.09375 | 4 | # Printing a quote using \n and \t as well as quotation marks in printed text
print ('Winston Churchill once said, \n\t"What is the purpose of living \n\tif it be not to strive for noble causes \n\tand to make this muddled world a better place \n\tfor those who live in it after we are gone."')
famous_person = "Winston... |
d8b1a9ab04860840488ba36ab6a573cc008501e8 | M1sterDonut/Exercises_Python-Crash-Course_Eric-Matthes | /guest_list.py | 4,375 | 3.984375 | 4 | #Try it yourself: lists, popping, deleting, etc.
guest_list = ['the dread pirate roberts', 'ragnar lothbrok', 'heath ledger', 'jimi hendrix']
print (guest_list)
print ("") #How else do you get an empty line in the print?
#3-4
invitation_part1 = "Dear "
invitation_part2 = ",\nYou're kindly invited for dinner.\nI look ... |
a09123591f18b44d4c10b1f134a7c74c7600d15d | M1sterDonut/Exercises_Python-Crash-Course_Eric-Matthes | /stages_of_life.py | 375 | 4.28125 | 4 | age = 42
if age < 2:
print (str(age) + " years? You're a baby!")
elif age <= 3:
print (str(age) + " years? You're a toddler!")
elif age <= 12:
print (str(age) + " years? You're a kid!")
elif age <= 19:
print (str(age) + " years? You're a teenager!")
elif age <=64:
print (str(age) + " years? You're an adult!"... |
57ddbd97d64bc45fff19be235369753831f3fc43 | Akash-Raj-ST/Lines-and-Dots | /Lines and Dots.py | 568 | 3.859375 | 4 | n=int(input("No of Lines:"))
fact=1
fact1=[1]
fact2=[0,1,1]
j=n*2
for i in range(1,j):
t=0
fact=fact*i
fact1.append(fact)
fact2.append(fact*2)
if fact1[-1]/fact2[-3]==n:
if n>=3:
l=len(fact1)-1
break
elif n==1:
l=len(fact1)
... |
b1b173ac8424c4df9e52189246f8e90ab69ae353 | VidhyasriG/Natural-Language-Processing | /Word Sense Disambiguation/scorer.py | 2,361 | 3.828125 | 4 | """
Course: AIT 690
Assignment: Programming Assignment 3 - WSD
Date: 04/04/2019
Team Name: ' A team has no name'
Members: 1. Rahul Pandey
2. Arjun Mudumbi Srinivasan
3. Vidhyasri Ganapathi
*****************************************************************************************
This code is used... |
6ab34dbd5b8fe53c7c6a51ab6dfbcb19404b63dc | ohsu-comp-bio/bergamot | /spence/utils.py | 735 | 3.5625 | 4 | import math
def logistic_function(t):
"""Returns the value after passing through logistic function.
"""
return (1 / (1 + math.exp(-t)))
def dot_product(data, coef, intercept):
"""Returns dot products of the data and coefficients.
Input
------------------------
data: [pandas.DataFrame]... |
0eb46fab6d91fe3c4dd9a771952a4e9efa941b5f | ohsu-comp-bio/bergamot | /HetMan/features/mutations/branches.py | 24,836 | 3.515625 | 4 |
from functools import reduce
from operator import and_
from re import sub as gsub
from itertools import product
from itertools import permutations as perm
class MuType(object):
"""A set of properties recursively defining a particular type of mutation.
This class corresponds to a mutation type defined throu... |
a6af074c9923029cca67c16d62de38af954be03d | lollipop190/Data-Science-Project | /crawler_and_data/python_sort/min_heap_sort.py | 1,503 | 4 | 4 | def min_heap_sort(arr, simulation=False):
iteration = 0
if simulation:
print("iteration", iteration, ":", *arr)
for i in range(0, len(arr) - 1):
iteration = min_heapify(arr, i, simulation, iteration)
return arr
def min_heapify(arr, start, simulation, iteration):
# Offset last_p... |
e5b0ca32969dd5197d160e3376f0a67420439e21 | lollipop190/Data-Science-Project | /Classification/java_cpp_clearComments.py | 1,532 | 3.546875 | 4 |
def java_clear(filename):
file = ''
multiline_comments = False
with open('../parser/' + filename ,encoding='utf-8') as f:
for line in f.readlines():
if multiline_comments:
if '*/' in line:
multiline_comments = False
if not line.sp... |
73aa98cbcb7e2595944bb604401fa31d6767d114 | knagakura/procon | /atcoder/abc056/c.py | 63 | 3.515625 | 4 | X = int(input())
i = 0
d = 0
while(d < X):
i+=1
d+=i
print(i) |
9e3e28eb26079e0bb5e177ab23bef3508cf33a58 | knagakura/procon | /atcoder/abc065/a.py | 138 | 3.515625 | 4 | X,A,B = map(int,input().split( ))
if 0 < B - A <= X:
ans = 'safe'
elif B - A <=0:
ans = 'delicious'
else:
ans = 'dangerous'
print(ans) |
404c99f063e75cc0bc9bda3eff39aaccc7ce8dcc | knagakura/procon | /atcoder/abc134/c.py | 214 | 3.53125 | 4 | N = int(input())
A = []
for i in range(N):
a = int(input())
A.append(a)
B = sorted(A)
maxA = B[-1]
maxA2 = B[-2]
for i in range(N):
if A[i] == maxA:
print(maxA2)
else:
print(maxA) |
9a9ed1d6e861ec48f260028bc55d57a9b1b16283 | wmt-vishwad/string | /strings.py | 1,324 | 3.859375 | 4 | my_string = """I
am
programmer"""
print(my_string)
my_strings = "hello"
char = my_strings[2]
print (char)
substring = my_strings[1:5]
print(substring)
substring = my_strings[::2]
print(substring)
substring = my_strings[::]
print(substring)
substring = my_strings[:: -1]
print(substring)
gre... |
cad1263bb0fc947e22ec05f4abbf5b8229ce5f64 | kakadeniranjan1999/Optimus-A-Personal-Jarvis | /guess_the_word_game.py | 3,026 | 3.65625 | 4 | import speech_recognition as sr
import pyttsx3
import random
r = sr.Recognizer()
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('rate', 150)
engine.setProperty('volume', 0.9)
man_voice_id = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_DAVID_11.0"
engine.set... |
f43a85221bc18f19bbd3b051e060adde6be7a6ab | kal4EaI/Free-Code-Camp | /Current/7-Scientific_Computing_With_Python/1-Arithmetic_Formatter/arithmetic_arranger.py | 4,072 | 3.9375 | 4 | import re
def add(a, b):
a = int(a)
b = int(b)
return a + b
def subtract(a, b):
a = int(a)
b = int(b)
return a - b
def arithmetic_arranger(problems, doSolve=False):
# Loop through input
# For each element
# Split up into a list of 3 elements
# check 1 & 3 elements for only nu... |
7a56a17b26e19108d2e7b9765f93e59c0ec846ee | ThornBirdlx/Learn-Python | /test5.py | 978 | 3.890625 | 4 | print("You enter a dark room with two doors,Do you go through door #1 or door #2?")
door = input(">>>")
if door == "1":
print("There's a giant bear here eating a cheese cake.What do you do?")
print("1.Take the cake")
print("2.Scream at the bear.")
bear = input(">>>")
if bear == "1":
print("The be... |
2c03cbfc8d364964d71dcb1ecd6100ef1918e1be | Veloc1tyE/ProjectEuler | /Python/summations.py | 2,516 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Sep 1 08:59:10 2019
@author: Veloc1ty
"""
"""
This is an awesome dynamic programming technique
Essentially we want an algorithm that figures out
how many ways we can express a number as a summation
of positive integers
"""
index = 1
while... |
f470b408331a50e32d7e557327d74dc0db42da18 | hym-dn/Beginning-Python | /Chapter6/6-1/6-1.py | 916 | 4 | 4 |
# 初始化字典
def init(data):
data['first']={}
data['middle']={}
data['last']={}
# 查找人员
def lookup(data,label,name):
return data[label].get(name)
# 存储人员信息
def store(data,full_name):
names = full_name.split() # 拆分全名,分割出first,middle,last
if len(names) == 2: names.insert(1, '') # 如果没有中间名,则将中间名设置为空
... |
43f0e99193ccfc44fe1cd543c5d77ace76d42c56 | barbarahf/Python_DAW | /Practicas/BarbaraHerrera_10.py | 134 | 3.828125 | 4 | texto = input("Introduce un texto: ").upper()
palabra = input("Introduce una palabra a buscar: ").upper()
print(texto.count(palabra))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.