blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
f1408f35e772b8c8027fb38ebc96099ae97661fd | joana94/intelligent-ts-predictor | /rnn_classes.py | 9,941 | 3.75 | 4 | import torch
from torch import nn, optim
class TradRNN(nn.Module):
"""
Class to initialize and instantiate an Elman's (traditional) Recurrent Neural Network.
Arguments of class constructor:
-------------------------------
input_size: int
The number of features of the t... |
9c52bb6e302bf6cf0e0528493a6024f298543211 | Psykepro/Algorithms | /Python/SortingAlgorithms/MergeSort.py | 1,297 | 4.03125 | 4 | # -- Big O notations -- #
# - Time Complexity - #
# Best - O(n * log(n))
# Average - O(n * log(n))
# Worst - O(n * log(n))
# - Space Complexity - #
# Worst = O(n)
class Merge:
@staticmethod
def sort(arr):
n = len(arr)
if n <= 1:
return arr
mid = n // 2
# Perform ... |
b005bc57c5183db90b39ad70ad3c73901a4b1f41 | jackpork0702/Predicting-Chronic-Hunger | /ML_toolbox/data_describe.py | 4,279 | 4.0625 | 4 | # -*- coding: utf-8 -*-
'''
This tool provides an easy and quick over view for data.
It helps user to select null features.
----------------------------------
This module require install pandas and numpy.
pip install pandas
pip install numpy
pip install matplotlib
pip install seaborn
'''
import pandas as pd
import... |
8dc6ea163c4de309151bf9845bf27824cf7c0552 | Srigadgeter/Basics | /looping.py | 2,935 | 4.3125 | 4 | # >>>>> While Loops <<<<<
i = 1
while i <= 3:
print('@' * i, i)
i = i + 1
print('While ends & this statement is out of while loop')
# =========================================
# Game 1
secret_number = 3
guess_count = 1
guess_limit = 3
print('Game 1 has been started')
print('You have three chances to guess the s... |
0de2a4fcc2168e516ea4ba7f8c28fcf7e37b5067 | SmischenkoB/campus_2018_python | /Andrii_Fokin/1/Jaden Casing Strings.py | 125 | 4 | 4 | incomingStr = str(input())
outStr = ''
for word in incomingStr.split():
outStr += word.capitalize() + ' '
print(outStr) |
176d94eda25dc4ba4a7c904a1d7fcd38faf4a15b | CherylTSW/Software-Projects-Sprint-1 | /lib/authentication.py | 2,026 | 3.796875 | 4 | from lib import database
# Function to add account to database
def add_account(conn, username: str, pwd: str, firstName: str, lastName: str, role: int):
# Add user into users table
userQuery = f"""INSERT INTO Users (username, firstName, lastName, role, password) VALUES
('{username}', '{firstName}', '{last... |
72b3bd8bf7f9227440558267208dde071401ad02 | AjayJohnAlex/Data-Structure | /Linked_list/linked_list_test.py | 1,268 | 4.0625 | 4 | class Node(object):
def __init__(self,data=None):
self.data = data
self.next_node = None
def __repr__(self):
return f"Node data is : {self.data} "
class LinkedList(object):
def __init__(self):
self.head = None
def addNode(self,data):
... |
b657fdbc72fd6428c82cf403fb27ec7427e2f8b5 | Nazgul-tech/python | /privet.py | 425 | 3.75 | 4 | # Простейший алгоритм, запрашивающий имя и затем приветствующий его обладателя.
print('Как тебя зовут?') # Вывод на экран текста вопроса
t = str(input('Введите свое имя')) # Ввод c клавиатуры имени
print('Привет,', t, '!') # Вывод на экран приветствия
|
dbac1e6a542f946e48b61d4c8eef4cd73ed215ea | Dinesh94Singh/PythonArchivedSolutions | /Concepts/Arrays/33.py | 2,519 | 4 | 4 | """
33. Search in Rotated Sorted Array
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate... |
2a265a847ffe42f78dbd8993e400067cfad468de | erogers6264/largest-four | /largest_consecutive_four.py | 1,220 | 3.796875 | 4 | #!/usr/bin/env python3
# Function takes in a list of ints and returns a
# list of ints consisting of the largest consecutive
# four elements
def largest_consecutive_four(list_of_ints):
# Takes a greedy approach trying one solution after
# another saving the best one so far
current_largest_sum = 0
current_largest_i... |
27221b8014f94e5b6fd876730d068d42bf58429d | jake-billings/edu-csci2511 | /check-prime/check_prime.py | 1,635 | 3.828125 | 4 | """
Name: Jake Billings
Date: 10/26/2017
Class: CSCI 2511 Discrete Structures
Desc: Implementation of a prime-checking algorithm for problem 4.3.1 of the midterm review
"""
# Import time so that we can benchmark the algorithm
from time import time
# Check if i is prime using the simplest algorithm I could thin... |
b79fa30645a6f77c59351f01c95d2ffee7a465d5 | lucusesson/coding | /CS116/a09q2.py | 2,874 | 3.78125 | 4 | ##
## ***************************************************
## Lucus Esson (20615533)
## CS 116 Winter 2016
## Assignment 9, Problem 2
## ***************************************************
##
import check
class Time:
'''Fields: hours, minutes, seconds'''
# requires:
# 0 <= hours <= 23
# 0 <= minutes <= 59
#... |
7aa9c495db660c40346ed7af33a1f506a15364fb | francescomantegna/tf_pos_tagging | /ExampleBayesClassifier.py | 4,015 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 19 18:26:25 2017
@author: patrizio
"""
'''
A Multilayer Perceptron implementation example using TensorFlow library.
This example is using the MNIST database of handwritten digits
(http://yann.lecun.com/exdb/mnist/)
Author: Aymeric Damien
Project: h... |
403ef6a7696028a82efee03f3867184e5f2b4698 | epmskorenkyi/python-training | /lesson03/task06.py | 563 | 4.28125 | 4 | """
Task06 Module
=============
Contains function which takes a string and replaces all vocal letters in it to
an uppercase using a str.replace method.
"""
def vocal_to_upper(string):
"""Takes a string and replaces all vocal letters in it to an uppercase
:Parameters:
string - string to modification
... |
a7071f3aa42d8db3ba0e6f58ad291df9f7d8c857 | j-python-programming/python-programming | /src/ex05-bounce-many.py | 2,084 | 3.625 | 4 | # Python によるプログラミング:第 5 章
# 練習問題 5.4 ボールの複数インスタンス
# --------------------------
# プログラム名: ex05-bounce-many.py
from tkinter import *
import time
# 定数
DURATION = 0.01
class Border:
def __init__(self, left, right, top, bottom):
self.left = left
self.right = right
self.top= top
self... |
7162f52a52921dac426fbd64cdb93025e03e5403 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2453/60870/282720.py | 132 | 3.84375 | 4 | array = input().split(',')
array = [int(x) for x in array]
num = input()
if num in array:
print('True')
else:
print('False') |
9830acca5b6a621ca316fa4af04856772997a5b9 | X-TJuliax/kdtree-nn-python | /nearestNeigh/kd_tree_nn.backup.py | 23,328 | 3.5625 | 4 | from nearestNeigh.nearest_neigh import NearestNeigh
from nearestNeigh.point import Point
from nearestNeigh.node import Node
import sys
class KDTreeNN(NearestNeigh):
def __init__(self):
self.root = None
# Holds results of NN search queries
# Used for detailed print/debug output
s... |
9e9927ad62588592833600af59a1cf12bbca3312 | MurrinB/Python_Projects | /Phone_Book_Project/phoneBook.py | 2,372 | 3.5625 | 4 | # Python Ver: 3.9
#
# Author: Britnee Murrin
#
# Purpose: Phonebook Demo. Demonstrating OOP, Tkinter GUI module,
# using Tkinter Parent and Child relationships.
#
# Tested OS: This code was written and tested to work with Windows 10
from tkinter import *
import tkinter as tk
from tkinter import messagebox
#... |
8b5b152b1e34c0f07a83c7a3f9b73b8518ab2ec6 | MarlenXique/lab-10-more-loops | /which floor.py | 377 | 4.03125 | 4 | maximum_stories = 6
userstring = input("On what floor of your building is your office")
usernum = int(userstring, 10)
while (usernum > maximum_stories):
print("You Entered: ", usernum, " but there are only ", maximum_stories, " floors in this building.")
userstring = input("Try again")
usernum = int(userstr... |
0ed63bd8a86ce6bf09e7c63211b45d7c3c1a99a6 | ls5835766/python | /test/liaoxuefeng/hight_faceToobject/_slots_.py | 2,021 | 3.765625 | 4 | # 使用__slots__
class Student(object):
pass
s = Student()
s.name = 'Michael' # 动态给实例绑定一个属性
print(s.name)
# 还可以尝试给实例绑定一个方法:
def set_age(self, age):
self.age = age
from types import MethodType
# 给实例绑定一个方法
s.set_age = MethodType(set_age, s)
s.set_age(25) # 调用实例方法
print(s.age) # 测试结果
# 但是,给一个实例绑定的方法,对另一个实... |
30826e327147c085342701818645b259aaa7059a | BbChip0103/statistics_practice | /_180923_sigmoid.py | 1,143 | 3.828125 | 4 | import math
import matplotlib.pyplot as plt
### 여기서 bx+a => wx+b
### a는 변곡선이 꺾이는 중심을 의미, b는 변곡선의 기울기를 의미
def sigmoid(x, a=0, b=1):
return 1 / (1 + math.exp(-1*(a + b*x)))
### a와 b 사이의 범위를 가지고, c는 변곡선의 기울기를, d는 변곡선의 중심을 의미
def sigmoid(x, a=0, b=1, c=1, d=0):
return a + ((b-a) / (1 + math.exp(c * (d-x))))
if _... |
936933f7711f495b3c3fffff32edc4f1c1f9ecb7 | xCrypt0r/Baekjoon | /src/11/11109.py | 429 | 3.90625 | 4 | """
11109. 괴짜 교수
작성자: xCrypt0r
언어: Python 3
사용 메모리: 29,380 KB
소요 시간: 148 ms
해결 날짜: 2020년 9월 21일
"""
def main():
for _ in range(int(input())):
d, n, s, p = map(int, input().split())
tp = d + n * p
ts = n * s
print('do not parallelize' if tp > ts else ('parallelize' if tp < ts else ... |
8ab6aaadb5c427201fce63752d44c6ea70a8a9e4 | krisszcode/1stweek | /feladati08.py | 269 | 3.90625 | 4 | number_of_numbers = input("Give me the number of numbers:")
min=98112
max=-98112
for i in range(int(number_of_numbers)):
number=int(input("give me a number:"))
if number < min:
min = number
if number > max:
max = number
print(min)
print(max) |
c7b2764c260f28b203799bde27dbc5ce52b2140d | jamilahhh21/PYTHON-PROGRAMS | /indices.py | 979 | 4.125 | 4 | '''An array a has to be rotated by the integer k places
and the induces in the queries array has to be outputted.
It should return an array of integers representing the values at the specified indices.
a: an array of integers to rotate
k: an integer, the rotation count
queries: an array of integers, the indices t... |
7ce583926db197fa6ac44afad659349b1ca4a5d7 | adriannovoatagle/Carrera-Tecnico-Superior-en-Soporte-de-Infraestructuras | /Programacion 1/Ejercicios/Operaciones - Ejercicio 5.py | 149 | 3.90625 | 4 | print ("Ingrese temperatura en grados Celcius: ")
x = float (input ())
print ("El valor de la temperatura en grados Fahrenheit es: ", (x * 1.8 + 32)) |
1ebae5c30032d18d9c7c43303ca9482d100135a9 | rosewambui/NBO-Bootcamp16 | /misiingno.py | 247 | 3.859375 | 4 | def find_missing(list1,list2):
difference= set(list1) ^ set(list2)
if list1 ==[] or list2==[]:
return 0
elif len(list11) == len(list2):
return 0
else:
return (list(difference)[0])
|
822e09b6a8d1b1023f610cc6715b5dee5070a78e | alexmjn/hash-tables | /letter_count.py | 420 | 3.859375 | 4 | from collections import Counter
def print_letter_counts(s):
counter = Counter()
for letter in s:
if letter >= 'a' and letter <= 'z':
counter[letter.lower()] += 1
counter = sorted([(v, k) for k, v in counter.items()], reverse=True)
for pair in counter:
print(f'Count: {pair[... |
65449b65106c0afac1f5db781c97cbbef79945ec | amauboussin/text-lime | /models/model_utils.py | 4,777 | 3.671875 | 4 | import numpy as np
import pandas as pd
"""
Functions to inspect the coefficients and classification results of models.
"""
def get_coef_df(model, feature_labels, class_names=None):
"""Get a dataframe of labeled coefficients from a vectorizer and fitted linear model
Args:
model: Sklearn estimator with ... |
04768019da348c46550e02f20506602c7bc25c0d | annapastwa/leet30dayschallenge | /April30dayschallenge/day18_Minimum_Path_Sum.py | 708 | 3.5 | 4 | class Solution(object):
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
if not grid or len(grid) == 0:
return 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if i > 0 and j > 0:
... |
d868d532f5b105d9293f9f94de241124c5a0bef9 | guibsonufam/bases | /crawler_racism/print-tweets.py | 1,788 | 4.0625 | 4 | '''
print-tweets.py
Prints basic information about tweets in console
@p_barbera
Usage:
## prints text of first 10 tweets
python print-tweets.py -o text -f tweets.json -k 10
## prints coordinates and text of first 10 geolocated tweets
python print-tweets.py -o geo -f tweets.json -k 10
'''
import sys
import json
i... |
49fd81b0bf26e4f5ee7e72e2a8eb0b23f3209273 | StarJins/SWCodingTest | /준석/line_coding_5.py | 1,011 | 3.53125 | 4 |
def checker(con, bro_init, turn):
#print(con, bro_init, turn)
if abs(con-bro_init) <= turn:
return 1
elif turn == 0 or bro_init > con:
return -1
if con%2 == 0: #even number
res = checker(int(con/2), bro_init, turn-1)
if(res == -1):
return -1
... |
091f2923a4e8ab4a7f6511488f8d55f21f13e992 | harrifeng/Python-Study | /Leetcode/Simplify_Path.py | 1,158 | 4.1875 | 4 | """
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
click to show corner cases.
Corner Cases:
Did you consider the case where path = "/../"?
In this case, you should return "/".
Another corner case is the path might contain multip... |
83b2d95d23771d0d1ed4a55994f4af290109dca2 | Nicole-peng/gy-1908A | /demo/day01/xun_huan_demo.py | 1,704 | 3.703125 | 4 | # # for循环
# '''
# for i in range(100):
# 代码块
# '''
#
# for i in range(10):
# print("重要的事情说n遍")
#
# # 打印出100以内的奇数
# for i in range(1,100,2):
# print(i)
#
# for i in range(1,100):
# if(i%2 == 1):
# print(1)
# # 求出1+2+3...+100和
s = 0
for i in range(1,101):
s = i + 1
print(s)
# # 求出100! 1*2*3*4.... |
155f2166276e1c75453b8bb4315968c27a1bbfc2 | okochunk/tutpy | /00 - Template/exam_logic_comparation.py | 602 | 3.96875 | 4 |
# 123 .... 10 11 12
input_user = float(input('input value less than 3 or greather than 10 : \n'))
is_kurang_dari_3 = input_user < 3
print(is_kurang_dari_3)
is_lebih_dari_10 = input_user > 10
print(is_lebih_dari_10)
is_valid_or = is_kurang_dari_3 or is_lebih_dari_10
print(is_valid_or)
#union
#...... 456789 ........ |
c9faaf78d26164052739c1f70add6d7bf7cde685 | vietsia/hoc-git | /dict1.py | 201 | 3.78125 | 4 | counts=dict()
print 'Enter a line of text:'
line =raw_input('')
words=line.split()
print 'Words:',words
print 'Couting...'
for word in words:
counts[word]=counts.get(word,0)+1
print 'Counts',counts
|
d77c0e93369b0f58d9ab7ecc1bd4684d768948ad | CHANDUVALI/Python_Assingment | /python20.py | 222 | 4.125 | 4 | #Implement a program to find the euclidean distance of two points
import math
x = (1, 2, 3)
y = (3, 2, 1)
distance = math.sqrt(sum([(a - b) ** 2 for a, b in zip(x, y)]))
print("Euclidean distance from x to y: ",distance)
|
98bc37b8f49fd18fb79b58864d224d8252e3714c | pulinghao/LeetCode_Python | /剑指Offer/剑指 Offer 20. 表示数值的字符串.py | 1,784 | 3.8125 | 4 | #!/usr/bin/env python
# _*_coding:utf-8_*_
"""
@Time : 2020/9/2 3:24 下午
@Author: pulinghao
@File: 剑指 Offer 20. 表示数值的字符串.py
@Software: PyCharm
"""
import leetcode_utils
class Solution(object):
def __init__(self):
pass
def func(self, root):
pass
def isNumber(self, s):
"""
... |
f67c2200546f8c21c93f35f1954789c59c4c5123 | KodeWorker/Leetcode | /Algorithms/151-reverse-words-in-a-string.py | 629 | 3.78125 | 4 | # incomplete description
# one or multiple spaces at the end of string will be ignored!!!
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
wl = s.split(" ")
ind = 0
while ind < len(wl):
if wl[ind] == ... |
a3b6f6f97a860b9be665d5822d296d212b099331 | fpecek/opencv-introduction | /src/08_filters.py | 5,805 | 3.515625 | 4 | import numpy as np
import scipy.signal
import matplotlib.pyplot as plt
import cv2
from utils import plot_image, plot_images_list
image_lena = cv2.imread('img/lena.jpg')
image = cv2.imread('img/havana.jpg')
image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
kernel_eye = np.eye(3)
def normalize(image):
image_nor... |
77b0f4df6773d54ad22b0fda8d6c69519b85ac59 | autofakt/ComplexNumberClass | /complexPython.py | 1,369 | 3.625 | 4 | class MyComplex:
def __init__(self, re = 0, im =0):
self.re = re
self.im = im
def __eq__(self, n):
self.re = n.re
self.im = n.im
return self
def __str__(self):
return "{} {} {}i".format(self.re, '+' if self.im >= 0 else '-', abs(self.im))
... |
bac339496df750c7e18f73cf140bbef5ddbe1d6a | hitanshkadakia/Python_Tutorial | /forloop.py | 729 | 4.28125 | 4 | #For loop
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
#Looping Through a String
for x in "happy_coding01":
print(x)
#break Statement
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
#continue Statement
fruits = ["apple"... |
1122534fa66064cf876eb87719fb12fd2261c2eb | caceresdaniel/4470-Chat-App | /server.py | 1,701 | 3.71875 | 4 | import socket
import sys
port = 0
host = ''
def listen(port):
s = socket.socket()
s.bind((host, port))
s.listen(5)
c = None
while True:
if c is None:
# Halts
print('[Waiting for connection...]')
c, addr = s.accept()
print('Got connection fro... |
ef605e1ca662f2873971f6027708de8746a86c63 | SASLEENREZA/Python_DeepLearning | /ICP-5/Source/LinearRegression.py | 674 | 3.875 | 4 | import numpy as num
import matplotlib.pyplot as mat
a=num.array([2.9,6.7,4.9,7.9,9.8,6.9,6.1,6.2,6,5.1,4.7,4.4,5.8])
b=num.array([4,7.4,5,7.2,7.9,6.1,6,5.8,5.2,4.2,4,4.4,5.2])
#calc mean for two lists
mean_a=num.mean(a)
mean_b=num.mean(b)
#calc deviations for slope
x=num.sum((a-mean_a)*(b-mean_b))
y=num.sum(pow(a-mean... |
8f8f7781593411c1f0d67ac08b34818b807ceaed | Ntaylor1027/Python-InterviewPrep | /Chapter 5 Arrays/SpiralOutput.py | 1,196 | 3.59375 | 4 | import unittest
import functools
"""
My version
Runtime: O(n)
Space: O(1)
"""
def spiralOutput(A):
left, top, right, bottom = 0, 0, len(A[0])-1, len(A)
s = []
while(left <= right and top <= bottom):
# Traverse top row
for i in range(left, right+1):
s.append(A[top][i])... |
6649fe77b448b86fbfefbb2d3d8708d24af64317 | mohmmed-aabed/Data-Structures-In-Python | /Recursion/fibonacci.py | 201 | 3.78125 | 4 | cash = {0: 0, 1: 1}
def fibonacci(n):
if n in cash:
return cash[n]
else:
cash[n] = fibonacci(n - 1) + fibonacci(n - 2)
return cash[n]
print(fibonacci(10))
print(cash)
|
f0b5e5adf32bd9d271161efbbf7b775f91bc8970 | I-in-I/Python-General-Projects | /Class Handling/private_variable_handling.py | 938 | 4.5625 | 5 | #This shows how to access private instance (through name mangling)
#and class attributes.
class A:
__x = 1
def __init__(self):
self.__var = 10
def get_var(self):
return self.__var
a = A()
#Printing the returned value of (private) __var from the
#"get" function in cla... |
599bfa22df3b0804d8a7f8263ea43b699534feaf | TaigoKuriyama/atcoder | /problem/abc169/c/main.py | 126 | 3.859375 | 4 | #!/usr/bin/env python3
from decimal import Decimal
a, b = input().split()
a = Decimal(int(a))
b = Decimal(b)
print(int(a * b)) |
0208ffc0aa7c384a225b68cbd1d29551d88ff87d | jamilahhh21/PYTHON-PROGRAMS | /timeunits.py | 580 | 3.953125 | 4 | '''UNITS OF TIME'''
d,h,m,s=map(int,input('Enter the number of days,hours,minute and second (: separation)= ').split(':'))
tot_sec=(d*24*60*60)+(h*60*60)+(m*60)+s
print('Total number of seconds=%d'%(tot_sec))
sec=int(input('Enter the total number of seconds='))
day=sec/(60*60*24)
sec=sec%(60*60*24)
hr=int(sec/(6... |
c971114b81da36691c475a2935f40639b595d93c | isaakh12/final_project | /make_pca.py | 2,607 | 3.859375 | 4 | def make_pca(df, vars):
'''
Function used to conduct a PCA
Input: dataframe, list of variables that you want to use in your PCA
Output: Eigenvalues, Eigenvectors, Proportion of variance taken up by first 2 PCs, Factor Loadings
'''
import numpy as np
from scipy import linalg
from matplotl... |
3639775b77b2be74bbda44800282a891153d9d22 | sy07/PyDjango | /day_5_tasks/assign_val.py | 170 | 3.578125 | 4 | class Demo:
name = ""
def __init__(self, name):
self.name = name
def fun(self):
print("My name is "+self.name)
af = Demo("Rambo")
af.fun()
|
0a5da47ba7297af7190377e20d52d8685e3823cb | AgustinParmisano/tecnicatura_analisis_sistemas | /programacion1/practica4/funciones.py | 435 | 3.640625 | 4 | # def nombre_func(parametro1, parametro2, parametro3):
# bloque_de_codigo
# return
n = input("Ingrese un numero: ")
def es_par(num):
if (num % 2) == 0:
return 1
else:
return 0
if es_par(n) == 1:
print("El numero %s es par " % (n))
else:
print("El numero %s no es par" % (n))
print(es_par(n))
resul = es_par... |
efb267c5e2dcc5d6bfde65a86a03aaa9bcc7225f | grigor-stoyanov/PythonOOP | /introduction/livedemo.py | 1,876 | 3.96875 | 4 | # a single method should do a single task
# dividing logic in too many functions on your code is called overarchitecture
[print(el) for el in dir(__builtins__)]
# A namespace is a mapping from names to objects i.e dictionary of assigned variables in the code
# on top is the built-in namespace after comes global and loc... |
370bb724e024ddf3e4c8fb2c9eafa12ee4a706a2 | zhuwenzhang/Python-base | /集合四则运算.py | 600 | 4.125 | 4 | set1 = {"green", "red", "blue", "red"}
print(set1)
set2 = set([7, 1, 2, 23, 2, 4, 5])
print(set2)
print("Is red in set1?", "red" in set1)
print("length is", len(set2))
print("max is", max(set2))
print("min is", min(set2))
print("sum is", sum(set2))
set3 = set1 | {"green", "yellow"}
print(set3)
set3... |
73014565010fea48511df179e3a8dd8a683a1ca9 | pranshu798/Python-programs | /Data Types/Dictionary/Adding elements to a Dictionary.py | 573 | 4.40625 | 4 | #Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
#Adding elements one at a time
Dict[0] = 'Python'
Dict[2] = 'with'
Dict[3] = 1
print("\nDictionary after adding 3 elements: ")
print(Dict)
#Adding set of values to a single key
Dict['Value_set'] = 2,3,4
print("\nDictionary after adding 3 ... |
5b56b5be82b6ead4de45b272276cd3e56378b9b9 | ddc899/cmpt145 | /assignments/assignment2/a2q1_testing.py | 5,724 | 3.5 | 4 | #Name: Jason Tran
#NSID: jat687
#Student Number: 11101081
#Course: CMPT 145-01
#Lab: L03
import a2q1
#UNIT TESTING
########################################################################################################################
#testing a2q1.get_confession()
test_get_confession = [
{
#ensure t... |
5de17838d91d1efd7bac411041c534e281ea55ff | shpona/python_progs | /problem1.py | 141 | 3.953125 | 4 | #Program is finding the sum of all the multiples of 3 jr 5 below 1000#
i=1
s=0
while i<1000:
if i%3==0 or i%5 ==0:
s=s+i
i=i+1
print (s)
|
a6f104a46efd7deb098828e8d0b5b5e6e6901f6d | lilu069/hw070172 | /L04/exercises_zelle/4_11.py | 349 | 4.0625 | 4 | def main():
print("This program illustrates a chaotic function")
n = 10
x = .25
y = .26
print("Index {0:>9}{1:>10}".format(x, y))
print("--------------------")
for i in range(n):
x = 3.9 * x - 3.9 * x * x
y = 3.9 * y - 3.9 * y * y
print("{2:^3}{0:>12.5f}{1:>10.5f}".... |
575e90d0ac39b208367496b46b98f146e213ed0a | JacobCollstrup/PythonBootCamp | /HangmanGame/WordBank.py | 1,516 | 3.5625 | 4 | from random import randint
def HangmanPics(number: int):
HANGMANPICS = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
... |
e31d0ac233aacea8d66a0736b3156acfc64df44f | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/bob/fa69b986405d4c57806f279c6e688cc5.py | 477 | 3.65625 | 4 | def is_nothing(sentence):
return sentence == ''
def is_yelling(sentence):
return sentence.isupper()
def is_question(sentence):
return sentence.endswith('?')
def hey(sentence):
"""sentence said to bob"""
sentence = sentence.strip()
if is_nothing(sentence):
return 'Fine. Be that way!'
... |
8adc475573705442312a86272f0b6d9e313f765f | socc-io/algostudy | /ProblemPool/sort_mergesort/becxer.py | 575 | 3.75 | 4 | def merge(P,Q):
ip = 0
iq = 0
res = []
while True:
if ip >= len(P) or iq >= len(Q):
break
if P[ip] > Q[iq]:
res.append(Q[iq])
iq += 1
elif P[ip] <= Q[iq]:
res.append(P[ip])
ip += 1
if ip < len(P):
res.extend(P[ip:])
if iq < len(Q):
res.extend(Q[iq:])
print str(P) + "+"+str(Q) + "=" +str... |
2b68815a254b615547fa215d26e7c143b502a92b | HenDGS/Aprendendo-Python | /python/Exercicios/3.6.py | 262 | 3.53125 | 4 | jantar=["Merlin","Altria","Gilgamesh"]
print("Infelizmente " + jantar[0] + " não poderá comparecer")
jantar[0]="Kiritsugu"
print("O novo convidado é: " + jantar[0])
jantar.insert(0,"Medusa")
jantar.insert(2,"Lancelot")
jantar.append("Mordred")
print(jantar)
|
796878755f27765f582a08991e6fb6df171d92b8 | piazentin/programming-challenges | /hacker-rank/implementation/utopian_tree.py | 488 | 3.859375 | 4 | # https://www.hackerrank.com/challenges/utopian-tree
cache = {0:1, 1:2, 2:3, 3:6, 4:7}
max_n = 4
def get_how_tall(n):
for i in range(max_n, n + 1):
if i % 2 == 0: # adding season
cache[i] = cache[i - 1] + 1
else: # doubling season
cache[i] = cache[i - 1] * 2
return ca... |
99ae80ef01d322a88a84d0224f87dc8bda60a679 | monybun/TestDome_Exercise | /Username(E20).py | 1,374 | 3.890625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Implement the validate function, which accepts a username and returns true if it's acceptable and false if it's not.
A username is valid if it satisfies the following rules:
The username must be at least 4 characters long.
The username must contain only letters, numb... |
d885a0bec6792fbd14bcd159874de1edbcee4303 | dh-ab93/OSS-SAKI | /1-naive-bayes/script.py | 6,511 | 3.515625 | 4 | import numpy
import pandas
import sklearn.feature_extraction.text
import sklearn.feature_selection
import sklearn.model_selection
import sklearn.naive_bayes
import sklearn.preprocessing
def df_from_csv(filepath: str) -> pandas.DataFrame:
# import csv data, do some simple cleanup steps
dataframe = pandas.read_... |
c3a5ee595d9f22ce47290bc49bd47b2904980114 | muskankapoor/fall2017projects | /Python/deep copy.py | 155 | 3.640625 | 4 | import copy
spam = ['A', 'B', 'C', 'D']
cheese = copy.copy(spam)
cheese[1] = 42
print (spam)
print (cheese)
""" copy.deepcopy() for lists within lists """ |
edc45e027597ebbc8d352410ab57b235c6b56cd2 | SemiMaks/bank_account_class | /accounts.py | 1,083 | 3.78125 | 4 | '''
Класс SavingAccount представляет
сберегательный счёт.
'''
class SavingsAccount:
# Метод __init__ принимает аргументы для
# номера счёта, процентной ставки и остатка
def __init__(self, account_num, int_rate, bal):
self.__account_mum = account_num
self.__interest_rate = int_rate
... |
8d0cba33a8f4932de25a59ce9730787368be12c5 | WizzCodes/List-Functions | /Tut4.py | 368 | 3.90625 | 4 | grocery = ("Sugar", "Bread", "Chicken Lollipop", "Jim jam", 65)
#print(grocery)
#print(grocery[3])number
"""
#numbers.sort()
#print(numbers[::-2])
#print(min(numbers))
"""
#numbers = [1, 2, 7, 6, 3]
#numbers.append(6)
#numbers.insert(1, 63)
#numbers.remove(2)
#numbers.pop()
#print(numbers)
#tp = (1,)
#pr... |
a9a6f1aba6ce336db53d98ebbd7138ac48a9d6d5 | surojitfromindia/PythonAlgos | /MergeSortExcersise.py | 927 | 4.15625 | 4 | def Mergesort(A):
if (len(A) > 1):
# calcualte middle point
middle = len(A) // 2
# create two new arrays ,
LA = A[:middle]
RA = A[middle:]
# call Mergesort on both halves
Mergesort(LA)
Mergesort(RA)
# let take 3 index
i = 0
j =... |
df0157a3bc8739ae0a6b027797b2934b18b34211 | Did-you-eat-my-burrito/python-lesson | /dict.py | 281 | 3.75 | 4 | #keyが名前,valueがスコアの辞書
name_score_dict = {"sean":120,"bob":20,"sarah":30,"josh":25,"alex":50}
name_score_dict["bob"] = 80
for name , score in name_score_dict.items():
print(name,score)
for name in name_score_dict.keys():
print(name_score_dict[name])
|
62e2a28d09113ae7a1b70afcf6396e8a82dfeca4 | tonghannteng/jetbrains-academy | /python-developer/tic_tac_toe_stage_3.py | 1,509 | 3.625 | 4 | # write your code here
cells = input('Enter cells:')
count_x = cells.count('X')
count_o = cells.count('O')
first_row, second_row, third_row = cells[:3], cells[3: 6], cells[6: 9]
print('---------')
print('|', first_row[0], first_row[1], first_row[2], '|')
print('|', second_row[0], second_row[1], second_row[2], '|')
pr... |
1a35e32ace52ac3e6b8cece2f1500afeda8c47bf | DRomanova-A/Base_project_python | /основы программирования python (ВШЭ)/solutions/week-5/task_5_03_flags.py | 991 | 4.03125 | 4 | '''
Флаги
Напишите программу, которая по данному числу n от 1 до 9 выводит на экран
n флагов. Изображение одного флага имеет размер 4×4 символов,
между двумя соседними флагами также имеется пустой (из пробелов) столбец.
Разрешается вывести пустой столбец после последнего флага.
Внутри каждого флага должен быть записан... |
5bb8c523b58727b91768b42a590b061d603d9425 | talebilling/hackerrank | /python/symmetric_difference_set.py | 750 | 4.125 | 4 | '''
input
4
2 4 5 9
4
2 4 11 12
Output the symmetric difference integers in ascending order, one per line:
5
9
11
12
'''
def main():
m, n = get_inputs()
m, n = make_sets(m, n)
united_set = make_difference_and_union(m, n)
print_united_set(united_set)
def get_inputs():
m_len = int(input())
m =... |
384ff5e9bd74b884d5571ccf5a8b90135f990dce | jgdj01/Projeto_Algoritmo | /shell sort/Shell_sort.py | 1,107 | 3.90625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Créditos pela função shell:
# https://rosettacode.org/wiki/Sorting_algorithms/Shell_sort#Python
import sys
import timeit
import math
def shell(seq):
inc = len(seq) // 2
while inc:
for i, el in enumerate(seq):
while i >= inc and s... |
c6061700872987902ac3118bd9a65a848449f3fa | thawfiqsuhail02/DataStructures | /CLL_full.py | 7,578 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 21 21:43:29 2020
@author: Dr
"""
class node:
def __init__(self, key, next=None):
self.key = key
self.next = next
def __str__(self):
return str(self.key)
def __repr__(self):
return str(self.key)
class circ... |
9ab61436812e4401d86cfa6060c80e7ecdedcdf3 | prashant97sikarwar/leetcode | /Hash table/happy_number.py | 855 | 3.703125 | 4 | """Write an algorithm to determine if a number n is "happy".
A happy number is a number defined by the following process:
Starting with any positive integer, replace the number by the
sum of the squares of its digits, and repeat the process until
the number equals 1 (where it will stay), or it loops endlessly
in a ... |
69365649fd3434a8767abe5c3d4d840d2a2653dc | lenatester100/class_assignment | /Quadratic Program.py | 434 | 4.1875 | 4 | print ("Welcome to the program! Please enter the value of A, B, C, and X at the corresponding prompts")
a = int(input("What is the value of A: "))
b = int(input("What is the value of B: "))
c = int(input("What is the value of C: "))
x = int(input("What is the value of X: "))
print ("The following quadratic was... |
132f43c25c0ac3c060adb09f482b05c314e2df84 | juneepa/LeetCode-Algorithms | /520. Detect Capital.py | 651 | 3.6875 | 4 | ## https://leetcode.com/problems/detect-capital/description/
## Check website above for more details
## Example:
## Input: "USA"
## Output: True
## Input: "FlaG"
## Output: False
## Easy, 35ms, 96.12%
class Solution(object):
def detectCapitalUse(self, word):
## 3 cases
## isupper() or islower()
... |
296fc1f8e5a748d1caa7e7a14c332b0123391c4b | evgeniarubanova/homework | /hw4/дздз.py | 163 | 3.90625 | 4 | print('Введите слово')
word = input()
for index,letter in enumerate(word):
if index%2!=0 and letter!='к'and letter!='а':
print(letter)
|
2ec58939d8b54b647e0cceb747eecc3ad22edc57 | ZordoC/the-self-taught-programmer-August-2019 | /Chapter 9 - Files/Challenge-3.py | 640 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 16 02:56:32 2019
@author: zordo
"""
# Challenge 3 - Take the items in this list of lists [["Top gun","Risky Business","Minority Report"], ["Titanic","The revenant","Inception"],
#["Training Day","Man on Fire","Flight"]]
movies = [["Top gun","Risk... |
a3b568d9f5d5700cea997525750f9bf2ea9b2ecf | sashaaero/binarysearch-problems | /algorithms/trie.py | 247 | 3.84375 | 4 | def make_trie(words):
_end = '.'
trie = dict()
for word in words:
current_dict = trie
for letter in word:
current_dict = current_dict.setdefault(letter, {})
current_dict[_end] = _end
return trie
|
d800fb0390e8fb59a12462971de1dc31416d63f1 | tikalestari/haberdashery | /Recursion/Problem_34.py | 859 | 3.78125 | 4 | '''
Return the list of lists that represent the coin combinations
That sum to K
'''
import sys
def coin_combos(coin_set, coin_lists, current_combo, index, k):
if k == 0:
current_sorted = sorted(list(current_combo))
if current_sorted not in coin_lists:
coin_lists.append(current_sorted)
... |
a23bf48f323ce51e0e0b12ff38a273e8227ab44a | mbmcmullen27/foobar | /lvl2/runner.py | 1,452 | 3.859375 | 4 | from fractions import Fraction
def solution(pegs):
dist = pegs[1]-pegs[0]
if len(pegs) == 2 and dist >= 3:
result=Fraction('2/3')*dist
return [result.numerator,result.denominator]
i=(3*dist)-1
while i >= 3 :
radius = i*Fraction('1/3')
candidate=assign(radiu... |
6c954cfe6139c8f53eeb442d5955840e0c6becd3 | witzkevin/prg105 | /pennies.py | 279 | 3.8125 | 4 | daysWorked = int(input("Number of days worked "))
dailyPay = .01
total = 0
print("day\tsalary")
for today in range(daysWorked):
dailyPennies = 2 ** today
total = total + dailyPennies
print(today + 1, "\t", dailyPennies)
pay = total * dailyPay
print("\n pay:", pay,)
|
6e92fea9bf924b99cf3795b042679f5a583f53dc | jpette/virtual_record_store | /virtual_record_store.py | 17,724 | 4.3125 | 4 | # John Pette - Python Project 1 - Record Store
# This program simulates a consumer's experience in a record store.
# The major classes are RecordStore, Customer, Music, Record, Cassette, and
# CD. The bulk of the methods are defined within the Customer class.
class RecordStore():
"""Representation of a record sto... |
f9c7cdda53d0e26566a441ceef0615af849b8d66 | upupsheep/2019-Spring-NCTU-Machine-Learning | /HW3/mlhw3.py | 7,003 | 3.578125 | 4 | import numpy as np
import random, math
import matplotlib.pyplot as plt
def gaussianDataGen(mean, var):
"""
Univariate gaussian data generator
(Applying Box-Muller Method)
"""
x = random.random()
y = random.random()
standard_norm = (-2 * math.log(x))**(1 / 2) * math.cos(
... |
76b09e69bb8b5ba619a102f8578566d1160b1302 | Prashanth073-cloud/Python-files | /Reading file grades.py | 1,546 | 3.59375 | 4 | #Name:Prashanth Chintala
#CNumber: C0759844
#Date:12/4/2019
#Question:Q7
def main():
examAnswersList = ['a','c','a','a','d','b','c','a','c','b','a','d','c','a','d','c','b','b','d','a'] #ExamAnsewers list
studentsAnswersList = []
gradesFile = open('grades.csv','r') #opening grades file
correctM... |
d076b57b3082617ff2896f8736f557fe08ec18fd | Tony-Leonovich/Homework | /Homework2.py | 3,089 | 4.0625 | 4 | #Задание №1
data = ['hello', 123, 65.34, ('first', '2nd', 3)]
for item in data:
print(type(item))
#Задание №2
my_list = []
lenght = int(input('Введите длину списка: '))
while len(my_list) < lenght:
my_list.append(input('Введите что-нибудь: '))
print(my_list)
for i in my_list:
i = int(i)
while i < len(m... |
6443e76e4a2f7f00228388d9736d4a9754177861 | kshashank03/exercism_python | /grains/grains.py | 226 | 3.671875 | 4 | def square(number):
if number > 0 and number < 65:
return 2**(number-1)
else:
raise ValueError("Need a value between 1 and 64 inclusive")
def total():
return sum([(2**(x-1)) for x in range(1,65)])
|
fa61a7d26d02c49968f58fdcb857be7c4e99121f | rheehot/Sparta-Algorithm | /week_2/01_print_all_linked_list.py | 2,065 | 3.84375 | 4 | #[3] -> [4]
#data next
class Node:
def __init__(self,data):
self.data=data
self.next=None
# 3을 가진 Node 를 만드려면 아래와 같이 하면 됨
node=Node(3)
# 노드들을 만들어서 연결해 보면
first_node=Node(5)
second_node = Node(12) # [12] 를 들고 있는 노드를 만듬
first_node.next=second_node #새로 만든 노드를 기존 노드로 연결
#위처럼 번거롭게 일일이 연결해... |
308be526aaf39a9f5be7ccb5210c9abdb46d1920 | shishengjia/PythonDemos | /数据结构和算法/找到最大或最小的N个元素_P7.py | 852 | 3.859375 | 4 | import heapq
nums = [1, 7, 3, 22, -3, 9]
# 最大和最小的三个数
print(heapq.nlargest(3, nums))
print(heapq.nsmallest(3, nums))
# 还可以接受一个参数key,处理更复杂的数据
records = [
{'name': 'Tom', 'score': 40},
{'name': 'Jack', 'score': 60},
{'name': 'Marry', 'score': 55},
{'name': 'Boen', 'score': 30},
{'name': 'Alex', 'sco... |
ba445e0fcbf182279a43330a86752602eeca1cb0 | tonydelanuez/python-ds-algos | /probs/merge-integer-ranges.py | 958 | 3.671875 | 4 | def merge_ranges(input_range_list):
#check for null or 1 list
if (len(input_range_list) <= 1 or input_range_list == None):
return input_range_list
output = []
i = 1
previous = input_range_list[0]
while i < len(input_range_list):
current = input_range_list[i]
#overlap exists
if(previous.upper_bound >= curr... |
5009218a95311bb93c7a31fcab001aa22bdc2626 | mike42/pyTodo | /todolist/ListBackend.py | 837 | 3.546875 | 4 | class ListBackend(object):
"""
Class to help manage the todo-list data structure in an array
"""
def __init__(self):
self.lst = []
self.fname = None
def load(self, fname):
self.fname = fname
with open(fname, 'r') as f:
for line in f:
self.... |
745423311c3d4027b7e066945f69eafcc6653030 | Slopez314/182CIS | /inclass 9.py | 244 | 4.03125 | 4 | def main():
the_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
the_number_n = 5
greater(the_list, the_number_n)
def greater(the_list, the_number_n):
for num in the_list:
if num > the_number_n:
print(num)
main()
|
a10895886797726409a04c74ed2aa13384084823 | LeonardoADS84/Curso-de-python | /lista.py | 446 | 3.921875 | 4 | carros =["HRV","Golf","Focus","New Fiesta"]
carros2 =["Fox","Gol","Uno","Creta"]
carros.append("Ronda Fit")
carros.append("Fusion")
carros.append("Polo")
#carros.remove("Fusion")
#carros.pop() exclui último item
#del carros[1]
#carros.clear()
#carros2=list(carros)recebe a lista carros para carro2
#car... |
68ac3788219e661eeaf76ca7c7c157c7569d636c | janhninini/Problem_Solving | /Basic/gcd.py | 109 | 3.59375 | 4 | x=int(input())
y=int(input())
for i in range[1:x]:
if x%i==0 and y%i==0:
print(i)
|
5395ccf601bff70f8c53cb8fb24828b4ded85532 | Neha-Deo/Mini-Codes-from-Scratch-using-Python | /WikiPedia Search Tool/wikisearch.py | 1,352 | 3.734375 | 4 | # 1) In Terminal Type : pip install wikipedia
# 2) Write Code :
import wikipedia
query=wikipedia.page("Database")
print(query.summary)
# 3) Run Code : python wikisearch.py
# 4) Output :
# A database is an organized collection of data, generally stored and accessed electronically from a computer system.
# Where data... |
f4ba6ea4761c09989a7cc75f2d8e71421b0974d1 | CppChan/Leetcode | /medium/mediumCode/c/Google/dian/FirstNontLetterSort.py | 301 | 3.625 | 4 | class Solution(object):
def first(self, input):
pre = None
for i in range(len(input)):
if not input[i].isalpha():continue
if pre==None: pre = i
elif ord(input[i].lower())<ord(input[pre].lower()):return i
return None
if __name__=="__main__":
s = Solution()
print s.first("ba") |
d68b0385462e06dc835f0db4f07504ff6950ecb6 | SarveshMohan89/Python-Projects | /find.py | 229 | 3.671875 | 4 | #Write code using find() and string slicing (see section 6.10) to extract the number at the end of the line below. Convert the extra
text = "X-DSPAM-Confidence: 0.8475";
x=text.find(':')
y=text[x+1:]
z=float(y)
print(z)
|
ea5b2d82eb523d45c3c100f0872229277fcba2be | bcowgill/bsac-linux-cfg | /bin/template/python/python-lite.py | 2,002 | 3.53125 | 4 | #!/usr/bin/env python
"""Documentaation for the program"""
import sys
import getopt
from traceback import print_exc, print_stack
import python_module
DEBUG=False
exit_code=0
# Lambda Functions
# User defined local Functions
def g():
print "g"
print_stack() # useful for debugging to see how got here.
d... |
679f43b49f498b581e6cacaf5ba966ce78dfa543 | bruiken/ModelChecking | /variableorderings/manualordering.py | 555 | 3.734375 | 4 | from variableorderings.baseordering import Ordering
class ManualOrdering(Ordering):
"""
ManualOrdering is a ordering which can be set manually.
"""
def __init__(self, ordering):
"""
Constructor for a ManualOrdering.
:param ordering: The manually chosen ordering.
"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.