blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
3b1843d0b9785aba7a040b5e472a3c50f33fc6d4 | NEO-Research-Group/EconomicData | /step3.py | 10,944 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Monday Aug 03 10:19:30 2020
"""
# Used to connect and query the database
import sqlite3
# libs for array use
import numpy as np
# lib containing the predefined K-MEANS in python
from sklearn.cluster import KMeans
# lib used to generate the possible permutation of N dig... |
59705b43fed5c733b4751707cb723faa04ad9a74 | ah858/python-flood-system-2017 | /floodsystem/geo_old.py | 824 | 3.734375 | 4 | """This module contains a collection of functions related to
geographical data.
"""
from .utils import sorted_by_key
from haversine import haversine
"""
This is Akil's code - Task 1C - RECOPIED IN TASK C FILE
"""
def stations_within_radius(stations, centre, r):
"""
This function takes a specified coordinate... |
907070679e6715ef9eefdfa48828de21e5c9353b | ah858/python-flood-system-2017 | /floodsystem/station.py | 3,155 | 3.765625 | 4 | """This module provides a model for a monitoring station, and tools
for manipulating/modifying station data
"""
class MonitoringStation:
"""This class represents a river level monitoring station"""
def __init__(self, station_id, measure_id, label, coord, typical_range,
river, town):
... |
a433ef6378c84e7957a53d9843a7f50d84b888b1 | sridharkumarkannam/brownlee | /ML/predictive_modeling_project_template.py | 1,727 | 3.5 | 4 | # Ch 18
# Predictive Modeling Project Template
# 1. Define Problem
# 2. Summarize Data
# 3. Prepare Data
# 4. Evaluate Algorithms
# 5. Improve Algorithms
# 6. Present Results
# Python Project Template
# 1. Prepare Problem
# a) Load libraries
# b) Load dataset (reduce dataset if necessary, model should build in ~30 ... |
c74a65e1a921748c9c0876d5d5959a13e327a62a | MistralHaze/pythonPracticePrograms | /VeryAwfulPasswordProgram.py | 946 | 4.03125 | 4 | #! python3
#very simple program to test and remember python
import sys
import pyperclip
storedPasswords = { 'awfulWebsite' : "whyDoIEvenCare",
'portfolio' : "trustInYourselfYouDumbyDoo",
'instagram': 'uSexyBro',
'university' : 'passwordChangeNo6'
}
if len(sy... |
53df6ccd90b5fc40f51a28b77661c8e15426c9da | njdevengine/pandas-python | /text-pandas-analysis-123.py | 1,894 | 3.65625 | 4 | #grab text file
#remove punctuation, special characters etc.
#split by spaces create an array of words
#create 2 word phrases create an array of 2 word phrases
#create 3 word phrases create an array of 3 word phrases
#create a dataframe for each with headers as word/phrase/phrase and count
#group by count for each
#sor... |
044c1fcd7f2bec2a0b74d90e2dcf4583a2ed876c | mayaugusto7/learn-python | /basic/functions_anonymous.py | 391 | 4.21875 | 4 | # funcoes anonimas no python não tem o def
# Para criar funções anonimas devemos usar a expressão lambda
sum = lambda arg1, arg2: arg1 + arg2
print("Value of total: ", sum(10, 20))
print("Value of total: ", sum(20, 20))
def sum(arg1, arg2):
total = arg1 + arg2
print ("Inside the function : ", total)
return t... |
6bc2dbc19391e9ef4e37a9ce96a4f5a7cdb93654 | skfreego/Python-Data-Types | /list.py | 1,755 | 4.53125 | 5 | """
Task:-Consider a list (list = []). You can perform the following commands:
. insert i e: Insert integer e at position i
. print: Print the list.
. remove e: Delete the first occurrence of integer e
. append e: Insert integer e at the end of the list.
. sort: Sort the list.
. pop: Pop the last element from th... |
39455266be68ea5fcbeb9de4fff222315e160d2e | Philipnah/Hangman-Python | /main.py | 822 | 3.75 | 4 | from random import randint
def getWord():
nWord = randint(0, 279486)
with open("Collins _Scrabble_Words_(2019).txt", "r") as f:
allWords = f.readlines()
global word
word = allWords[nWord]
word = word[:-1]
i = 0
underscore = ""
while i < len(word)... |
9d0ffc578b22a264c125596cf2fd856494bfad92 | Bowser1704/CCNU-OS-2020-Fall | /page-replacement/page-replacement.py | 1,483 | 3.6875 | 4 | from collections import deque
PHYSICAL_PAGE_NUM = 3
requests = input().split()
requests = [int(x) for x in requests]
def fifo(requests):
print("\nFirst In First Out")
pagefault_times = 0
pp = deque(list(), maxlen=PHYSICAL_PAGE_NUM)
for request in requests:
if request not in pp:
if... |
912b7bced8898d94396c0c2919602bdffd9d696d | TLohan/airline-fuel-manager | /app/currency.py | 493 | 3.90625 | 4 | """
currencyClass.py
"""
class Currency:
""" Models a Currency
Args:
code: the three character code used to represent the currency
name: the currency's name
buys: value in € that one unit of the currency buys
sells: value of this currency that €1 buys
... |
5d3dc391e5acdaeb8ce83f60f35c5ffe12d2366b | TLohan/airline-fuel-manager | /app/destinationFrame.py | 1,283 | 3.734375 | 4 | from tkinter import *
class DestFrame(Frame):
""" Frame which displays a Destination Airport """
def __init__(self, airport, parent=None):
Frame.__init__(self, parent)
self.airport = airport
self.__make_widgets()
self.isPacked = False
def __make_widgets(self):
... |
b0e41d008ea4081f7604077c13351a2243e7a22a | Skg-754/MyRenamingApp | /Sources/utils.py | 2,866 | 3.609375 | 4 |
# -*- coding: utf-8 -*-
import re
# utilitaires maison pour l'incrémentation des amorces et la vérification de la validité des noms de fichier
def increment(amorce, nb) :
"""
permet de réaliser l'incrémentation à partir du amorce
amorce numérique
amorce alphabétique
retourne une l... |
d13083fb845dd32e401cdbeceb0139aa79882ba0 | brunomleite/Carnaval_Casseb | /trab3.py | 1,170 | 3.609375 | 4 | from tkinter import *
import random
counter = 0
contador = 0
segundinhos = 2000
def adicionar():
global contador
global segundinhos
contador += 1
segundinhos -= 30
print("Contador: " + str(contador) + "\nSegundos: " + str(segundinhos))
x1 = random.randint(0, 492)
y1 = random.randint(0, 570)
button.place(x =... |
ec5738f3915590b61a8eb2daa039e411e1266cd6 | rtmoffat/pylearn | /fac.py | 106 | 3.53125 | 4 | def fac(n):
if (n<=1):
return 1
else:
return (n * fac(n-1))
x=input("Enter number:")
print(fac(x))
|
169ab388fc116ac97c9323894c9afcba8d3cd8d4 | Reo122/21724612 | /assignment1/sonar.py | 4,777 | 3.984375 | 4 | ################################################################################
# #
# INTRODUCTION #
# ... |
b006b532aec4f4845dea4fb2ac36df1425ce3eb1 | Bashorun97/Algorithms | /Python/Strings/kmp.py | 246 | 3.53125 | 4 | def pi_array(pattern):
failure = [0]
i = 0
j = 1
while j < len(pattern):
if pattern[i] == pattern[j]:
i += 1
elif i > 0:
i = failure[i-1]
continue
j += 1
failure.append(i)
return failure
print(pi_array('abcdabc'))
|
398eb2560fcb3ac8f39b4be97b3bfe818dd47e85 | Bashorun97/Algorithms | /Python/Strings/compute_hash.py | 592 | 3.734375 | 4 | #!/usr/bin/env python3
class Hash:
def __init__(self, string, **kwargs):
self.string = string
self.p_pow = kwargs['p_pow']
self.hash_value = kwargs['hash_value']
self.m = kwargs['m']
self.p = kwargs['p']
# Compute hash with rolling function
def compute_hash(self):
for i in self.string:
... |
e704b2e3fe594e448740511643014759abb58702 | AndriiHorbatiuk/Python | /OOP/class_oop.py | 429 | 3.859375 | 4 | class ProductInShop(object):
name = 'product name'
price = 0
qnty = 1
color = 'green'
def __init__(self,one):
self.sum = one
lego = ProductInShop(17)
lego.name = 'Lego Konstruktor'
lego.price = 15
lego.qnty = 10
lego.color = 'blue'
print lego.name, lego.price, lego.sum
print lego.__class__.__name__
""... |
481fe3290c04bafa07f34fb8e5fe47deb58a9ae2 | SammieSunshine/TA-python-course | /Databases and Python Challenge/ChallengeSteps246.py | 511 | 4.03125 | 4 | #
#
# Python Ver: 3.8.5
#
# Author: Samantha Billips
#
#
# Challenge Objective: Practice of the Python range() function
#
#
# 1) Use Range() function with one parameter to display 0,1,2,3
range1 = range(4)
for i in range1:
print(i)
# test successful
# 2) Use Range() function with 3 parameters to display 3210
ra... |
5168f579ac9570551137b0c072fc4594ba9aee5f | Rohan191/ML_CS6510_Assignments | /kNN/kNearestNeighbour.py | 9,043 | 3.78125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 6 09:30:39 2017
@author: rohantondulkar
"""
"""
#==============================================================================
# Call the function runKNN() form this files to run the program as shown below
#
# import kNearestNeighbour as knn
# k... |
3d719582b6c2ff83811c8ac28793000d80cafd63 | kimxoals/Algorithm_Practice | /09/namu_0918.py | 265 | 3.609375 | 4 | a, b = map(int, input().split())
c, d = map(float, input().split())
def find_max(a, b):
if isinstance(a, int):
print(a if abs(a) > abs(b) else b)
elif isinstance(a, float):
print("{:.2f}".format(max(a, b)))
find_max(a, b)
find_max(c, d)
|
168844158368651c62e239ef63c2ef5926cf2aa3 | kimxoals/Algorithm_Practice | /sorting.py | 699 | 3.671875 | 4 | import pprint
from itertools import permutations
def sort(a):
n = len(a)
cnt = 0
for j in range(1, n):
x = a[j]
i = j - 1
while (i >= 0) and (a[i] > x):
cnt += 1
a[i + 1] = a[i]
i -= 1
# print(cnt, a)
a[i + 1] = x
return c... |
7d32610b6e5c6247fa3b1ce093f1b6ee05fd102e | kimxoals/Algorithm_Practice | /09/namu_0904.py | 125 | 3.640625 | 4 | def get_max(n1, n2, n3):
print(max(n1, n2, n3))
num1, num2, num3 = map(int, input().split())
get_max(num1, num2, num3)
|
0f1dab32751260e0c0f2052abfc878a45f358b1b | kimxoals/Algorithm_Practice | /10/namu_1013.py | 141 | 3.671875 | 4 | def recur(n):
if n < 3:
return n
else:
return (recur(n - 1) * recur(n - 2)) % 100
n = int(input())
print(recur(n))
|
dc533ec69000a2e896e7e33810cfb38503a2e428 | buy/leetcode | /python/96.unique_binary_search_trees.py | 639 | 3.734375 | 4 | # Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
# For example,
# Given n = 3, there are a total of 5 unique BST's.
# 1 3 3 2 1
# \ / / / \ \
# 3 2 1 1 3 2
# / / \ \
# ... |
da1d64fe08316bf68a2363c444af0d980ddf8833 | buy/leetcode | /python/43.multiply_strings.py | 583 | 3.75 | 4 | # Given two numbers represented as strings, return multiplication of the numbers as a string.
# Note: The numbers can be arbitrarily large and are non-negative.
class Solution:
# @param {string} num1
# @param {string} num2
# @return {string}
def multiply(self, num1, num2):
result = 0
f... |
80612a7405e7f0609f457a2263715a5077eaa327 | buy/leetcode | /python/94.binary_tree_inorder_traversal.py | 1,313 | 4.21875 | 4 | # Given a binary tree, return the inorder traversal of its nodes' values.
# For example:
# Given binary tree {1,#,2,3},
# 1
# \
# 2
# /
# 3
# return [1,3,2].
# Note: Recursive solution is trivial, could you do it iteratively?
# confused what "{1,#,2,3}" means? > read more on how binary tree is ser... |
1f0f0bf595295f4c7ed95324bc6d8d784ff8b361 | buy/leetcode | /python/121.best_time_to_buy_and_sell_stock.py | 694 | 3.578125 | 4 | # Say you have an array for which the ith element is the price of a given stock on day i.
# If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
class Solution:
# @param {integer[]} prices
# @return {integ... |
e8689f10872987e7c74263e68b95788dce732f56 | buy/leetcode | /python/145.binary_tree_postorder_traversal.py | 983 | 4.125 | 4 | # Given a binary tree, return the postorder traversal of its nodes' values.
# For example:
# Given binary tree {1,#,2,3},
# 1
# \
# 2
# /
# 3
# return [3,2,1].
# Note: Recursive solution is trivial, could you do it iteratively?
# Definition for a binary tree node.
# class TreeNode:
# def __ini... |
89a098dcd396a5dc4a9dfd7ce80567ec481e2dab | buy/leetcode | /python/46.permutations.py | 875 | 3.71875 | 4 | # Given a collection of numbers, return all possible permutations.
# For example,
# [1,2,3] have the following permutations:
# [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
class Solution:
# @param {integer[]} nums
# @return {integer[][]}
# 5:56
def permute(self, nums):
if not nums... |
8a06066c1d5fef1d9290ef740f21b8ef449e695a | buy/leetcode | /python/86.partition_list.py | 1,365 | 3.859375 | 4 | # Partition List Total Accepted: 31967 Total Submissions: 116485 My Submissions Question Solution
# Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
# You should preserve the original relative order of the nodes in each of the two partitions... |
d11420d6aa770e4657e7a66087843a3c7c9d1df1 | buy/leetcode | /python/28.str_str.py | 430 | 3.84375 | 4 | # Implement strStr().
# Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
class Solution:
# @param {string} haystack
# @param {string} needle
# @return {integer}
def strStr(self, haystack, needle):
n = len(needle)
for i in range(... |
595ae525b4e162411a4b7074f62d530ca5dcc052 | buy/leetcode | /python/36.valid_sudoku.py | 1,063 | 3.921875 | 4 | # Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
# The Sudoku board could be partially filled, where empty cells are filled with the character '.'.
# A partially filled sudoku which is valid.
# Note:
# A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled ce... |
7b3267353e6bab8cbcd6951e0f364722a764a488 | AllenLiuX/Python-Basics | /basic learning/function 2.py | 365 | 3.953125 | 4 | import math
def move(x, y, step, angle):
if not isinstance(x, (int, float)):
raise TypeError('bad operand type')
nx = x + step*math.cos(angle)
ny = y + step*math.sin(angle)
return nx, ny
x = float(input('x ='))
y = float(input('y ='))
step = float(input('step ='))
angle = float(input('angle ='... |
e1e664fe4c27448292d462f4e123ff3b2026b4dc | drunkymonky/test2 | /main10.py | 589 | 3.546875 | 4 | class Fraction():
def __init__(self, d1, d2):
self.d1 = d1
self.d2 = d2
def plus(self, o):
a = self.d1
b = self.d2
c = o.d1
d = o.d2
return Fraction(a * d + b * c, b * d)
def minus(self, o):
return Fraction(self.d1 * o.d1 - self.d2 * o.d2)
... |
56eaa6efc91bd2eca3866bfb507ff5369bd31dfb | gakunkel/python-challenge | /PyBank/main.py | 2,090 | 3.640625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[3]:
# script for PyBank
import csv
import os
budget_input = os.path.join("budget_data.csv")
budget_output = os.path.join("budget_analysis.txt")
# data to keep report on/keep track of: months, net profit/loss, change in profit/loss, greatest profit increase & loss decreas... |
b3d97937d53d5f6a34838de4930b29bf39b2d728 | laurascotch/FolderOrganizer | /FolderOrg.py | 3,901 | 4.0625 | 4 | import os
import shutil
def create_folders(directories, directory_path):
"""
Create the folders in <directory_path> where the files will be moved to.
:param directories: dictionary containing the names of the sorted folders and the extensions that correspond to those folders.
:param directory_... |
4f229ecdf13d59e4a3ec05eb8a2be639cfcbc027 | vvu060/Python-Practice-Projects | /Gas Prices.py | 828 | 3.640625 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
gas = pd.read_csv('F:/Python Codes/Matplotlib/gas_prices.csv')
plt.figure(figsize=(8,5), dpi=150)
plt.title('Gas Prices in USD', fontdict={'fontweight': 'bold', 'fontsize': 20})
plt.plot(gas.Year, gas.USA, 'b.-', label='USA')
plt.plot(gas.Y... |
06dc7790c9206822c66d72f4185f16c0127e377d | AlexandrKnyaz/Python_lessons_basic | /lesson02/home_work/hw02_easy.py | 1,716 | 4.125 | 4 | # Задача-1:
# Дан список фруктов.
# Напишите программу, выводящую фрукты в виде нумерованного списка,
# выровненного по правой стороне.
# Пример:
# Дано: ["яблоко", "банан", "киви", "арбуз"]
# Вывод:
# 1. яблоко
# 2. банан
# 3. киви
# 4. арбуз
# Подсказка: воспользоваться методом .format()
fruits_list = ['Абрико... |
7fb143bcbb720c944d3ba954e97dae9f503b8283 | nayanika2304/DataStructuresPractice | /Heaps/create_heap.py | 518 | 3.5625 | 4 | '''
Heap is a special tree structure in which
each parent node is less than or equal to its child node.
Then it is called a Min Heap.
If each parent node is greater than or equal to its child node
then it is called a max heap.
It is very useful is implementing priority queues
where the queue item with higher weightage... |
90e23a616d25743e305af8a87bdebf1a3bd288c8 | nayanika2304/DataStructuresPractice | /Practise_linked_list/sum_list_forward_order.py | 1,738 | 3.984375 | 4 | class Node:
# Constructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# Function to insert a new node at the beginning
def append(self, da... |
7cda0f78322d282a3d04abf91a6033433526695c | nayanika2304/DataStructuresPractice | /Practise_array_strings/string_permutation.py | 1,987 | 3.96875 | 4 | '''
Check Permutation: Given two strings,
write a method to decide if one is a permutation of the other.
Ask - if case sensitive or considers white space
base case : if the strings are of different length
it cannot be a permutation
two methods :
A) Sorting : if two strings are sorted and then equal, they are in perm... |
8f5d33183271397e07fd1b45717bc15dc24ba80f | nayanika2304/DataStructuresPractice | /Practise_graphs_trees/random_node.py | 2,420 | 4.21875 | 4 | '''
You are implementing a binary tree class from scratch which, in addition to
insert, find, and delete, has a method getRandomNode() which returns a random node
from the tree. All nodes should be equally likely to be chosen. Design and implement an algorithm
for getRandomNode, and explain how you would implement the ... |
4774e23e3a65b54ff0e96736d0d491a965c6a1b4 | nayanika2304/DataStructuresPractice | /Practise_linked_list/remove_a_node_only pointer_ref.py | 1,885 | 4.375 | 4 | '''
Implement an algorithm to delete a node in the middle (i.e., any node but
the first and last node, not necessarily the exact middle) of a singly linked list, given only access to
that node.
iterating through it is a problem as head is unkniwn
faster approach is to copy the data of next node in current node
and de... |
1b08b4f8622e7d695b5001b97b2f9abde8486b81 | jayyok/ensiie-P | /Python/seCroiseOuPas.py | 239 | 3.734375 | 4 | #!/usr/bin/python3
x1 = int(input("x1:\t"))
y1 = int(input("y1:\t"))
x2 = int(input("x2:\t"))
y2 = int(input("y2:\t"))
det = (x1 * y2) - (x2 * y1)
if(det==0):
print('Les segments ne se croisent pas !')
else:
print('elles se croisent') |
6286f3dfaa5de1d6c43249dafcdde3ff9731f3a8 | SavinSpring/api-smart-fuzzing | /morpher/collector/range_union.py | 3,581 | 3.75 | 4 | '''
Contains the L{RangeUnion} class for maintaining a "covering" set of ranges
@author: Rob Waaser
@contact: robwaaser@gmail.com
@organization: Carnegie Mellon University
@since: October 26, 2011
'''
from collections import namedtuple
from collections import deque
class RangeUnion(object):
'''
... |
e53660ef56c49b751efe8f67ff930d86d286103c | nadyat/Programming-Stuff | /Variables Programming Worksheet.py | 547 | 3.90625 | 4 | #Task 1 : 100th Birthday
name=input("Please enter your name: ")
age=int(input("Please enter your age: "))
currYear=int(input("What is the current year?"))
hundredYear=(100-age)+currYear
print("Nice to meet you "+name+"\nIn the year "+str(hundredYear)+" you will be 100 years old.")
#Task 2 : Cylinders
pi=3.1415926
radi... |
4dc4b6838cdd6ff7838df9e2820fa825b39e8bc6 | natasharamos16/Python | /a3.py | 1,051 | 4.0625 | 4 | # Natasha Ramos-Gomez
# COP4538
# 2/2/2020
#creating main function
def main():
#prompting user input to enter range of numbers
userInput = int(input("Enter unique integers to be entered in ascending order: "))
list = []
while(userInput > 0):
#prompting user to enter numbers
... |
30e6aa7338668f601654b079c52e05283176f696 | fanyichen/assignment6 | /neb330/Interval.py | 4,006 | 3.90625 | 4 | import re
import operator
class Interval(object):
def __init__(self, string_interval):
#initialize attributes
self.string_rep = string_interval
self.lower_bound = 0
self.upper_bound = 0
self.lower_bound_inclusive = False
self.upper_bound_inclusiv... |
68aa0bc4b5d9b37725ec8b8a92d9f7c1e6c492e1 | fanyichen/assignment6 | /yd604/intervals.py | 3,510 | 3.96875 | 4 | # Define the call interval() and function mergeIntervals(int1, int2), mergeOverlapping(intervals), insert(intervals, newint)
class interval():
def __init__(self, input_interval):
self.input_interval = str(input_interval)
if self.input_interval[0] == "(":
self.lower = int(self.input_inter... |
9d6206550419e7ecdef7a1796d44997681a9ede5 | fanyichen/assignment6 | /kk3175/assignment6.py | 4,114 | 4.21875 | 4 | """Main program that prompts a user for integer intervals and creates a list containing merges of the intervals."""
from interval import Interval
from errorHandling import InvalidIntervalError
from errorHandling import MergeError
import re, sys
# Merges two intervals if they overlap. If the two intervals do not overl... |
1b7908cb6311c024e394c89e97eaa912bd08de93 | fanyichen/assignment6 | /sx444/interval.py | 4,203 | 4.0625 | 4 | import re
import operator
class interval(object):
# define a class named interval that represents the range of integers between a lower bound and upper bound.
def __init__(self,interval_string): # this is a constructor that takes a string representation of the interval.
self.interval_string = interval_s... |
df691cd40bb51d1c159c8c0ece23a8c956b16560 | fanyichen/assignment6 | /up276/as6_package/assignment6.py | 4,684 | 4.0625 | 4 | '''
Created on Oct 27, 2015
@author: Urjit Patel - up276
'''
import re
from Interval import Interval,Interval_Exception
def main_function():
'''
Body of main_function from where all necessary execution of the program starts.
Flow of the Program is as below,
main_function() <-> insert(list,new_int... |
9bfb2c0a94932c1cb265d76365eecf4f7cd86d75 | fanyichen/assignment6 | /kl1405/interval.py | 1,320 | 4 | 4 |
# coding: utf-8
# In[ ]:
class interval(object):
"""A class for generating interval"""
def __init__(self, string):
self.string = string
# Get the bound
self.bound()
# Check if valid or not
self.Check()
def bound(self):
# Split the string into two parts.
... |
c173928913363f978662919341813f5ae867bf95 | fanyichen/assignment6 | /lt911/assignment6.py | 1,816 | 4.28125 | 4 | # This program is to manage the user-input intervals. First have a list of intervals entered,
# then by taking new input interval to merge intervals.
# input of valid intervals must start with [,(, and end with ),] in order for correct output
import re
import sys
from interval import interval
from interval_functions i... |
3bcef78629c202e088f1e22dad11b5b457e00741 | fanyichen/assignment6 | /yf511/main6.py | 1,526 | 3.671875 | 4 | from dealinterval import *
import sys
def main():
interval_list = []#creat an empty interval list for further step
try:
while True:
if len(interval_list) == 0:
initial_list_input = raw_input('List of intervals?')
if initial_list_input ==... |
18db9d8c0ecb06174f4d8a74b2cef8f290f29b46 | fanyichen/assignment6 | /sb5518/assignment6.py | 3,092 | 4.28125 | 4 | __author__ = 'sb5518'
"""
This program requests input from user. First, user should input a list of comma separated intervals. Intervals can have closed or open bounds. Some examples of intervals would be:
[1,4] represents the numbers 1 through 4
(2,5] represents the numbers 3 through 5
[4,8) represents the number... |
c139812a4e5f6d9aae3530edfc787e8f788ec3fd | fanyichen/assignment6 | /mtd368/assignment6.py | 1,493 | 3.796875 | 4 | import intervalevaluation
import sys
import re
from intervalevaluation import Interval, insert
# This try/except design I discussed with Sida because I was struggling with how to start the program. I tride mimicking what was in Adventure and failed.
if __name__ == '__main__':
try:
while True:
... |
20ecb005c9d06bccd0a91585c591452bba7884bc | fanyichen/assignment6 | /yf511/dealinterval.py | 4,476 | 3.96875 | 4 | import re
import main6
"""Creat an interval class to Interpret the interval and form into correct representation. Raise Error when the string is incorrect."""
class dealinterval(object):
def __init__(self, string):
#get rid of "([and ])" in the interval and split string by comma
self.string = strin... |
407b2d137fdfef769f0aa555e721adf17e5f2466 | asis45/python | /caeser.py | 1,201 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 26 08:16:47 2020
@author: Hp
"""
#caeser cipher algorithm
ALPHABET = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ'
KEY = 4
#caesar encryption algorithm
def caesar_encrypt(plain_text):
cipher_text = ''
plain_text = plain_text.upper()
for c in plain_text:
index... |
b79a5a6ff35eb12861811419e19a7af0986e18a9 | L200180068/Algostruk | /modul6/modul6(1).py | 2,500 | 3.75 | 4 | def gabungkanDuaListUrut(A,B):
la = len (A) ; lb = len(B)
C = list() # C adalah list baru
i = 0; j = 0
#Gabungkan keduanya samapai salah satu kosong
while i < la and j < lb:
if A[i] < B[j]:
C.append(A[i])
i += 1
else:
C.append(A[i])
... |
29816333038bf4bf14460d8436d1b75243849537 | kevgleeson78/Emerging-Technonlgies | /2dPlot.py | 867 | 4.15625 | 4 | import matplotlib.pyplot as plt
# numpy is used fo scientific functionality
import numpy as np
# matplotlib plots points in a line by default
# the first list is the y axis add another list for the x axis
# To remove a connecting line from the plot the third arg is
# shorthand for create blue dots
# numpy range
x = n... |
f17209f360bf135a9d3a6da02159071828ca0087 | hamishscott1/Number_Guessing | /HScott_DIT_v2.py | 1,120 | 4.3125 | 4 | # Title: Guess My Number v2
# Date: 01/04/2021
# Author: Hamish Scott
# Version: 2
""" The purpose of this code is to get the user to guess a preset number.
The code will tell them if the number is too high or too low and will
tell them if it is correct."""
# Setting up variables
import random
int_guess = 0
... |
fd4b084531d68577c6ba3c066575fba247aa6daa | summen201424/pyexercise-1 | /venv/totalexercise/algorithm.py | 618 | 4.28125 | 4 | #sqrt_newton
# import math
# from math import sqrt
# num=float(input("请输入数字:"))
# def sqrt_newton(num):
# x=sqrt(num)
# y=num/2.0
# count=1
# while abs(y-x)>0.0000001:
# print(count,y)
# count+=1
# y=((y*1.0)+(1.0*num)/y)/2.000
# return y
# print(sqrt_newton(num))
# print(sqr... |
da822cc0642fffd324ecf4e7fc4340f961900892 | mbfisher/advent-of-code | /2022/day17/day17.py | 6,873 | 3.640625 | 4 | import unittest
from collections import deque
from pathlib import Path
from typing import Set
class Chamber:
def __init__(self, debug=False):
self.debug = debug
self.columns = {i: set() for i in range(7)}
self.heights = {i: 0 for i in range(7)}
def tower_height(self):
return ... |
218ae6f23117fcfd3bb081220609f465c92af064 | jtlai0921/XB1817- | /XB1817《資料結構 使用Python》範例程式檔案/CH07/BT_Linked.py | 1,334 | 4.03125 | 4 | #使用Doubly Linked List來處理二元樹
class bitTree():
def __init__(self, root):
self.left = None #left Node
self.right = None # right Node
self.root = root
def leftChild(self):
return self.left #回傳left node data
def rightChild(self):
return self.right #回傳right node data
def setRoot(s... |
ee7713d6f322ca845c41106eb5702867cca60dcb | jtlai0921/XB1817- | /XB1817《資料結構 使用Python》範例程式檔案/CH06/Py_deque.py | 475 | 3.6875 | 4 | from collections import deque #匯入雙佇列模組
data = deque([97, 92, 63, 55, 124], 4)
print('雙佇列', data)
print('移除最右端', data.pop())
print('Index:', data.index(63))
data2 = deque(data, 6)
data2.append('One')
data2.append('Two')
data2.appendleft(27)
print('雙佇列', data2)
data2.rotate(1)
print('\n右旋轉:', data2)
data2.rotate(-2)... |
16cfe722dfae7009cacdfb8f5e0e9a2cb8f7ceef | jtlai0921/XB1817- | /XB1817《資料結構 使用Python》範例程式檔案/課後習題/Ex_10_1.py | 381 | 3.890625 | 4 | #第10章-循序搜尋-實作題(一)
def smallValue(Ary):
length = len(Ary)
smallest = Ary[0] #先指定第一個項目為最小值
#從第2個項目開始比對
for item in range(1, length):
if Ary[item] < smallest:
smallest = Ary[item]
return smallest
number = [79, 91, 86, 76, 97, 17, 57, 87, 56, 66, 4, 24]
print('最小值', smallValue(number)) |
d7fd56e01a4395a3f2e1b620dbf972f668cd1ee6 | jtlai0921/XB1817- | /XB1817《資料結構 使用Python》範例程式檔案/CH06/queuePriority.py | 1,217 | 3.75 | 4 | #以List實作Priority Queue 不能運作
class PQcolor:
def __init__(self, elem, prior):
self.elem = elem
self.prior = prior
class PriorityQueue :
'''產生不受限的空白優先佇列'''
def __init__(self):
self.Ary = []
def isEmpty(self): #空白佇列已True回傳
return len(self) == 0
def __len__( self ): #取時佇列長度
ret... |
09ad12b5945c35221e88012f43adc4c5bf88d4be | jtlai0921/XB1817- | /XB1817《資料結構 使用Python》範例程式檔案/CH08/graph_bfs.py | 972 | 3.71875 | 4 | from collections import deque
vertex = dict() #產生字典物件
vertex['A'] = ['B', 'D', 'C']
vertex['B'] = ['A', 'D']
vertex['C'] = ['D', 'A']
vertex['D'] = ['B', 'A', 'C']
vertex['E'] = ['F', 'C']
vertex['F'] = ['E']
def bfSearch(vertex, root):
visited = list()
que = deque([root])
visited.append(root)
node = root... |
379aef6fbfd467e7bf1b0c3fe5b8a3d02b783f5a | jtlai0921/XB1817- | /XB1817《資料結構 使用Python》範例程式檔案/CH05/gcd.py | 318 | 3.90625 | 4 | #以遞廻求最大公倍數
def gcd(n1, n2):
#如果n1<n2就置換
if (n1 < n2):
n1, n2 = n2, n1
#如果n1除n2的餘數為0,n2就是最大公倍數
if n1 % n2 == 0:
return n2 #基本案例,終止遞廻
else:
return gcd(n2, n1%n2) #遞廻關係式
print('GCD is',gcd(36, 42))
|
f62585f4f7d3f515af132dd7d48e41ab62ddbf3b | jtlai0921/XB1817- | /XB1817《資料結構 使用Python》範例程式檔案/CH03/Array2D.py | 358 | 3.796875 | 4 | # 讀取二維List
number = [[11, 12, 13], [22, 24, 26], [33, 35, 37]]
for idx, one in enumerate(number): # 第一層for廻圈
print('第{}列:'.format(idx), end = '')
for two in one: # 第二層for廻圈
print(two, end = ' ') #輸出之後不換行
print() #完成第二層for廻圈之後換行
else:
print('串列讀取完畢!')
|
eaac51435711dffa5394b43cc6098ed10bc308c1 | jtlai0921/XB1817- | /XB1817《資料結構 使用Python》範例程式檔案/CH03/RowMajor2D.py | 560 | 3.78125 | 4 | #二維陣列-以列為主
array2D = [[11, 12, 13, 14],
[22, 24, 26, 28], [33, 35, 37, 39]]
#讀取以列為主的二維陣列
print('以列為主')
for idx, one in enumerate(array2D):
print('第 {0} 列- '.format(idx), end = '')
for two in one:
print(format(two, '<3'), end = '')
print()
#讀取以欄為主的二維陣列
print('以欄為主')
print([[row[column] for row... |
c33ba903b2c475779348977bbfaa83d5e8e52819 | jtlai0921/XB1817- | /XB1817《資料結構 使用Python》範例程式檔案/CH03/Array2DSparse.py | 1,032 | 3.65625 | 4 | #3-tuple處理稀疏矩陣
aryA = [[0, 0, 0, 27, 0], [0, 0, 13, 0, 0],
[0, 41, 0, 0, 36], [52, 0, 9, 0, 0], [0, 0, 0, 18, 0]]
#取得矩陣列數、欄數
aryARow = len(aryA)
aryAColumn = len(aryA[0])
number = 0 #統計非零項目
print('讀取稀疏陣列')
for row in aryA:
for column in row:
print('{0:>3d}'.format(column), end = '|')
... |
4149056ac28f83f974e45d3981bc66b2f3ff43c2 | jtlai0921/XB1817- | /XB1817《資料結構 使用Python》範例程式檔案/CH01/fuc01.py | 225 | 3.65625 | 4 | #定義函式
def funcMax(n1, n2):
if n1 > n2:
result = n1
else:
result = n2
return result
# 呼叫函式
num1, num2 = eval(input('輸入兩個數值:'))
print('較大值', funcMax(num1, num2))
|
c9ae0f73e5624512ca8a1ba9add65993921a22e0 | purplepotatodonkey/Redpill | /pythonscripts/get_data.py | 2,142 | 3.625 | 4 | import praw
import pandas as pd
reddit = praw.Reddit("bot1", user_agent="bot1 user agent")
sub = ['ApplyingToCollege'] # make a list of subreddits you want to scrape the data from
for s in sub:
subreddit = reddit.subreddit(s) # Chosing the subreddit
########################################
# CREATING DICT... |
bff206f2151e60b05c1ca0c35c37f80d95879c01 | DeVatos-Lokos/PythonBasics | /if_statement/if_statement.py | 2,815 | 3.90625 | 4 | # En esta práctica verémos el condicional if,
# que permite dirigir el flujo del código
# en función de una condición de evaluación,
# el simil en español es el si
# p. ej si (if) llovio, no tiendo la ropa, si no (else) llovió sí la tiendo
class Ropa:
def __init__(self):
pass
def tender(self, clima): ... |
fb67b16d4d78e1ddb213ab62c708aa01d0631272 | joshua1955/python_scripts | /kostu.py | 276 | 3.78125 | 4 | #Koctu
#Show generation of random num
import random
die1=random.randint(1, 6)
die2=random.randrange(6) + 1
total = die1 + die2
print("При броске выпало", die1, "и", die2, "очков в сумме", total)
input("\n\nНажмите Enter для выхода")
|
e995bf856a613b5f1978bee619ad0aaab4be80ed | saibeach/asymptotic-notation- | /v1.py | 1,529 | 4.21875 | 4 | from linkedlist import LinkedList
def find_max(linked_list):
current = linked_list.get_head_node()
maximum = current.get_value()
while current.get_next_node():
current = current.get_next_node()
val = current.get_value()
if val > maximum:
maximum = val
return maximum
#Fill in Func... |
5e8379d787e81200a6c5994ffa911c1a95c7504f | ryscet/recrutation_neuroinformatics | /task3/correlate_imgdata.py | 3,030 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Parses the results from csv files into a single dataframe.
Uses seaborn to find correlation between average size and age and between average intensity and age.
"""
import csv
import glob
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
def ma... |
d367fa104c4c778b062dde6d52a931c185cfcdb0 | jieuhyl/Deep_Learning | /Natural_Language_Processing/Basic/nlp_1.py | 4,741 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 15 15:55:27 2020
@author: Jie.Hu
"""
#import nltk
#nltk.download()
#import gensim
''' Tokenize '''
from nltk.tokenize import sent_tokenize, word_tokenize, WordPunctTokenizer
# Define input text
input_text = "Do you know how tokenization works? It's actuall... |
47e9cf4b797f0b65e2b893aeaf5b0cd18423dceb | LiamLowndes/Hacker-Rank-Solutions | /Python 3/DeafualtDict/Answer.py | 581 | 3.6875 | 4 | #Create a default dictionary
from collections import defaultdict
d = defaultdict(list)
#Collect user input
temp = input().split()
n = int(temp[0])
m = int(temp[1])
#Add the letters to the dictionary as well as the position they occupy
for i in range(n):
d[input()].append(i+1)
#Print out the positions of all the ... |
b85c14c6b937d1d2e81fbe41ed603cca1d3ceb2b | karomoon/Card_game | /player.py | 2,437 | 3.703125 | 4 | from card import Card
import random
class Player:
def __init__(self, name="You", score=0):
self.name = name
self.talker = False
self.score = score
self.hand = []
self.guess = 0
self.taked = 0
def __str__(self):
return self.name
def take_card(self,... |
d95e36c587d03ca718c856a77b3e4577365106a6 | alejandro123210/learn-python | /bubbleSort.py | 509 | 3.609375 | 4 | array_to_sort = [415124, 10, 5, 13, 12, 42, 52, 346, 486, 3, 52, 5743, 754, 86, 53, 46, 57, 96]
should_stop = False
while should_stop == False:
should_stop = True
for back_index in range(len(array_to_sort) -1):
front_index = back_index + 1
if array_to_sort[back_index] > array_to_sort[front_index... |
2c57243d901f2298481d749b603b5945cf8b1990 | mark-heiple/P490 | /MLP/datafile.py | 4,152 | 3.796875 | 4 | import numpy as np
#for saving output
import pandas as pd
from pandas import DataFrame
#clears the console
def clear():
sys.stderr.write("\x1b[2J\x1b[H")
## This object implements a data file that can read and write
## 2 dimensional numpy arrays. Each row must have the same number of
## columns, the number of ... |
02a7ab067157be02467fd544a87a26fb7d792d7b | mayurimhetre/Python-Basics | /calculator.py | 735 | 4.25 | 4 | ###### Python calculator Program ##############################
### taking two numbers as input from user and option
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choose = int(input("Enter your option : 1,2,3,4 : "))
a = int(input("Enter First Number :"))
b = int(... |
d2b92a80e116b50bfe6714a5f35a06fbd8d60397 | sbeaudoin74/BowlingGameKata | /BowlingGameTests.py | 2,924 | 3.71875 | 4 | import unittest
from Main import Game
class BowlingGameTests(unittest.TestCase):
def setUp(self):
self.g = Game()
def rollMany(self, n, pins):
for index in range(0, n, 1): # Remember Python does '<' for indexing by default
self.g.roll(pins)
# Test for a gutte... |
e22a7e850c077be3966ae3d7c37ba7361c4025a0 | 2Meme2code/leetcode | /1603.py | 522 | 3.703125 | 4 | class ParkingSystem(object):
def __init__(self, big, medium, small):
"""
Keep a small array of fixed length with the number
of slots available for each size.
"""
self._slots = [big, medium, small]
def addCar(self, carType):
"""
Add a car to the park... |
76e6500822c6d9cfa18227163b387a30cf8da419 | 2Meme2code/leetcode | /204.py | 461 | 3.703125 | 4 | class Solution(object):
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
if n < 3:
return 0
arr = [0] * n
arr[0] = 1
arr[1] = 1
sqrt = int(math.sqrt(n))
for i in range(2, sqrt + 1):
j = 2
wh... |
4b4871bf549219dfba5f7251b47a5cc47baf74a9 | 2Meme2code/leetcode | /349.py | 347 | 3.5625 | 4 | class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
output = []
for i in nums1:
for j in nums2:
if i == j:
output.append(i)
... |
d3fe57abbfd7b4ac4cf708b81d450d3508aabe60 | 2Meme2code/leetcode | /1342.py | 307 | 3.625 | 4 | class Solution(object):
def numberOfSteps (self, num):
"""
:type num: int
:rtype: int
"""
steps=0
while num>0:
if (num%2)==0:
num=num/2
else:
num=num-1
steps=steps+1
return steps
|
e9bc1883e3c1edff5344491f3d83e500d634832a | tanmaya191/Mini_Project_OOP_Python_99005739 | /6_OOP_Python_Solutions/set 1/amstrong_check.py | 728 | 3.90625 | 4 | """Function To check Amstrong Number"""
def order(var2):
"""Function to check no of digits in a number"""
order_n = 0
while var2 != 0:
order_n = order_n + 1
var2 = var2 // 10
return order_n
def is_armstrong(var1):
"""Fuction to check amstrong"""
num_order = or... |
3ee30894a4086c02e8f9ffe65d0aacde1b95bb70 | tanmaya191/Mini_Project_OOP_Python_99005739 | /6_OOP_Python_Solutions/set 3/odd_element.py | 404 | 3.875 | 4 | """code to find the odd man out of a list"""
arr = [4, 4, 4, 4, 4, 4, 4, 4, "a"]
print("array is", arr)
ele_count = {}
for ele in arr:
if ele in ele_count:
ele_count[ele] += 1
else:
# setting the count to 1
ele_count[ele] = 1
# printing the elements frequencies
for key, valu... |
523f44dfb04138b92c56d603b07f8e4c3a9f75b3 | tanmaya191/Mini_Project_OOP_Python_99005739 | /6_OOP_Python_Solutions/set 1/arithmetic_operations.py | 561 | 4.1875 | 4 | """arithmetic operation"""
print("Enter operator")
print("1 for addition")
print("2 for subtraction")
print("3 for multiplication")
print("4 for division")
op = int(input())
print("Enter 1st number")
num1 = int(input())
print("Enter 2nd number")
num2 = int(input())
if op == 1:
print(num1, "+", num2, "... |
ee6a4589b17ed32172b53dca9e9a054b71ebea60 | tanmaya191/Mini_Project_OOP_Python_99005739 | /6_OOP_Python_Solutions/set 1/vowel_check.py | 488 | 4.21875 | 4 | """vowel or consonant"""
print("Enter a character")
char = input()
if len(char) == 1:
if char == "a" or char == "e" or char == "i" or char == "o" or char == "u":
print(char, "is a vowel")
elif char == "A" or char == "E" or char == "I" or char == "O" or char == "U":
print(char, "is a vow... |
b00b97949fca592da8e1c48c2be0077c3837bdd9 | jcl240/distancetophilosophy | /Source.py | 1,453 | 3.75 | 4 | import urllib.request
def main():
print("Enter the name of the article: ")
a = input()
nextLink = inputarticle(a)
if(nextLink == None):
return
while not(nextLink == "Philosophy"):
print(nextLink)
nextLink = inputarticle(nextLink)
print ("Philosophy!")
return True
d... |
6d639d8f8060ab27f1b8b81cff877ccf453563ad | mikasa42/Computacao-I | /pin.py | 170 | 3.875 | 4 | # nome : mikaela data :18/04/2019
n=int(input( "Escreva um numero inteiro"))
for num in range(1,n,1):
if(num%4==0 and num%3!=0):
print("PIN")
else:
print(num)
|
e374da82e910b66997c400c713cc4a4a1efd9217 | mikasa42/Computacao-I | /exercicio8.py | 274 | 3.890625 | 4 |
n = int(input('Digite o intervalo \n'))
for cont in range(1,n+1):
resp = 0
for i in range(2,cont):
if(cont%i==0):
resp+=1
if(resp == 0 ):
print(cont, "Este numero é primo")
else:
print(cont,'Este numero não é primo')
|
2f563e53a9d4c0bbf719259df06fb0003ac205bc | sweetise/CondaProject | /weight_conversion.py | 433 | 4.28125 | 4 | weight = float(input(("Enter your Weight: ")))
unit = input(("Is this in 'lb' or 'kg'?"))
convert_kg_to_lb = round(weight * 2.2)
convert_lb_to_kg = round(weight / 2.2)
if unit == "kg":
print(f" Your weight in lbs is: {convert_kg_to_lb}")
elif unit == "lb":
print(f" Your weight in kg is: {convert_lb_to_kg}")
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.