blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
5857e15c9760b7395614d4097b01bd91482306bb | pkarczma/yield-generator | /Particle.py | 713 | 3.59375 | 4 | import random
class Particle():
# Particle is a generic particle class
# containing all the parameters of itself
def __init__(self, pt=0., eta=0., phi=0.):
# Each particle has:
# - a transverse momentum pt
self.pt = pt
# - a pseudorapidity eta
self.eta = eta
... |
fca87a12cf205a31dd0ca6942c9cb893ae32da26 | jeffreyvt/FIT3139-Computational-Science | /week2/q1_realToBin.py | 1,593 | 3.640625 | 4 | """
Student ID: 2594 4800
Name: JiaHui (Jeffrey) Lu
Aug-2017
"""
def int2bin(num):
"""
Converts base 10 integer value to binary
:param num: integer value in base 10
:return: binary value of the input with the right sign
"""
if num == "0":
return "0"
elif num == "-0":
return ... |
c57d586716bfaad519f7d738186deb5bfdc10f8c | NikitaDanila/Python_-Reuven-s_OOP_course | /Exercises1/1.py | 238 | 3.859375 | 4 | class Scoop(object):
def __init__(self, flavour):
self.flavour = flavour
s1 = Scoop('vanilla')
s2 = Scoop('chocolate')
s3 = Scoop('strawberry')
print(s1.flavour)
for one_scoop in [s1, s2, s3]:
print(one_scoop.flavour)
|
dde69cbddbda9962433573dfc08642c44e0f50d8 | asperaa/back_to_grind | /DP/GFG._MCM_Naive.py | 718 | 3.734375 | 4 | """We are the captains of our ships, and we stay 'till the end. We see our stories through.
"""
"""MCM [Naive]
"""
def mcm_helper(num, i, j):
if i >= j:
return 0
min_cost = float('inf')
for k in range(i, j):
left_cost = mcm_helper(num, i, k)
right_cost = mcm_helper(num, k+1, j)
... |
e96be587fa7c9c0d1dd80c28cb53887c319526ce | tsukudabuddha/Hacker-Rank-Challenges | /camel-case.py | 203 | 3.859375 | 4 | """CamelCase Hackerrank."""
def num_of_words(s):
"""Take in camel case word and return word count."""
wc = 1
for letter in s:
if letter.isupper():
wc += 1
return wc
|
dd539c4a6e3fd6b58813ada8953e46ed71a7ca69 | mankarali/PYTHON_EDABIT_EXAMPLES | /58_hot_pics_of_danny_deVito.py | 921 | 4.03125 | 4 | """
Hot Pics of Danny DeVito!
I'm trying to watch some lectures to study for my next exam but I keep getting distracted by meme compilations, vine compilations, anime, and more on my favorite video platform.
Your job is to help me create a function that takes a string and checks to see if it contains the following wor... |
a810001f3d1a51dad1568d6c92a195567fa03989 | schugh1/Python | /area.py | 231 | 4.15625 | 4 | def area(base, height):
'''(number, number) -> float
Return the area of triangle with given base and height.
>>>area(10, 40)
200.0
>>>area(3.4, 7.5)
12.75
'''
return base * height / 2
|
28fb88e7b04ba4fe7279f1c2008d86861f9b6061 | 462548187/python | /07_引用/hm_01_引用.py | 1,120 | 3.65625 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author : Sandy
@Version :
----------------------------------
@File : hm_01_引用.py
@Description :
@CreateTime : 2020/3/4 12:49 下午
@Software : PyCharm
-----------------------------------
@Modif... |
9ced3dacaf210f456ae7bb517a5361a2a1a85ab1 | Alonski/superbootcamp | /hangman_tdd/__init__.py | 1,571 | 3.5625 | 4 | # hangman.py
class GameOver(Exception):
def __init__(self, word):
# Call the base class constructor with the parameters it needs
print("Excepting", word)
Exception.__init__(self, 'The word was "{}"'.format(word))
class Hangman:
def __init__(self, secret_word, tries):
self.my_... |
e3029ff7bde01ddffe4091002c239ea1abe5d84d | salmanwahed/pythonic | /recursion/palindrome_recursive.py | 347 | 4.21875 | 4 | st = raw_input('Enter a string>>')
def is_palindrome(st):
""" Check if the given string is palindrome or not"""
if st == '' :
return True
else :
if st[0] != st[len(st)-1] :
return False
else :
st = st[1:-1]
return is_palindrome(st)
... |
dd67d9684f95eac0a7784d0679a235eb82f6cdf0 | IAMebonyhope/python-15-days-of-code | /day15.py | 1,523 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 10 03:51:46 2020
@author: HP
"""
def binary_adder(num1, num2):
"""
recieves binary numbers as integer input and returns the sum as an integer
"""
#first determine the longer bin_number
max_len = max(len(str(num1)), len(str(num2)))
#function to convert number... |
6aa470c0adc2215fc6a40e4a285c01ca104e66d8 | allisonlynnbasore14/CodingLearing | /Extra/chatper13.py | 6,173 | 3.828125 | 4 |
import string
import random
import requests
pride_and_prej_full = requests.get('http://www.gutenberg.org/files/1342/1342-0.txt')
print(pride_and_prej_full)
#the function skip_head will take a text as input and process everyline.
#It only breaks out of the loop when the condition of the heading being
#over is reached... |
607014d66a6f2c5d1686b843884878910617ea10 | juna21-meet/meet2019y1lab4 | /funturtle.py | 340 | 3.671875 | 4 | import turtle
turtle.shape('square')
turtle.shape('turtle')
finn=turtle.clone()
finn.shape('square')
finn.goto(100,100)
finn.goto(200,100)
finn.goto(200,0)
finn.goto(100,0)
finn.goto(100,100)
charlie=turtle.clone()
charlie.shape('triangle')
charlie.penup()
charlie.goto(-100,0)
charlie.pendown()
charlie.goto(-100,100)
... |
7938bd0e01c5e61647328d7a45957082b5ec1448 | eliasrilegard/grundprog | /eliasril-labb-4/extra2.py | 862 | 3.9375 | 4 | '''Om man upprepar en perfekt riffelblandning av
en vanlig kortlek med 52 kort ett antal gånger
så kommer man att återfå den ursprungliga
ordningen mellan korten.
Hur många gånger behövs?'''
cards = 52 # Jämt antal
def shuffle(arr):
arr1 = arr[:cards//2] # Split the array in two
arr2 = arr[ca... |
7eb229ecd99d55030747e1f0ee0d668a08756d38 | shahabalam3628/pyhton_program_and_notes | /loops/for/else_with_for.py | 110 | 3.578125 | 4 | for i in range(0,5):
print(i)
else:print("for loop completely exhausted, since there is no break."); |
c2c77da4c0439a295a92a2b756eb3519b2ed1c8f | huanmengmie/python_study | /base_test/dictionary&set/user_pw.py | 1,136 | 3.609375 | 4 | # -*- coding:UTF-8 -*-
"""模拟登陆注册功能"""
db = {}
def newUser():
prompt = 'enter your name: '
while True:
name = input(prompt)
if name in db:
prompt = 'name taken, try another: '
continue
else:
break
pwd = input('password: ')
db[name] = pwd
def ... |
ef425d66f0c464de1ee44d5d8d5a51ac36dd9dc1 | mjdecker-teaching/mdecke-1300 | /notes/python/classes.py | 6,007 | 4.3125 | 4 | ##
# @file classes.py
#
# Modules and packages in Python based on: https://docs.python.org/3/tutorial
#
# @author Michael John Decker, Ph.D.
#
# python namespace is a mapping from names to objects
# E.g.,builtin namespace (interpretter startup), global namespace (created when read in), function local namespace (on cal... |
e5b6846bccf0f14310f0df714795ae47fe82a478 | anirudhn18/msba-python | /Lab7/lab7ex2.py | 552 | 3.71875 | 4 |
import numpy as np
import csv
ranking_list = list()
with open('Files/Ranking.txt','r') as f:
for row in csv.reader(f):
ranking_list.append(row)
ranking_arr = np.array(ranking_list,dtype = str)
print ranking_arr
uni = raw_input('University Name: ')
print '{} is highly ranked in:'.format(uni)... |
4f31c3dd8ffd3793a345c483711f70279d663bc2 | abid-mehmood/SP_Labs | /Labs/Lab06/question 3.py | 149 | 3.984375 | 4 | n=input("Enter numbers: ")
#t=tuple(n)
li=n.split(",")
t=()
mylist=[]
for values in li:
mylist.append(values)
t=tuple(mylist)
print (t)
print (li)
|
999f0000bcbcdc91ec5c29c9a3d4048830fb92fd | andrekantunes/kaggle-courses | /04-pandas/01-practice-create-read-write.py | 1,346 | 4.03125 | 4 | # Practice 1 - Create, Read and Write
import pandas as pd
# Question 1 -
# Create a dataframe
# fruits = pd.DataFrame({ 'Apples': [30], 'Bananas': [21]})
fruits = pd.DataFrame([[30, 21]], columns=['Apples', 'Bananas'])
print(fruits)
# Question 2 -
# Create fruit sales dataframe
#fruits = pd.DataFrame({ 'Apples': [... |
baefd441e27aeb7808801db052f43058856e5097 | Jitha-menon/jithapythonfiles | /PycharmProject/Object oriented Programming-oops/Inheritance/multilevel person parent child.py | 466 | 3.71875 | 4 | class Mother:
def printa(self):
print('jitha is mother')
class Child(Mother):
def setval(self,name,age):
self.name=name
self.age=age
print(self.name,self.age)
class Father(Child):
def printc(self,name,age):
self.name=name
self.age=age
print(self.name,... |
fe0629d7172a58b42adec4ca09d600004e39d069 | quinb96/EnDec | /Encrypt_File.py | 532 | 4 | 4 | from cryptography.fernet import Fernet
import os
EncText = raw_input("Select file you want to encrypt: ")
os.path.abspath(EncText)
file = open("key.key", "rb")
key = file.read()
file.close()
with open(EncText, "rb") as f:
data = f.read()
fernet = Fernet(key)
encrypted = fernet.encrypt(data)
filename = raw_input("... |
7c363a30c8dc8fbdc4a41dc5ff7b5635b3ccb2c1 | vankhoakmt/pyHTM | /pyhtm/nodes/ImageSensorFilters/BaseFilter.py | 1,882 | 3.578125 | 4 | import random
class BaseFilter:
def __init__(self, seed=None, reproducible=False):
"""
Args:
seed: Seed for the random number generator. A specific random number
generator instance is always created for each filter, so that they
do not affect each other.
... |
4495332703f83411d72167da2e9395892ba6ef27 | maximillianus/machine-learning | /NLP/youtubeAPI_comments.py | 5,746 | 3.671875 | 4 | '''
This script is to test and play around with youtube API
using Python to scrape comments.
'''
# Libraries
from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.tools import argparser
import httplib2
from httplib2 import socks
import os
import sys
# Setup a proxy
## ANZ pro... |
ed08df05ccc35b794ff1f96df12b6edff8b72d4c | vitkhab/Project-Euler | /0045/solution.py | 1,116 | 3.96875 | 4 | #!/usr/bin/env python
from time import time
from math import sqrt
def hexagonal(n):
return n * (2 * n - 1)
def is_natural_number(n):
return n % 1.0 == 0 and n > 0
def solve_quadratic_equation(a, b, c):
root1 = (-1.0 * b + sqrt(b**2 - 4.0 * a * c)) / (2.0 * a)
root2 = (-1.0 * b - sqrt(b**2 - 4.0 * ... |
51a104d6042ed5c3233eea505b0fb0602af9c398 | i0nics/network-scanner-python | /portscanner.py | 6,378 | 3.921875 | 4 | #!/usr/bin/env python3
# Programmer: Bikram Chatterjee
# Port Scanner
# Description: This program identifies the status of transport layer ports. To accomplish this, this program uses the
# argparse module to get info about the desired ports, target, protocol etc from the user and then checks for any
# invalid port ran... |
a958847b53a4f976a5540417b93be9985555842a | Dayeon1233/Python_algorithm | /programmers_level2/멀쩡한사각형/20210627_멀쩡한사각형.py | 260 | 3.625 | 4 | import math
def solution(w,h):
gcd = math.gcd(w,h)
naw = w// gcd
nah = h//gcd
return w*h - (naw + nah -1) * gcd
#def solution(w, h): return w * h - w - h + gcd(w, h)
if __name__ == "__main__":
W = 8
H = 12
print(solution(W,H)) |
2ea6a5cce51827bba44d6e8bb4d3a7093b7656b0 | manuphatak/python-design-patterns | /strategy_pattern.py | 1,582 | 3.65625 | 4 | #!/usr/bin/env python
# coding=utf-8
TAX_PERCENT = .12
class TaxIN(object):
def __init__(self):
self.country_code = 'IN'
def __call__(self, bill_amount):
return bill_amount * TAX_PERCENT
class TaxUS(object):
def __init__(self):
self.country_code = 'US'
def __call__(self, b... |
feb12bc0f7973bbe2bed29dc601ef7b9288df621 | mathildaj/Python-Game | /Yahzee_Game/yahzee.py | 3,663 | 3.515625 | 4 | """
Planner for Yahtzee
Simplifications: only allow discard and roll, only score against upper level
"""
# Used to increase the timeout, if necessary
import codeskulptor
import math
#import poc_holds_testsuite
codeskulptor.set_timeout(20)
def gen_all_sequences(outcomes, length):
"""
Iterative function that e... |
05a54e838dc3992d0495d83cb8c1365aadf7d1a8 | PaulineMalova/Python | /Random Package/random2.py | 588 | 4.03125 | 4 | def List():
x=[[1,2,4],[9,6,5],[8,3,7]]
flat = []
for y in x:
for z in y:
w = z
flat.append(w)
flat.sort()
return (flat)
def fruit_dict():
fruits_list = ["mangoes","apples","oranges","bananas","pawpaws","melons"]
g = dict()
for fruit in fruits_list:
g[fruit] = len(fruit)
return g
def intere... |
7ee2288b3361978e3f02f0d30fbe1569154e1b12 | hangnguyen81/HY-data-analysis-with-python | /part03-e03_most_frequent_first/most_frequent_first.py | 1,420 | 4.125 | 4 | #!/usr/bin/env python3
'''
Write function most_frequent_first that gets a two dimensional array and an index c of a column as parameters.
The function should then return the array whose rows are sorted based on column c, in the following way.
Rows are ordered so that those rows with the most frequent element in colum... |
73bef6f02ee6a1cd78207ddec10947f486e6fbcd | Garric81/docker | /python-app/main.py | 293 | 3.921875 | 4 | import calendar
print('Добро пожаловать вк кадендарь\n')
year = int(input("Пожалуйста введите год:"))
month = int(input('Ведите номер любого месяца'))
print(calendar.month(year,month))
print('Всего хорошего') |
88d0fac8e9c94e3c1bf72a56b370e406af7f63cf | WillRDorval/ECOR1042 | /T099_P4_filter_edge.py | 6,125 | 4.03125 | 4 | """
Name: William Dorval
Student Number: 101187466
Class: ECOR1042
Section: D
"""
import math
from Cimpl import choose_file, load_image, copy, create_color, show, Image
def grayscale(input_image: Image) -> Image:
"""
copied from simple cimpl filters
"""
result = copy(input_image)
for x, y, (r, g... |
190e9611b092af55086323730b8cec3e7dcd2737 | ichko/algo-playground | /hackerrank/quadrant-queries.py | 5,410 | 3.765625 | 4 | #!/bin/python3
# Problem - <https://www.hackerrank.com/challenges/quadrant-queries/problem>
# cat quadrant-queries.inp | py quadrant-queries.py
import math
import os
import random
import re
import sys
# test_input = """4
# 1 1
# -1 1
# -1 -1
# 1 -1
# 5
# C 1 4
# X 2 4
# C 3 4
# Y 1 2
# C 1 3
# """
# _old_input = i... |
8fe09f7b4b499c80e5b973aaa3d226b21073b5f9 | choigabin/Certificate_Cospro | /cospro_winter2/day02/g18.py | 528 | 3.5625 | 4 | #이름에 특정문자가 들어가있는 사람을 구하는 함수 수정하기
def solution(name_list):
answer = 0
for name in name_list: #리스트의 길이만큼 포문 돌리기
for n in name: #각 이름의 길이만큼 포문 돌리기
if n == 'j' or n == 'k': #이름에 j, k가 있다면,
answer += 1 #answer에 1 증가
break
return answer
names = ['james', 'kim j... |
74a9fd89955b308cd5b16b9a2494adc7ad0d73ee | intelbala/Python-Mega-Project | /tKinterApp/script.py | 583 | 4.21875 | 4 | from tkinter import * #tkinter comes by default with Python 3.
"""
Tkinter GUI is made of of 2 components
1. Window
2. Widgets
"""
window = Tk()
def km_to_miles():
# print(e1_value.get())
miles = float(e1_value.get()) * 1.606
t1.insert(END,miles)
b1=Button(window, text="Execute",command=km_to_miles) ... |
2cfbc7be4980ddd814aa04153db9d45f215c75ac | SixuLi/Leetcode-Practice | /Second Session(By Frequency)/1192. Critival Connections in a Network.py | 2,884 | 3.71875 | 4 | # Solution 1: Brute Force(TLE)
# Remove each edge once a time, and use DFS to test whether the left graph is still
# connected.
# Time Complexity: O((E+V)E), where E is the number of edge in the graph
# Space Complexity: O(E+V), where V is the number of vertex in the graph
from collections import defaultdict
class ... |
8ddb8b39b814ae031e49a9ca998aab07127e8a33 | IlyaTroshchynskyi/python_education_troshchynskyi | /OOP_1/transport_additional_2.py | 7,051 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""calc
Implements the Transport and Engine
"""
import time
from abc import ABC, abstractmethod
class TransportInterface(ABC):
"""
Interface of Transport
"""
@abstractmethod
def start_drive(self):
"""
Interface start driving
"""
...
... |
8f7166006d6435a2d66f19282802263e44bd49a3 | Mumujane/PythonAdvance | /Decorator/MyFun.py | 234 | 3.53125 | 4 | class MyFun(object):
def __init__(self, fun):
self.fun = fun
def __call__(self, *args, **kwargs):
print("hello")
self.fun()
@MyFun # MyFun => test = MyFun(test)
def fun1():
print("test")
fun1() |
0d4139ea21ce09ed71663f9042b975cd2b6d281c | sol4ik/interview-techdev-guide | /Algorithms/Searching & Sorting/Counting Sort/counting_sort.py | 594 | 4.09375 | 4 | def countSort(array):
"""
Counting Sort algorithm implementation on Python.
:param array: array that need to be sorted
:return: resulting sorted array
"""
output = [0 for i in range(256)]
count = [0 for i in range(256)]
result = ["" for element in array]
for i in array:
resul... |
41657794cf9bb5c78cb161a17a241f094919eedc | WillDutcher/project-2-data-visualization | /exercises/cubes.py | 695 | 4.40625 | 4 | """
A number raised to the third power is a cube.
Plot the first five cubic numbers and then plot the first 5000 cubic numbers.
"""
import matplotlib.pyplot as plt
# First 5
x_values = range(1, 6)
y_values = [x**3 for x in x_values]
plt.style.use('fast')
fig, ax = plt.subplots()
ax.scatter(x_values, y_v... |
25913f1845e877961fed7536a07b4f4f85c41a83 | ZhouPan1998/DataStructures_Algorithms | /4-递归/04-绘制谢尔平斯基三角.py | 947 | 3.734375 | 4 | # -*- coding: utf-8 -*-
import turtle
pen = turtle.Pen()
pen.speed(0)
screen = turtle.Screen()
color_map = ['blue', 'red', 'green', 'white', 'yellow', 'violet', 'orange']
def draw_triangle(a, b, c, color='black'):
pen.color(color)
pen.up()
pen.goto(a)
pen.down()
pen.begin_fill()
pen.goto(b)... |
d15a029f8994e3e15b0c2796d4fe6726fefbd027 | uniyalabhishek/LeetCode-Solutions | /Python/1221. SplitAStringInBalancedStrings.py | 1,123 | 3.90625 | 4 | '''
Problem link: https://leetcode.com/problems/split-a-string-in-balanced-strings/
Balanced strings are those who have equal quantity of 'L' and 'R' characters.
Given a balanced string s split it in the maximum amount of balanced strings.
Return the maximum amount of splitted balanced strings.
Example 1:
Input: s ... |
3b3fb3673dcbc6594e9112056326dc40dcad6d74 | tonyyo/algorithm | /Letcode/中等/445_两数相加2.py | 875 | 3.703125 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
tail, curNode = None, None
carry = 0
if l1.val == 0:
return l2
if l2.val == 0:
return l1
... |
6d2a1f2c757a6cd5aec8ca96a6147227f009ce7a | pugzillo/kpop_song_analyses | /src/wikipedia_api_test.py | 592 | 3.578125 | 4 | #!/usr/bin/python3
"""
search.py
MediaWiki API Demos
Demo of `Search` module: Search for a text or title
MIT License
"""
import requests
S = requests.Session()
URL = "https://en.wikipedia.org/w/api.php"
TOPIC = "Izone"
SEARCHPAGE = "Izone Category: K-pop music groups"
PARAMS = {
"action": "q... |
fde7eef66c11b54b5d155c295a2a0f10cf50a888 | PapaGede/python-from-windows | /globalintro.py | 1,693 | 4.15625 | 4 | # import math
# radi=int(input("Please enter your radius \n"))
# print("You entered: " ,radi)
# surfaceArea= 4*math.pi*math.pow(radi,2)
# print("The surface area of the sphere is: ",surfaceArea)
# print("\n")
# volume= (4/3)*math.pi*math.pow(radi,3)
# print("The Volume of the sphere is: ",volume)
# import datetime
# p... |
96f76ccf8d4e777826704f837f49bac6b76b9d2a | govardhananprabhu/DS-task- | /amicable pair.py | 1,189 | 4.1875 | 4 | """
Amicable numbers are two different numbers so related that the sum of the proper divisors of each is equal to the other number. (A proper divisor of a number is a positive factor of that number other than the number itself.
In des
First and the last consists of two integers x and y.
Ot des
Print '1' if the... |
77c9c10089acb6bee61a05ed0e2c643ee4b77550 | alvi-subhan/Python-programms | /saylani 2.py | 142 | 3.609375 | 4 | x=input("type anything ")
lis=[]
for c in x:
lis.append(c)
lis=lis[::2]
#merging the items in list
merg=[''.join(lis[:])]
print (merg[0])
|
79d53fab5939cfa9d98887ca722aa1611e5b3c48 | CamiboKnuth/AES_Encryptor | /EncryptionTool.py | 7,810 | 3.6875 | 4 | #
# Imperative script for encrypting and decrypting files and directories
# using AES encryption. File and directory data is encoded in binary.
# File and directory names are encoded in base32 after converstion from binary.
#
import os
import sys
import hashlib
import base64
from Crypto.Cipher import AES
#default pas... |
4802baf8e3cac8665e9f021bb7374a5cc9b8797e | menard-codes/freeCodeCamp_Arithmetic_arranger | /arithmetic_arranger.py | 2,044 | 3.671875 | 4 | def searchFormat(problems):
if len(problems) > 5:
return 'Error: Too many problems.'
operations = [problem.split(' ') for problem in problems]
for operation in operations:
if '+' in operation or '-' in operation:
for content in operation:
if content.isdigit():
if len(content) > 4:
return 'Err... |
4e6e34320a4b774f09caaf7591556a9146ab2cef | colinxy/ProjectEuler | /Python/project_euler37.py | 1,254 | 3.90625 | 4 | # Truncatable primes
"""
The number 3797 has an interesting property. Being prime itself,
it is possible to continuously remove digits from left
to right, and remain prime at each stage: 3797, 797, 97, and 7.
Similarly we can work from right to left: 3797, 379, 37,
and 3.
Find the sum of the only eleven prim... |
58e1a8a5aa0fc10ee7e5b96a1ceee7858b9007eb | swayambhoo/Conv_Approx_to_LDR | /Python_Implementation/multCirculant.py | 1,100 | 3.765625 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 16 14:05:16 2017
@author: swayambhoo
"""
import numpy as np
from numpy.fft import fft, ifft
def multCirulantMatVec(C,X):
"""
Returns circulant matrix multiplication via standard matrix multiplication.
Inputs:
1) 'C' is the cir... |
4db0c40e4841e37037bb441b20ec40f417fe56ba | tanmaymudholkar/project_euler | /1-49/thirty_nine.py | 1,274 | 3.65625 | 4 | #!/usr/bin/env python
from __future__ import print_function, division
from math import ceil, sqrt
def getListOfSolutions(perimeter):
listOfSolutions = []
upperLimit = int(ceil(perimeter/(2+sqrt(2))))
for shortestSide in range(1,upperLimit):
if (perimeter*(perimeter-2*shortestSide))%(2*(perimeter-... |
1d2266a9321ab80a56c688fecdbd056ed51f12fd | Irstenn/pythonProject | /Exercises_project.py | 707 | 4.09375 | 4 | from datetime import datetime
user_input = input("Entre ton but et sa date de fin separes par une colonne \n")
# on decoupe ce que l'utilisateur rentre dans un tableau en champs
input_list = user_input.split(":")
goal = input_list[0]
deadline = input_list[1]
# print(datetime.datetime.strptime(deadline, "%d.%m.%Y"))
... |
292aab05543c981d82bac6c02f36bf77bb06d2fa | gouravshenoy/Artificial_Intelligence_P551 | /graph_traversal/graph_traversal.py | 10,218 | 3.765625 | 4 | __author__ = 'Gaurav-PC'
import os
import argparse
from queue import Queue
class Graph_Node:
"""
Class represents node in a graph
"""
def __init__(self, name, path, cost, level=None):
self.name = name
self.path = path
self.cost = cost
self.level = level
class Graph_... |
50f5ed65908338a53ea66b6f5508ea16e1105b9c | rr-/aoc | /2015/19/solve | 1,126 | 3.625 | 4 | #!/usr/bin/env python3
from pathlib import Path
def part1(replacements, pattern):
def generate():
for i in range(len(pattern)):
for left, right in replacements:
if pattern[i : i + len(left)] == left:
yield pattern[:i] + right + pattern[i + len(left) :]
... |
981cd3305ffde29f1fde2af8f50c3fa286f5a1e6 | sainatarajan/pix2shape | /diffrend/numpy/quaternion.py | 3,630 | 3.625 | 4 | import numpy as np
from diffrend.numpy.vector import Vector
class Quaternion(object):
"""
Usage:
1. Rotate a vector p about an axis q by angle theta:
Quaternion(angle=theta, axis=q).R * p [Here p is in homogeneous coordinates and can be 4 x N matrix]
2.
"""
def __init__(self, coeffs=N... |
1618939d0e3ab51ad32faee2e8fb423c879ac48b | shikhayadav2481996/python-basics-in-jupyter- | /PRANJAL SIR class1 jupyter .py | 3,710 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed May 13 01:34:27 2020
@author: sakshi
"""
# object or data types in python
# 1) tuple
# 2) list
# 3) dictionary
# 4) sets
# for runnning code in jupyter
# shift enter
# crtl enter
# alt enter
# if jupyter get hanged then go to kernal and then restart ... |
6a981cf9edcc19feba588c02766afee61fe83cef | sumithkumarEsap/Python | /Source/ASSIGNMENT-1/ARR.py | 625 | 3.90625 | 4 | import numpy as np
a = np.random.randint(1,20,15)
print("Original array:")
print(a)
s = sorted(a) # Sorting the array
print(s)
x = 0 # initializing the reference value
c = 1
d = {}
for i in s: #loop for iterating items in s
j = i+1
c = 0
for j in s: #Anothe loop for comparing one element with rest
... |
8bf8e1ddf06b015fc97661281c4e1ac5f6ad403c | MiguelElias/FundamentosPython | /Teste de perfomace 1/TP1-Exercicio8.py | 1,302 | 4.125 | 4 | #Escreva um programa em Python que receba três valores reais X, Y e Z,
#guarde esses valores numa tupla e verifique se esses valores podem ser os
#comprimentos dos lados de um triângulo e,
#neste caso, retorne qual o tipo de triângulo formado.
import turtle
x = int(input('Ditite o lado X do triangulo : '))
y = int(inpu... |
143e4b94d35f9673c38144d8fccb9196dc1ea26f | falcon-ram/PythonTest | /test34_classinheritance.py | 2,164 | 3.984375 | 4 | class Employee:
raise_amount = 1.04 # Class variable
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'
def fullname(self):
return f'{self.first} {self.last}'
def app... |
70676e04eb19ad7759ab036d7a0b933b2bc8d26d | dcthomson/Advent-of-Code | /2016/23 - Safe Cracking/part2rewrite.py | 729 | 3.578125 | 4 | import time
a = 12
b = 11
while True:
d = a
a = 0
while True:
c = b
while True:
a += 1
c -= 1
# print("a:", a, "b:", b, "c:", c, "d:", d)
if c == 0:
break
d -= 1
if d == 0:
break
b -= 1
c = b... |
bb577191d37059da67615c6a9b355f252bad7f46 | Oleg2394/python-fofanov | /4. Функции и модули/5. Вложенные функции и область видимости переменных/5. Вложенные функции и область видимости переменных.py | 972 | 3.546875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
greeting = "Hello from global scope"
def greet():
greeting = "Hello from enclosing scope"
def nested():
greeting = "Hello from local scope"
print(greeting)
nested()
# In[2]:
greet()
print(greeting)
# In[3]:
#list... |
5977e30776f36211e7dfaeb1765797875f374316 | youinmelin/practice2020 | /data_wrangling/deal_excel/sort_excel/find_files.py | 1,229 | 3.96875 | 4 | import os
"""
os.walk(top, topdown=True, onerror=None, followlinks=False)
我们一般只使用第一个参数。(topdown指明遍历的顺序)
该方法对于每个目录返回一个三元组,(dirpath, dirnames, filenames)。
第一个是路径,第二个是路径下面的目录,
第三个是路径下面的非目录(对于windows来说也就是文件)
"""
def pick_file(key_word=''):
"""
find files in current path(includes subfolde... |
d6157464b8a9962b1cfafa9e7b74344677b31ea6 | stilyantanev/Programming101-v3 | /Application/3-Caesar-cipher/caesar_cipher.py | 486 | 4.15625 | 4 | def caesar_encrypt(str, n):
n %= 26
char_list = list(str)
for char in char_list:
if(ord(char) + n) <= 122 or (ord(char) + n) <= 90:
char = chr(ord(char) + n)
elif(ord(char) + n) > 122 or (ord(char) + n) > 90:
char = chr(ord(char) + n - 26)
print(char, ... |
c24aea0c007a1ad8791043995858d503b5fa129b | vijayvardhan94/CS-325-Projects | /masxsubarray.py | 560 | 3.5625 | 4 | input_data = [1,2,3,-9, 5, 7, -99, 2, 8]
def max_sub_array(input_data):
global_max = 0
for i in range(len(input_data)+1):
for j in range(len(input_data)+1):
iter_max = sum(input_data[i:j])
print(iter_max, input_data[i:j])
if iter_max > global_max:
glob... |
71c76eed8a09e3b1447d485f3cac200180e4d89a | n57uctf/yetictf-2021-school | /PPC/Re/build/app/SquareCrosswordGenerator.py | 2,090 | 3.609375 | 4 | import random
from RegexSequenceDirector import *
import RegexGenerators
symbols = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
def random_word(len):
"""
:param len: The length of the word
:return: string: Random word, containing a set of the symbols's elements
"""
return ''.jo... |
c1f8bd7dbace33ef53ab32739775b0b59e589b55 | joycecodes/problems | /leetcode/890. Find and Replace Pattern.py | 1,248 | 4.21875 | 4 | """
You have a list of words and a pattern, and you want to know which words in words matches the pattern.
A word matches the pattern if there exists a permutation of letters p so that after replacing every
letter x in the pattern with p(x), we get the desired word.
(Recall that a permutation of letters is a bijectio... |
1ebf9f377f57c8a5c3cb832a052380b6068c4779 | RicardoAriel09/Exercicios-em-python | /Curso em Video/Exercício 72.py | 347 | 3.90625 | 4 | t = ("zero", "um", "dois", "três", "quatro", "cinco", "seis", "sete","oito", "nove", "dez", "onze", "doze", "treze", "quartoze", "quinze", "dezeseis", "dezessete", "dezoito", "dezenove", "vinte" )
num = int(input("Digite um número inteiro: "))
for cont in range(0, len(t)):
if num == cont:
print(f"O número d... |
214d2994fac5981b513a2b4f61b3715495a87a61 | dannymulligan/Project_Euler.net | /Prob_135/prob_135a.py | 3,739 | 3.515625 | 4 | #!/usr/bin/python
# coding=utf-8
#
# Project Euler.net Problem 135
#
# Determining the number of solutions of the equation
# x^2 − y^2 − z^2 = n.
#
# Given the positive integers, x, y, and z, are consecutive terms of
# an arithmetic progression, the least value of the positive integer,
# n, for which the equation, ... |
e6fe9dd1e1cca10ca5f80a03b3841cc26af521f1 | raisok/Gui_learning | /Canvas.py | 824 | 3.59375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: Canvas.py
Description :
Author : yueyao
date: 2020/1/7
-------------------------------------------------
Change Activity:
2020/1/7:
---------------... |
fec2502445a7d598e377ec0bd947094d1fd37361 | michaelzhou88/Amazon-Price-Tracker | /scraper.py | 3,681 | 3.796875 | 4 | """
A automation script used to keep track of price drops of products sold on www.amazon.co.uk
Code written by Michael Zhou
"""
# Imported libraries used to:
# Make HTTP requests
import requests
# Extract data out of HTML and XML files
from bs4 import BeautifulSoup
# Simple Mail Transfer Protocol library
import sm... |
475fdcfd6c0f9ef7fc954ded43176187f8cdabea | shwaldemar/python-scrabble-list-dictionary-enumeration-practice | /scrabble.py | 1,791 | 3.921875 | 4 | letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
points = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 4, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10]
letter_to_points = {
key:value
for key,value
in zip(letters, points)
}
letter_to_... |
0c148c8b56a5c12f4e5bf9e79ba6fedc633a6eea | felipemcm3/ExerPython | /Pythonexer/ExerPython/aprendendopython/ex062.py | 379 | 3.734375 | 4 | p = int(input('Informe o primeiro termo'))
r = int(input('Informe a razão da progressão aritimetica'))
aux = 10
cont = 0
print('Imprimindo os 10 primeiros termos:')
while aux != 0:
print(p, end = ' ')
p += r
aux -= 1
cont += 1
if aux == 0:
aux = int(input('\nInforme mais quantos termos quer ... |
bd0c7aa56d5d34585eda399698dd610e8c2a5ee7 | Gamefalcon24/Grade-Calculator | /main.py | 2,525 | 3.640625 | 4 | import tkinter
from tkinter import *
import tkinter.messagebox
from tkinter.font import Font
main = Tk()
main.config(background='#4d4949')
main.title('Grade Calculator')
#Fonts
bigFont = Font(
family="Microsoft YaHei",
size=24
)
# --- VARS ---
GradeBox1 = tkinter.DoubleVar()
GradeBox2 = tkin... |
0ee26bab5cd35f0ff082004efb675a43a89e37c3 | kafeikele/reboot | /first/raw_input_and_input.py | 1,159 | 4.3125 | 4 | #_*_coding:utf8_*_
print 'hello world'
#print "What your name?"
myname = input('what your name: ')
print "Nice to meet you , " + myname
print "Nice to meet you , too"
print "The length of your name is: "
print len(myname)
print "What is your age?"
myage = input('please input: ')
print "You will be " + str(myage+ 1) + ... |
a08269b0f85d8bfbbe8f5d581d7ca965956b9aa0 | Meao/py | /repl/3-2LogicTables.py | 2,211 | 4.0625 | 4 |
# Кривцун Марина, группа ИВТ2-3
# 21.09.2018, Лабораторная работа 2
# Нужно сделать: конъюнкция, дизъюнкция и импликация
"""
выводить таблицы истинности для трех операций: конъюнкция, дизъюнкция и импликация
"""
print('Отрицание')
print('–'*6)
print(chr(124) + "A"+chr(124)+ chr(172)+'A' + chr(124))
a = True
print(c... |
f2828f50b0d75ef6503e7d3a3a91b50f623ffecc | patsess/dash-practice | /dashpractice/data.py | 425 | 3.5 | 4 |
import pandas as pd
def get_data():
# TODO: docstr
df = pd.read_csv(
'https://gist.githubusercontent.com/chriddyp/' +
'5d1ea79569ed194d432e56108a04d188/raw/' +
'a9f9e8076b837d541398e999dcbac2b2826a81f8/' +
'gdp-life-exp-2007.csv', index_col=0)
df.index.name = 'country_id'
... |
8d0bf8306f468d6f3b1a36a6566479d1ea691074 | muhammad-masood-ur-rehman/Skillrack | /Python Programs/only-fibonacci.py | 788 | 4.0625 | 4 | Only Fibonacci
N integers are passed as input. The program must print only the integers that are present in the Fibonacci series.
Input Format: The first line contains N. The second line contains N integers separated by a space.
Output Format: Integers that are part of the Fibonacci series in their order of occurrence... |
003e0142692a4c96192b53fecaf6ee98217e3af7 | MahsanulNirjhor/Python_training | /list.py | 174 | 3.75 | 4 | my_list = ['January','February','March']
print(my_list)
print(my_list[2])
#Add
my_list.append('April')
print(my_list)
#Remove
my_list.remove("April")
print(my_list) |
cd405ccb38384d57ea3f09be26c9b08ab69e44e1 | mohamed-elsayed/python-scratch | /oop.py | 17,836 | 4.25 | 4 | # =================================================
################ OOP ####################
# =================================================
# Objective
# Define what OOP
# Understand encapsulation and abstraction
# Create classes and instances ans attach methodsand properties to each
# What is OOP ?... |
1f02f34ba2044a51d65cbc5ba9b73e7468a4ff63 | lipioliveira/old | /Exercicios Curso em video Python/022.py | 384 | 4 | 4 | nomeCompleto = str(input("Digite seu nome completo:")).strip()
print("Analisando seu nome...")
print("Seu nome em maiúsculo é {}".format(nomeCompleto.upper()))
print("Seu nome em minúsculo é {}".format(nomeCompleto.lower()))
print("Seu nome tem {} letras".format(len(nomeCompleto)-(nomeCompleto.count(" "))))
print("Seu ... |
ea02b13319884d20a0c7d57a9a99639ec36bf7fb | mymleo/myLintcode | /Algorithm/2 - Breadth First Search/Required/Solution in Python/number_of_islands.py | 1,848 | 4.03125 | 4 | """Description
Given a boolean 2D matrix, 0 is represented as the sea, 1 is represented as the
island. If two 1 is adjacent, we consider them in the same island. We only
consider up/down/left/right adjacent.
Find the number of islands.
"""
"""Example
Example 1:
Input:
[
[1,1,0,0,0],
[0,1,0,... |
c4536692a3f608bd051d0b8a24958619f47cf965 | wangzihao0214/Leetcode | /48. Rotate Image/main.py | 657 | 3.515625 | 4 | class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
x_center = (n - 1) / 2
i = 0
while i < x_center:
length = n - i * 2
for... |
7bb4cba3e209e6775c32754b693dc279bb4050f9 | ppmx/sudoku-solver | /sudoku.py | 4,069 | 3.96875 | 4 | #!/usr/bin/env python3
"""
A1 A2 A3 | A4 A5 A6 | A7 A8 A9
B1 B2 B3 | B4 B5 B6 | B7 B8 B9
C1 C2 C3 | C4 C5 C6 | C7 C8 C9
–––––––––+––––––––––+–––––––––
D1 D2 D3 | D4 D5 D6 | D7 D8 D9
E1 E2 E3 | E4 E5 E6 | E7 E8 E9
F1 F2 F3 | F4 F5 F6 | F7 F8 F9
–––––––––+––––––––––+–––––––––
G1 G2 G3 | G4 G5 G6 | G7 G8 G9
H1 H2 H3 | H4... |
bf2891e4a5079c08948b7b8c6f86647a9fc81f92 | Marxinchina/high-accuracy-algorithm | /huge_int.py | 8,540 | 3.765625 | 4 | """
实现高精度大数的四则运算
"""
PRECISION = 500
# 首先创建高精度大数类
class HugeInt:
def __init__(self, s='0', precision=PRECISION): # 默认数是0
self.negative = ''
# self.string = s
self.nums = [0 for i in range(precision)]
self.len = len(s)
if s[0] == '-':
self.str2huge... |
f08600d896c00e8519d79ea19bcc9574d9312f5a | navazl/cursoemvideopy | /ex057.py | 195 | 3.984375 | 4 | sexo = str(input('Digite o seu sexo M/F: ')).strip().upper()
while sexo not in 'MF':
sexo = str(input('Dados invalidos digite novamente M/F: ')).strip().upper()
print(f'Sexo {sexo} registrado!') |
7a800030439ef63663b82f337c03c9d24356a836 | borislavstoychev/Soft_Uni | /soft_uni_fundamentals/final_exam_preparation/04 April 2020 Group 2/1_password.py | 986 | 3.875 | 4 | def take_odd(l):
result = ""
for i in range(1, len(l), 2):
result += l[i]
print(result)
return result
def cut(l, i, length):
result = l[:i] + l[i + length:]
print(result)
return result
def subst(l, substring, substitute):
result = l.replace(substring, substitut... |
0f28125412b260e61926203ff51b43c52b3d72ff | daniel-reich/ubiquitous-fiesta | /iLLqX4nC2HT2xxg3F_9.py | 187 | 3.515625 | 4 |
def deepest(lst):
res = []
for x in lst:
count = 1
for y in str(x):
if y=='[':
count+=1
if y==']':
break
res.append(count)
return max(res)
|
7a3375663e4860c589a06da5ebd9276a819a7bab | RHaddlesey/Python | /Python Code Complete/q6.py | 1,688 | 4.09375 | 4 | #Using instead of adding task 1 and 2 in here
words = ['#+/084&"', '#3*#%#+', '8%203:', ',1$&', '!-*%',
'.#7&33&', '#*#71%', "&-&641'2", '#))85', '9&330*']
clues = ['A#', 'M*', 'N%']
complete = ['ACQUIRED', 'ALMANAC', 'INSULT', 'JOKE',
'HYMN', 'GAZELLE', 'AMAZON', 'EYEBROWS',
'AFF... |
ed51b061d2c95e6692c665601dd1a0fc1d18b344 | gxgarciat/Playground-CSwithPy | /U1_E2.py | 310 | 4.125 | 4 | def main():
"""
Convert the following into code that uses a while loop.
prints Hello!
prints 10
prints 8
prints 6
prints 4
prints 2
:return:
"""
print('Hello!')
i = 10
while i > 0:
print(i)
i = i - 2
if __name__ == "__main__":
main() |
93456178790a91bae2320c41b5a21932c6d03d05 | yopiyama/Cipher | /math/mymath.py | 2,246 | 3.875 | 4 | #! user/bin/env python3
# codingg: utf-8
"""
My Math package
"""
import math
import random
def ex_euclid(a, b):
"""
Extended Euclidean algorithm
a * x + b * y = gcd(a, b)
Parameters
----------
a : INT
a
b : INT
b
Returns
-------
y : INT
y
"""
... |
8b8ddd5901862ad30b4cbd763f4f1dbec02f78c5 | mertcaliskan01/Flask | /Predict/trim_dataset.py | 426 | 3.59375 | 4 | """
Assume our dataset has 53 samples and our batch size is 25. Then, we have to remove(trim) the remaining samples.
This function does just that.
"""
def trim_dataset(matrix, batch_size):
"""
trims dataset to a size that's divisible by BATCH_SIZE
"""
no_of_rows_drop = matrix.shape[0] % batch_... |
ae112c77a283108dc8be480c6dacf2af00bb17df | sial-ari/project_euler | /problem_7.py | 215 | 3.75 | 4 | num = 1
i = 2
def isPrime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
while num < 10001:
i += 1
if isPrime(i):
num += 1
print i
|
7bdb4a419f8d680dc38c124e818c1111ddfa9c6b | nhantrithong/CP1404Programming | /Powerpoint Activities/Ppt8.py | 847 | 3.921875 | 4 | #Write a loop that prints Olympic years (every 4 years) from 1990 to now
#def main():
#for i in range(1990,2019,4):
#print(i)
#main()
#Write a function that returns the average value of a list of numbers passed into it
#import random
#list = []
#def main():
#for i in range(10):
#generated = r... |
47c16c165668bfaa5986e7a705933c31ba8325ff | gleissonbispo/python-curso-em-video | /Ex011/Ex011.py | 381 | 3.71875 | 4 | print('{:#^40}'.format(' Medidor de Tinta '))
altura = float(input('Qual a alura da sua parede?'))
largura = float(float(input('Qual a altura da sua parede?')))
m2 = altura * largura
tinta = m2 / 2
print(f"""\nSua parede tem {altura:.2f}m de altura e {largura:.2f}m de largura totalizando {m2:.2f}m2
Dessa forma serão... |
18cf7907e2d03c81fa9bb36891220286d0c5fca1 | darkterbear/advent-of-code | /2019/day1/day1p2.py | 205 | 3.65625 | 4 | file = open('./input')
def findFuel(mass):
raw = mass // 3 - 2
if raw <= 0:
return 0
return raw + findFuel(raw)
sum = 0
for line in file:
sum += findFuel(int(line))
print(sum)
|
b42a8a2ca43248aefe5a23cd301203d3b9e49113 | EYcab/Python-Codes- | /python/Python reinforced/WordOrder.py | 744 | 3.953125 | 4 | __author__ = 'Chenxi'
#!/usr/bin/python
import sys
if sys.version_info[0]>=3: raw_input=input
# h = {} is another good way to declare a dictionary h is set
h={}
for i in range(int(raw_input())):
s=raw_input().rstrip()
if s not in h:
h[s]=[i,0]
h[s][1]+=1
print(len(h))
#print h.items()
# result: [(... |
fb69db928b57a456540548bb204b9f9fa117d644 | RakeshKumar045/DataStructures_Algorithms_Python | /Data Structures - Arrays/Merge Sorted Arrays.py | 606 | 3.921875 | 4 | # def mergesortedarr(a,b):
# x=a+b
# x.sort()
# return x
# a=[1,2,3,4]
# b=[3,7,9,12]
# qw=mergesortedarr(a,b)
# print(qw)
# In interview we must solve only like this
def mergesortedarr(a, b):
if len(a) == 0 or len(b) == 0:
return a + b
mylist = []
i = 0
j = 0
while i < len(a) and j < ... |
469c3775a8ad3f751bbe31b3a133c6dbdc6eb89c | Hugo-Oliveira-RD11/aprendendo-PYTHON-iniciante | /download-deveres/para-execicios-curso-em-video/exe056.py | 1,133 | 3.765625 | 4 | from time import sleep
conta = 0
contaidade = 0
for pessoas in range(1, 5):
print('-' * 10, end='')
print('{}° PESSOA'.format(pessoas), end='')
print('-' * 10)
nome = input('qual e o seu nome :')
idade = int(input('qual e a sua idade :'))
sexo = input('qual e o seu sexo ( F / M ):').lower()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.