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 |
|---|---|---|---|---|---|---|
67229be22129d042877f6613c3492baf88025e2e | StefanFNorling/Misc-Projects | /venv/pd15.py | 1,158 | 3.75 | 4 | def timeconverter(num):
return str(num // 60) + ":" + str(num % 60)
print(timeconverter(int(input("Enter a number to put into hours and minutes: "))))
def no_teen_sum(a, b, c):
teens = [13,14,17,18,19]
nums = [a,b,c]
sum = 0
for num in nums:
if num not in teens:
sum += num
r... |
65a9d683e1d6de902b1a9f8c0f022b4c0a9c49b6 | StefanFNorling/Misc-Projects | /venv/pd1.py | 305 | 3.65625 | 4 | file = open("programaday1.txt", "r")
numberofstrings = int(file.readline())
i = 0
while i < numberofstrings:
original = file.readline()[:-1]
index = len(original) - 1
newstring = ""
while index >= 0:
newstring += original[index]
index -= 1
print(newstring)
i += 1 |
f748c058739ca78132f7ff46cff692da671fc827 | StefanFNorling/Misc-Projects | /AllShortestPaths.py | 578 | 3.609375 | 4 | # Stefan Norling
# sfn2mc
# Based on my algorithms homework question which I misinterpreted
# Finds all minimum length spanning trees
input = open("nodes_and_edges.txt", "r")
vertices = input.readline().split()
nodesedges = []
for vertice in vertices:
nodesedges.append([int(vertice), []])
numNodes = len(vertices... |
32e87a7eab690a54f3671f3de99f7bee2bd483b7 | prastabdkl/pythonAdvancedProgramming | /chap1basic/commands.py | 398 | 3.859375 | 4 | import math
print('hello')
type('1')
type('1.0')
type('Nepal') #type finding
float_value = 2.6
print(int(float_value))
float_value = -2.6
print(int(float_value))#type casting
radius = 5
num = 25
print(math.pi)
print(math.sqrt(25))
print(math.e)
print(math.fmod(151.5,19))
print('The area of circle is ',math.pi*rad... |
d629f2ec6d54528064dfbc4276315505f5bd00fe | prastabdkl/pythonAdvancedProgramming | /chap7lists/chap7twodimensionallist.py | 504 | 3.921875 | 4 | # two dimensional list
# # Author: Prastab Dhakal
# Chapter: Lists and tuples
import random
# Constants for rows and columns
ROWS = 3
COLS = 4
def main():
# Create a two-dimensional list.
values = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
# Fill the list with random numbers.... |
577014780eb3d53d8f3a1e8a71abb44d513d5077 | prastabdkl/pythonAdvancedProgramming | /graphics/gui/salary_tax_single.py | 1,123 | 3.5625 | 4 | import tkinter
import tkinter.messagebox
def tax_calculation(monthly_amount,value1,value2,value3,value4):
tax_first=0.01
tax_second=0.1
tax_third=0.2
tax_fourth=0.3
tax_remain=0.36
first=400000
second=100000
third=200000
fourth=1300000
# monthly_amount = float(self.monthly_sal... |
f7df966b90cd84cadf6805203d190df700a58f9f | prastabdkl/pythonAdvancedProgramming | /chap7lists/plotting/sec5piechart.py | 511 | 4.25 | 4 | # plotting a Piechart
# Author: Prastab Dhakal
# Chapter: plotting
import matplotlib.pyplot as plt
def main():
#create a list of values
values=[20,60,80,40]
#title
plt.title("PIE CHART")
#create a list of labels for the slices.
slice_labels=['1st Qtr','2nd Qtr','3rd Qtr','4th Qtr']
... |
131e0b25d4a9876e25575d0ced4c44f1579517dd | prastabdkl/pythonAdvancedProgramming | /chap5function/others/feetandinchadd.py | 559 | 4.09375 | 4 | #wap to ask user for two input of feet and inches and add them using a function.
#using split function to split the input separated by white space
# def add_feetinch(feet,inch):
# print('#enter codes here')
# #hgjghj
# def main():
# feet1,inch1 = input('Enter the first feet and inch').split()
# print(... |
c4eed4a3bed17bb04a04ac4f06d8ae8360256a31 | prastabdkl/pythonAdvancedProgramming | /chap4loopbasicclock.py | 305 | 3.890625 | 4 | import time
for hours in range(24):
for minutes in range(60):
for seconds in range(60):
print('%02d:%02d:%02d'%(hours,minutes,seconds))
#print(hours, ':', minutes, ':', seconds)
time.sleep(1)
#WAP to show prime numbers
#of a given range by user using loop |
941f9950cf21e526a0cb8c50feb2a553d6e5d4c3 | prastabdkl/pythonAdvancedProgramming | /chap6FilesAndException/others/save_file_records.py | 2,541 | 4.125 | 4 | # This program gets employee data from the user and
# saves it as records in the employee.txt file.
# read the records and show until the end is reached handles the value errors,
# read file error and searches the file until the end is reached
#
# Author: Prastab Dhakal
# Chapter: Files and Exception(Complex problem)... |
dfda49154e9f16ea9e230a0c66fd661f5af4bb6b | gusev-ea/python_gusev_ea | /z6.py | 847 | 3.84375 | 4 | import math
def getNumber01(num):
while type:
getNumber = input('Введите число ' + num + ': ')
try:
getTempNumber = float(getNumber)
except ValueError:
print('"' + getNumber + '"' + ' - не является числом')
else:
break
return float(... |
ce2d8c0d05b2dac8934bd7aba1b7365197258263 | aishuse/lumipjt | /oop/book.py | 1,760 | 3.6875 | 4 | class Book:
book_list={
'alchemist':{'name':'alchemist','author':'paulo','price':300,'av_copies':20,'sold':563},
'Vivekadeepini': {'name': 'Vivekadeepini', 'author': 'Shankaracharya', 'price': 250, 'av_copies': 120, 'sold': 32},
'Devadas': {'name': 'Devadas', 'author': 'sarat', 'price': 100,... |
89e4d152140d2dadbdc79c535c24be419d06df6a | rodri0315/pythonCSC121 | /chapter8/vowels_constants.py | 983 | 4.03125 | 4 | # Author: Jorge Rodriguez
# Date: April 2, 2017
# Lab Vowels and Constants
# main
def main():
#Get string from user
user_input = input('Enter a string: ')
# Report the vowels and constants.
print('That string has {} vowels and {} contants.'.format(num_vowels(user_input), num_constants(user_input)))
... |
645fa097b91b25884ece0ffac416632da73c760c | rodri0315/pythonCSC121 | /chapter7/name_search.py | 2,019 | 4.0625 | 4 | # Author: Jorge Rodriguez
# Date: March 28, 2017
# Name search
boy_names = []
girl_names = []
def main():
# receive list of boy names from file
input_file = open("BoyNames.txt", "r")
# check user answers against correct answers
list_names = input_file.readlines()
# Clean up the entries by removi... |
d5fc347cad1f2a3a1cd26cab15653aea5f9bb986 | rodri0315/pythonCSC121 | /chapter3/area_of_rectangles.py | 966 | 4.59375 | 5 | # Chapter 1 Assignment
# Author: Jorge Rodriguez
# Date: February 5, 2017
print('You will enter the length and width for two rectangles')
print('The program will tell you which rectangle has the greater area')
# get length and width of 2 rectangles
rect_length1 = float(input('Enter the length of the first rectangle: '... |
689fb3c2abd319c7485666a51cb0b56dd1206570 | rodri0315/pythonCSC121 | /chapter11/person_cust_class.py | 1,951 | 3.5625 | 4 | # Author: Jorge Rodriguez
# Date: April 23, 2017
# Person Customer Class Lab
class Person:
# init method to initialize the attributes
def __init__(self, name, address, phone):
self.__name = name
self.__address = address
self.__phone = phone
# set methods to set the name, address, ... |
3df36096a7a65bbcd6d3adc46bcd407e353b4dfc | vesloguzov/testBot | /test_dych.py | 2,647 | 3.984375 | 4 | # -*- coding: utf-8 -*-
from datetime import datetime
year_transition = {
"transition_enable": True,
"date": {
"month": 7,
"day": 1
},
"before": 775,
"after": 776,
}
def check_years(expect, answer_given):
birthday_str = answer_given[0].replace(" ", "")
new_birthday_str = ... |
38e46b041f0cdf56198d0ee99b9c8afd6d04e48e | Darshan110801/Heap-Management-Simulator | /BT19CSE070_CPL_ASSIGN3_CODE.py | 9,547 | 3.5625 | 4 | from tkinter import *
#globals
mem_size = 64
#Linked list utilities
class free_node:
def __init__(self,tag,size):
self.tag = tag
self.size = size
self.next = None
self.prev = None
#initially whole memory is free
free_head = free_node(0,mem_size)
def delete_node(itr):
global fre... |
9fb688ab976e7e7b34912c125ce5a07fda536bd3 | kiniakash22/BankingSystem | /piggyBankOOP.py | 4,623 | 3.546875 | 4 | from prettytable import PrettyTable
account_no = 1000
def generate_account_no():
global account_no
account_no += 1
return account_no
class Bank:
def __init__(self):
self.account_list = []
pass
def add_account(self, account):
self.account_list.append(account)
def che... |
a024416865ffd0f88b3597953416ab25f2029af5 | DaianeCamara/Exercicios_Fundamentos_Python | /Exercicios/7_Condicoes_aninhadas(if,elif,else).py | 6,741 | 4 | 4 | # Aprova ou não o financiamento bancário para compra de uma casa
casa = float(input('DIgite o valor do imóvel em R$'))
sal = float(input('Digite o salário do comprador em R$'))
anos = int(input('Digite o número de anos de duração do financiamento: '))
prest = (casa/(12*anos))
print(f'Para pagar uma casa de R${casa... |
be0a91090edda476213ff1df8d672428a83c42c2 | DaianeCamara/Exercicios_Fundamentos_Python | /Exercicios/15_Funcao_Parte01.py | 1,777 | 3.96875 | 4 | # Função que calcula área
def area(larg, comp):
ar = larg * comp
print(f'A área de um terreno {larg} é {comp} de {ar}m²')
print(' Controle de terreno')
print('-' * 40)
l = float(input('LARGURA (m): '))
c = float(input('COMPRIMENTO (m): '))
area(l, c)
# Um print especial
def escreva(txt):
print('... |
43e8ff3af5505aad8ecce15a40c33238adf79320 | VladimirMatveev/pythonbook | /Exercise_9/exe9.py | 2,063 | 3.828125 | 4 | def good():
return ['Harry', 'Ron', 'Hermione']
print(good())
print('==================================================')
def get_odds():
for x in range(10):
if x % 2 == 1:
print(x)
#get_odds()
def my_range(first=1, last=10, step=2):
number = first
while number < last:
yie... |
3ee2f3c4cc7ae909e3a88c326b34c3283269191e | leejjoon/pysao | /lib/PylabBlockingInput.py | 1,541 | 3.75 | 4 | import time
import threading
class BlockingInputHelperThread(threading.Thread):
""" A helper thread inside which the blocking function will be run.
"""
def __init__(self, blocking_function):
self.blocking_function = blocking_function
threading.Thread.__init__(self)
self.exception... |
fab42d2bbb28bff895054c136584314f4091fb20 | xis24/CC150 | /Python/FreqOfMostFrequentElement.py | 965 | 4.25 | 4 | from typing import List
class FreqOfMostFrequentElement:
'''
The frequency of an element is the number of times it occurs in an array.
You are given an integer array nums and an integer k. In one operation, you can choose an index of nums and increment the element at that index by 1.
Return the maxim... |
29108375b2c46d239764d70dd6b7fc4416c5e89d | xis24/CC150 | /Python/SortColors.py | 931 | 4.15625 | 4 | from typing import List
class SortColors:
# 1. discuss the approach
# 2. run the test case
# 3. ask if I can start to code
# 4. start to code
# 5. run test case with code
# 6. time complexity and space complexity
def sortColors(self, nums: List[int]) -> None:
zeros = 0 # positio... |
f98f9112ecc3bac185b0858c45511bcbbb50c2eb | xis24/CC150 | /Python/MaxAverageSubstree.py | 838 | 3.578125 | 4 | from typing import Optional
import math
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
class MaxAverageSubstree:
def maximumAverageSubtree(self, root: Optional[TreeNode]) -> float:
self.max_avg = -math.inf
... |
93fd53c6112d475c08af16540450b28647a1e560 | xis24/CC150 | /Python/KClosestPoints.py | 2,661 | 3.859375 | 4 | from typing import List
import heapq
class KClosestPoints:
# nlog(n)
'''
C++'s STL, for example, uses QuickSort most of the time but will switch to either HeapSort or InsertionSort depending on the nature of the data.
Java uses a variant of QuickSort with dual pivots when dealing with arrays of primi... |
970a9bd9a94a50f34c8d3dada702da15888d4ae0 | xis24/CC150 | /Python/WordSearch.py | 2,735 | 3.71875 | 4 | from typing import List
import collections
# word search i
class WordSearch:
def exist(self, board: List[List[str]], word: str) -> bool:
self.rows = len(board)
self.cols = len(board[0])
for i in range(self.rows):
for j in range(self.cols):
if self.backtrack(bo... |
177faaa802de56480481d33da2e5446c6d4b9f73 | xis24/CC150 | /Python/TimeBasedKeyValueStore.py | 1,295 | 3.984375 | 4 | import collections
# Design a time-based key-value data structure that can store multiple values for the
# same key at different time stamps and retrieve the key's value at a certain timestamp.
# Implement the TimeMap class:
# TimeMap() Initializes the object of the data structure.
# void set(String key, String valu... |
686f8653002f14cd8819d96677bbc07fbfdbe48d | xis24/CC150 | /Python/AlienDictionary.py | 1,958 | 3.515625 | 4 | from typing import List
from collections import defaultdict, deque
class AlienDictionary:
def alienOrder(self, words: List[str]) -> str:
# initialize data structure
# store character mapping from one c -> its children
adj_list = defaultdict(set)
in_degree = {c: 0 for word in words... |
38b0fc9660b1ad6658707b91834a8ad37acee695 | xis24/CC150 | /Python/BinarySearchReview.py | 1,507 | 4.03125 | 4 | import bisect
class BinarySearchReview:
# find the left most insertion place
def bisect_left(self, arr, target):
left = 0
right = len(arr)
while left < right:
mid = (left + right) // 2
if arr[mid] < target:
left = mid + 1
else:
... |
41f5949310aff27ca144d9b24b7a628c648cd63d | xis24/CC150 | /Python/DesignFileSystem.py | 2,105 | 3.921875 | 4 | import collections
from typing import Collection, DefaultDict
class TrieNode(object):
def __init__(self, name) -> None:
self.children = collections.defaultdict(TrieNode)
self.name = name
self.value = -1
class DesignFileSystem:
# simple solution
# Time complexity: O(M) where M is... |
01e5026fa24a646fd0099e908e420f19f1cbca0c | xis24/CC150 | /Python/fb/MinRemoveToMakeValidParentheses.py | 2,391 | 3.734375 | 4 | class MinRemoveToMakeValidParentheses:
'''
Given a string s of (, ) and lowercase english characters.
Remove min number of parentheses to make string valid. And Return that string
'''
# 1. We use stack to save the index of (, whenver we see a ), we check
# a. if stack is empty, this is inval... |
3234c2c53012af3d4defc8901a3155fdc99bcd7b | dfighter1312/ml_pipeline_weather_forecast | /core/data/window.py | 3,967 | 3.5625 | 4 | import tensorflow as tf
import numpy as np
class WindowGenerator():
"""
Create a window of consecutive samples of data.
Use to make a set of predictions which can benefit training.
Attributes:
-----------
input_width (int):
Number of consecutive history data.
label_wid... |
ad3213887e7faf6f7fe42bf6af4e817b475fb0fd | hieuptch2012001/Python_codeforces | /800/11_05_2021/236A.py | 190 | 3.515625 | 4 | def main():
a = input()
set_a = set(a)
if len(set_a) % 2 == 0:
print('CHAT WITH HER!')
else:
print('IGNORE HIM!')
if __name__ == "__main__":
main()
|
96e6ee1c955d96ad7c6b08208d55325ba9422629 | hieuptch2012001/Python_codeforces | /800/17_05_2021/344A.py | 220 | 3.5625 | 4 | def main():
n = int(input())
a = "00"
b = 0
for i in range(n):
c = input()
if a != c:
b = b + 1
a = c
print(b)
if __name__ == '__main__':
main() |
2d8c9ba19b177f95ecf6e65da4c5a5c353390d42 | travisthurston/OOP_example | /Card.py | 549 | 4.125 | 4 | #Card class is a blueprint of the card object
#This is the parent or base class for Minion
class Card:
#initializer to create the attributes of every class object
def __init__(self, cost, name):
self.cost = cost
self.name = name
#attributes - argument - parameter - describes the object
... |
4a2186d1443b1dcba7bd4a02c93afe9cb55e4855 | Ustabil/Python-part-one | /mini_projects/guess_the_number/guess_the_number.py | 2,497 | 4.28125 | 4 | # template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
#Codeskulptor URL: http://www.codeskulptor.org/#user40_06oB2cbaGvb17j2.py
import simplegui
import random
current_game = 0
# helper function to start and restart t... |
a7ffc4213e3d452bedc77176e1209332d976862b | RishabhShekhar/DelhiGov_Python | /Day_8/Structure_FlappyBird.py | 1,854 | 3.625 | 4 | import pygame, random
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("FLAPPY BIRDS")
x = 200
y = 300
jump = False
speed = 1
def draw_circle(x, y):
pygame.draw.circle(screen, (255, 0, 0), (x, y), 30)
pipe1 = [400, 0, 50, random.randint(50, 250)]... |
f65d470b3985f8e096d235f0f56ff52d26961b71 | grebwerd/python | /practice/practice_problems/merge.py | 703 | 3.8125 | 4 | class Solution:
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
read_pointer1 = m-1
read_pointer2 = n-1
... |
5a5590671f8c21cb76c07d08aba345f3d1bc72d9 | grebwerd/python | /practice/practice_problems/flipAndInvertImage.py | 393 | 3.5 | 4 | class Solution:
def flipAndInvertImage(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
for l in A:
l.reverse()
for index, value in enumerate(l):
if value is 0:
l[index] = 1
... |
4523e4efe62db4005d9e09b9fa8e5f20b548ef81 | grebwerd/python | /practice/practice_problems/shortestPath.py | 1,021 | 4.15625 | 4 | def bfs_paths(graph, start, goal):
queue = [(start, [start])] #queue is a list made up of a tuple first tuple is a start and the second tuple is a list
while queue:
(vertex, path) = queue.pop(0)
for next in graph[vertex] - set(path): #for each next adjacency node not in the set already
... |
a0d1853760023341fe0923065cac084c1efdc563 | grebwerd/python | /practice/practice_problems/breadthFirstSearchIterative.py | 541 | 4.03125 | 4 | def bfs_iterative(graph, start):
queue, path = [start], []
while queue:
vertex = queue.pop(0)
if vertex in path:
continue
path.append(vertex)
for neighbor in graph[vertex]:
queue.append(neighbor)
print("The path is ", queue)
return path
... |
86392f375b4895f7df885e88d608e2dc9a1823ff | hmazidi/random_chess | /RandomChess.py | 2,812 | 4 | 4 | class RandomChess:
"""
RandomChess is a class for creating random first rank according to a certain random mode which
specifies the rules with which the randomly shuffled peices should be situated
"""
import random
def __init__(self):
# firstRank=['rookKingSide','knightKingSide... |
eb1d685a640e9babe6a329dbbb8239d05697d9a9 | abaker2010/python_design_patterns | /state/state.py | 1,466 | 3.625 | 4 | """
State
- A pattern in which the object's behavior is determined by its state. An
object transitions from one state to another (something needs to trigger
a transition).
- A formalized construct which manages state and transitions is called a state
machine.
Motivation
- Consider an ordinary telephone
- What you... |
befb06130ebf46def192f3a33c799e7139303290 | abaker2010/python_design_patterns | /decorator/decorator.py | 861 | 4.125 | 4 | """
Decorator
- Facilitates the addition of behaviors to individual objects without
inheriting from them
Motivation
- Want to augment an object with additional functionality
- Do no want to rewrite or alter existing code (OCP)
- Want to keep new functionality separate (SRP)
- Need to be able to interact with existin... |
abaa8b12db17d40c841cedff21f3ae751e861189 | infinitewarp/infinitewarp-python-utils | /infinitewarp_utils/timing.py | 1,821 | 3.953125 | 4 | """Time related helpers."""
import functools
from timeit import default_timer
def timed(func):
"""Decorate function to print elapsed time upon completion."""
@functools.wraps(func)
def wrap(*args, **kwargs):
t1 = default_timer()
result = func(*args, **kwargs)
t2 = default_timer()
... |
ea4158d6ecf8b0e620430e378927cd60b6622823 | JingLin07/louplus-python | /03-income-tax-calculator-use-config-file/calculator.py | 7,049 | 3.625 | 4 | """ 计算社保和个人所得税
步骤:解析参数 -> 读取社保配置文件 -> 读取员工数据 -> 计算 -> 输出
每一个步骤都实现为相应的类,通过类实例完成相应的工作。
执行方式:
python3 calculator.py -c test.cfg -d user.csv -o gongzi.csv
"""
import sys
class ArgError(Exception):
pass
class Args:
"""命令行参数解析类
"""
def __init__(self, args):
"""
Args:
... |
3c55edc7c0e6be0434463be8247d2c1ab25e5dcf | sjain93/python_fundamentals2 | /exercise3.py | 140 | 3.6875 | 4 | def is_even(arg):
if arg % 2 == 0:
print('True')
else:
print('False')
is_even(2)
is_even(4)
is_even(6)
is_even(5)
|
4c51da8fc86c6f406ffeac2c2ded01f5c5e3a666 | ravikiranjois1/personal-projects | /Language_Classifier/trainer.py | 28,336 | 3.6875 | 4 | import csv
import sys
import pandas as pd
from csv import reader
import numpy as np
import math
import pickle
from Dtree import DTree
from Leaf import Leaf
eps = np.finfo(float).eps
_author = 'RJ'
'''
This is a code that classifies given 15 word sentences as English or Dutch.
The code uses Decision Tree and Ada Boo... |
a938bb7abe79578a12ecce8b15ac95750bb38557 | kangshuaibo/My-Python-Learn | /密码学/cipher.py | 4,482 | 3.515625 | 4 | #coding=utf-8
import sys
ciphertexts=[
"315c4eeaa8b5f8aaf9174145bf43e1784b8fa00dc71d885a804e5ee9fa40b16349c146fb778cdf2d3aff021dfff5b403b510d0d0455468aeb98622b137dae857553ccd8883a7bc37520e06e515d22c954eba5025b8cc57ee59418ce7dc6bc41556bdb36bbca3e8774301fbcaa3b83b220809560987815f65286764703de0f3d524400a19b159610b11ef3e"... |
aa6ccf9028ea74474cfb6476b1e89b1556d58f98 | zainabasim/Python_codes | /int(input).py | 303 | 3.859375 | 4 | z=int(input("write the first value...."))
a =int(input("write the second value...."))
sum =z+a
minus =z-a
multiply =z*a
divide =z/a
remainder=z%a
print("addition",sum)
print("subtraction",minus)
print("multiplication",multiply)
print("division",divide)
print("remainder",remainder
|
404bdc02637b6578c2b5536ba9f7afa8a5239a94 | ben174/tictactoe | /board.py | 7,807 | 4.09375 | 4 | class Board(object):
""" Represents a stateless tic-tac-toe board. """
def __init__(self, grid=None):
if grid:
self.grid = grid
else:
self.grid = [[0] * 3 for _ in xrange(3)]
def move(self):
"""
Attempts to make a move by iterating through a list of ... |
0499609b9d65fb529673c5bf80a286f6f9bf511c | tpnguye5/CryptoUSF-ComAnalysis- | /Cryptanalysis.py | 7,005 | 4 | 4 | #---------Crytanalysis----------
# Goal: Write a cryptoanalytic toolkit in Python to analyze the statistical properties of files.
# Instructions:
# From the command-line, take in some text file, like a book.
# Parse through it and create a dictionary that will keep track of all the "keys" that appear.
# Sort it
... |
64dfb5aee27d04a34eff8a1982c778854024864a | AlexanderOnbysh/algorithmic-toolbox | /course1/week3/largest_number.py | 297 | 3.9375 | 4 | # Uses python2
import sys
def compare(a, b):
return 1 if a + b > b + a else -1
def largest_number(a):
return ''.join(sorted(a, cmp=compare, reverse=True))
if __name__ == '__main__':
input = sys.stdin.read()
data = input.split()
a = data[1:]
print(largest_number(a))
|
9de95ac202398d80119a215aa880dac33e86e9f1 | TheDeathlyCow/tns-winter | /data/tns-winter/distance_calculator.py | 468 | 3.828125 | 4 | import math
class Point:
def __init__(self, x, z, h=0):
self.x = x
self.z = z
self.h = h
def __sub__(self, other):
return math.sqrt( (self.x - other.x) ** 2 + (self.z - other.z) ** 2 + (self.h - other.h) ** 2 )
if __name__ == '__main__':
A = Point(-934, -1398)
... |
db5ca7c2ceee206ca8e56939ad0ce51c627cdb9f | fedral/leetcode2019 | /117_connect.py | 1,652 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 24 11:21:28 2019
@author: fed
"""
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, left, right, next):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution(object):
def conn... |
f6ffa6f021e11700f983eeb20733b275bf044ad5 | fedral/leetcode2019 | /236_lowestCommonAncestor.py | 815 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 23 14:12:52 2019
@author: fed
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p... |
55db5d3c41d588b12285979128896d74d4858ed5 | fedral/leetcode2019 | /143_reorderList.py | 790 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 23 13:51:10 2019
@author: fed
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reorderList(self, head):
"""
:type head: ListN... |
ecdadff3948cc5ae5ae47147a03d667df0d7eb42 | fedral/leetcode2019 | /543_diameterOfBinaryTree.py | 738 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jul 6 21:39:51 2019
@author: fed
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def diameterOfBinaryTree(self, root):
... |
b4e08e5ff6a66cde279cfdd9f163843ad0592211 | fedral/leetcode2019 | /2_addTwoNumbers.py | 1,409 | 3.796875 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
l3=Li... |
61d49d6f94bfcfd78eb70f7782449972e018fd1f | fedral/leetcode2019 | /80_removeDuplicates.py | 528 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 21 22:52:04 2019
@author: fed
"""
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
l=0
while(l<len(nums)-2):
r=l+2
if nums[r]==nums[l]:
... |
037f8b17897b06e655a3b598ac7b02b477dbb7c3 | Fahmiady11/tugasStrukturData | /polindromCheck.py | 653 | 3.546875 | 4 | def createDeque():
d = []
return d
def addFront(d, data):
d.insert(0, data)
return d
def addRear(d, data):
d.append(data)
return d
def removeRear(d):
data = d.pop()
return data
def removeFront(d):
data = d.pop(0)
return data
def isEmpty(d):
return (d==[])
def size(d):
... |
98b0831cc43df495cd8cf0b108f4e37cd332e596 | itsmohitj/Leetcode-Solutions | /selfDividingNumbers.py | 955 | 3.984375 | 4 | """
A self-dividing number is a number that is divisible by every digit it contains.
For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.
Also, a self-dividing number is not allowed to contain the digit zero.
Given a lower and upper number bound, output a list of every pos... |
3e82d65fef6c7c661efdee097e12051e8acc8e43 | itsmohitj/Leetcode-Solutions | /decompressRLElist.py | 724 | 3.796875 | 4 | #We are given a list nums of integers representing a list compressed with run-length encoding.
#Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0). For each such pair, there are freq elements with value val concatenated in a sublist.
#Concatenate all the sublists from left t... |
fd062da97484ea2aa9fdf8b47e77c427051185cd | itsmohitj/Leetcode-Solutions | /canMakeAP.py | 748 | 4.0625 | 4 | """
Given an array of numbers arr. A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same.
Return true if the array can be rearranged to form an arithmetic progression, otherwise, return false.
Input: arr = [3,5,1]
Output: true
Explanation: We can... |
d4143f772b5a281e23e07457dde3b1e9f9860219 | itsmohitj/Leetcode-Solutions | /finalPrices.py | 1,884 | 3.734375 | 4 | """
Given the array prices where prices[i] is the price of the ith item in a shop. There is a special discount for items in the shop, if you buy the ith item, then you will receive a discount equivalent to prices[j] where j is the minimum index such that j > i and prices[j] <= prices[i], otherwise, you will not receive... |
9a141198af757ca16e1ecc39d262dbb4003640ed | itsmohitj/Leetcode-Solutions | /singleNumber3.py | 645 | 3.953125 | 4 | """
Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order.
Input: nums = [1,2,1,3,2,5]
Output: [3,5]
Explanation: [5, 3] is also a valid answer.
"""
class Soluti... |
1a6039fb4a3fd45ff573f376e846f9c277a03598 | itsmohitj/Leetcode-Solutions | /averageSalary.py | 588 | 3.90625 | 4 | """
Given an array of unique integers salary where salary[i] is the salary of the employee i.
Return the average salary of employees excluding the minimum and maximum salary.
Input: salary = [4000,3000,1000,2000]
Output: 2500.00000
Explanation: Minimum salary and maximum salary are 1000 and 4000 respectively.
Average... |
0d5ed7b8f439fcc02de01889aa089193ceec62e5 | kunlay/Training | /Score.py | 886 | 3.953125 | 4 | # x = 2
# y = 3
# print(x+y)
male = 2
female = 3
single = 2
married = 3
age_greater_18 = 3
age_less_18 = 1
my_score = male + female + single + married + age_greater_18 + age_less_18
# print(my_score)
client_name = input("enter name? \n")
client_bod = int(input("enter age? \n"))
client_location = input("enter locati... |
1d117abeac955798d93812a7ce470e6aebce2e16 | adiyosef/PycharmProjects2 | /devexp/Project1/Live.py | 1,283 | 4.03125 | 4 |
import Utils
import MemoryGame
import GuessGame
# an intro message
def welcome(name):
return "Hello " + name +" and welcome to the World of Games (WOG).\nHere you can find many cool games to play.\n"
# Choosing a game to load and difficulty
def load_game():
game_number = input("Please choose a game to pl... |
415d317a775790d68ef8082786a042f4c0c7fb21 | adiyosef/PycharmProjects2 | /devexp/homework1_extra.py | 1,414 | 4.09375 | 4 | ###### class 1 extra #####
# def hello_my_name_is():
# print("hello")
# print("adi")
#
#
# hello_my_name_is()
#
#
# def sum_of_two_numbers():
# x = int(input("please enter first number:"))
# y = int(input("please enter second number:"))
# sum = x + y
# print("the sum of the to numbers is " + str... |
4e4d92c6e5118dcb84bedbec6f760d6d0b6ec730 | delacroix11134/htmlTest | /Python/01_變數與型別.py | 1,513 | 4.09375 | 4 | ## Python的變數與型別
# 定義變數
msg = 'Hello'
print(msg)
# python不會自動轉換型別 需用函數把數字轉換成字串
str = '99999'
print(int(str))
## 串列
# 定義串列(陣列)
list1 = [1,2,3,4,5,6]
print( len(list1) ) # 6
print( list1[0] ) # 1
# 用.append()新增物件到list
list1.append(7)
print(list1) # [1, 2, 3, 4, 5, 6, 7]
# 用.remove()移除物件
list... |
77dfbf09dee2096cb7dc153e96808b50c8695b42 | tmlishuai2/Algorithms | /leetcode/0032-longest-valid-parentheses/py/stack-scan-twice-without-extra-space.py | 986 | 3.71875 | 4 | def longestValidParentheses(s):
"""
:type s: str
:rtype: int
"""
left = 0
right = 0
length = len(s)
longest = 0
# from left to right
current_start = 0
for i in range(length):
if s[i] == '(':
left = left + 1
else:
right = right + 1
... |
df7641c8d27b1b6742fa742d6bdc9f97e03f17af | tmlishuai2/Algorithms | /leetcode/0009-palindrome-number/py/slow-solution.py | 415 | 3.640625 | 4 | class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
if x % 10 == 0 and x != 0:
return False
reverse = 0
while reverse < x:
reverse = reverse *... |
57f23128a02d1aa40f82efc26b8c8114ae280ffc | brandontarney/all_machine_learning | /algorithms/neural_network_ff_bp.py | 15,396 | 3.671875 | 4 | #!/bin/python
# #@author Brandon Tarney
#@date 11/10/2018
#@description Feedforward Neural Networks w/ Backpropogation
from base_model3 import BaseModel
import numpy as np
import pandas as pd
#=============================
# NeuralNetworkFFBP
#
# - Class to encapsulate a Feedforward Neural Network tr... |
c397587243592290c06374ead89a667b1bee979b | brandontarney/all_machine_learning | /algorithms/knn_pandas.py | 1,938 | 3.875 | 4 | #!/usr/local/bin/python3
#Brandon Tarney
#SRC - https://www.dataquest.io/blog/k-nearest-neighbors-in-python/
def euclidean_distance(row):
"""
A simple euclidean distance function
"""
inner_value = 0
for k in distance_columns:
inner_value += (row[k] - selected_player[k]) ** 2
return math... |
eafcc51707c205f14458b5de97f13ad2a3e7b736 | eyadsibai/hydrat | /src/hydrat/task/task.py | 3,093 | 3.640625 | 4 | """
A Task is a container for a pairing of training data and test data.
It is useful in the context of techniques such as cross validation,
where the same set of training and test data must be reused in
different experiments.
Basic tasks are just little boxes that store training and test data.
Slightly more sophistic... |
31b264ac2feea331770cca756ebcbc1d5fcb010d | eyadsibai/hydrat | /src/hydrat/common/timer.py | 770 | 4.03125 | 4 | from timeit import default_timer
class Timer(object):
"""
Simple timing context manager. Sets an attribute "duration"
which records the last interval timed.
"""
def __init__(self):
self.timer = default_timer
self.start = None
self.end = None
def __enter__(self):
self.start = self.timer()
... |
3cde469a56f5b776510a33534af61edddc52354e | kingkaki/Python-Design-Patterns | /Singleton/servers.py | 832 | 3.765625 | 4 | # -*- coding: utf-8 -*-
# @Author: King kaki
# @Date: 2018-07-20 17:35:11
# @Last Modified by: King kaki
# @Last Modified time: 2018-07-20 17:46:56
'''
两个实例Server.display()
对同一类进行的增删操作
server1
server2
server3
server1
server2
server3
server4
server1
server2
'''
class Server:
_instance = None
servers = ['server... |
69ceec17993f350329a7f6214657fc9aae84ef1a | Zolton/Sprint-Challenge--Algorithms | /recursive_count_th/count_th.py | 806 | 4.21875 | 4 | '''
Your function should take in a single parameter (a string `word`)
Your function should return a count of how many occurences of
***"th"*** occur within `word`. Case matters.
Your function must utilize recursion. It cannot contain any loops.
'''
test = "THtHThth"
test2 = "abcthefthghith"
test3 = "abcthxyz"
count = ... |
9bb550f126278914bffca50fa491c36cf20d8f48 | aman-agarwal/NetworkSimulator | /input.py | 812 | 3.734375 | 4 | import json
def input(fname):
"""Reads input json file and returns the network specification as a dictionary.
The dictionary format is:
{
"Hosts" : Number of hosts,
"Routers" : Number of routers,
"Links" : [ [Link Rate (Mbps), Link Delay (ms), Link Buffer (KB),
... |
46f94b0dfe69c2d261f690db03d562b80bd72304 | Zchhh73/Python_Basic | /chap11_module/module_random.py | 359 | 3.953125 | 4 | import random
# random模块
# (0,1)的随机数
print('(0,1)的随机数')
for i in range(0, 10):
x = random.random()
print(x)
print('(0,5)的随机数')
for i in range(0, 10):
x = random.randrange(5)
print(x, end=" ")
print('\n')
print('(5,10)的随机数')
for i in range(0, 10):
x = random.randrange(5, 10)
print(x, end=" ")
|
4ddfed41d2ee5061ff77fae870bd826c63632b4a | Zchhh73/Python_Basic | /chap6_struct/struct_while.py | 103 | 3.5625 | 4 | i = 0
while i * i < 100000:
i += 1
print("i = {0}".format(i))
print('i * i = {0}'.format(i * i))
|
7c2549bcb4f95d76184c334a4968773a0ab7e500 | Zchhh73/Python_Basic | /chap6_struct/struct_break_continue.py | 208 | 4.15625 | 4 | for item in range(10):
if item == 3:
break
print('Count is : {0}'.format(item))
print('\n')
for item in range(10):
if item == 3:
continue
print('Count is : {0}'.format(item)) |
2699dc3c6149ad0ccff96dab80c436a28027b28b | Zchhh73/Python_Basic | /chap16_tcp/net_url.py | 999 | 3.6875 | 4 | # URL(Uniform Resource Locator)统一资源定位器
import urllib.request
import urllib.parse
'''
打开网站
with urllib.request.urlopen("http://www.baidu.com") as response:
读取数据,字节序列数据
data = response.read()
转化为字符串
html = data.decode()
print(html)
'''
# 发送GET请求
url = 'http://www.51work6.com/service/mynotes/WebServ... |
54778795535841159edff3e2f4e3c0abf033d721 | Zchhh73/Python_Basic | /chap10_error/error_tryexcept.py | 602 | 3.796875 | 4 | #语句嵌套
import datetime as dt
def read_date_from_file(filename):
try:
file = open(filename)
try:
in_date = file.read().strip()
date = dt.datetime.strptime(in_date,'%Y-%m-%d')
return date
except ValueError as e:
print('处理ValueError异常')
... |
a189a61c35b260a52be747c545d3d32aaf71b417 | zijiezhu/BigData-Labs | /lab2/reduce.py | 1,892 | 3.984375 | 4 | #!/usr/bin/env python
#Reduce function for computing matrix multiply A*B
#Input arguments:
#variable n should be set to the inner dimension of the matrix product (i.e., the number of columns of A/rows of B)
import sys
import string
#import numpy
#number of columns of A/rows of B
n = int(sys.argv[1])
#Create data s... |
42c68546b37245ee0e7483270483e399d3064096 | Lousm/Python | /01_py基础/第2周/day05/test01.py | 256 | 3.625 | 4 | class Student():
@property
def age (self):
return self.__age
@age.setter
def age(self, value):
if not isinstance(value,int):
value=0
self.__age=value
stu=Student()
stu.age='asda'
print('年龄',stu.age) |
27cd51426e6b63ab9c30deee18fe157a989ec197 | Lousm/Python | /练习/5.25/test.py | 1,094 | 3.640625 | 4 | class People():
tax=0
def __init__ (self ,name,age,work,salary,energy=100):
if 0<=energy<=100:
self.__energy=energy
else:
raise Exception('精力值应在0到100之间')
self.name=name
self.age=age
self.work=work
self.salary=salary
def ea... |
bfc625a289a64da4b214b2787552f67b6670f1dc | Lousm/Python | /练习/7.23注册,登录/1.py | 377 | 3.8125 | 4 | def bim(height,weight):
x=weight/(height**2)
if x<18.5:
print('过轻')
elif x<23.9:
print('正常')
elif x<27:
print('过重')
elif x<32:
print('肥胖')
else:
print('非常肥胖')
while True:
height=float(input('请输入身高(m):'))
weight=float(input('请输入体重(kg):'))
bim(h... |
b341ed8e913632b0dcf6c5f780b8e9d08b44f80e | Lousm/Python | /04_爬虫/练习/面试/01列表分组.py | 323 | 3.703125 | 4 | num = list(range(1, 101))
c = [num[i:i + 3] for i in range(0, len(num), 3)]
print(c)
a = [i for i in range(100) if i % 2 == 0]
print(a)
b = {key: value for key, value in enumerate(reversed(range(100)))}
print(b)
d = {i for i in range(100)}
print(d)
e = [range(10), range(10, 20)]
f = [j for i in e for j in i]
print(... |
9ad465abc7b49c53b21b65897650da85f39303f0 | Lousm/Python | /01_py基础/第1周/day05/test06.py | 2,383 | 4.40625 | 4 | # 学生管理
a = {'001': {"name": '小张', 'age': 21, "address": "北京"},
'002': {"name": '小明', 'age': 22, "address": "山东"},
'003': {"name": '小王', 'age': 23, "address": "河北"},
'004': {"name": '小李', 'age': 24, "address": "北京"}}
def add():
snum = input("请输入你要添加的学号:")
while True:
if snum in a:
... |
b41a813e42492f15c4836a718bf29a08b16436e0 | Lousm/Python | /练习/7.23注册,登录/login.py | 931 | 3.5 | 4 | class Login(object):
def __init__(self, path):
self.path = path
self.keys=[]
self.values=[]
with open(self.path, 'r', encoding='utf-8') as fil:
self.data = eval(fil.readline())
self.keys=self.data.keys()
self.values=self.data.values()
def log... |
a036e09953d645d1f91bf956f41d08c399559036 | Lousm/Python | /01_py基础/第1周/day03/test07.py | 709 | 3.984375 | 4 | a="abcdefgh"
print(a[len(a)-1])#字符串最后一位
print(a[-1])
print(a[0:3])
print(a[2:4])
print(a[:-1])
print(a[2:-1:4])
b='123456789'
x=b.find('123',2,8)
print(x)
c='我叫小明,我来自东北,我21'
print(c)
d=c.replace("小明","老王")
e=c.replace("我","ni",3)
print(d)
print(e)
f="bei jing huan ying ni"
g=f.split(' ')
print(g)
h="2018-07-11"
j... |
b3fa150becb603912eb1ce0fac4d4d9e3461434a | Lousm/Python | /算法/01_二分查找.py | 717 | 3.796875 | 4 | def binarySearch(list, num):
low = 0 # 要查找的范围
high = len(list)-1
while low <= high: # 只要范围没有缩小到只剩一个函数
mid = (low+high)//2 # 找到范围中间的数的下标
a = list[mid] # 每次猜的数(猜中间值)
if a == num: # 找到了元素
print("找到了,在列表的第%d位" % (mid+1))
return mid
elif num < a: # 猜的... |
a6a240231ff89b63b700a52aec5799ba572b5fdc | Lousm/Python | /练习/5.18/test01.py | 205 | 3.65625 | 4 | set1={1,2,3,4,5,6}
set2={4,5,6,7,8,9}
print('交集:',set1.intersection(set2))
print('并集:',set1.union(set2))
print('差集:',set1.difference(set2))
print('对称集:',set1.symmetric_difference(set2)) |
3579398ad89ccb01dd0cfa6ca00aa85b40a83903 | newhierarchy/Python-Scripts | /MITx - 6.00.1x Solutions/Week 2 PSet 1/W2 PS1 - 1 - Count Vowels.py | 148 | 3.6875 | 4 | s = 'aeious'
s= s.lower()
count = 0
for a in range(len(s)):
if s[a] in 'aeiou':
count += 1
print("Number of vowels: " + str(count))
|
e6242210d953d3d5510850db8d418e3310821b08 | newhierarchy/Python-Scripts | /MITx - 6.00.1x Solutions/Week 2 PSet 2/W2 PS2 - 1 - Calculating the Minimum.py | 662 | 3.875 | 4 | balance = 4842
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
bal = balance
sumPayments = 0
for i in range(1,13):
# Minimum payment paid
minPayment = monthlyPaymentRate * bal
# Sum the payments
sumPayments += minPayment
# Your unpaid balance
uBal = bal - minPayment
# The new balanc... |
f6e6511d1fd4665f97d54c171b0fd05c1d2c5a52 | jakoblumpkin/Phone-Numbers-Kata | /generate_data.py | 1,003 | 3.6875 | 4 | """
Use this script to generate a file of names and phone numbers suitable for load testing the Phone Numbers code kata.
"""
import csv
import os
from random import choice, sample, randrange
phone_number_digits = ["", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
phone_number_partitions = ["", "-", " "]
def rand... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.