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 |
|---|---|---|---|---|---|---|
5e9c28929debc8678159e54ab2594942483ce13d | davinbirdi/CardProblem | /deckofcardsFunctions.py | 1,526 | 3.765625 | 4 | # --------------------------------------
# Functions:
# --------------------------------------
# Function: Create Card Deck
# Inputs: None
# Outputs: Deck of 52 suited cards
def createDeck():
deck = []
card_nums = list(range(1, 14))
card_suites = ['H', 'D', 'S', 'C']
for x in card_num... |
45c1771c5a496bf65e92c07f5fcb8a6d5891f5f4 | chuanski/py104 | /LPTHW/2017-04-26-10-31-18.py | 1,422 | 4.53125 | 5 | # -*- coding: utf-8 -*-
# [Learn Python the Hard Way](https://learnpythonthehardway.org/book)
# [douban link](https://book.douban.com/subject/11941213/)
# ex6.py Strings and Text
x = "There are %d types of people." % 10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not)
yy ... |
7f120f64bfb8b35309363cf5394f74a2e278d929 | RM1708/Sandlot-PY | /GEdit_Python/gedit_python.py | 265 | 3.828125 | 4 | #!/usr/bin/env python
import sys
x = 3
y = 4
z = x + y
print("Program evaluates a defined function z.")
print("Enter z<Enter> and then <Ctrl-D>")
result = eval(sys.stdin.read())
#enter "z" at the command line
#Press Ctrl-D to end entry
print (result, type(result))
|
b95f6a18aaa30a7adddd0b5ee3b4eb1f52ab6c8e | JustSage/Numeric-Analysis-Final-Project | /methods/cubic_spline.py | 3,647 | 4.03125 | 4 | """
Natural cubic spline.
"""
import numpy as np
from methods.gauss_seidel_method import gauss_seidel
from math import pi
def natural_cubic_spline(points):
""" Finds the natural cubic spline of a function given
:param points: An array of point tuples (xi, yi)
:return: A function
... |
4504fdabb7ca47f4c3e20e13050b12971cadb240 | BhagyeshDudhediya/PythonPrograms | /5-list.py | 2,285 | 4.5625 | 5 | #!/usr/bin/python3
import sys;
# Lists are the most versatile of Python's compound data types.
# A list contains items separated by commas and enclosed within square brackets ([]).
# To some extent, lists are similar to arrays in C.
# One of the differences between them is that all the items belonging to a list can b... |
ed871e8bf632e9db119245d7b68af57af885343a | BhagyeshDudhediya/PythonPrograms | /2-quoted-strings.py | 994 | 4.3125 | 4 | #!/usr/bin/python
# A program to demonstrate use of multiline statements, quoted string in python
import sys;
item_1 = 10;
item_2 = 20;
item_3 = 30;
total_1 = item_1 + item_2 + item_3;
# Following is valid as well:
total_2 = item_1 + \
item_2 + \
item_3 + \
10;
print("total_1 is:", tot... |
278a65027db7c1722ef3bf0ebf1571ef9bc7342e | BhagyeshDudhediya/PythonPrograms | /advanced-python/archives.py | 1,097 | 3.640625 | 4 | from abc import ABC, abstractmethod
from zipfile import ZipFile
from glob import glob
from tarfile import TarFile
class ArchiveManager:
"""abstract class"""
def save(self):
"""abstract method"""
pass
class ZipArchive(ArchiveManager):
"""concrete class"""
def __init__(self, name):
... |
4df0cac6d76dda3a1af63e399d508cec7159e781 | BhagyeshDudhediya/PythonPrograms | /18-loop-cntl-statements.py | 2,145 | 4.53125 | 5 | #!/usr/bin/python3
# The Loop control statements change the execution from its normal sequence. When the execution leaves a scope,
# all automatic objects that were created in that scope are destroyed.
# There are 3 loop control statements:
# 1. break, 2. continue, 3. pass
# BREAK STATEMENT
# The break statement is ... |
f862cd29a0e5f35e30ad2ca1eba3a58c9174865d | BhagyeshDudhediya/PythonPrograms | /advanced-python/person.py | 357 | 3.765625 | 4 | class Person:
"""base class"""
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
def get_info(self):
print ('First name:', self.first_name)
print ('Last name:', self.last_name)
if __name__ == '__main__':
p = Person('Mahe... |
1370807d55c14807b0c38bd17210d33afd2fd486 | BhagyeshDudhediya/PythonPrograms | /advanced-python/multi-threading/using-fork.py | 1,048 | 3.859375 | 4 | import os
# This will fail on windows as fork() is not defined for windows machine
# fork() returns 2 values, it returns 0 in child's context and returns
# non-negative value (childs PID) in parents context
# When a process is forked, everything including a program counter is shared
# between child and parent. Hence, ... |
888ad3b14ca21815e1984d686b1827e715410522 | irmaR/halloween_coding | /The_horror_of_pointers/haunted_variables.py | 1,657 | 4.0625 | 4 | #Haunted Python code
#In this example our variable b was possessed by some misterious entity and got changed
#without us knowing, by some phenomenon we cannot quite explain ... (for now)
a = [2, 4, 8]
print("My array a is: ", a)
b = a #ok I declare here that b is equal to a, right? Perfectly ok. I just want a copy ... |
42f256b73a99315c0a17806ef2ee1c76166a7281 | yucongshen/spiderProject | /basic/urllib_urlopen.py | 1,118 | 3.59375 | 4 | # !/usr/python/bin
# -*- coding: UTF-8 -*-
import urllib
#按字节读取
def read():
source=urllib.urlopen("http://blog.kamidox.com")
content=source.read(100)
print content
def readline():
source=urllib.urlopen("http://blog.kamidox.com")
for i in range(10):
print ('line: %d: %s' %(i+1,source.readli... |
49da84798e3df53e56671287c625dc5d725e42f3 | Niloy28/Python-programming-exercises | /Solutions/Q14.py | 578 | 4.1875 | 4 | # Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters.
# Suppose the following input is supplied to the program:
# Hello world!
# Then, the output should be:
# UPPER CASE 1
# LOWER CASE 9
in_str = input()
words = in_str.split()
upper_letters = lower_... |
b87b690823dd5501ff4418ae82c52f20d3d634d0 | Niloy28/Python-programming-exercises | /Solutions/Q11.py | 501 | 4 | 4 | # Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and
# then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence.
# Example:
# 0100,0011,1010,1001
# Then the output should be:
# 1010
str... |
2011bfbaa6c9e7a7322311891800f564646bc651 | Niloy28/Python-programming-exercises | /Solutions/Q13.py | 505 | 4.0625 | 4 | # Write a program that accepts a sentence and calculate the number of letters and digits.
# Suppose the following input is supplied to the program:
# hello world! 123
# Then, the output should be:
# LETTERS 10
# DIGITS 3
in_str = input()
words = in_str.split()
letters = digits = 0
for word in words:
f... |
a3448baed64d761ef8d75a91f8ed21256bca52a6 | Niloy28/Python-programming-exercises | /Solutions/Q29.py | 258 | 3.96875 | 4 | # Define a function that can accept two strings as input and concatenate them and then print it in console.
def concatanateString(s1, s2):
'''Returs concatanated form of s1 and s2'''
return s1 + s2
print(concatanateString("Gaja ", "Kha"))
|
345ce55214f53b15b5c95309c21ad414da483d78 | Niloy28/Python-programming-exercises | /Solutions/Q24.py | 528 | 4.125 | 4 | # Python has many built-in functions, and if you do not know how to use it, you can read document online or find some books. But Python has a built-in document function for every built-in functions.
# Please write a program to print some Python built-in functions documents, such as abs(), int(), raw_input()
# And add... |
da81d7c444c0465736cf3fc0e085db8fa8c607e1 | Niloy28/Python-programming-exercises | /Solutions/Q22.py | 692 | 4.40625 | 4 | # Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically.
# Suppose the following input is supplied to the program:
# New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.
# Then, the output should be:
# 2:2... |
aaf4c40442c2bbd859e2eea7fa103fc27c02b314 | Niloy28/Python-programming-exercises | /Solutions/Q71.py | 152 | 3.59375 | 4 | # Please generate a random float where the value is between 10 and 100 using Python math module.
from random import random
print(random() * 100)
|
b2ba0782b339b8a9d555378872260f0bae6852e6 | Niloy28/Python-programming-exercises | /Solutions/Q53.py | 603 | 4.3125 | 4 | # Define a class named Shape and its subclass Square. The Square class has an init function which takes a length as argument.
# Both classes have a area function which can print the area of the shape where Shape's area is 0 by default.
class Shape(object):
def __init__(self, length=0):
pass
d... |
0870d3f73baba9157e9efc8e59cdf6bf630af41a | Niloy28/Python-programming-exercises | /Solutions/Q57.py | 365 | 4.40625 | 4 | # Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the user name of a given email address.
# Both user names and company names are composed of letters only.
import re
email_id = input()
pattern = r"([\w._]+)@([\w._]+)[.](com)"
match = re.searc... |
bc8085f25f4721abff11ab10e2c1994ae1d79276 | Niloy28/Python-programming-exercises | /Solutions/Q77.py | 334 | 3.90625 | 4 | # Please write a program to randomly generate a list with 5 numbers, which are divisible by 5 and 7 , between 1 and 1000 inclusive.
import random
def generator(start=1, end=1000):
for i in range(start, end+1):
if i % 5 == 0 and i % 7 == 0:
yield i
print(random.sample(list(generat... |
0b69e07cf5ee6963767afa0539a63c54292fda1d | olayinka91/PythonAssignments | /RunLenghtEncoding.py | 848 | 4.34375 | 4 | """Given a string containing uppercase characters (A-Z), compress the string using Run Length encoding. Repetition of character has to be replaced by storing the length of that run.
Write a python function which performs the run length encoding for a given String and returns the run length encoded String.
Provide dif... |
e3983a3e29767d37f0a050193ae050c86e27a71a | scottshepard/advent-of-code | /2020/day22.py | 2,373 | 3.578125 | 4 | from utils import read_input
class Game:
def __init__(self, p1, p2, mode='normal'):
self.p1 = p1.copy()
self.p2 = p2.copy()
self.round = 0
self.mode = mode
self.configurations = []
self.solved = False
def __next__(self):
if (self.p1, self.p2) in self.c... |
d7956a07c20c0d7431b4441c7c989de641ddb3a3 | scottshepard/advent-of-code | /2017/day08.py | 3,209 | 4.03125 | 4 | # --- Day 8: I Heard You Like Registers ---
#
# You receive a signal directly from the CPU. Because of your recent assistance
# with jump instructions, it would like you to compute the result of a series
# of unusual register instructions.
#
# Each instruction consists of several parts: the register to modify,
# whethe... |
1b35fc1954236228becb580c96e2beda6a3145cc | scottshepard/advent-of-code | /2020/day05.py | 1,235 | 3.5 | 4 | from utils import read_input
input = read_input('day05.txt')
def search_once(char, front, back):
half = int((back - front + 1) / 2)
if (char == 'F') | (char == 'L'):
return front, back-half
elif (char == 'B') | (char == 'R'):
return front + half, back
assert search_once('F', 0, 127) == (... |
f555d539f0e1426c8339f1101b834dac81fa7683 | scottshepard/advent-of-code | /2017/day05.py | 3,461 | 3.75 | 4 | # --- Day 5: A Maze of Twisty Trampolines, All Alike ---
#
# An urgent interrupt arrives from the CPU: it's trapped in a maze of jump
# instructions, and it would like assistance from any programs with spare cycles
# to help find the exit.
#
# The message includes a list of the offsets for each jump.
# Jumps are rel... |
4f701b58fcf157bd5f96991e082a8b00a6bb220c | scottshepard/advent-of-code | /2015/day17/day17.py | 1,869 | 4.125 | 4 | # --- Day 17: No Such Thing as Too Much ---
#
# The elves bought too much eggnog again - 150 liters this time. To fit it all
# into your refrigerator, you'll need to move it into smaller containers.
# You take an inventory of the capacities of the available containers.
#
# For example, suppose you have containers of ... |
6e945b13ee573409bf45972946b45177888231ac | AaronFR/TradeGame-Python | /test.py | 173 | 4.03125 | 4 | import re
x = "5 food"
number_regex = re.search("[-+]?[0-9]+", x)
string_regex = re.search("[a-z]+", x)
print(int(number_regex.group()))
print(string_regex.group())
|
16c1cd16da3e139863197e7fef84e041224ab80c | muditkapoor/mk_pbd | /CA5/CA5 - Part B.py | 1,728 | 3.8125 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
#Created on Sun Nov 26 13:51:23 2017
@author: muditkapoor 10352635
"""
def sum(values):
return reduce(lambda x, y: x+y, values)
def add(first, second):
return map(lambda x, y: x+y, first, second)
def max(values):
return reduce(lambda a,b: a if (a>b)... |
ff57e95e12b7753f4838043ef323204dba5dff74 | eschenau/cs313e-voting | /ballotclass.py | 487 | 3.546875 | 4 | class Ballot (Candidate):
'''
'''
def __init__ (self, preferences):
'''
'''
self.votes = tuple(preferences)
self.owner = 0
list_candidates[self.votes[self.owner] - 1].give_ballot(self)
def show_ballot (self):
print (self.votes)
def next_vote (self):
while not list_candidates[self.votes[self.owner]... |
6120b69539fe2551e32abebc557233ed59ba0091 | CompbioLabUnist/Helixco_Cavity | /jwlee230/Program/Python/step12.py | 1,462 | 3.546875 | 4 | """
Step 12: Read raw TSV file and make PKL file
"""
import argparse
import gzip
import pickle
import pandas
def read_data(path: str) -> pandas.DataFrame:
"""
read_data: Read & clearify data from TSV
"""
if not path.endswith(".tsv"):
raise ValueError("Input is not TSV")
data = pandas.read... |
aafdadf3403cdc802b4e5437bdaa37baea7d500e | deadwhisperme/lab6 | /A.py | 970 | 3.53125 | 4 | '''
Задача A
++++++++
В массиве ровно два элемента равны. Найдите эти элементы.
Программа получает на вход число N, в следующей строке заданы N элементов списка через пробел.
Выведите значение совпадающих элементов.
+-------------+-------+
| Ввод | Вывод |
+=============+=======+
| 6 | 5 |
+---... |
5976af374be056c97d27421cefac260c402594c3 | yongkangzhao/LeetCode-Practice | /Algorithms/medium/16 3Sum Closest.py | 1,420 | 4.0625 | 4 | '''
Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example 1:
Input: nums = [-1,2,1,-4], target = 1
Output: 2
Explanation: The sum that i... |
f22792b19d0d822b27c214b038b86232790bc7df | manatee2k3/Python_Games | /Hangman/Hangman.py | 2,449 | 3.765625 | 4 | ## Hangman ##
import random
man = {'head': ' ', 'torso': ' ', 'L-arm': ' ', 'R-arm': ' ', 'L-leg': ' ', 'R-leg': ' '}
def hangman_board(man):
print('____________________')
print()
print(' |--| ')
print(' |/ '+ (man)['head'] + ' ')
print(' | ' + (man)['R-arm'] + (man)['torso'] + (ma... |
0aef4a43c2ededc35bb1a192d53f3f81f0328fcd | JackNova/advent-of-code-2015 | /day15/solution.py | 6,701 | 4.09375 | 4 | import re
import operator
from itertools import permutations
def prod(iterable):
return reduce(operator.mul, iterable, 1)
# --- Day 15: Science for Hungry People ---
# Today, you set out on the task of perfecting your milk-dunking cookie recipe.
# All you have to do is find the right balance of ingredients.
# You... |
ef984045e0252f517f2877cb020fa77a3037f844 | JackNova/advent-of-code-2015 | /day09/solution.py | 3,165 | 4.09375 | 4 | import re
from itertools import permutations
# --- Day 9: All in a Single Night ---
# Every year, Santa manages to deliver all of his presents in a single night.
# This year, however, he has some new locations to visit; his elves have
# provided him the distances between every pair of locations. He can start and
# e... |
55d3950652733ec67c8c3d27c5d9675c07a7c5fb | ditesh/python-sorts | /sort.py | 1,659 | 3.5 | 4 | #!/usr/bin/env python
# Implementations of common sorts
# Ditesh Shashikant Gathani (c) 2010
import sys
import support
def main(argv=None):
sorts = ["merge", "quick", "bubble", "selection", "insertion"]
if argv is None:
argv = sys.argv
if len(argv) != 3:
print >> sys.stderr, "Invalid ar... |
875493eace0aa959516daffb0a13fe12fc4b8f4a | adriellison/UFC | /1-Semestre/Curso extra de python/aula 06/quest07.py | 202 | 3.6875 | 4 | pares = []
cont = 0
for i in range(15):
pares.append(int(input("Digite um valor: ")))
for i in range(15):
if(pares[i] % 2 == 0):
cont += 1
print("\nPares: ", pares)
print("\nQuantidade: ", cont) |
96ca0a8dbb98f46a07b1bf2f23dfb820792ea01e | jhemesonmotta/Heap-Sort | /heapsort.py | 827 | 3.828125 | 4 | def trocar(lista, i, j):
lista[i], lista[j] = lista[j], lista[i]
return lista
def heapficar(lista, tamanho, i):
l=2 * i + 1
r=2 * (i + 1)
max=i
if l < tamanho and lista[i] < lista[l]:
max = l
if r < tamanho and lista[max] < lista[r]: ... |
e1a30bebe9d6b695de0d01a1ed15856298f5250c | fabianschilling/wumpus-speechify | /wumpus.py | 33,443 | 3.5625 | 4 | # Speech Technology Final Project
# Speech interface to a text-based adventure game
# Iris Hartl (ihartl@kth.se)
# Benjamin Coors (coors@kth.se)
# Fabian Schilling (fabsch@kth.se)
############################################################################### MODULES #######
import random
import os
import subprocess
... |
0bdc824c7774d0e9239cbd6ad9348daa87e4a64b | rshrc/machinelearning | /Decision Tree Regression/decision_tree_regression.py | 635 | 3.609375 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset = pd.read_csv('Data.csv')
X = dataset.iloc[:,1:2].values
y = dataset.iloc[:,2].values
# Fitting the dataset
from sklearn.tree import DecisionTreeRegressor
regressor = DecisionTreeRegressor(random_state = 0)
regressor.fit(X, y)
y_pred = ... |
4ffca3122329e11026c9c6ce363d4d05595542a1 | Nani-o/adventofcode2018 | /aoc/day3.py | 2,154 | 3.578125 | 4 | #!/usr/bin/env python
import re
def part1(puzzle_input):
claims = puzzle_input.rstrip('\n').split('\n')
all_claimed_inches = set()
multiple_claimed_inches = set()
for claim in claims:
m = re.search('@ (.+),(.+): (.+)x(.+)', claim)
start_x = int(m.group(1))
start_y = int(m.group... |
2512e2afaa0ef4ad8770dd1900c33506cb2ae4e4 | Nani-o/adventofcode2018 | /aoc/day1.py | 636 | 3.875 | 4 | #!/usr/bin/env python
def part1(puzzle_input):
frequency_changes = list(map(int, puzzle_input.split()))
return sum(frequency_changes)
def part2(puzzle_input):
frequency_changes = list(map(int, puzzle_input.split()))
current_frequency_result = 0
frequency_results = set([current_frequency_result])
... |
d6918e40fb0dbcfb58d12b35ed6f6662fcd6a1cd | Nani-o/adventofcode2018 | /aoc/day14.py | 644 | 3.671875 | 4 | #!/usr/bin/env python
def part1(puzzle_input):
recipe_numbers = int(puzzle_input)
scores = [3, 7]
x, y = 0, 1
while len(scores) <= recipe_numbers + 10:
# print("({}, {})".format(x, y))
# print(scores)
new_recipes = scores[x] + scores[y]
if new_recipes >= 10:
s... |
0c42e8665ea4bbf35ac346f1b2f191cd4b8d8caa | davidsims9t/deep-learning | /ann.py | 2,052 | 3.78125 | 4 | # Part 1 - Data Processing
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler
# Import data set
dataset = pd.read_csv('Churn_Modelling.csv')
# All indexes from 3 - 12
... |
be02f65d2ced10abea7bdbef5ecde8ddab5f7ab6 | csy9730/pyScrawler | /code/scrapy/eScrapy/eStaticClass.py | 766 | 3.609375 | 4 | class A:
member = "this is a test."
def __init__(self):
pass
@classmethod
def Print1(cls):
print ("print 1: ", cls.member)
def Print2(self):
print( "print 2: ", self.member)
@classmethod
def Print3(paraTest):
print ("print 3... |
1b3963182b37bdc34e4e7afd3ccfe1530f0529a9 | zhoufel1/pypass | /core/passwords.py | 480 | 3.5 | 4 | import random
from constants import UPPER, LOWER
def generate_password(length: int) -> str:
return ''.join([determine_character_type(random.randint(0, 2))
for i in range(length)])
def determine_character_type(value: int) -> str:
if value == 0:
return LOWER[random.SystemRandom().ra... |
053699bdc95f9bf5833916aca6da13fbe99c4a10 | MatheusL3/python-news | /teste_003.py | 799 | 4.125 | 4 | nome = str(input('Digite seu nome completo: '))
print('Seu nome com todas as letras maiúsculas é {}'.format(nome.upper()))
print('Seu nome com todas as letras minúsculas é {}'.format(nome.lower()))
print('Seu nome contem {} letras ao todo, e {} sem contar espaços'.format(len(nome), len(nome.replace(" ", ""))))
print('A... |
687bc236a0e2db8cd2501ffba12d41974ca7cbea | SavaTudor/StudentsLabsGrades | /domeniu/entitateLab.py | 997 | 3.609375 | 4 | class Laborator(object):
def __init__(self, nrLab_nrProb, descriere, deadline):
"""
:param nrLab_nrProb: a string with the format "labNumber_problemNumber"
:param descriere: a non-empty string
:param deadline: a string with the format "DD.MM.YYYY"
"""
self.__nr = nrLa... |
71c191949dcd6285e37992ab745c38e9d9dc624e | Sougata024/Stone-Paper-Sizer-Game | /Game/Stone Paper Game.py | 801 | 3.859375 | 4 | import random
r=random.randint(1,4)
a=r
if(a==1):
a='stone'
elif(a==2):
a='paper'
else:
a='sizer'
i=input("Enter Your Choice Here:")
print("Your Choice is:"+i)
print("Computer Choice:"+a)
if(a=='stone' and i=='stone'):
print("Tie")
elif(a=='stone' and i=='paper'):
print("You Won... |
84cb436340dc4bdc7aac34b399f5f2e69a9dc33d | imgzon3/data-structure | /Stack/stack_linked_list.py | 3,658 | 4.0625 | 4 | class Node: # class Node
def __init__(self, data: int):
self.data = data # 저장하는 데이터 값
self.next = None # 다음 node의 주소값 저장
class S_linked_list:
def __init__(self): # 선언시 head와 tail값은 None
self.head = None
self.tail = None
def empty(self)-> bool: # 리스트가 비어있는지 확인하는 함수
... |
4ab575f96a108bcd5edb9ace3b50c03a2d875151 | imgzon3/data-structure | /Heap/array_base_heap.py | 3,862 | 3.9375 | 4 | '''
heap 필요한 것
1. 저장할 배열
2. min-heap, max-heap 구별(+1, -1입력받고, 곱해서 구별하기)
heap functions
0. is_empty()
1. swap()
2. upheap()
3. downheap()
4. insert()
5. pop()
6. top()
7. size()
8. print()
8-2. print_g()
9. find()
'''
class Heap:
def __init__(self, dir: int): # 1 입력받으면 min-heap, -1 입력받으면 max-heap
"""heap을 생... |
836f46b265dede71a8c4870269a18eb7ec5f7511 | kaltsimon/crypto-challenges | /src/encode_decode.py | 2,642 | 3.65625 | 4 | """Crypto Challenges Set 1."""
from functools import wraps
def int_seq_to_bytes(func):
"""Wrap a function that returns an int sequence to return a bytearray."""
@wraps(func)
def wrapped(*args, **kwargs):
seq = func(*args, **kwargs)
return bytes(seq)
return wrapped
@int_seq_to_bytes
... |
2170fd9fc73383da02094835ed18b7306e5f423f | cyrillelamal/pogrom | /sem4/task2/secundo.py | 764 | 4 | 4 | # Дополнение программы «Калькулятор» декоратором, сохраняющий
# действия, которые выполняются в файл-журнал.
FILE = "./log.txt"
def logger(func):
def calc_with_log(*args, **kwargs):
res = func(*args, **kwargs)
with open(FILE, "at") as f:
operator, a, b = args
f.write(f"{a} ... |
176d381792f5ced3e67364e71c2fa88e1b626c69 | cyrillelamal/pogrom | /sem6/task2/primo.py | 636 | 4.09375 | 4 | # На основе кода, предоставленного преподавателем, реализовать генератор
# чисел ряда Фибоначчи. Генератор требуется создать двумя вариантами: с
# помощью генератора списков, с помощью функции, внутри которой yield.
END = 10
fibonacci = [0, 1]
fibonacci += [
(fibonacci := [fibonacci[1], fibonacci[0] + fibonacci[1... |
3855d4b133a3766d0d46c32e12ddbec56a4f0b87 | bjak/sywtltc_chapter_3_3 | /test_stats.py | 952 | 3.765625 | 4 | """Test for Stats Function"""
import stats
def test_stats_median():
"""Tests for Median Function Stats"""
assert stats.median([1, 2, 3, 4, 5]) == 3
assert stats.median([5, 7, 9, 11, 13]) == 9
assert stats.median([3, 6, 9, 12, 15]) == 9
def test_stats_range_1():
"""Tests for Range Function Stats""... |
8e22fd7026602da6873f297a45234aed9109c447 | Crockcharterings/onlyinpgh | /utils/time.py | 2,757 | 3.609375 | 4 | from pytz import timezone, utc
# cliff's notes on converting a UTC dt:
# >>> from pytz import timezone
# >>> utc = timezone('utc'); est = timezone('US/Eastern')
# >>> utc_dt = utc.localize(dt) % change the tz-agnostic datetime into a utc datetime
# >>> est_dt = est.normalize(utc_dt.astimezone(e... |
97c7505176de1256cf2b04458200733256fdcff2 | yesayayova/8puzzle_A_algorithm | /solve.py | 2,467 | 3.625 | 4 | # Check Puzzle-8 inputted exist in the state
def is_contain(puzzle, state):
for item in state:
if puzzle.tolist() == item[0].tolist():
return True
return False
def solve(puzzle, goal):
# Initializing state to save nodes has been generated
# Storage format: Tuple (puzzle, id_node, id_parent, g(n), h(n))
... |
5c83ef88e1950a772610d11dc495637097d95643 | Ahalyasiddi/99003197-python1 | /review 2/final.py | 2,589 | 3.703125 | 4 | import re
class Profile:
print(re.match("[A-Z][a-z]+", "Caloriecalculator"))
def __init__(self):
self.age = int(input('What is your age: '))
self.gender = input('What is your gender: ')
self.weight = int(input('What is your weight: '))
self.height = int(input('What i... |
2cf91a4c819fa8cb5f459c0d81facfcf64edd12e | AlxndrBorodin/learn-homework-2 | /1_date_and_time.py | 528 | 4.03125 | 4 |
from datetime import date, datetime, timedelta
from time import strftime
def print_days():
dt = date.today()
delta = timedelta(days=1)
dt_yesterday = dt - delta
dt_30days = dt - 30*delta
print(f'Вчера было {dt_yesterday}, сегодня - {dt}, а 30 дней назад было {dt_30days}')
def str_2_datetime(date... |
d4c3f23b8aa3ffa5a1209eee113690467165258a | jiapengwei/PythonExercise | /Sklearn/vir_data.py | 265 | 3.515625 | 4 |
#用函数来建立 100 个 sample,有一个 feature,和一个 target,这样比较方便可视化。
X, y = datasets.make_regression(n_samples=100, n_features=1, n_targets=1, noise=10)
#用 scatter 的形式来输出结果
plt.scatter(X, y)
plt.show() |
42c15d17340b3ffcf196f504777efc10fdae72aa | jessica-collins/decoder | /a1.py | 7,286 | 4.125 | 4 | #!/usr/bin/env python3
"""
Assignment 1
CSSE1001/7030
Semester 2, 2018
"""
from a1_support import is_word_english
__author__ = "Jessica Collins 44345956"
#ENCRYPTION FUNCTION
def encrypt(text,offset):
""" Returns the entered text with the chosen coding offset
Parameter:
text (str): The t... |
8f1e54fdc78494c67ca10d46ae95e847d7bba6cd | FlimothyCrow/Python | /poker.py | 4,036 | 3.59375 | 4 | from enum import Enum
class Card :
def __init__(self, value, suit):
self.value = value
self.suit = suit
class Hand :
def __init__(self, cards):
self.cards = cards
class RankedHand :
def __init__(self, rank, tiebreaker): # fudge tiebreaker as inputNumber for suit strength
s... |
da4f9a53ed3cf46a2f7166c5fc0b052bb5e16b50 | FlimothyCrow/Python | /managrams.py | 1,355 | 3.8125 | 4 | def anagrams(list0, list1) :
orderedList0 = sorted(list0, key = str)
orderedList1 = sorted(list1, key = str)
if orderedList0 == orderedList1 :
return True
else:
return False
def fizzBuzz(listOfInts) :
parsedList = []
for element in listOfInts :
if element % 3 == 0 and e... |
c8f5d4b64a8a023245c5d24370f367e52ccc885d | FlimothyCrow/Python | /mergeSort.py | 1,050 | 3.90625 | 4 | spicyList = [1, 31, 8, 29, 100, 5, 2, 9, 50]
dumbList = []
def mergeSort(numbers) :
sortedList = []
if len(numbers) > 1 :
midPoint = len(numbers) // 2
left = numbers[:midPoint]
right = numbers[midPoint:]
sortedLeft = mergeSort(left)
sortedRight = mergeSort(right)
... |
c1c5094a3dfe984fbd70ff016ac12252bc3f6b2f | pranaykanavaje/text-summarizer | /textutil.py | 6,036 | 3.578125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import re
class RatedWordgroup:
def __init__(self,wordgroup,rating):
self.wordgroup = wordgroup
self.rating = rating
def __str__(self):
result = str(self.wordgroup) +" - " + str(self.rating)
return result
def __eq__(self,other):
... |
cc76241b9575e7626fc3339a37641b9c24f761f9 | bmoe/AOC2018 | /13-prog.py | 4,653 | 3.84375 | 4 |
UP = '^'
DOWN = 'v'
LEFT = '<'
RIGHT = '>'
DIRECTIONS = [UP, DOWN, LEFT, RIGHT]
data = '13-input'
test_data = '13-input-test'
# Moving onto this thing, going this direction.
# You are now going this possibly new direction.
# Intersections are crazy though. Gotta ask the
# car for that one.
# So .. map road kind ->... |
10b722766a55b493d8a06893fefd2fc7b2522e77 | bhayden2458/si475 | /translate.py | 134 | 3.65625 | 4 | import numpy as np
def make_trans_matrix(m, n):
return np.array([[1,0,m],[0,1,n],[0,0,1]])
A = make_trans_matrix(5, 3)
print(A)
|
1c307d156e4f879272378f4b081754073fd4b634 | yawei798/AlgorithmsAndDataStructures | /算法总结/BubbleSort_1.py | 1,813 | 3.953125 | 4 | """
冒泡排序(英语:Bubble Sort)是一种简单的排序算法。它重复地遍历要排序的数列,一次比较两个元素,
如果他们的顺序错误就把他们交换过来。遍历数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。
这个算法的名字由来是因为越小的元素会经由交换慢慢“浮”到数列的顶端。
冒泡排序算法的运作如下:
1、比较相邻的元素。如果第一个比第二个大(升序),就交换他们两个。
2、对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。这步做完后,最后的元素会是最大的数。
3、针对所有的元素重复以上的步骤,除了最后一个。
4、持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。
"""
""... |
1ba686fc9c3d7797f1c85a263291107f8d54d707 | yawei798/AlgorithmsAndDataStructures | /用Python解决数据结构和算法/5:搜索和排序/five_7.py | 791 | 3.828125 | 4 | """
希尔排序
"""
def shellSort(alist):
gap = len(alist)//6
while gap > 0:
for start in range(gap):
gapInsertSort(alist, start, gap)
print('After increments of size', gap, 'The list is', alist)
gap = gap//6 # gap必须得有1才可以,不然是不能排序正确的
def gapInsertSort(alist, start, gap):
... |
f1bb1354d1b085f5f02328998b35f300af44dede | iman-keangkasa/python-playground | /test.py | 3,614 | 3.9375 | 4 | """
Testing different concepts in Python programming
and computations
"""
def multiple_return():
"""Testing multiple returns.
syntax: v,w = test.multiple_return()
v = 5
w = 6"""
a = 5
b = 6
return a, b
def separate_dict(a):
"""The way to separate a dictionary keys
and values"""
... |
c369a0945e2532234bdf66880470bcd656b0ef0c | mazabache/CEBD1160 | /HomeWorkPythonW1/Home Work Python Week 1 - Advanced - Question 1.py | 367 | 3.890625 | 4 | import string
import operator
input_str=input("Enter a string:")
Letters=list(string.ascii_letters)
result={}
for char in Letters:
result.update({char:input_str.count(char)})
print("\nAlphabetical Order")
print(result)
sorted_x={}
sorted_x = sorted(result.items(), key=operator.itemgetter(1),reverse=True)
print("\... |
33cd3de6a288997f3906bd2abdea3478ade87c56 | mazabache/CEBD1160 | /HomeWorkPythonW1/Home Work Python Week 1 - Advanced - Question 2.py | 287 | 3.734375 | 4 | import string
words = input("Please enter a sentence: ")
words = words.strip(string.punctuation)
counter = dict()
words = words.split()
for word in words:
if word in counter:
counter[word] += 1
else:
counter[word] = 1
print(counter)
|
efdf27ee4de6c08b676ed8a009505c84272cdf74 | jackdo20/mytraining | /python/clas.py | 382 | 3.9375 | 4 | class Menu(object):
menu=[]
i=0
def __init__(self,mn):
self.menu.append(mn)
def show_menu(self):
print('your menu is:')
for i in self.menu:
print( i)
print('Please order your food!')
while True:
food=raw_input()
if food=='ok':
m.show_menu()
br... |
b9aaceed023e6a55f1858e6658d9eb0abf83fba3 | HannahMGustafson/Euler_Project | /EulerProject/Euler10.py | 213 | 3.859375 | 4 | def is_prime(num):
val = True
for x in range(2,int(num**0.5)+1):
if num%x == 0:
val = False
break
return val
summation = 2
for x in range(3,2000000,2):
if is_prime(x):
summation += x
print summation |
c8e3706e7a677f6e7f4aa907c1a8697013620c11 | HannahMGustafson/Euler_Project | /EulerProject/Euler60_mod.py | 2,184 | 3.78125 | 4 | import itertools
def is_prime_two(num1, num2):
# type: (object, object) -> object
numcon1 = int(str(num1)+str(num2))
if is_prime(numcon1):
numcon2 = int(str(num2)+str(num1))
if is_prime(numcon2):
return True
return False
def is_prime(num):
val = True
if num == 1:
... |
966ec4799da7e6ebe6459ac56bb57b9eeedc9c4f | HannahMGustafson/Euler_Project | /EulerProject/Euler31.py | 328 | 3.5 | 4 | possible = 0
for p200 in range(0,2):
for p100 in range(0,3):
for p50 in range(0,5):
for p20 in range(0,11):
for p10 in range(0,21):
for p5 in range(0,41):
for p2 in range(0,101):
if 2*p2+5*p5+10*p10+20*p20+50*p50+100*p100+200*p200 <= 200:
possible += 1
print possible
print ... |
4c80183280d770504c91e0ac4a653ecca8c369d6 | HannahMGustafson/Euler_Project | /EulerProject/Euler14.py | 273 | 3.515625 | 4 | def coll(num):
if num%2 == 0:
num = num/2
elif num%2 != 0:
num = num*3 + 1
return num
maxcount = 0
for x in range(1,1000001):
count = 1
num = x
while num != 1:
num = coll(num)
count += 1
if count > maxcount:
maxcount = count
maxnum = x
print maxnum
|
4480a11989b0aff1a142c6b09466cac32818705b | backtrackbaba/fsdse-python-assignment-8 | /even_numbers.py | 147 | 3.59375 | 4 | lis=[]
def get_even_numbers(num):
if(num>0):
for num in range(1,num):
if(num%2==0):
lis.append(num)
return lis
get_even_numbers(10)
|
42d36aef393b1a01a20a7df6d0890c693165f819 | cdivyanambiar/Genetic-Algorithm-Based-Sudoku-Solver | /GA_Sudoku_Solver.py | 2,211 | 3.890625 | 4 | """
This program is to solve sudoku using genetic algorithm.
"""
import sys
import time
import math
from SudokuSolver.CreatePuzzle import CreatePuzzle
from SudokuSolver.Sudoku import Sudoku
if __name__ == '__main__':
arguments = sys.argv[1:]
Nd = 4
input = "1234"
file = 'Sudoku_4.json'
if len(argu... |
d95b4261803a3095fd8bea31dab0c2bb5055c086 | forteek/pathfinder | /app/model/Heap.py | 1,974 | 3.703125 | 4 | #
class Heap:
def __init__(self):
self._array = []
@staticmethod
def get_parent(pos):
return (pos + 1) // 2 - 1
@staticmethod
def get_children(pos):
right = (pos + 1) * 2
left = right - 1
return left, right
@staticmethod
def swap(array, a, b):
... |
43f237f516d5b662963cec836a01b25c66bc76d3 | deca007/python | /test3.py | 792 | 4.0625 | 4 | __author__ = 'ankurs'
import random
guess_num = random.randint(1,20)
name = input("Enter your name? ")
if name == "Sanyukta" or name == "sanyukta":
print("Hello Saand, I have a number between 1 and 20. Can you guess it?")
else:
print("Hello " +name + ", I have a number between 1 and 20. Can you guess it? ")
gu... |
7fd3959130221543f5554a6415447f9e190eab16 | henrycjc/tropofy_event_tracking_demo | /create.py | 743 | 3.515625 | 4 | import random
foods = ["Banh Mi",
"Rice Noodle Salad",
"Prawn Soup",
"Vietnamese Spring Rolls",
"Honey Chicken",
"Lemon Chicken",
"Wonton Soup",
"Chinese Spring Rolls",
"Sweet and Sour Pork",
"Spanish Meatballs",
"Seafood Paella"... |
eab9502d7f45173642f6c2a8a2575b6ffb9c4065 | ameerfaisal89/Spark_ChicagoCrime | /problem1.py | 2,153 | 3.8125 | 4 | from pyspark import SparkConf, SparkContext;
import pyspark.sql as sql;
import csv;
def csvParse( t ):
'''
Takes a tuple and converts the first element from a CSV string to a list object containing
each field from the CSV string as an element.
@param tup tuple whose first element is a comma-separated... |
c5eaf0c94fc0f52310cdb975260181b4f5c4fbe8 | NovaStrikeexe/FtermLabs | /131 b part.py | 528 | 3.9375 | 4 | max_y = float(input("input y line: "))
if max_y > 0.278:
"""y = []
x = 9
while x < 10:
y.append(5 * x / (x * x + 81))
x += 0.01
print(max(y))"""
print("You used the max function! It will not work!")
else:
x = int(input("Input epsi... |
e67363c2be2fc782679324cffb7afa0900c3b493 | NovaStrikeexe/FtermLabs | /Massive.py | 697 | 4.1875 | 4 | import random
n = 0
n = int(input("Enter the number of columns from 2 and more:"))
if n < 2:
print("The array must consist of at least two columns !")
n = int(input("Enter the number of columns from 2 and more:"))
else:
m = [][]
for i in range(0, n):
for j in range(0, n):
m... |
fe0004a380012ba1138fc4cb6fce9e167821c673 | NovaStrikeexe/FtermLabs | /SUM LAST AND FIRST.py | 676 | 4.15625 | 4 | print("Start program.....")# 1.42
#Найти сумму первой и последней цифр любого целого положительного числа.
print("====================")
x = int(input("input x:"))
print("====================")
if x < 0:
print("Your x is negative it wouldnt work")
elif x < 10:
print("Only one simbol in list:", x)
else:... |
d3d3e1bd76011772b1617b8c1a2ca18b4e6ec080 | NovaStrikeexe/FtermLabs | /list of lists.py | 1,230 | 4.46875 | 4 | #3.49
#Дано натуральное число n>=2, список списков, состоящий из n элементов по n чисел в элементе.
# Список заполняется случайным образом числами из промежутка от 0 до 199.
# Найти количество всех двухзначных чисел, у которых сумма цифр кратна 2.
import random
i = 0
z = 0
j = 0
n = 0
n = int(input("Enter the ... |
b81f5cc81b217a4b57fe23211f6a7efe1c9dd016 | snazzy888/Practicals | /prac_09/subject_list_v2.py | 1,052 | 3.96875 | 4 | """
CP1401 Checkpoint 2
Subject List - Extended Version
See the demonstration videos for details and explanations
"""
def main():
"""Get and display subject codes."""
subjects = []
subject = get_subject()
while subject != "":
subjects.append(subject)
subject = get_subject()
number_... |
bfded0dbe0c4bf0f778db4cf58d86eb7069532f7 | hiteshvermaa/Data-Science | /Linear Regression/linear_regression.py | 563 | 3.515625 | 4 | import matplotlib.pyplot as plt
from scipy import stats
x = [5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6]
y = [99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86]
slope, intercept, r, p, std_err = stats.linregress(x, y)
def myfunc(x):
return slope * x + intercept
mymodel = list(map(myfunc, x))
# prin... |
df72aa0c39491f140532ccdb7c9d8107e6ff6de6 | riturajbasant/LearnPython | /facto.py | 170 | 4.0625 | 4 | def factorial(n):
x = 1
while(a>=1):
x = x*n
n = n-1
return x
n = int(input("Enter Number "))
print(factorial(a))
|
8e33cbd8cbe3efa86b4c74f35214faa25ede5c33 | riturajbasant/LearnPython | /enumerate.py | 297 | 4.03125 | 4 | # enumerate is a predefined function and it will return index as well as values
# we will pass a sequence as a parameter in enumberate
'''
for i, j in enumerate (range (4,30,2)):
print(i,j)
'''
#zip
for i, j in zip(range(4,10,1), range(1,6)):
print(i, "+", j, "=", i +j)
|
cf5abf6b4b8dc7f29d81a66161833133315b49ea | riturajbasant/LearnPython | /infiniteloopinfor.py | 712 | 4.0625 | 4 | #Making infinate loop
#repeat function is used to repeat a word and creates infinite loop
'''
ctr = 0
from itertools import repeat
for i in repeat('hello'):
print(i)
ctr+= 1
if ctr ==10:
break
'''
'''
#it will repeat the list till infinity
ctr = 0
from itertools import cycle
... |
0ee66518a54adf969661ad33b91752d508391bad | scarter13/House-Hunting | /hourly_pay.py | 319 | 4.34375 | 4 | hours_worked = float (input("Enter Hours Worked: "))
hourly_rate = float (input("Enter Hourly Rate: "))
#if you worked more than 40
if hours_worked > 40:
overtime = hours_worked - 40
wages = (40* hourly_rate + overtime * hourly_rate * 1.5)
else:
wages = hours_worked * hourly_rate
print ("Total: $", wages) |
2909cc43229422c8205933df710f060cc730841c | akshaykhatale/Machine_Learning_Python | /1_Regression/2_multiple_linear_regression/multiple_linear_regression.py | 1,420 | 3.796875 | 4 | #Multiple linear regression
#importing libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#IMPORTING DATA
dataset = pd.read_csv("50_startups.csv")
x=dataset.iloc[:,:-1].values
y=dataset.iloc[:,4].values
#Creating dummy variables for categorical data
from sklearn.preprocessing import La... |
f3e5f5381ff45695eac29600d47f8480b259f60b | Shirley95/Python-Battle | /main.py | 10,334 | 3.78125 | 4 | from classes.game import Person, bcolors
from classes.magic import Spell
from classes.inventory import Item
import random
'''
Initialization means assigning initial value to variables after declaring or while declaring. All variables are always given an initial value at the point the variable is declared. Thus, all var... |
82419175c7058754d85657382d1822a7fc4d3d23 | pengLP/LeetCode | /python/chuji/chuji-array/leetCode_48.py | 733 | 3.921875 | 4 | """
旋转图像
给定一个 n × n 的二维矩阵表示一个图像。
将图像顺时针旋转 90 度。
"""
class Solution:
def rotate(self, matrix):
for i in range(0,int(len(matrix)/2)):
start = i
end = len(matrix) - i -1
for j in range(0,end-start):
temp = matrix[start][start+j]
matrix[start]... |
db853c44cc90a12092ae133051d8ccaf35d4e4b9 | pengLP/LeetCode | /python/chuji/chuji_tree/leetCode_104.py | 684 | 3.71875 | 4 | """
二叉树的最大深度
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def creat(str):
print(str)
list = []
for i in range(len(str)):
if(str != None):
list.appe... |
6598a40314edb7b4745017714e579969cf078fb9 | pengLP/LeetCode | /python/chuji/chuji_str/leetCode_28.py | 792 | 3.953125 | 4 | """
实现 strStr()
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
"""
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if(needle == ""):
return 0
i = 0
j = 0
tmp = 0
while(i<len(haystack)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.