blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
d840cb2ca2cc12e6a4f065e40085098efc5f4f45 | ausaafnabi/30DaysOfAlgorithms | /GreedyAlgorithm/Day_3/GraphColouring.py | 1,188 | 3.6875 | 4 |
class Graph:
def __init__(self,edges,N):
self.adj = [[] for _ in range(N)]
# add edges to undirected graph
for (src,dest) in edges:
self.adj[src].append(dest)
self.adj[dest].append(src)
def colorGraph(graph,colors,N):
# stores color assigned to each V
resul... |
839891e58fdceb5afeac05012de0e001e86c1cb0 | adc-code/Math_Various | /LinearRegression/LinearRegression_SciKitLearn.py | 1,283 | 3.765625 | 4 | #
# LinearRegression_SciKitLearn.py
#
# Calculates simple linear regression; slope and intercept of line of best with along with R^2
#
# Usage: > python LinearRegression_SciKitLearn.py <InputFile>
#
from sklearn import linear_model
from sklearn.metrics import mean_squared_error, r2_score
import numpy as np
import sys... |
508a2a4d467b6314b54a50fac957df3c9a2c0742 | Aman-gusain1998/UML-university-management-system- | /core_utils/ums_utils/teacher.py | 1,126 | 3.625 | 4 | class Teacher:
def __init__(self,cursor):
self.cursor=cursor
def get_teacher_name(self,roll_no):
self.cursor.execute("select teacher_name from teacher where student_roll_no="+roll_no)
teachername=self.cursor.fetchall()
return teachername
def get_teacher_department(self,roll... |
9eeabc5f5c5d92f49b3598733434087ba4cc502a | jtlai0921/euler. | /scratch/closure_fun.py | 2,195 | 3.65625 | 4 | #!/usr/bin/env python
from itertools import tee, takewhile, count, ifilterfalse #, ifilter
from math import sqrt
def isprime(number):
if number<=1 or number%2==0:
return False
check=3
maxneeded=number
while check<maxneeded+1:
maxneeded=number/check
if number%check==0:
... |
c08617a8cce802138e31c87022295217d354a781 | amr-ayoub/lin_alg | /Lin_Alg/src/vector/vect.py | 2,359 | 3.515625 | 4 | import math
class Vector(object):
def __init__(self, coordinates):
try:
if not coordinates:
raise ValueError
self.coordinates = tuple(coordinates)
self.dimension = len(coordinates)
except ValueError:
raise ValueError('The coordinates... |
7ddd3037499aa907eb976ee304d40d8380a88f4a | marvincosmo/Python-Curso-em-Video | /ex069 - Análise de dados do grupo.py | 947 | 3.953125 | 4 | """ 69 - Crie um programa que leia a idade e o sexo de várias pessoas. A cada pessoa cadastrada, o programa deverá
perguntar se o usuário quer ou não continuar. No final, mostre:
A) quantas pessoas tem mais de 18 anos.
B) quantos homens foram cadastrados.
C) quantas mulheres tem menos de 20 anos. """
m18 = h = mm20 = ... |
f56e20d7a5bf92d0ee777b212bc80435cac4246a | Avani18/Hackerrank-Python | /12. Python Functionals/Map_And_Lambda_Function.py | 270 | 4.09375 | 4 | cube = lambda x: x**3
def fibonacci(n):
# return a list of fibonacci numbers
l = [0,1]
for i in range(2,n):
l.append(l[i-2] + l[i-1])
return(l[0:n])
if __name__ == '__main__':
n = int(input())
print(list(map(cube, fibonacci(n))))
|
d0b87f8441341b246176762bac801890eee6053b | FranzDiebold/project-euler-solutions | /src/p026_reciprocal_cycles.py | 2,579 | 3.875 | 4 | """
Problem 26: Reciprocal cycles
https://projecteuler.net/problem=26
A unit fraction contains 1 in the numerator.
The decimal representation of the unit fractions with denominators 2 to 10 are given:
1/2 = 0.5
1/3 = 0.(3)
1/4 = 0.25
1/5 = 0.2
1/6 = 0.1(6)
1/7 = 0.(142857)
1/8 = 0.1... |
25bb2fc7c26d921ee4aacff98c7ca4fa86441b3b | mukundkri/testing | /testcase.py | 2,718 | 3.90625 | 4 | def reverse(lst):
return lst[::-1]
def test_reverse1():
input = [1, 2, 3, 4]
output = [4, 3, 2, 1]
ev = reverse(input)
if output == ev:
return True, None
else:
return False, "Four Element Case failed"
def test_reverse2():
input = [1, 2, 3, 4, 5]
output = [5, 4, 3, 2... |
076e692318b4c368c0cb43d33a0bc5dea670ffdf | julie98/Python-Crash-Course | /chapter_9/dice.py | 406 | 3.53125 | 4 | from random import randint
class Die():
def __init__(self,sides = 6):
self.sides = sides
def roll_die(self):
return randint(1, self.sides)
results = []
die_one = Die(10)
for roll_number in range(10):
result = die_one.roll_die()
results.append(result)
print(results)
results = []
die_two = Die(20)
for roll_nu... |
d0269081fa81fbf2e95500754dc5d370ec5d5b89 | ZhiyuSun/leetcode-practice | /practice/practice.py | 1,206 | 3.53125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
class Solution(object):
def find_next_node(self, current_position, step):
master = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,
21,22,23,24,25,31,32,33,1]
branch = [26,27,28,29,30]
if current_position == 19 and step > 0:
... |
55a943281093be07a7a6224f702b4ec0cc734ea5 | methane/gdd11 | /hitori/hitori.py | 1,186 | 3.796875 | 4 | #!/usr/bin/env python
# coding: utf-8
# ただの深さ優先探索.
# 無限ループしないように、 /2 操作で変化がない場合を切る.
def read_input():
problem = []
with open('input.txt', 'r') as f:
N = int(f.readline().strip())
i = 0
while True:
l = f.readline().strip()
if not l:
if i != N:
... |
3a2d54737ae39ab4ab6f1b086895865dab6b625c | ny1103/USTC | /leetcode-plugin/cn/[4]寻找两个有序数组的中位数.py | 2,062 | 3.734375 | 4 | # -*- coding: utf-8 -*-
# 给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。
#
# 请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。
#
# 你可以假设 nums1 和 nums2 不会同时为空。
#
# 示例 1:
#
# nums1 = [1, 3]
# nums2 = [2]
#
# 则中位数是 2.0
#
#
# 示例 2:
#
# nums1 = [1, 2]
# nums2 = [3, 4]
#
# 则中位数是 (2 + 3)/2 = 2.5
# for循环遍历两个列表失败—— ValueError: too many va... |
e462fa37aacc83108b2489e4cf116542abff5c1a | hmnathel/nyc-mhtn-ds-071519-lectures | /week-1/Calculator.py | 1,584 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import math
class Calculator:
def __init__(self, data):
assert all(isinstance(x, (int, float)) for x in data), "list can only be numbers"
self.data = data
self.__update()
def __update(self):
... |
9261365e4726614ac27f96caa7fb15f39e3ffa37 | Giantcatasaurus/All-my-projects | /Quiz.py | 838 | 3.9375 | 4 | a = 0
print("Hi! I am Quiz-Bot. Initializing quiz...")
print("If there are any word answers, capitalize it.")
answer1 = input("What is 1 + 1? ")
if answer1 == "2":
print("Correct!")
a = a + 1
else:
print("Wrong!")
answer2 = input("What is 1 + 4? ")
if answer2 == "5":
print("Correct!")
a = a + 1
else... |
44708e742eccc8312fb712a9005d0bd8676b4202 | MarcosLazarin/Curso-de-Python | /ex049b.py | 256 | 3.96875 | 4 | #Refazer o ex009, mostrando a tabuada de um número que o usuário escolher, só que agora utilizando o laço FOR.
n = int(input('Digite um número que você queira saber a tabuada: '))
for a in range(1, 11):
print('{} x {} = {}'.format(n, a, n * a))
|
fa64141ea139a1e457bbf94956ea9957651b2967 | e1four15f/python-intro | /lesson2/ExC.py | 132 | 4 | 4 | n = int(input())
def factorial(n):
curr = 1;
for i in range(1, n+1):
curr *= i
return curr
print(factorial(n)) |
963418ba1d8f9a76a80b01c765c38ab363891e36 | NHlaing/Programming_Basic_With_Python | /Chapter2/Area.py | 231 | 4.28125 | 4 | #READ height of rectangle
#READ width of rectangle
#COMPUTE area as height times width
height = input("Enter Height Of Rectangle: ")
width = input("Enter Width Rectangle: ")
area = int(height) * int(width)
print("Area is ", area)
|
9b0d7d8a9ba5fde81ca5b2bb4a24927404d8043d | zoomie/algorithms_practise | /python/stack.py | 469 | 3.8125 | 4 |
class Stack:
def __init__(self, first_element):
self.data = []
self.current_min = first_element
def add(self, item: int):
if item < self.current_min:
self.current_min = item
self.data.append(item)
def pop(self) -> int:
return self.data.pop()
def mi... |
4e7f7bdf3ee0e028460b65a204cddc20492b40c5 | tanyinqing/Python_20170902 | /h11/h11_shape.py | 751 | 3.84375 | 4 |
class Shape(object):
def area(self):
print('in shape:area...')
pass
def perimeter(self):
print('in Shape:perimeter...')
pass
class Circle(Shape):
def area(self):
print('in Circle:area...')
# 继承父类
class Square(Shape):
def print_info(self):
print('a new de... |
dcc136f8079cefa4581e841cffba3ca6a115e94e | bhavaniravi/caching-in-python | /lru_caching_example/lru_caching.py | 902 | 3.75 | 4 | from functools import lru_cache
# 1. A simple example
@lru_cache(maxsize=32)
def add(a, b):
return a + b
numbers = [(1, 2), (2, 3), (3, 4), (1, 2), (1, 2)]
[add(a, b)for a, b in numbers]
print (add.cache_info())
# 2. Cache invalidation example
a = [10, 11, 12, 13, 14, 15, 16]
@lru_cache(maxsize=32)
def ... |
10d65e3a11418067f820ac524984cff643066205 | havu73/discoverHomomorphisms | /word.py | 9,647 | 3.734375 | 4 | import letter
import root_list
import copy
class Word:
def create_root_list():
a=letter.Letter("a",1)
b=letter.Letter("b",1)
c=letter.Letter("c",1)
d=letter.Letter("d",1)
A=letter.Letter("a",-1)
B=letter.Letter("b",-1)
C=letter.Letter("c",-1)
... |
cb3b153fea4f0e6d0a92c235e4c14e6dd4846724 | Laurasoto98/TicTacToe | /tic_tac_toe_random.py | 5,189 | 4.0625 | 4 | """
Course: Python for Scientist (Part-I)
"""
#%%
def author():
return 'Laura Soto'
#%%
import random
import copy
# %%
def DrawBoard(Board):
rows=len(Board)
columns=len(Board[0])
if rows!=3 or columns!=3:
print('No valid')
print(' --+--+--')
for i in range(0,rows):
... |
9af4a1c052bd492b2a268032cc794681ec423062 | matiasmasca/python | /ucp_intro/031_strings.py | 2,144 | 4.4375 | 4 | frase = "Curso de Python"
print(frase)
# Es posible realizar operaciones con cadenas. Por ejemplo, podemos "sumar" cadenas añadiendo una a otra. Esta operación no se llama suma, sino concatenación y se representa con el signo +.
# Concatenación
print(frase + " esta muy bueno")
print("muy " + "pero " + "muy " + "bueno... |
9caa89350a0bf56232a9936a28813aa06752caac | ravinaNG/python | /Function/check_element.py | 632 | 4.09375 | 4 | def check_numbers(number1, number2):
print " << Of integer >> "
if(number1 % 2 == 0 and number2 % 2 == 0):
print "Both numbers are even."
else:
print "Both numbers are not even."
print "--------------------------------------"
check_numbers(12, 13)
def check_numbers_list(list1, list2):
length = len(list1)
a ... |
fe654a74c36bf234ee0d07b1084df37c0f6fd48b | DanielleRenee/python_practices | /danielle-oo.py | 3,091 | 4.25 | 4 | class Book(object):
"""A Book Object."""
def __init__(self, title, author, pub_yr='Unknown'):
self.title = title
self.author = author
self.pub_yr = pub_yr
def __repr__(self):
return '<Book. Title: %s.>' % (self.title)
class Library(object):
"""A collection of book objec... |
9421a1937eca823adf0f2384d9f8e9304189a00a | kevinktom/Advent-of-Code-2020 | /Day 16/ticket_translation.py | 5,737 | 3.578125 | 4 | def create_input_array():
filepath = 'input.txt'
input_numbers = []
with open(filepath) as fp:
lines = fp.readlines()
cnt = 0
group = []
for line in lines:
if line == "\n" and group:
input_numbers.append(group)
group = []
... |
0d5c3fc94c5e462609b24bff0cf25137c20b03b6 | Janepoor/Python-Practice- | /sample2.py | 1,590 | 3.609375 | 4 | '''input
IBM cognitive computing|IBM "cognitive" computing is a revolution|IBM cognitive computing| 'IBM Cognitive Computing' is a Revolution?
"Computer Science Department"|Computer-Science-Department"|the "computer science department"
'''
import string
input1=' IBM cognitive computing |IBM "cognitive" computing ... |
9da82081778ca244fe0bf755838a6e1259aceeb2 | Constantine19/cs265-fall-2017 | /assn4/accounts | 5,597 | 3.765625 | 4 | #!/usr/bin/python
'''
CS 265 Assignment 4
Author: Konstantin Zelmanovich
Date: 12/11/2017
Description: This is a command-line utility that lists bank account information and transactions such as deposits and withdrawals
Platform: Python 2.7.12 on tux4.cs.drexel.edu
'''
import os
import sys
from datetime import date
... |
541c4d146cd22c9b19e0a6fe03379a7a6d6d78de | IamJenver/mytasksPython | /follow_rules.py | 590 | 3.796875 | 4 | # На вход программе подается натуральное число n. Напишите программу,
# которая выводит числа от 1 до n включительно за исключением:
# чисел от 5 до 9 включительно;
# чисел от 17 до 37 включительно;
# чисел от 78 до 87 включительно.
n = int(input())
for i in range(1, n + 1):
if 5 <= i <= 9 or 17 <= i <= 37 or 78 <... |
76ce336f19035f376335c517f261f64d9eff0fdd | imgomez0127/daily-programming | /algorithm-implementations/segmented_sieve.py | 820 | 3.53125 | 4 | import math
def sieve(a, b):
is_prime = [not (i in (0, 1)) for i in range(int(b**0.5)+1)]
high_primes = [True for _ in range(b-a+1)]
for i in range(int(b**0.25)+1):
if is_prime[i]:
for j in range(i**2,int(b**0.5)+1,i):
is_prime[j] = False
low_primes = [i for i,primal... |
0cb919e9153abeab0434615666cda2dd0b78f107 | magik2art/DZ_9_Pavel_Mamaev | /task3.py | 722 | 3.65625 | 4 | class Worker:
def __init__(self, name, surname, position, wage, bonus):
self.position_name = name
self.position_surname = surname
self._position = position
self.position_income = {"wage": wage, "bonus": bonus}
class Position(Worker):
def __init__(self, name, surname, position... |
7f260fcd89a3b08050e50365c25cab1f0177ed9e | TahiraFatima98/day-27 | /multiplication table.py | 125 | 3.8125 | 4 | a=int(input('Enter any no: '))
print('Multiplication table of:', a)
for i in range(1, 11):
print(a, 'x', i, '=', a*i)
|
42caeb2c399184e4ba45f0b128dc88e9d47c373f | Connor-Knabe/Coding-Challenges | /Python/Warmup-1/missing_char.py | 135 | 3.671875 | 4 | str = "kitten"
n = 1
front = str[:n] # up to but not including n
back = str[n+1:] # n+1 through end of string
print front + back
|
01fd2f62f2c35add5844241134c610ddf3b6fa94 | Hidenver2016/Leetcode | /Python3.6/61-Py3-M-Rotate List.py | 2,315 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu May 16 18:00:07 2019
@author: hjiang
"""
"""
Given a linked list, rotate the list to the right by k places, where k is non-negative.
Example 1:
Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3... |
d6b5a9d0dd1edc2ea26f80af580334114d81d175 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_74/387.py | 1,080 | 3.640625 | 4 | #!/usr/bin/env python
import sys
import re
Pos = { 'O' : 0, 'B' : 0}
def getNext(L, color, event):
for i in range(event*2,len(L),2):
if L[i] == color:
return (i/2, int(L[i+1]))
def stepRobot(L, color, goal, event, dis):
global Pos
if goal == None:
return 0
# print "stepRobot", color, goal, event, Pos
if ... |
da39bd7c7b010217c456ad05a1ca984afa1ddb67 | stephsorandom/PythonJourney | /Functions and Methods/Functions.py | 3,035 | 4.3125 | 4 | def Keyword:
stands for the definition of the function
def name_of_function():
'''
Docstring explains the function with 3 Quotes.
Everything inside the function is indented
'''
- Python uses snake casing in functions..all... |
0074dcaf526f3a85e4deaddf55287306f6d199f6 | Carter-Co/she_codes_python | /lists/Q3.py | 502 | 4.34375 | 4 | #Ask user for three names, add them to a list and print
name_1 = input("Enter a name")
name_2 = input("Enter a second name")
name_3 = input("Enter a third and final name")
print(name_1 + name_2 + name_3)
#num1 = input("Enter a number")
#num2 = input("Enter another number")
#additiontotal_value = int(num1) + int(num2... |
6d40c96832f88ffb8ea9c6291144537f21dc36ee | miolfo/file-line-calculator | /line-calculator.py | 1,747 | 3.609375 | 4 | import os
import argparse
def calculate_lines(path, extension):
dirs = os.listdir(path)
linecount = 0
for dir in dirs:
if os.path.isfile(os.path.join(path, dir)):
linecount += get_lines_in_file(path, dir)
return linecount
def calculate_lines_recursive(path, extension):
linecoun... |
1fa4ee63bfa6d099be2e87dc3775a1ece9d8b8dc | scouvreur/hackerrank | /30-days-of-code/python/day_8.py | 432 | 3.796875 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
num_entries = int(input())
phone_book = {}
for i in range(num_entries):
line = str(input()).split()
phone_book.update({line[0]: int(line[1])})
while True:
try:
key = str(input())
try:
print("{}={}".format(ke... |
a6ba83934b3388a7cbd7dbb3505f44454bf9cb21 | MichellCazares/pythonLA2 | /Ejercicio1.py | 217 | 3.65625 | 4 | #
def main():
st = float(input("Ingrese su sueldo: "))
if(st<1000):
st = st*1.15
elif(st>=1000):
st = st*1.12
print("Su sueldo nuevo es: ",st)
if __name__ == "__main__":
main()
|
43126234e08b7b6274f7e221bbcdc022a5791e46 | habit456/Python3_Projects_msc | /connected.py | 1,162 | 3.625 | 4 | # my goal is to create a matrix that randomly generates 1s and 0s
# for each value. And then to find the longest connection in that matrix
import numpy as np
class Matrix:
def __init__(self, rows, columns):
self.matrix = np.array([[0 for column in range(columns)] for row in range(rows)])
s... |
891c57f43bbd0c9e5260ed93f34b655756009ebe | ferfabricio/MITx-6.00.1x | /L4P5.py | 637 | 3.59375 | 4 | import unittest
def clip(lo, x, hi):
'''
Takes in three numbers and returns a value based on the value of x.
Returns:
- lo, when x < lo
- hi, when x > hi
- x, otherwise
'''
return min(x, lo) == x and lo or (max(x, hi) == x and hi or x)
class TestClip(unittest.TestCase):
def te... |
f26ec94b66ec965b425e2539960880d76a08a836 | fako/python_introduction | /play.py | 1,957 | 3.84375 | 4 | """
A script to play around with Python a bite
To setup run:
conda create --name pi
pip install -r requirements.txt
"""
from pprint import pprint
import pandas as pd # data analysis library
from tamagotchi import KillerRabbit
if __name__ == "__main__":
# Creating some rabbits!
snuggles = KillerRabbit("Snug... |
31933bade91519911f544a1e5255d5222f7ab31e | ekoz/python-study | /3.8/cv2/chapter02/01_img_add.py | 996 | 3.5 | 4 | # -*- coding: utf-8 -*-
# @author : eko.zhan
# @time : 2021/8/23 23:05
import cv2
import numpy as np
# Load two images
img1 = cv2.imread("../data/messi8.jpg")
img2 = cv2.imread("../data/opencv-logo.png")
img2 = cv2.resize(img2, (80, 80))
# cv2.imshow("1", cv2.resize(img2, (80, 80)))
# cv2.waitKey()
# I wan... |
39c0da5844a822d6d3cd3dc8f5d5eb4d33e08e15 | hemantkumbhar10/Practice_codes_python | /University_admission_class.py | 1,780 | 3.5625 | 4 | class Student:
def __init__(self):
self.__student_id = None
self.__age = None
self.__marks = None
self.__course_id = None
self.__fees = None
def set_student_id(self, student_id):
self.__student_id = student_id
def set_age(self, age):
self._... |
9845a6cef9c3ac685768547a1567c0d5e94613d0 | rnsdoodi/Programming-CookBook | /Back-End/Databases/SQLite/Python-APIs/simple_csv.py | 1,822 | 3.65625 | 4 | import sqlite3
import csv
conn = sqlite3.connect('library.db')
c = conn.cursor()
c.execute('DROP TABLE IF EXISTS book_s')
c.execute('''CREATE TABLE "book_s"(
"title" TEXT,
"price" TEXT,
"rating" TEXT,
"in_stock" INTEGER)
''')
fname = 'filename.csv'
with open(fname, 'r+') as csv_file:
csv_reader = csv.rea... |
2ae775ba2801a78f83f2e900e87af01bca626c94 | renansald/Python | /cursos_em_video/Desafio85.py | 302 | 3.984375 | 4 | numero = [[], []];
for x in range(0, 7):
num = int(input("Informe um número: "));
if(num%2 == 0):
numero[0].append(num);
else:
numero[1].append(num);
numero[0].sort();
numero[1].sort();
print(f"Os números pares foram {numero[0]}\nOs números inmpáres foram {numero[1]}")
|
23d37f9ee8fd8f75da492ac9dca8b74699fd629e | mtknguyen03/MaiTranKhoiNguyen-c4t6 | /mini_hack/cang_vl_7.py | 77 | 3.65625 | 4 | n = input("Number? ")
m = int(n)
for i in range(m, -1, -1):
print(i)
|
be7235d5a6c583383bc3183a53cb2a6e97fcc449 | yblanco/design-pattern | /src/libs/ObjectPool.py | 773 | 3.640625 | 4 | import time
class PoolReusable:
def __init__(self, size=5):
self._max = max;
self.size = 1;
self._reusables = [Reusable(_) for _ in range(size)]
def acquire(self):
if len(self._reusables) == 0:
raise Exception("Pool empty")
return self._reusables.pop()
def release(self, reusable):
... |
b572501005a33a2802d3d2166168f47ddbd6c83f | AAKA999/Tic_Tac_Toe | /2player_tic_tac_toe.py | 3,843 | 3.90625 | 4 | import random
def display_board(current_board):
print(current_board[1]+'|'+current_board[2]+'|'+current_board[3])
print(current_board[4]+'|'+current_board[5]+'|'+current_board[6])
print(current_board[7]+'|'+current_board[8]+'|'+current_board[9])
def player_input():
selection=input('Player 1 ch... |
a72c94036650fc9543fb54724b46d938379e710f | b166erbot/300_ideias_para_programar | /tipo_de_pessoa3.3.1.py | 277 | 4.03125 | 4 | def main():
pessoa = input('digite um tipo de pessoa F/J: ').upper()
if pessoa == 'F':
print('pessoa física')
elif pessoa == 'J':
print('pessoa jurídica')
else:
print('tipo de pessoa inválido')
if __name__ == '__main__':
main()
|
551566e534ecdf178f37e3f4c224d8df0beee4db | samirelanduk/inferi | /inferi/datasets.py | 4,442 | 3.75 | 4 | """Contains the Dataset class."""
from .variables import Variable
class Dataset:
"""A collection of :py:class:`.Variable` objects which describe the same
experimental units.
:param \*variables: The Variables that make up the Dataset.
:raises TypeError: if non-Variables are given."""
def __init__... |
a1061d4dec85b69f9751ea39a3f7140afc3cb370 | maheshmasale/pythonCoding | /AlgoHW3/Ema's Supercomputer.py | 2,824 | 3.9375 | 4 | #https://www.hackerrank.com/challenges/two-pluses?h_r=next-challenge&h_v=zen
#!/bin/python3
def get_item(grid, position):
return grid[position[0]][position[1]]
def get_positions(grid, position, offset_amt=1):
positions = []
positions.append(get_position(grid, position, 'up', offset_amt))
positions.ap... |
d66b312ec236404a78d2deadbffc687fac7f4d57 | Michabele/pdsnd_github | /bikeshare.py | 9,502 | 4.3125 | 4 | import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name o... |
9d50c5d6c6c40e6d8d46bc9ded80c13774bc985a | latata666/newcoder | /leecode/lec_322_coinChange.py | 1,114 | 3.640625 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/6/15 10:56
# @Author : Mamamooo
# @Site :
# @File : lec_322_coinChange.py
# @Software: PyCharm
"""
给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。
如果没有任何一种硬币组合能组成总金额,返回 -1
输入: coins = [1, 2, 5], amount = 11
输出: 3
解释: 11 = 5 + 5 + 1
"""
import functools
class Solution:
... |
1984a9f1a651382543ffe067e6fecc101f746c22 | tyagian/Algorithms-and-Data-Structure | /practice/system/logs_2/read_file_enumerate_count_freq.py | 1,601 | 4.03125 | 4 | #https://stackabuse.com/read-a-file-line-by-line-in-python/#readafilelinebylinewithaforloopmostpythonicapproach
"""
To read line by line without loading file in memory
with open('Iliad.txt') as f:
for index, line in enumerate(f):
print("Line {}: {}".format(index, line.strip()))
with open("sample.txt") as ... |
a6340770379a5d2d8aa0d2321176fa8b6dd2be7c | thraddash/python_tut | /22_advance_concept/uppercase_name.py | 929 | 4.4375 | 4 | #!/usr/bin/env python
a="""
def person_name(name):
return name
upper_name = person_name("John Wick")
print(upper_name)
"""
def person_name(name):
return name
upper_name = person_name("John Wick")
print(a)
print(upper_name)
b="""
##################################################
covert output to uppercase
cha... |
e00dcb6ea88b8f6e518dafaa82596937527d8ce6 | zuosong/python | /cgi-bin/friends2.py | 1,345 | 3.640625 | 4 | #!/usr/bin/env python
import cgi
header = 'Content-Type:text/html\n\n'
formhtml='''<HTML><HEAD><TITLE>
Friends CGI Deom</TITLE></HEAD>
<BODY><H3>Friends list for: <I>NEW USER</I></H3>
<FORM ACTION="/cgi-bin/friends2.py">
<B>Enter your Name:</B>
<INPUT TYPE=hidden NAME=action VALUE=edit>
<INPUT TYPE=text NAME=person ... |
40bd014df322f0433dc868b3b7a42cf600fd2d07 | satyam-seth-learnings/ds_algo_learning | /Applied Course/4.Problem Solving/1.Problems on Array/28.Game of Life.py | 2,102 | 3.828125 | 4 | # https://leetcode.com/problems/game-of-life/
# Logic-1
class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
rows=len(board)
cols=len(board[0])
neighbors=[(1,0),(1,-1),(0,-1),(-1,-1),(-1,0... |
4f795f244105b6b2cfba6ffc76af923ad3a2ed1a | mbalakiran/Python | /Bala Kiran LAB 3/wordlistfilewriter.py | 1,296 | 4.21875 | 4 | def main():
#Asking for the number of words user wants to enter
numberofwords = int(input("Enter the number of words to be written to a file: "))
#Creating an file with the write funtion w
wordfile = open("Written file.txt", "w")
#Enetering the number of the words informed by the user
word = i... |
7946ae5e32580592c37fc737dbf0820d89676e5d | Caio-Margutti-Alves/Programming_Challenges | /Code in Game/speed.py | 275 | 3.5 | 4 | #!/usr/bin/python3
import datetime
s = input()
while s != "0 0 0":
d, s1, s2 = (int(x) for x in s.split())
#print (d,s1,s2)
h = 3600
a1 = d*h/s1
a2 = d*h/s2
ans = abs(a1-a2)
#print (ans)
ans = str(datetime.timedelta(seconds=ans))
print (ans)
s = input() |
835e382f52de53093caef02c4acd25ede727eb20 | gnikolaropoulos/AdventOfCode2020 | /day24/main.py | 2,080 | 3.546875 | 4 | from collections import defaultdict, Counter
def get_puzzle_input():
instructions = defaultdict(list)
j = 0
with open("input.txt") as input_txt:
for line in input_txt:
i = 0
while i < len(line.strip()):
if line[i] == "e" or line[i] == "w":
... |
a11d8b3d392dcaa3e99483edc2cbf81fb9ca358d | drajan21/Object-Oriented-Programming | /libPrjPython/Book.py | 1,118 | 3.5625 | 4 | from Media import Media
class Book(Media):
def __init__(self, callno, title, subject, author, description, publisher, city, year, series, notes):
super(Book, self).__init__(callno, title, subject, notes)
self.author = author
self.description = description
self.publisher = publi... |
83aecdfcecceb7c13a0e88fe46926c05f520639f | kkk12538/python-visualization | /可视化编程小项目/数据处理/气温折线图.py | 576 | 3.5625 | 4 | import csv
import matplotlib.pyplot as plt
with open('weather.csv') as file:
reader=csv.reader(file)
# header_row=next(reader)
# print(header_row)
# for index,column_header in enumerate(header_row):
# print(index,column_header)
a=[]
for row in reader:
for i in row:
a.... |
41badc6c42b6630dfb7d3208bb11238e7e766482 | harishk-97/python | /hacker rank/program3.py | 146 | 3.671875 | 4 | a=int(input())
p=a
for i in range(a):
b=''
for i in range(a):
if(i<p-1):
b+=' '
else:
b+='#'
p=p-1
print(b)
|
ab379fadd5d5fcae01d856f606b93a13349d8b7c | Lucas-Severo/python-exercicios | /mundo03/ex088.py | 930 | 4.15625 | 4 | '''
Faça um programa que ajude um jogador da MEGA SENA a criar palpites.
O programa vai perguntar quantos jogos serão gerados e vai sortear 6 números entre 1 e 60 para cada jogo,
cadastrando tudo em uma lista composta.
'''
from random import randint
from time import sleep
jogos = []
numeros = []
print('-'*30)
print(... |
17f95176c391ac0b30cde3c4371652cd1a6d32e6 | toniall/webscraping | /tweet_scraper.py | 1,596 | 3.640625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# =========== Código para scrapear tweets empleando GetOldTweets3 ==============
#
# Objetivo: con este código se scrapea tweets, más o menos recientes de @nperedo.
#
# Notas: idealmente quisiéramos scrapear tweets recientes de todos los usuarios;
# \sin embargo, para ello se... |
72dc44e6be256b1d0c7fb04e8a782c088e10e85f | mazerlodge/MrRobot | /DarleneDecode.py | 3,553 | 3.703125 | 4 | #!/usr/local/opt/python/bin/python3.7
# Version: 20170707-1815
# Opens data file and outputs first two letters of every sixth word.
import sys
from ArgTools import ArgParser
# Hard coded constants
DATA_FILE__MAC = "./darlene_code.txt"
DATA_FILE__WIN = ".\\darlene_code.txt"
# Setup variables
osType = "NOT_SET"
data... |
39290d24d9e11d27c619d77bbff3c742e54f3a0e | syurskyi/Python_Topics | /070_oop/001_classes/examples/Python_3_Deep_Dive_Part_4/Section 8 Descriptors/103. Properties and Descriptors - Coding.py | 7,208 | 4 | 4 | # %%
'''
### Properties and Descriptors
'''
# %%
'''
Let's start by creating a property using the decorator syntax:
'''
# %%
from numbers import Integral
class Person:
@property
def age(self):
return getattr(self, '_age', None)
@age.setter
def age(self, value):
if not isinstance(... |
673e3bade2f90528ce2fac21e928d5db6cf683a7 | MarianoAIglesias1994/Data_Analytics | /Exercise_1/Coding_1.py | 2,527 | 3.59375 | 4 | # ------------------------------------------------------------------------------
# Original code
# ------------------------------------------------------------------------------
#import random
# def weighted_random(values, weights):
# total_weight = sum(weights)
# In this line and in the following one, a normaliz... |
aeea46377810ce62cccd29f0f33a0e01f132e724 | annusingh100995/Data_Analysis | /PARAMETER EVALUATION AND HYPER_PARAMETER_TUNING/data_preprocessing.py | 6,773 | 3.515625 | 4 | import pandas as pd
from io import StringIO
# Making a sample incomplete data
csv_data = \
'''A,B,C,D
1.0,2.0,3.0,4.0
5.0,6.0,,8.0
10.0,11.0,12.0,'''
# converting the file into a dataframe for data manipulation
df = pd.read_csv(StringIO(csv_data))
#sum: return the number of missing values per column
... |
f9f1a14179463a3fee894e183674aaab442deca2 | ZhengLiangliang1996/Leetcode_ML_Daily | /BinarySearch/287_FindTheDuplicateNumber.py | 1,259 | 3.765625 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2021 liangliang <liangliang@Liangliangs-Air>
#
# Distributed under terms of the MIT license.
class Solution(object):
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
... |
06391af0fe3b295fe5d777afb23307ae4cece87b | SageBinder/MAT276-Final-Project | /ThrownBallEulerStudentWithDrag.py | 14,551 | 3.546875 | 4 | # Written by Chris McCarthy July 2019 SIMIODE DEMARC
# Drag = 0 Student Version
#=========================================== for online compilers
import matplotlib as mpl
#=========================================== usual packages
import numpy as np
from matplotlib import pyplot as plt
import math
plt.rcParams.updat... |
1f5cb91d3f23b41b6a9fcbbaa331e9b3bf216360 | cxyang/myexercise | /part1.py | 330 | 3.703125 | 4 | # coding=utf-8
class Solution(object):
def isAnagram(self, s, t):
if len(s) != len(t):
return False
return sorted(s) == sorted(t)
def main():
s = "hello world"
t = "world hello"
solution = Solution()
print(Solution().isAnagram(s, t))
if __name__ == "__main__":
... |
9c166bfc1e2f6b9864f3e9975111cb7dfdb25aa8 | abhishekkr/tutorials_as_code | /talks-articles/languages-n-runtimes/python/Googles.Python.Class--Day1-and-Day2/day02_eg04.py | 547 | 3.65625 | 4 | #!/usr/bin/env python -tt
# List Comprehension
def ls_a():
import os
import re
fylz = os.listdir('/tmp')
hidden = [ f for f in fylz if re.search(r'^\.', f)]
print sorted(hidden)[0]
def main():
lst = ['aaaa', 'b', 'cccccc', 'dd', 'eee']
print lst
lst2 = [ len(s) for s in lst ]
print "lst2 = ... |
eb138b8d9396dbb1ab1f35d0d69b6a7f0bb3e63f | hermann-roemer/py_learn | /tktest01.py | 1,443 | 3.84375 | 4 | from tkinter import *
import datetime
dtm=datetime.datetime.now().strftime("==%A, %d.%m.%Y, %H:%M ==")
global ln
ln=0
print(ln)
def okbtn_pressed(xxx):
ln=3
if xxx.num == 1:
txt = "LB"
elif xxx.num == 2:
txt = "MB"
elif xxx.num ==3:
txt = "RB"
else:
... |
99b9f4959c047aa1ad02866b2e8bc086e935d2e1 | eugeniodias5/Snake | /snake/snake.py | 10,018 | 3.765625 | 4 | import pygame, sys, random
import math
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
size = width, height = 600, 600
pygame.init()
screen = pygame.display.set_mode(size)
pygame.display.set_caption('Snake')
GREENBLOCKSIDE = 15
SPEEDINCREASE = 0.05 #Speed increased when the snake eats the apple
class ... |
9a31dd2868530de24759b1a9298fef245f291060 | eessm01/100-days-of-code | /e_bahit_data_science/working_strings_replace.py | 1,208 | 3.75 | 4 | """CIENCIA DE DATOS CON PYTHON by Eugenia Bahit. 2 edition. pages 11-12"""
# dar formato a una cadena, sustituyendo texto dinámicamente
cadena = 'bienvenido a mi aplicación {0}'
print(cadena.format('en Python'))
cadena = 'Importe bruto: ${0} + IVA: ${1} = IMPORTE NETO: {2}'
print(cadena.format(100,21,121))
cadena = ... |
006640d6b872a7cc369cf7296f3ad3c06028a0a0 | Pavan9676/Python-Codes | /BasicProgramOfArrays/AdditionOfSubArray.py | 387 | 3.703125 | 4 | from array import *
arr = array('i', [])
arr1 = array('i', [])
n = int(input("Enter size of array: "))
for i in range(n):
x = int(input("Enter next value: "))
arr.append(x)
print(arr)
a = int(input("Enter starting value: "))
b = int(input("Enter ending value: "))
for i in range(a-1, b):
y = arr[i]
arr1.... |
9f53c7e06c61a1ce3d38474d892c726376285cbc | DJV23/DarthVeder | /Programming/ClassesandGraphics.py | 2,686 | 4.0625 | 4 | """
ClassesandGraphics.py
Ved Ballary
Last edit: 17 November 2017
Version 1
This program randomly moves randomly generated ellipses and rectangles.
Sample Python/Pygame Programs
Simpson College Computer Science
http://programarcadegames.com/
http://simpson.edu/computer-science/
Explanation video: http://youtu.be/vRB_... |
bf1d75e197ef97eb8e3e8ab298963c2d16762142 | naveenraj93/HackerRank_Interview_Preparation | /Warm-up Challenges/03 Jumping on the Clouds.py | 564 | 3.59375 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
noOfClouds = int(input())
cloudArr = input().split()
noOfJump = 0
currentCloud = 0
i = 1
twoPlaceFlag= 1
while i < noOfClouds:
twoPlaceFlag += 1
if currentCloud == i:
pass
elif cloudArr[i] == '0':
if twoPlaceFlag =... |
1f7527eaff36eb0b7599ed6503c9cee825421541 | leuduc2002/minhduc | /cai.hinh.canh.hinh.phi.tieu.py | 226 | 3.84375 | 4 | from turtle import *
speed(0)
for i in range(4):
if i % 2 == 0:
pencolor("blue")
else:
pencolor("red")
side = i + 3
for _ in range(side):
forward(100)
left(360 / side)
mainloop() |
932c40eb454e40ce1e2ffb86d9ef50f8b1489ac7 | bramil20/GradueteJavaProject | /Dictionary/Dictionary.py | 191 | 3.875 | 4 | classmates={'Marco':'cool but smells', 'Luca': 'not a good guy', 'Peter':'well known lair'}
#print(classmates)
#print(classmates['Peter'])
for j,k in classmates.items():
print(k+"-"+j) |
fc5d705a47143bd8a463b3013da221b729ecba8f | ronys79/DI_Bootcamp | /Week6/hackathon2/calculator.py | 3,238 | 4.15625 | 4 | from tkinter import *
root=Tk()
root.title("Simple Calculator")
e= Entry(root, width=35, borderwidth=5)
e.grid(row=0, column=0, columnspan=3)
e.insert(0, ' ')
def button_click(number):
# e.delete(0, END)
current = e.get()
e.delete(0, END)
e.insert(0, str(current) + str(number))
def button_clears():
... |
8ddc10ac21f3cc069ebd5d5eb3c4aa3fcaddbfa3 | tristanbatchler/MATH3302-Scripts | /transmit.py | 20,528 | 3.75 | 4 | from typing import *
from math import inf
from random import random
from itertools import combinations
class AmbiguityError(BaseException):
"""Raised when ambiguity arises and there is no suitable return value"""
pass
def legal(word: str) -> bool:
allowed = '01'
for b in word:
if b not in allo... |
cd3430e18c7fc1b3395c5124712549f73feaadee | wduncan21/Mooc | /EdX/edx_intro_to_data_science/final/f6.py | 917 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun May 7 15:29:52 2017
@author: lwang138
"""
def find_combination(choices, total):
"""
choices: a non-empty list of ints
total: a positive int
Returns result, a numpy.array of length len(choices)
such that
* each element of result is 0 or 1
... |
81e6dd38cb38a7fee61b4b1e3eac35823d55ba0a | youjin9209/2016_embeded_raspberry-pi | /pythonBasic/grade_elif.py | 187 | 3.71875 | 4 | score = int(input("total"))
if score >= 90:
print("su")
elif 80 <= score < 90:
print("wu")
elif 70 <= score < 80:
print("mi")
elif 60 <= score < 70:
print("yang")
else:
print("ga")
|
b117663558840538a3260aeb97f8d63a832e605c | mcedster/FirstProject | /src/Enemy.py | 3,352 | 3.671875 | 4 | import random
class enemy:
def __init__(self, name):
if name == "imp":
self.max_health = 10
self.health = self.max_health
self.attack = 0
self.armor = 0
self.magic_resist = 0
self.item = 0
self.speed = 1
self.le... |
234dab557674f37573904a83b7f427d116871a0a | Surenu1248/Python_Assignment_Set_2 | /21.py | 1,047 | 4.21875 | 4 |
#a) Round of the given floating point number. Example: n=0.543 then round it next
# decimal number, i.e n=1.0 Use round() function
import math,random
x = 6.574
print("Round value of {} is: ".format(x), round(x))
# b) Find out the square root of a given number. (Use sqrt(x) function)
y = 9
print("Square root of {... |
9a84aa60add7d1c70bf405fb9d50719e6faaa686 | emmanuelluur/scratch_api | /scratch_api.py | 528 | 3.578125 | 4 | #!/usr/bin/env python
# coding: utf-8
import requests
# Use scratch api
# in request api search user and projects user
res = requests.get("https://api.scratch.mit.edu/users/masg92")
resP = requests.get(f"https://api.scratch.mit.edu/users/masg92/projects")
# store responses on variable as json type
user = res.j... |
6a7c57027a019ca543eaf27371a639261e050dbc | rakshit6432/HackerRank-Solutions | /Python/06 - Itertools/01 - itertools.product().py | 415 | 3.890625 | 4 | # ========================
# Information
# ========================
# Direct Link: https://www.hackerrank.com/challenges/itertools-product/problem
# Difficulty: Easy
# Max Score: 10
# Language: Python
# ========================
# Solution
# ========================
from itertools import product
A = li... |
cd9f9b3cd7c00e13adfe86c795f452bf73991ebe | srush-shah/Python-Programiz | /Functions/Ex12.py | 298 | 4.25 | 4 | # Python program to find the sum of natural numbers using recursive function
def recur_sum(n):
if n <= 1:
return n
else:
return n + recur_sum(n-1)
# change this value for a different result
num = 16
if num < 0:
print('Enter a positive number')
else:
print('The sum is',recur_sum(num)) |
147a379004cbe2cea6410f9a43f29cc7feb49113 | Okeoma/Codility_python | /common_prime_divisors.py | 1,037 | 3.734375 | 4 | def gcd(x, y):
# Compute the greatest common divisor
if x%y == 0:
return y
else:
return gcd(y, x%y)
def hasSamePrimeDivisors(x, y):
gcd_value = gcd(x, y) # The gcd contains all
# the common prime divisors
while x != 1:
x_gcd = gcd(x, gcd_value... |
e0829b10c48f89503e0b989d406902a3b5939539 | djun02/par-ou-impar | /main.py | 760 | 3.71875 | 4 | from tkinter import *
class App:
def __init__(self, master = None):
self.a = master
self.label = Label(self.a)
self.label["text"] = "Digite um número"
self.label.grid(columnspan=2)
self.entry = Entry(self.a)
self.entry.grid(row=1, column=1)
self.button = B... |
1c3a4144838f40c30ad9fa490de7350be0a01d12 | niranjan-nagaraju/Development | /python/leetcode/reverse_linked_list_ii/reverse_linked_list_ii.py | 2,560 | 4.1875 | 4 | #+encoding: utf-8
'''
https://leetcode.com/problems/reverse-linked-list-ii/
92. Reverse Linked List II
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL
'''
# Definition for singly-linked... |
bc276bf28c174f57cdea272c92e29d04d4b7a940 | du-phan/Rosalind | /Enumerating k-mers Lexicographically/solution.py | 791 | 3.515625 | 4 | def enumerate(link):
file = open(link,'rU')
input = file.readlines()
symbol = input[0].split()
symbol = ''.join(symbol)
n = int(input[-1])
'''
symbol_list = {}
counter = 0
for x in symbol:
symbol_list[counter] = x
counter += 1
'''
result = [[None]*n for i in range(len(symbol)**2)] #*(len(symbol)**2)... |
b9c23add3801523535e717c66eb6edea19cd9361 | zhangyuanqiao93/pyTest | /py1/test.py | 3,276 | 4.03125 | 4 | # print('100+300')
# 以#开头的语句是注释,注释是给人看的,可以是任意内容,解释器会忽略掉注释。
# 其他每一行都是一个语句,当语句以冒号:结尾时,缩进的语句视为代码块。
a = 100
if a > 0:
print(a)
else:
print(-a)
# //十六进制的123
b = 0x123
# 字符串内部既包含'又包含"怎么办?可以用转义字符\来标识
print('I\'m \"OK\"!')
# Python允许用'''...'''的格式表示多行内容
# Python还允许用r''表示''内部的字符串默认不转义
print('''line1
line2
line3''')
... |
3c5c9ec4b039d8ec37b361f3aac01f7b700e9827 | ApexTone/Learn-Python | /sort.py | 812 | 4.0625 | 4 | def merge(array1, array2):
answer = list()
while len(array1) > 0 and len(array2) > 0:
buffer1 = array1[0]
buffer2 = array2[0]
if buffer1 <= buffer2:
answer.append(buffer1)
array1.pop(0)
else:
answer.append(buffer2)
array2.pop(0)
... |
e068f81b486aed65e3809d9a36baa0735244f39c | gkotas/ProjectEuler | /problems/pe019.py | 1,015 | 4.09375 | 4 | """
Counting Sundays
Problem 19
You are given the following information, but you may prefer to do some research
for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.