blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
c32d0f7b44749e6ae0ecec14ed2a2002e9b8bb7b | rootme254/Python-Projects | /shop.py | 3,154 | 4.21875 | 4 | '''
This is a shopping list like ile inatumiwa in jumia the online shopping
Create a class called ShoppingCart.
Create a constructor that has no arguments and sets the total attribute to zero, and initializes an empty dict attribute named items.
Create a method add_item that requires item_name, quantity and pri... |
e604fb50261893929a57a9377d7e7b0e11a9b851 | georgeyjm/Sorting-Tests | /sort.py | 2,686 | 4.34375 | 4 | def someSort(array):
'''Time Complexity: O(n^2)'''
length = len(array)
comparisons, accesses = 0,0
for i in range(length):
for j in range(i+1,length):
comparisons += 1
if array[i] > array[j]:
accesses += 1
array[i], array[j] = array[j], arr... |
c444e7a76a76479c82d08818bcdb38b51cfe073e | 4dasha45/COM411 | /basics/data_visuialisation/function/ascii_code.py | 238 | 4.09375 | 4 | print("program started")
print("Please enter a standard character:")
word=input()
if (len(word)==1):
print("th ascii code for {}is {}".format(word,ord(word)))
else:
print("A single character was expected")
print("end the program") |
4f4431799d2dc9cf46e296cf132e3f77bdeffc3d | asiskc/python_assignment_jan5 | /student.py | 1,030 | 3.875 | 4 | class CheckError():
def __init__(self,roll):
if(roll>24):
raise NameError()
dict = {
1: "student1",
2: "student2"
}
choice = 1
while (choice==1):
try:
choice = int(input("choose an option"))
if (choice == 1):
roll = int(input("roll no:"))
name... |
7c314615e75b8f7f02f68c040f50f854bcb8e1cb | jilljenn/tryalgo | /tryalgo/knapsack.py | 3,210 | 3.984375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""\
Knapsack
jill-jênn vie et christoph dürr - 2015-2019
"""
# snip{
def knapsack(p, v, cmax):
"""Knapsack problem: select maximum value set of items if total size not
more than capacity
:param p: table with size of items
:param v: table with value of ... |
5f5e2d3f7bf5b6e1553e8c10d331d5d4143346af | jilljenn/tryalgo | /tryalgo/gauss_jordan.py | 2,290 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""\
Linear equation system Ax=b by Gauss-Jordan
jill-jenn vie et christoph durr - 2014-2018
"""
__all__ = ["gauss_jordan", "GJ_ZERO_SOLUTIONS", "GJ_SINGLE_SOLUTION",
"GJ_SEVERAL_SOLUTIONS"]
# snip{
# pylint: disable=chained-comparison
def is_zero(x): ... |
1204ef8366837b66f591ff142e663df7302c87b5 | jilljenn/tryalgo | /tryalgo/graph01.py | 1,275 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""\
Shortest path in a 0,1 weighted graph
jill-jenn vie et christoph durr - 2014-2018
"""
from collections import deque
# snip{
def dist01(graph, weight, source=0, target=None):
"""Shortest path in a 0,1 weighted graph
:param graph: directed graph in listlist... |
322e307335af2bdf4474d2f78117c867668243ef | jilljenn/tryalgo | /tryalgo/levenshtein.py | 817 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""\
Levenshtein edit distance
jill-jenn vie et christoph durr - 2014-2018
"""
# snip{
def levenshtein(x, y):
"""Levenshtein edit distance
:param x:
:param y: strings
:returns: distance
:complexity: `O(|x|*|y|)`
"""
n = len(x)
m = len(y)... |
eea13b5f1c5f7a88cbba2d5a56e5101de59a96dd | jilljenn/tryalgo | /tryalgo/dijkstra.py | 2,886 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""\
Shortest paths by Dijkstra
jill-jênn vie et christoph dürr - 2015-2018
"""
# pylint: disable=wrong-import-position
from heapq import heappop, heappush
from tryalgo.our_heap import OurHeap
# snip{
def dijkstra(graph, weight, source=0, target=None):
"""single s... |
1f90271814c98307cdfb0dc1111f011c619498ba | eliaskousk/example-code-2e | /24-class-metaprog/setattr/example_from_leo.py | 340 | 3.71875 | 4 | #!/usr/bin/env python3
class Foo:
@property
def bar(self):
return self._bar
@bar.setter
def bar(self, value):
self._bar = value
def __setattr__(self, name, value):
print(f'setting {name!r} to {value!r}')
super().__setattr__(name, value)
o = Foo()
o.bar = 8
print(o... |
a82eb08a4de5bab1c90099a414eda670219aeb95 | eliaskousk/example-code-2e | /21-async/mojifinder/charindex.py | 2,445 | 4.15625 | 4 | #!/usr/bin/env python
"""
Class ``InvertedIndex`` builds an inverted index mapping each word to
the set of Unicode characters which contain that word in their names.
Optional arguments to the constructor are ``first`` and ``last+1``
character codes to index, to make testing easier. In the examples
below, only the ASC... |
a04924cd0fc7da072413c4062f8a2a1258f58e32 | eliaskousk/example-code-2e | /05-data-classes/dataclass/coordinates.py | 512 | 3.5625 | 4 | """
``Coordinate``: simple class decorated with ``dataclass`` and a custom ``__str__``::
>>> moscow = Coordinate(55.756, 37.617)
>>> print(moscow)
55.8°N, 37.6°E
"""
# tag::COORDINATE[]
from dataclasses import dataclass
@dataclass(frozen=True)
class Coordinate:
lat: float
lon: float
def __... |
f23ba5514189ed232eeaaf3cd6a4ea8fb799864e | eliaskousk/example-code-2e | /20-executors/getflags/slow_server.py | 3,986 | 3.515625 | 4 | #!/usr/bin/env python3
"""Slow HTTP server class.
This module implements a ThreadingHTTPServer using a custom
SimpleHTTPRequestHandler subclass that introduces delays to all
GET responses, and optionally returns errors to a fraction of
the requests if given the --error_rate command-line argument.
"""
import contextl... |
d2977b7a63a6f0bebe59544ccaf8fc1763570d1c | eliaskousk/example-code-2e | /05-data-classes/typing_namedtuple/coordinates.py | 487 | 3.765625 | 4 | """
``Coordinate``: a simple ``NamedTuple`` subclass with a custom ``__str__``::
>>> moscow = Coordinate(55.756, 37.617)
>>> print(moscow)
55.8°N, 37.6°E
"""
# tag::COORDINATE[]
from typing import NamedTuple
class Coordinate(NamedTuple):
lat: float
lon: float
def __str__(self):
ns =... |
06b96c803dcc6f53a2db59b8ba48e68c47e4df33 | anqi117/py-study | /namecard-func.py | 2,341 | 3.703125 | 4 | card_infor = []
def print_menu():
print("="*50)
print(" 名片系统 v1.0")
print("1. add a new card")
print("2. delete a card")
print("3. update a card")
print("4. search a card")
print("5. show all of cards")
print("6. exit")
print("="*50)
def add_new_card_info():
new_name = input("name: ")
new_qq = input("qq: "... |
50dc5fc8bf4ec94682c5d984b9e57cb46b35fc28 | hcmMichaelTu/python | /lesson08/sqrt_cal2.py | 793 | 3.859375 | 4 | import math
def Newton_sqrt(x):
y = x
for i in range(100):
y = y/2 + x/(2*y)
return y
def cal_sqrt(method, method_name):
print(f"Tính căn bằng phương pháp {method_name}:")
print(f"a) Căn của 0.0196 là {method(0.0196):.9f}")
print(f"b) Căn của 1.21 là {method(1.21):.9f}")
... |
dd7145fa02abd11c3490fa783f40f8b696c8261e | hcmMichaelTu/python | /lesson12/turtle_draw.py | 336 | 3.78125 | 4 | import turtle as t
t.shape("turtle")
d = 20
actions = {"L": 180, "R": 0, "U": 90, "D": 270}
while ins := input("Nhập chuỗi lệnh cho con rùa (L, R, U, D): "):
for act in ins:
if act in actions:
t.setheading(actions[act])
else:
continue
t.forward(d)
print("... |
01b471090a34326b7c1c1a898ec5a25a9dbb0164 | hcmMichaelTu/python | /lesson04/string_format.py | 165 | 3.640625 | 4 | import math
r = float(input("Nhập bán kính: "))
c = 2 * math.pi * r
s = math.pi * r**2
print("Chu vi là: %.2f" % c)
print("Diện tích là: %.2f" % s)
|
87b04bf978a40493536c104be127f2ff83c55f74 | hcmMichaelTu/python | /lesson18/Sierpinski_carpet.py | 684 | 3.71875 | 4 | import pygame
def Sierpinski(x0, y0, w, level):
if level == stop_level:
return
for i in range(3):
for j in range(3):
if i == 1 and j == 1:
pygame.draw.rect(screen, WHITE, (x0 + w//3, y0 + w//3, w//3, w//3))
else:
Sierpinski(x0 ... |
71fb5ab35539839f8d8810bbd26003f5ba605ee2 | hcmMichaelTu/python | /lesson12/turtle_escape.py | 328 | 3.828125 | 4 | import turtle as t
import random
t.shape("turtle")
d = 20
actions = {"L": 180, "R": 0, "U": 90, "D": 270}
while (abs(t.xcor()) < t.window_width()/2 and
abs(t.ycor()) < t.window_height()/2):
direction = random.choice("LRUD")
t.setheading(actions[direction])
t.forward(d)
print("Congratulati... |
9a171f9585f56bb701ddbf6d88c6437c5123eca2 | hcmMichaelTu/python | /lesson14/tri_color_wheel.py | 1,797 | 3.6875 | 4 | import turtle as t
import time
import math
class TriColorWheel:
def __init__(self, omega, center=(0, 0), radius=100,
colors=("red", "green", "blue"),
up_key=None, down_key=None):
self.center = center
self.radius = radius
self.colors = colors
... |
db6bca60ff9d43d14f893a5d2afaf0dcb825091b | hcmMichaelTu/python | /lesson08/Newton_sqrt2.py | 166 | 3.75 | 4 | def Newton_sqrt(x):
if x < 0:
return
if x == 0:
return 0
y = x
for i in range(100):
y = y/2 + x/(2*y)
return y
|
a4fbc2deb5430e99feeeafc0af267677f4e957fc | hcmMichaelTu/python | /lesson05/square.py | 192 | 3.71875 | 4 | import turtle as t
t.shape("turtle")
d = int(input("Kích thước hình vuông? "))
t.forward(d); t.left(90)
t.forward(d); t.left(90)
t.forward(d); t.left(90)
t.forward(d); t.left(90)
|
2d17aba920279d5c521fcd5646ef53b844dde294 | hcmMichaelTu/python | /lesson06/exam.py | 191 | 3.65625 | 4 | điểm_thi = float(input("Bạn thi được bao nhiêu điểm? "))
if điểm_thi < 5:
print("Chúc mừng! Bạn đã rớt.")
else:
print("Chia buồn! Bạn đã đậu.")
|
113c8f8c95c6b98f181af8c197305be9729c853e | hcmMichaelTu/python | /lesson15/turtle_escape.py | 552 | 3.65625 | 4 | import turtle as t
import random
t.shape("turtle")
d = 20
try:
while (abs(t.xcor()) < t.window_width()/2
and abs(t.ycor()) < t.window_height()/2):
direction = random.choice("LRUD")
if direction == "L":
t.setheading(180)
elif direction == "R":
... |
30ab7ff7d01d2d2ac154a8a1643169059633d8a8 | hcmMichaelTu/python | /lesson12/turtle_draw2.py | 349 | 3.625 | 4 | import turtle as t
def forward(deg):
def _forward():
t.setheading(deg)
t.forward(d)
return _forward
t.shape("turtle")
d = 20
actions = {"Left": 180, "Right": 0, "Up": 90, "Down": 270}
for act in actions:
t.onkey(forward(actions[act]), act)
t.onkey(t.bye, "Escape"... |
f7627d984bb9d995801c88ebe76baffac933ebca | hcmMichaelTu/python | /lesson17/triangle.py | 271 | 3.5 | 4 | import sys
char = input("Nhập kí hiệu vẽ: ")
n = int(input("Nhập chiều cao: "))
stdout = sys.stdout
with open("triangle.txt", "wt") as f:
sys.stdout = f
for i in range(1, n + 1):
print(char * i)
sys.stdout = stdout
print("Done!")
|
5d437d6e804b72f26526c22418c8f2cb719ed1d6 | hcmMichaelTu/python | /lesson18/guess_number2.py | 872 | 3.765625 | 4 | import random
def binary_guess():
if left <= right:
return (left + right) // 2
else:
return None
def hint(n, msg):
global left, right
if msg == "less":
left = n + 1
else:
right = n - 1
max = 1000
print("Trò chơi đoán số!")
print(f"Bạn đoán một co... |
4de83b6bff15ac23aa0a775e068a487b51c771e4 | mikemeko/6.01_Tools | /src/core/math/line_segments.py | 2,443 | 3.671875 | 4 | """
Utility for line segments.
(1) Check whether two line segments intersect. Credit to: http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect
(2) Translate segments.
"""
__author__ = 'mikemeko@mit.edu (Michael Mekonnen)'
from core.util.util import overlap
from math imp... |
fe5ece5986e3f29e5f82a7512ea54746f2efa9bc | guimesmo/python-demo | /frase_do_dia_typed.py | 1,260 | 3.578125 | 4 | import random
import typing
class Frase:
def __init__(self, conjunto: str, idioma_padrao: str = "pt"):
self.conjunto = conjunto
self.idioma_padrao = idioma_padrao
self.output = dict()
self.parse()
def __str__(self):
return self.output.get(self.idioma_padrao, "Nã... |
62bb6e65edf4da3a18f8f681413b99518182631f | lokeki/python | /ZadSrdZaw/wykladI/Zad8EnumerateZip.py | 1,292 | 3.71875 | 4 | #wyk/enumerate/zip
'''
workDays = [19, 21, 22, 21, 20, 22]
print(workDays)
print(workDays[2])
enumerateDays = list(enumerate(workDays))
print(enumerateDays)
#enumerate - numerujemy kazdy element z listy i tworza sie tumple
for pos, value in enumerateDays:
print("Pos:", pos, "Value:", value)
month = ['I', 'II', ... |
14547f40099598502bbadfea46a328fb21330128 | lokeki/python | /ZadSrdZaw/wykladI/Zad11Generator.py | 1,645 | 3.671875 | 4 | #generator zazwyczaj się używa kiedy jest duza baza danych
'''
listA = list(range(6))
listaB = list(range(6))
print(listA, listaB)
product = []
for a in listA:
for b in listA:
product.append((a,b))
print(product)
#skrocona wersja z ifem (lista)
product = [(a,b) for a in listA for b in listaB if a % 2 !... |
a0556b957eaf8394c0277e7830d7b347319bb402 | lokeki/python | /ZadSrdZaw/wykladI/Zad18FunkcjaArgumentemFunkcji.py | 969 | 3.53125 | 4 | # Funkcja jako argument funkcji
'''
def Bake (what):
print("Baking:", what)
def Add (what):
print("Adding:",what)
def Mix (what):
print("Mixing:", what)
cookBook = [(Add, "milk"), (Add, "eggs"), (Add, "flour"), (Add, "sugar"), (Mix, "ingerdients"), (Bake, "cookies")]
for activity, obj in cookBook:
a... |
dc30adb10fb9d8482e0f4febadf412dd4524bc80 | lokeki/python | /ZadSrdZaw/wykladI/Zad24OptymalizacjaFunkcjiCache.py | 737 | 3.5625 | 4 | #Optymalizacja funkcji przez cache# musi byc deterministyczna, miec zawsze takie
# same argumenty i taki rezultat
'''
import time
import functools
@functools.lru_cache()
def Factorial (n):
time.sleep(0.1)
if n == 1:
return 1
else:
return n * Factorial(n - 1)
start = time.time()
for i in r... |
30532ca431def7eaaba8588814e5b22873ff8017 | lokeki/python | /ZadSrdZaw/wykladI/Zad19FunkcjaZwracaFunkcje.py | 1,208 | 3.53125 | 4 | # Zwaracanie funkcji
#
# def Calculate ( kind = "+", *args):
# result = 0
#
# if kind == "+":
#
# for a in args:
# result += a
#
# elif kind == '-':
#
# for a in args:
# result -= a
#
# return result
#
# def CreateFunction(kind = "+"):
# source = '''
# def f(*... |
8a23940de2d48ab3b767e90e2e3a3e55836daffd | andyreagan/2018-advent-of-code | /2019-mm-month-of-python/13-manselmi/bruteforce.py | 489 | 3.953125 | 4 | import sys
def collatz_f(i: int) -> int:
if i % 2 == 0:
return int(i / 2)
else:
return int(3*i + 1)
def get_path_length(i: int) -> int:
# print(i)
l = 1
while i != 1:
i = collatz_f(i)
l += 1
# print(i, l)
return l
def main(n):
all_path_lengths = ... |
8122e6d19531fc76d06288aaf9dfb1590aca10d7 | webclinic017/StockPredictor-1 | /CAP4621_Stock_Prediction_Project.py | 15,684 | 3.59375 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Dhruv's Section
# In[ ]:
get_ipython().system('pip install matplotlib')
get_ipython().system('pip install seaborn')
get_ipython().system('pip install yfinance')
import platform
import yfinance as yf
import datetime
import matplotlib.pyplot as plt
import seaborn
# prints th... |
02960d761aec2401238739d0c6cee1a6a5b54571 | Wowol/Blackjack-Reinforcement-Learning | /game/card.py | 333 | 3.875 | 4 | from random import randint
class Card:
"""Generate one card and store its number in value field
"""
value = 0
def __init__(self):
number = randint(1, 13)
if number == 1:
self.value = 11
elif number > 10:
self.value = 10
else:
self.va... |
d81541f0bfae3d2a5323f517300afa9501bdf685 | ntshcalleia/Listas_AlgGraf_2017_2 | /lista2/questao5.py | 1,868 | 3.734375 | 4 | import math
def troco(T):
moedas = {
1: 0,
5: 0,
10: 0,
25: 0,
50: 0,
100: 0
}
while(T > 0): # Criterio guloso: escolher maior moeda possivel. Colocar quantas der dela
if T >= 100:
moedas[100] = int(math.floor(T/100))
T = T % ... |
f8576b094f7f0676433b035d8630f2a64477eb85 | Huitzoo/Rosalind_Bioinformatics | /rabbits.py | 299 | 3.671875 | 4 | def main():
months = int(input('Enter the months'))
litters = int(input('Enter the number of litters'))
fibo = [1,1]
if months <= 2:
print('1')
else:
for i in range(2,months):
fibo.append(litters*fibo[i-2]+fibo[i-1])
print(fibo)
main()
|
e9f2417dd3507d88cfb24b12c8c927c259e7fc91 | halesahinn/Searching-Reverse-Complement-of-DNA-Motif | /Project1_150114063_150116841_150114077.py | 2,536 | 3.5625 | 4 | #Büşra YAŞAR-150114063
#Emine Feyza MEMİŞ-150114077
#Hale ŞAHİN-150116841
import operator
import re
import os
import sys
from os import path
#print("Please enter the input file path :")
#path = input()
def reverse(s):
str = ""
for i in s:
str = i + str
return str
def readFile(file_path):
... |
235a6863fd259e561c92567af98b6ccf29a7fee0 | optimizely/pycon2019 | /lambda_calculus_seminar/pylambda1.py | 202 | 4.09375 | 4 | '''
'''
f = lambda x: 3*x + 1
f(2) # eli5 - you replace the x with the 2
f(4)
'''
def f(x):
return x
def f(x):
return x(x)
'''
def f(x):
def g(y):
return x(y)
return g
|
314411a03d4703ed284d6f12d7f1c356eab8a094 | pandast3ph4n/password-generator | /passgen.py | 1,071 | 3.5625 | 4 | import random
import string
import tkinter as tk
pool = string.ascii_letters + string.digits + string.punctuation
def generate_password(length=12, random_length=False):
if random_length:
length = random.randrange(10, 16)
if length < 4:
print('hey din dust.... ikke noe tull')
return F... |
8a5bb6ad81f3f444da59c72d9c3f3f4dbaf9cfa3 | ccmien/Fundamentals-of-Computing-Projects | /Word Wrangler.py | 4,042 | 4.0625 | 4 | """
Student code for Word Wrangler game
"""
import urllib2
import codeskulptor
import poc_wrangler_provided as provided
WORDFILE = "assets_scrabble_words3.txt"
# Functions to manipulate ordered word lists
def remove_duplicates(list1):
"""
Eliminate duplicates in a sorted list.
Returns a new sorted lis... |
ae97a6da42d85c675d029aacdd0991f18ec08c6c | SofiaDaniela/Mision_02 | /extraGalletas.py | 446 | 3.890625 | 4 | # Autor: Sofía Daniela Méndez Sandoval, A01242259
# Descripción: Cantidad de Ingredientes para # de Galletas
cantidad = int(input("¿Cuántas galletas realizará?: "))
azucar = (cantidad*1.5)/48
mantequilla = cantidad/48
harina = (cantidad*2.75)/48
print("Para realizar el determinado número de galletas, necesitará: ")
... |
c4061364eb081676fcaa1c2720decd4187d1eef9 | vamsikvs1994/Web_crawler | /word_counter.py | 3,854 | 4.09375 | 4 | '''
Author: Venkata Sai Vamsi Komaravolu
Date: 30th December 2017
File Name: word_counter.py
Description:
This python program performs the word count in a web-page given the URL. It makes use of certain
methods and packages available in python.
The working of this program classified as mentioned below:
1. Open th... |
2aefeb397fb1ea15bc2519fa34be929718bf4a9a | agoldh20/exercism | /python/pangram/pangram.py | 249 | 3.609375 | 4 | import re
def is_pangram(sentence):
sentence = sentence.lower()
sentence = re.sub(r'([^a-z])', "", sentence)
if len(list(set(sentence))) < 26:
return False
elif len(list(set(sentence))) == 26:
return True
pass
|
3eb68789808cd0ae37f3509e941521452b9141f7 | IlkoAng/Python-OOP-Softuni | /exercise1-first-steps-oop/04-cup.py | 407 | 3.59375 | 4 | class Cup:
def __init__(self, size, quantity):
self.size = size
self.quantity = quantity
def fill(self, mil):
if self.size >= self.quantity + mil:
self.quantity += mil
def status(self):
result = self.size - self.quantity
return result
cup... |
cbc85235c505b37df1c409b2a9b9a070ae497e42 | liu-creator/python__basic | /Py_mysql/一次插入多条数据.py | 1,135 | 3.59375 | 4 | '''插入100条数据到数据库(一次插入多条)'''
import pymysql
import string,random
#打开数据库连接
conn=pymysql.connect('localhost','root','123456')
conn.select_db('testdb')
#获取游标
cur=conn.cursor()
#创建user表
cur.execute('drop table if exists user')
sql="""CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varc... |
54873a969653a53afa1be805c1c8b96dcd77daa3 | MattBJ/Radar_Object_Detection_System | /Data_Simulations/Sampled_Frequency_Data_out.py | 9,078 | 3.5 | 4 | # Matthew Bailey
# Simulation python code:
# Purpose: Generate 3 sampled frequency data sets that represent a moving ordinance and 2 stationary objects in a 3D Area
# Secondary purpose: Ditch the stationary objects (explain how it would've worked) - Use only x,x',y, and y' and assume stationary Z, as everythin... |
0a6ff68dfe1aa589b13e7baeddc216e2780ca7ec | ngantonio/DataScience-Analysis | /practicas con bases de datos/coutingDomains.py | 1,457 | 3.59375 | 4 | """ cuenta el número total de dominios de emails
y los almacena en una base de datos
"""
import sqlite3 as sql
# Iniciamos las variables de conexión, y creamos la base de datos.
connection = sql.connect('domaindb.sqlite')
cur = connection.cursor()
# Verificamos si la tabla existe, si no, la creamos.
cur.ex... |
492009c5e453bbcd947240576e7741225109328e | Tachone/PythonCode | /countline0007/countline0007.py | 1,154 | 3.640625 | 4 | #!/usr/bin/env python
#coding=utf-8
# 统计目录下文件的代码行数
import os
def walk_dir(path):
file_path=[]
for root,dirs,files in os.walk(path):
for f in files:
if f.lower().endswith('py'):
file_path.append(os.path.join(root,f))
return file_path
def count_codeline(path):
file... |
8f2417a4bd242c6372d79c5244b5af3be83ca9a2 | MahadiRahman262523/Python_Code_Part-2 | /formatted string.py | 198 | 3.875 | 4 | '''
num1 = 20
num2 = 30
print("sum is = ",num1 + num2)
'''
'''
num1 = 20
num2 = 30
print(f"{num1} + {num2} = {num1 + num2} ")
'''
print("mahadi rahman", end = " ")
print("01301442265")
|
4ee6c5e0690d7c0302b76dbebff6751bbf507c1e | MahadiRahman262523/Python_Code_Part-2 | /factorial.py | 119 | 3.953125 | 4 | n = int(input("enter any positive number = "))
fact = 1
for i in range(n) :
fact = fact*(i+1)
print(fact) |
67293e2d186feadeafd7db8ea20284a37e3b93bd | MahadiRahman262523/Python_Code_Part-2 | /sum of n number.py | 130 | 3.9375 | 4 |
n = int(input("enter any integer value = "))
sum = 0
i = 1
while i <= n :
sum = sum + i
i = i + 1
print(sum)
|
ad0b647a1611a07369624c42e3cea0484b7afd4c | flaherty-kr/DS2000HW | /conv.py | 247 | 3.96875 | 4 | # Kristen Flaherty
# Sec 01
#key parameters
#input
km = float(input('Please enter the number of kilometers:\n'))
#km to miles conversion
conv = .621
full_miles = int(km * conv)
#print full miles statement
print("The number of full miles is:", full_miles)
|
77019b16ce59e91dc2f26b3a73a6f353873b9b6c | cbstudent/Exercises | /4. Sorting/mergeSort.py | 606 | 4.03125 | 4 | def mergeSort(array):
_mergeSort(array, 0, len(array) - 1)
return array
def _mergeSort(array, lo, hi):
if lo >= hi:
return
mid = (lo + hi) // 2 + 1
_mergeSort(array, lo, mid - 1)
_mergeSort(array, mid, hi)
merge(array, lo, mid, hi)
def merge(array, lo, mid, hi):
copy = array[:]
p1 = lo
p2 = mid
... |
837e845a9c83a16b34c9581c2bad17b55eda0102 | cbstudent/Exercises | /3. Arrays/threeNumberSum.py | 599 | 3.96875 | 4 | def threeNumberSum(array, targetSum):
# Sort the array (can be sorted in place, because we don't care about the original indices)
array.sort()
res = []
# Use two pointers, one starting from the left, and one starting from the right
for idx, curr in enumerate(array):
i = idx + 1
j = len(array) - 1
... |
9c5cd49ac894af1653d42d202d98446ac5814a77 | cbstudent/Exercises | /7. Graphs/hasSingleCycle.py | 441 | 3.71875 | 4 | def hasSingleCycle(array):
# Write your code here.
idx = 0
counter = 0
while counter < len(array):
# If we've jumped more than once and we find ourselves back at the starting index, we haven't visited each element
if counter > 0 and idx == 0:
return False
jump = array[idx]
idx = (idx + jump) % len(ar... |
19dcfff0b8fc4eaa073e604d83e2519e862d5353 | SteventsStuff/ElementaryTasks | /tests/t3_triangles_test.py | 1,728 | 3.578125 | 4 | #!/usr/bin/env python3
import unittest
import tasks.t3_triangles as triang
from tasks.t3_triangles import Triangle
class TestTriangle(unittest.TestCase):
def setUp(self) -> None:
self.triangle_1 = Triangle("tr1", 12, 15, 14)
self.triangle_2 = Triangle("tr2", 10.5, 13.5, 12.5)
self.triangle... |
bb3e8df598c01c38d5982158ec26c99f8e77fb3c | blaise594/PythonPuzzles | /printStatements.py | 687 | 4.09375 | 4 | #The Purpose of this program is to demonstrate print statements
# Print full name
print("My name is Daniel Rogers")
# Print the name of the function that converts a string to a floating point number
print("The float() function can convert strings to a float")
# Print the symbol used to start a Python comment
print(... |
639d50d4d0579ee239adf72a08d7b4d78d9b91b6 | blaise594/PythonPuzzles | /weightConverter.py | 424 | 4.21875 | 4 | #The purpose of this program is to convert weight in pounds to weight in kilos
#Get user input
#Convert pounds to kilograms
#Display result in kilograms rounded to one decimal place
#Get user weight in pounds
weightInPounds=float(input('Enter your weight in pounds. '))
#One pound equals 2.2046226218 kilograms
weightI... |
2b32c38f8df34e7624b993aba7ba38a88059dcbb | i-djurdjevic/BioinformaticsCourseBook | /poglavlja/9/kodovi/SuffixArrayMultiple.py | 1,715 | 3.8125 | 4 | #Formiranje sufiksnog niza na osnovu niza niski strings
def suffix_array_construction(strings):
suffix_array = []
for s in range(len(strings)):
string = strings[s] + '$'
for i in range(len(string)):
suffix_array.append((string[i:],s, i))
suffix_array.sort()
return suffix_array
#Funkcija vraca pozicije na ... |
f25285c2cc809eeb16fd3696bbfa60ddc341e9e9 | juliali/ClassicAlgorithms | /undirected_graph/ugraph_circle.py | 1,159 | 3.59375 | 4 | import queue
import os
import csv
def is_undirected_graph_circled(adj_matrix):
n = len(adj_matrix)
degrees = [0] * n
visited = []
q = queue.Queue()
for i in range(0, n):
degrees[i] = sum([int(value) for value in adj_matrix[i]])
if degrees[i] <= 1: ... |
9d2a6aa7b90925def161452c31235a27d5af40ca | bushidosds/MeteorTears | /lib/utils/fp.py | 979 | 3.625 | 4 | # -*- coding:utf-8 -*-
import os
def iter_files(path: str, otype='path') -> list:
r"""
Returns a list of all files in the file directory path.
:param path: file path, str object.
:param otype: out params type, str object default path.
:return: files path list.
:rtype: list object
"""
... |
b858cea86ba5635c86653bcc25a02aa9319d3104 | rdauncey/CS50_problem_set_solutions | /pset6/credit.py | 2,025 | 4 | 4 | from cs50 import get_string
from sys import exit
def main():
# Get input from user
number = get_string("Number: ")
digits = len(number)
# Check length is valid
if digits < 13 or digits > 16 or digits == 14:
print("INVALID")
exit(1)
# Luhn's algorithm
if luhns(number) is ... |
abe6d35e9add0faca38e2eb800fef850dee91aed | paperbackdragon/python-300 | /project/dbhelper.py | 2,907 | 3.875 | 4 | """
Database Helper
Author: Heather Hoaglund-Biron
"""
import sqlite3
class DatabaseHelper:
"""
A DatabaseHelper reads and writes MP3 metadata to an SQLite database. It is
necessary to close the connection to the database when finished with the
close() method.
"""
def __init__... |
3f04d5bef7608689c343a5eddb61c3ac1939a3e8 | boconganh/algorithm | /python/merge-sort.py | 418 | 3.609375 | 4 | def merge(A,p,q,r):
n1=q-p+1
n2=r-q
L=A[p:p+n1]+[float("inf")]
R=A[q+1:q+1+n2]+[float("inf")]
#print A[p:r+1],L,R
i=0
j=0
for k in range(p,r+1):
if L[i]<=R[j]:
A[k]=L[i]
i+=1
else:
A[k]=R[j]
j+=1
def merge_sort(A,p,r):
if p<r:
q=(p+r)//2
merge_sort(A,p,q)
merge_sort... |
a2dad7fea5ec6e42767c6ab36c4658c857d5548c | boconganh/algorithm | /python/find-max-subarray.py | 997 | 3.59375 | 4 |
def find_max_cross_subarray(A,low,mid,high):
left_sum=float("-inf")
sum=0
for i in range(mid,low-1,-1):
sum+=A[i]
if sum>left_sum:
left_sum=sum
max_left=i
right_sum=float("-inf")
sum=0
for j in range(mid+1,high+1):
sum+=A[j]
if sum>right_sum:
right_sum=sum
max_right=j
retur... |
ac8ff352c058b7b1e3885d3bca7611f29437f2b4 | SaeedTaghavi/MonteCarloIntegration | /test.py | 1,391 | 3.640625 | 4 | import numpy as np
import random
def calc_pi(N):
inCircle = 0
for i in range(N):
point = (random.random() , random.random())
r = point[0]*point[0] + point[1]*point[1]
if r < 1.0 :
inCircle = inCircle +1
# plt.plot(point[0], point[1], 'r.')
# else:
... |
eac27c0231a6e7acfd305620cff56fd69e3f6d3e | apan64/basic-data-structures | /Lab_11.py | 1,194 | 3.703125 | 4 | import math
class AdjMatrixGraph:
def __init__ (self, n):
self.n = n
self.array = []
for x in range(n):
q = []
for y in range(n):
q.append(int(0))
self.array.append(q)
def display (self):
for x in range (self.n):
... |
ab96fe2f94f539e7535d8110c3dafcd2f35cf097 | apan64/basic-data-structures | /Lab_6.py | 2,569 | 3.921875 | 4 |
class Node:
def __init__ (self, x, q):
self.data = x
self.next = q
class Stack:
def __init__ (self):
self.top = None
def isEmpty (self):
return self.top == None
def push (self, x):
self.top = Node (x, self.top)
def pop (self):
if ... |
02856d56ce1a0c1a834220d6e0eb7d259010e53d | naitiknakrani/Machine-Learning-algorithms | /1.3-polynomial-regression.py | 3,466 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 11 17:42:30 2021
@author: naitik
"""
import matplotlib.pyplot as plt
import pandas as pd
import pylab as pl
import numpy as np
%matplotlib inline
df = pd.read_csv("FuelConsumptionCo2.csv")
df.head() # show data
df.describe() #summarize data
cdf = ... |
7ebafa063d92a5960289cba76c3043e18990810e | IqbalHadiSubekti/Factorial | /factorial.py | 462 | 4.0625 | 4 | count = 0
while count == 0:
def factorial(n):
if 1 <= n <= 2:
return n
elif 3 <= n <= 5:
return n + 1
elif 6 <= n <= 8:
return n + 2
elif 9 <= n <= 11:
return n + 3
else:
print("Input Salah")
n = int(input("Input: "))
print("Output:... |
5e238d1bc97635963bcb15b615c9e94fbf7c7b5f | dharanpreethi/Text-Minining_Indian-English-Liteature | /Text_mining/Corpus_tm.py | 2,458 | 3.890625 | 4 | # Corpus of text analysis
# Now, we can mine the corpus of texts using little more advanced methods of Python.
#1.Install glob using pip and import the module
#2. Import other necessary modules which we already installed in our previous analysis
#3. Asterisk mark will import all plain text files in the corpus
#4. Cre... |
8160b104778db2c44617989b4a58d2f9873fa57c | AYBUcode/CENG113fall2020 | /Week3p.py | 141 | 3.828125 | 4 | a=3.556; b=4; c="abc"
print('{0}+{1}={2}'.format(a,b,a+b))
print("the value of a:%10.0f!!"%(a))
x = int(input("Enter a value: "))
print(x*2) |
24a70d398de181471d15d36d995c8585b1c35ea7 | quentinb28/problem-solving-challenges | /codility/flags.py | 1,694 | 3.6875 | 4 | def solution(A):
# initialize list of peaks indexes in between peaks
peaks = [0] * len(A)
# last item should be index outside of peaks length
next_peak = len(A)
peaks[-1] = next_peak
# stops at 0 because we want to avoid index out of range within if statement
for i in range(len(A) - 2, 0... |
4c22ce72238761ce47b68c340174df50866a6a35 | quentinb28/problem-solving-challenges | /sherlock-and-anagrams/sherlock-and-anagrams-exercise.py | 1,063 | 3.890625 | 4 | from collections import Counter
from itertools import combinations
s = 'ifailuhkqq'
def sherlockAndAnagrams(s):
# Variable to store all possible combinations
all_combinations = []
# Iterate through substrings starting points
for i in range(0, len(s) + 1):
# Iterate through substrings endi... |
39347b2b248bd565b8a1df9753681900855e88d0 | quentinb28/problem-solving-challenges | /new-year-chaos/new-year-chaos-exercise.py | 585 | 3.578125 | 4 | q = [2, 1, 5, 3, 4]
def minimumBribes(q):
# Initiate total number of bribes
total_bribes = 0
# Iterate through each runner backward
for i in range(len(q) - 1, -1, -1):
# Stop execution if a runner bribes more than two runners
if q[i] - (i + 1) > 2:
print('Too chaotic')... |
79fb67bd7592371aaf3861d4e0f9dc84f3a94fdd | y001003/PythonStudy | /_class/class_overriding_1.py | 2,318 | 3.75 | 4 | #일반 유닛
class Unit: # 부모 class
def __init__(self, name, hp, speed):
self.name = name
self.hp = hp
self.speed = speed
print("{0} 유닛이 생성되었습니다.".format(self.name))
def move(self, location):
print("[지상 유닛 이동")
print("{0} : {1} 방향으로 이동합니다. [속도 {2}]"\
... |
2c8446bcdebf09395972b1f4fc94eecc00a29fde | y001003/PythonStudy | /_class/class_super_1.py | 2,233 | 3.75 | 4 | #일반 유닛
class Unit: # 부모 class
def __init__(self, name, hp, speed):
self.name = name
self.hp = hp
self.speed = speed
print("{0} 유닛이 생성되었습니다.".format(self.name))
def move(self, location):
print("[지상 유닛 이동")
print("{0} : {1} 방향으로 이동합니다. [속도 {2}]"\
... |
36b67db6ed6e02eb188301bea8a878aa34166ad6 | y001003/PythonStudy | /_file/input_output_1.py | 856 | 3.765625 | 4 |
# print("Python","Java","JavaScript", sep=" vs ", end="?")
# print("무엇이 더 재미있을까요?")
# import sys
# print("Python","Java", file=sys.stdout)
# print("Python","Java", file=sys.stderr)
# dictionary
# scores = {"수학":0, "영어":50, "코딩":100}
# for subject, score in scores.items():# items() : key와 value 쌍으로 보내줌
# ... |
3bdb316174a1c4996567dd5bb66fd25ab8891b57 | y001003/PythonStudy | /_for,while/for_2.py | 519 | 3.671875 | 4 | # 출석번호가 1 2 3 4, 앞에 100을 붙이기로 함 -> 101, 102,103,104.
# students = [1,2,3,4,5]
# print(students)
# students = [i+100 for i in students]#students 값을 i에 대입해서 각 i +100
# print(students)
# 학생 이름을 길이로 변환
# students = ["Iron man", "Thor", "I am groot"]
# students = [len(i) for i in students]
# print(students)
# 학... |
c0287f0659be8e9c8b945efbeb98e648caf565a9 | y001003/PythonStudy | /_class/class_heritage_1.py | 1,683 | 3.6875 | 4 | #일반 유닛
class Unit: # 부모 class
def __init__(self, name, hp):
self.name = name
self.hp = hp
print("{0} 유닛이 생성되었습니다.".format(self.name))
#공격 유닛
class AttackUnit(Unit): # 자식 class
def __init__(self, name, hp, damage):
Unit.__init__(self, name, hp)
self.damage = da... |
c3a23f4391d29250c7ff9ee4fa0ad9cd133abbe7 | priancho/nlp100 | /05.py | 900 | 4.3125 | 4 | #usage example:
#python3 05.py 2 "This is a pen."
import re
import sys
# extract character n-grams and calculate n-gram frequency
def char_n_gram(n, str):
ngramList = {}
n=int(n)
str = str.lower()
wordList=re.findall("[a-z]+",str)
for word in wordList:
if len(word) >= n:
for i in range(len(word)-n+1):
i... |
af416cceefc1c63424869b66e5fbbaccf9e1f4a5 | silvaniodc/python | /Aulas Python/E_hoje.py | 1,049 | 3.546875 | 4 | # -*- coding: UTF-8 -*-
# O que Silvanio vai fazer no Domingo?
def hoje_e_o_dia():
from datetime import date
hj = date.today()
dias = ('Segunda-feira', 'Terça-feira', 'Quarta-feira', 'Quinta-feira', 'Sexta-feira', 'Sábado', 'Domingo')
dia = int(hj.weekday())
if dia == 3 :
print 'Hoje é %s e Silvânio vai c... |
fee0f545fe5e9ec8758ef45e2411e1a2e76801c4 | rustikk/OpenCV-Basics | /opencv-getting-setting/gett_setting_code_along.py | 1,990 | 3.546875 | 4 | import argparse
import cv2
#construct the argument parser
ap = argparse.ArgumentParser()
#if no argument is passed, "adrian.png" is used
ap.add_argument("-i", "--image", type=str, default="adrian.png",
help="path to input image")
#vars stores the arguments in a dictionary
args = vars(ap.parse_args())
#load the image,... |
bc44e991bdb4525bbca5a93fe4e6db50947fe225 | kerroggu/AtCoderLibrary | /src/UnionFind.py | 1,325 | 3.609375 | 4 | ## Tested by ABC264-E
## https://atcoder.jp/contests/abc264/tasks/abc264_e
## Tested by ABC120-D
## https://atcoder.jp/contests/abc120/tasks/abc120_d
class UnionFind:
def __init__(self,n):
# 負 : 根であることを示す。絶対値はランクを示す
# 非負: 根でないことを示す。値は親を示す
self.parent=[-1]*n
# 連結成分の個数を管理
sel... |
053d941b6d0539e9510961fd68a4a70123ff0cc7 | DouglasCremonese/Uri | /1042.py | 266 | 3.734375 | 4 | # Exercício 1042 Uri Online Judge
# Programador: Douglas Garcia Cremonese
lista = list()
a, b, c = map(int, input().strip().split(" "))
lista.append(a)
lista.append(b)
lista.append(c)
lista.sort()
for i in range(3):
print(lista[i])
print()
print(a)
print(b)
print(c) |
8a56d576c3c6be23f5fdbb3ad70965befbac04f7 | juancebarberis/algo1 | /practica/7-10.py | 898 | 4.3125 | 4 | #Ejercicio 7.10. Matrices.
#a) Escribir una función que reciba dos matrices y devuelva la suma.
#b) Escribir una función que reciba dos matrices y devuelva el producto.
#c) ⋆ Escribir una función que opere sobre una matriz y mediante eliminación gaussiana de-
#vuelva una matriz triangular superior.
#d) ⋆ Escribir una f... |
49ff1527a9468412bde79ed0664bdbf5ebbdac99 | juancebarberis/algo1 | /tp2/modulos/input.py | 2,558 | 3.625 | 4 | #Este módulo contiene funciones del tipo input que intervienen en la jugabilidad
#y el movimiento de Snake.
from modulos.terminal import timed_input
def inputJugada(movimiento, variables, _ESPECIALES, snake):
"""
Comprueba lo ingresado por el usuario desde el teclado.
Evalúa si pertenece a un movimiento, ... |
aa85396997537a23bda51f9247ef62426ba564a3 | juancebarberis/algo1 | /practica/mapEnClase.py | 182 | 3.609375 | 4 | def map(seq, funcion):
res = []
for elem in seq:
res.append(funcion(elem))
return res
def por_2(n): return n * 2
seq = [1,2,3,4,5,6,7,8]
print(map(seq, por_2)) |
51956c3e996f59440be71017a4160422f79b320b | juancebarberis/algo1 | /pre-parcialito/parcialito_3.py | 2,155 | 3.734375 | 4 | '''
1. Escribir una funci´on reemplazar que tome una Pila, un valor nuevo y un valor viejo y
reemplace en la Pila todas las ocurrencias de valor viejo por valor nuevo. Considerar que la
Pila tiene las primitivas apilar(dato), desapilar() y esta vacia().
'''
def reemplazar(pila, nuevo, viejo):
pilaAuxiliar = Pila()
#... |
ef2adcd35cf3050024eaad85e20cfa17d87d6132 | juancebarberis/algo1 | /practica/6-1.py | 1,072 | 4.03125 | 4 | #Ejercicio 6.1. Escribir funciones que dada una cadena de caracteres:
#a) Imprima los dos primeros caracteres.
#b) Imprima los tres últimos caracteres.
#c) Imprima dicha cadena cada dos caracteres. Ej.: 'recta' debería imprimir 'rca'
#d) Dicha cadena en sentido inverso. Ej.: 'hola mundo!' debe imprimir '!odnum aloh'
#e... |
04dcc88ad0fb461fa9aafe3e290ab9addb03c08e | juancebarberis/algo1 | /practica/5-4.py | 1,135 | 4.125 | 4 | #Ejercicio 5.4. Utilizando la función randrange del módulo random , escribir un programa que
#obtenga un número aleatorio secreto, y luego permita al usuario ingresar números y le indique
#si son menores o mayores que el número a adivinar, hasta que el usuario ingrese el número
#correcto.
from random import randrange
... |
e08f787de4a2297aa6884dbb013e92f612423cc5 | juancebarberis/algo1 | /practica/7-7.py | 877 | 4.21875 | 4 | #Ejercicio 7.7. Escribir una función que reciba una lista de tuplas (Apellido, Nombre, Ini-
#cial_segundo_nombre) y devuelva una lista de cadenas donde cada una contenga primero el
#nombre, luego la inicial con un punto, y luego el apellido.
data = [
('Viviana', 'Tupac', 'R'),
('Francisco', 'Tupac', 'M'),
... |
f9209f14d346695a6956bdc5180624ca6144b176 | juancebarberis/algo1 | /ej1/norma.py | 694 | 3.515625 | 4 | # NOMBRE_Y_APELLIDO = JUAN CELESTINO BARBERIS
# PADRÓN = 105147
# MATERIA = 7540 Algoritmos y Programación 1, curso Essaya
# Ejercicio 1 de entrega obligatoria
def norma(x, y, z):
"""Recibe un vector en R3 y devuelve su norma"""
return (x**2 + y**2 + z**2) ** 0.5
assert norma(-60, -60, -70) == 110.0
assert no... |
ce044a40bf93a96235b26cbd956382cbdb23c054 | stavanmehta/image-test | /image_helper/shortest_sequence.py | 458 | 3.75 | 4 |
def solution(N):
# write your code in Python 3.6
commands = list()
L = 0
R = 1
def getL():
return 2 * L - R
def getR():
return 2 * R - L
print L
if N < 0:
L = getL()
commands.append(L)
while L >= N:
L = getL()
if L + R ... |
52bd4fcad10f017b48d79ab42a97e75fa9c7b7f4 | AshleySetter/LearningTravis | /UnecessaryMath.py | 139 | 3.71875 | 4 | def multiply(a, b):
"""
multiplies 2 python objects,
a and b and returns the result
"""
result = a*b
return result
|
7926f12749d7c6331283b2b5c7006ecddd3a88e0 | frollo/AdvancedProgramming | /Lab-7/es1.py | 783 | 3.609375 | 4 | import sys
from re import sub
def isMinor(word):
return (word == "the") or (word == "and") or (len(word) <= 2)
if __name__ == '__main__':
kwicindex = list()
counter = 0
titles = dict()
with open(sys.argv[1], "r") as file:
for line in file:
counter += 1
line = sub("[... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.