blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
efe9eeb458d3b941dfe54537a375fb3549177d95 | dmartinez81/Python | /Valid_Parentheses.py | 1,019 | 3.828125 | 4 | # class Solution(object):
def isValid(s):
"""
:type s: str
:rtype: bool
"""
if len(s) == 1: return False
middle = len(s)//2
for i in range(0, middle):
# s = "([])"
if s[i] == '(' and s[len(s)-1-i] == ')' or s[i] == '{' and s[len(s)-... |
e6e6a115ad2d3bbb87775e9d06ae05011ba303b4 | RobyJacob/Coding-problems | /balancedarr.py | 397 | 3.765625 | 4 | def balancedSum(arr):
# Write your code here
acc_sum = [0 for j in range(len(arr)+1)]
for j in range(len(arr)):
acc_sum[j+1] = arr[j] + acc_sum[j]
total = sum(arr)
for i in range(len(arr)):
left_arr_sum = acc_sum[i]
right_arr_sum = total - acc_sum[i+1]
if left_arr_... |
39286f09d355474fe924b8273f32dc793ed1b775 | vigneshtmjv/python-programming | /vicky.py | 85 | 3.6875 | 4 |
a=input("enter the data to be reversed")
b=list(reversed(a))
print("\n",''.join(b))
|
608d1f46cc2c1d17f5cfae0afb30116322b513a8 | hinamiqi/PMRL | /objects.py | 2,523 | 3.796875 | 4 | import abc
'''OBJECTS'''
class Obj(metaclass=abc.ABCMeta):
pickable = True
penetrable = True
bold = False
@abc.abstractmethod
def __str__(self):
return " "
def color(self):
#return 2
return ('w','b')
def descr(self):
return "void"
def fdescr(s... |
f48c8e4e53f7f4a1a6c1e2fff5d8c28a21986530 | tushark26/Coding-algos | /Python/Trees - Traversal - Leetcode 230.py | 1,962 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 30 12:31:14 2020
@author: tushar
"""
def kth_smallest_element(root, k):
# Count to iterate over elements
# till we get the kth smallest number
count = 0
ksmall = -9999999999 # store the Kth smallest
curr = root # to store the current node
while... |
829cf54cf81bc6e9a62e32389007e4089f227902 | zxt2012bs/testpython | /code/Average2.py | 218 | 3.90625 | 4 | # 3 numbers with format: 1,2,3
number1, number2, number3 = eval(input("请输入三个数字:"))
average = (number1 + number2 + number3)/3
print(number1, number2, number3, "这3个数字的平均数是", average)
|
6ce391ef4554effa469854fa1778b005932197e8 | Ryuuken-dev/Python-Zadania | /Moduł I-lekcja 6/Dodatkowe/Triangle_area.py | 441 | 3.9375 | 4 | length_of_a_side = int(input('Podaj długość boku trójkąta równobocznego: '))
height_of_a_triangle = (length_of_a_side ** (1/3)) / 2
area_of_a_triangle = ((length_of_a_side ** 2) ** (1/3)) / 4
side_area_of_a_cone = 3.14 * (length_of_a_side / 2) ** 2
cone_capacity = (1/3) * side_area_of_a_cone * height_of_a_triangle
prin... |
78a1b8f86aea0e74d7e4ea806b60992abd7f7dd4 | hiteshpindikanti/Coding_Questions | /DCP/DCP119.py | 1,191 | 4.3125 | 4 | """
This problem was asked by Google.
Given a set of closed intervals, find the smallest set of numbers that covers all the intervals. If there are multiple smallest sets, return any of them.
For example, given the intervals [0, 3], [2, 6], [3, 4], [6, 9], one set of numbers that covers all these intervals is {3, 6}.... |
e07c289f26cac14d129c15951ee0fea481f7f394 | flextedlinyc1983/python | /my_program.py | 353 | 4.03125 | 4 | if 3 > 2:
print('It works!')
def hi(name):
print('Hi ' + name + '!')
hi('Belle')
class Car:
def __str__(self):
return 'Car: ' + self.name
def __init__(self, name):
self.name = name
def run(self):
print(self.name + ' Run!')
benz = Car('ted')
benz.run()
print(benz)
boys = ['ted 1', 'ted 2', 'ted 3'... |
d0bd6735f2d52639e9def96f5e206b30f54ddafc | andrea270872/machineLearningTasks | /lecture1/perceptron_v0_3.py | 3,653 | 3.78125 | 4 | # 9 July 2013
# Andrea Valente www.create.aau.dk/av
# Lecture 1 Machine Learning lecture notes
#
# 1) load all 7 images, as 16x16 grayscale images
# 2) Alien, Bee, Female and Male should be accepted
# 3) train a perceptron to recognize the "good" images and reject the bad ones
# 4) see how well the trained perception p... |
30345bee56b2c15d5a15a01e223d39de2447b5ca | ivan-yosifov88/python_fundamentals | /functions_exercise/facrotial_division.py | 394 | 4.15625 | 4 | def factorial_divisor(a, b):
factorial_num_a = 1
for num_a in range(2, a + 1):
factorial_num_a *= num_a
factorial_num_b = 1
for num_b in range(2, b + 1):
factorial_num_b *= num_b
result = factorial_num_a / factorial_num_b
print(f"{result:.2f}")
first_number = int(input())
se... |
782472c070ab2db6a8d889db198adc1faf9ad543 | chagan1985/PythonByExample | /ex067.py | 216 | 3.90625 | 4 | #####
# Python By Example
# Exercise 067
# Christopher Hagan
#####
import turtle
for i in range(0, 10):
turtle.right(36)
for i in range(0, 8):
turtle.forward(100)
turtle.left(45)
turtle.exitonclick()
|
45ee8dbbfb52ed571d5d2cb92569c04c14244c1e | amomin/proje | /python/pe451.py | 730 | 3.84375 | 4 | import time
import MillerTest
isPrime = MillerTest.MillerRabin
t1 = time.time()
X = 10000
N = X + 1
#p = [[0]*(N+1),[1]*(N+1)]
def square(a,n):
return (a*a) % n
total=0
for k in range(3,N):
n=k-1
found = False
if isPrime(k):
n=1
elif ((k % 2) == 0) and isPrime(k/2):
n=1
elif ((k % 3) == 0 ) and isPrime(... |
2ca5379e9b98e80264dc3324efb9b66700887c42 | hsi-cy/codewars | /SOLVED/Search_for_letters.py | 883 | 4.25 | 4 | """
Create a function which accepts one arbitrary string as an argument, and return a string of length 26.
The objective is to set each of the 26 characters of the output string to either '1' or '0' based on the fact
whether the Nth letter of the alphabet is present in the input (independent of its case).
So if an '... |
156c219861a7257804f7d365d2ca108634f5792d | KevinHenneberger/CS110 | /notes/booleans.py | 1,263 | 3.78125 | 4 | #==============================
# CW Pt 1: Boolean Functions
#==============================
"""
def grade(score):
if (score >= 90):
return 'A'
elif (score >= 80):
return 'B'
elif (score >= 70):
return 'C'
elif (score >= 60):
return 'D'
else:
return 'F'
def ... |
6fe5629d245e3c37c22531665c895a35f4eb4848 | Lostefra/deep_comedy | /metrics/rhyme.py | 5,565 | 3.703125 | 4 | import re
from metrics import syllabification as s
# Rhyme scoring and extraction module. Exploits information about accents, syllables and heuristics to perform
# the difficult task of determining if two words form a rhyme.
# Computes a rhyming score between two words.
def rhyme_score(w1, w2):
if w1 == "" or w2... |
a9faced31adf99f1adca5616b2c9dc9e786013c9 | Mingqianluo/A1805A | /A1807/06day/02-单例.py | 283 | 3.578125 | 4 | class Dog():
instance = None
def __new__(cls):
if cls.instance == None:
cls.instance = super.__new__(cls)
return cls.instance
else:
return cls.__instance
def __init__(self,name):
dog1 = Dog()
print(id(dog1))
|
049e0724ba8baa6243e0aa03ab326c39a70c0872 | eduardomessias/repl-algorithms | /algorithms/gdc.py | 182 | 3.75 | 4 | # Euclidian application for greater common divisor
def gcd (x, y):
while (y):
x, y = y, x % y
return x
print ("Greater common divisor for 60 and 48: ")
print (gcd (60, 48)) |
d290773a912e0d72e5fcbd7fc98fa0db1f7eb467 | fernandovmac/lyrics_analyzer | /flask_server/lyrics_api.py | 3,956 | 3.5625 | 4 | #https://api.lyrics.ovh/v1/artist/title
import requests
import argparse
def get_client_request(artist_requested, song_requested):
r = requests.get(f'http://127.0.0.1:5000/getquery?')
if r.status_code == 200:
payload = r.json()
artist_requested = payload['artist']
song_requested = paylo... |
4c82b55d674452b374cf91e1e7bcc0b9038b747d | maurob/repartija | /tests.py | 3,696 | 3.59375 | 4 | # -- coding=utf-8 --
import unittest
from repartija import Repartija
class Test(unittest.TestCase):
def test_precio_de_hora_igual(self):
""" Si cobramos igual la hora, deberíamos repartirnos en función de las horas trabajadas """
uut = Repartija()
uut.set_precios_por_hora({'martin': 10, '... |
ad57bb9a21d1df4404501cdf4a6e4240a33d00d1 | niyogakiza/april-2020-machine-learning | /model-persistence/model-persistence.py | 3,205 | 3.859375 | 4 | # To do this, the pickle module can be used. The pickle module is used to store Python objects. This module is a part
# of the standard library with your installation of Python. The pickle module transforms an arbitrary Python object
# into a series of bytes. This process is also called the serialization of the object.... |
7304583883f94d40ea0de75e4e827bfa2fb4c32d | kerniee/ibc-2020-matvey | /day_5/birthday_paradox.py | 806 | 3.734375 | 4 | import math
import random
def do_for(f, num_of_people, times):
res = 0
for i in range(times):
res += f(num_of_people)
return res / times
def gen_day_of_birth():
# Num of a day in year
return random.randint(1, 365)
def check_group(num_of_people):
# Return 1 if group with random numbers of people
#... |
927b4b6fe8ca97d6859285ee2b2890a2a887bc15 | scottwedge/Python-4 | /module_3/socketServer/socketServerFramework/lame-MulitThreadTCPServer.py | 2,632 | 3.65625 | 4 | #!/usr/bin/python
# this will be a multi threaded TCP Server that will serve forever until SIGINT
## this is not the right way of doing a threaded socketServer
## after reading the documentation, the better way has path:
# /home/kevin/Python/module_3/socketServer/socketServerFramework/better-multiThreadSocketServer.... |
3bd2bd7d59883eb3c384d6fe2f82e4effb86edda | wangJI1127/wj_leetCode | /lintCode/_155_minimum_depth_of_binary_tree.py | 1,075 | 4.25 | 4 | """
给定一个二叉树,找出其最小深度。
二叉树的最小深度为根节点到最近叶子节点的最短路径上的节点数量。
样例
样例 1:
输入: {}
输出: 0
样例 2:
输入: {1,#,2,3}
输出: 3
解释:
1
\
2
/
3
它将被序列化为 {1,#,2,3}
样例 3:
输入: {1,2,3,#,#,4,5}
输出: 2
解释:
1
/ \
2 3
/ \
4 5
它将被序列化为 {1,2,3,#,#,4,5}
"""
"""
Definition of TreeNode:
"""
class TreeNode:
def _... |
7a879a8389750c713de7888914f2cb428cc3852a | thaus03/Exercicios-Python | /Aula07/Desafio014.py | 193 | 4.25 | 4 | # Escreva um programa que converta uma temperatura digitada em ºC e converta par ºF
temp = float(input('Digite a temperatura em ºC: '))
print(f'{temp} C corresponde a {(temp * 1.8)+32} F')
|
66010885681722d77942f1d9f50d1d408ed4e34d | alexalex222/My-Leetcode-Practice | /python/kthlargestelement.py | 342 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun May 31 21:06:35 2015
@author: Kuilin
"""
class Solution:
# @param {integer[]} nums
# @param {integer} k
# @return {integer}
def findKthLargest(self, nums, k):
return sorted(nums, reverse = True)[k-1]
mysol = Solution()
a = [3,2,1,5,6,4]
result = mys... |
ee85ec58626c83f5a4e094f98fc459abdab64dab | dinghb/CodePracticeChallenge | /easy/003_Sum-of-Numbers/resolve1.py | 212 | 3.84375 | 4 | def get_sum(a, b):
if a == b:
return a
elif a > b:
tmp = a
a = b
b = tmp
sum = 0
for i in range(a, b + 1):
sum += i
return sum
print(get_sum(0, 2))
|
a2621192cbfefc5277d7451fdf0a28cb739be653 | parksjsj9368/TIL | /ALGORITHM/PROGRAMMERS/ALGORITHM_TEST/10. 메뉴 리뉴얼.py | 740 | 3.546875 | 4 | from itertools import combinations # 조합을 위한 모듈
from collections import Counter # 등장횟수를 위한 모듈
def solution(orders, course):
answer = []
for i in course :
array = []
for j in orders :
j = sorted(j)
array.extend(list(map(''.join, combinations(j,i))))
# print(array... |
5d28454bc93a06b8fdce069c912fc6f8ce3afd02 | akmalmuhammed/Skools_Kool | /Chapter_14/Exercise4.py | 2,593 | 3.953125 | 4 | __author__ = 'matt'
"""
Write a program that searches a directory and all of its subdirectories, recursively, and returns a list of complete paths for all files with a given suffix (like .mp3). Hint: os.path provides several useful functions for manipulating file and path names.
"""
import os
from collections import ... |
9d9dfa3aeb7ace3ae52ee5530f09204c77fa496c | pythonarcade/arcade | /arcade/examples/sprite_bullets_random.py | 3,181 | 3.859375 | 4 | """
Show how to have enemies shoot bullets at random intervals.
If Python and Arcade are installed, this example can be run from the command line with:
python -m arcade.examples.sprite_bullets_random
"""
from __future__ import annotations
import arcade
import random
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
SCREEN_TITL... |
57bf64fdf9d0b43f2a5bfa944b9dfd6038f02a7b | stombya/PythonBeginnerPrograms | /Python Programs/celestialcal.py | 747 | 3.875 | 4 | # Welcome to my Celestial program
# Alex Stomberg
# Period 7 #
# 10/5/2018
# weight, venus,moon,jupiter,choice
print ("Welcome to the celsetial program!\n")
weight = int(input("What is your earth weight:"))
print ("\n1.venus")
print ("2.moon")
print ("3.mars")
print ("4.jupiter")
choice = ... |
772e120d94a4d1360a1755052ac16a1184f22cf1 | cipheraxat/Data-Dashboard | /wrangling_scripts/wrangle_data.py | 3,045 | 3.671875 | 4 | import pandas as pd
import plotly.graph_objs as go
# Use this file to read in your data and prepare the plotly visualizations. The path to the data files are in
# `data/file_name.csv`
def return_figures():
"""Creates four plotly visualizations
Args:
None
Returns:
list (dict): list contai... |
3500d905914f65739d515d74505414d8fdd59681 | MattVil/Clusturing_Zoo | /utils.py | 1,001 | 3.609375 | 4 | import numpy as np
import matplotlib.pyplot as plt
def print_it(it):
print("#"*80)
print("#" + " "*78 + "#")
print("#\t\t\t\t Iteration {}:\t\t\t\t #".format(it))
print("#" + " "*78 + "#")
print("#"*80)
def load_data(data_path):
"""Return data from a txt file as array"""
return np.l... |
ade43b3172c47aa45fc3c3893b3ee9eb454598d8 | kapil-varshney/utilities | /training_plot/train.py | 1,985 | 3.5625 | 4 | #import the required libraries
import keras
import numpy as np
from keras.datasets import cifar10
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras.layers import Dense, Flatten, Dropout, Activation
from keras.layers import Conv2D, MaxPooling2D
from trainingplot import T... |
586cb88c8533292d3f5eb86f66c6cf689c5ee8af | sudh29/Data-Structure-Code | /Array/15_nextperm.py | 1,065 | 3.9375 | 4 | # Implement next permutation, which rearranges numbers into the
# lexicographically next greater permutation of numbers.
# If such an arrangement is not possible, it must rearrange it
# as the lowest possible order (i.e., sorted in ascending order).
# The replacement must be in place and use only constant extra m... |
9286097cb660012260fc6c9293951d5f78bebb8f | sd37/random-code | /rq/balanced_brackets.py | 843 | 3.90625 | 4 | class Stack(object):
def __init__(self):
self.storage = []
def __repr__(self):
return str(self.storage)
def push(self,e):
self.storage.append(e)
def pop(self):
if self.isEmpty():
return 'Empty'
return self.storage.pop()
def isEmpty(self):
return not bool(self.storage)
def balanc... |
ec07603ca60b1b5c38d2751cebfe19318f06c13a | madasuvamsi/AlgorithmsInPython | /PowerSetProblem.py | 157 | 3.875 | 4 | x=[1,2]
subset=[[]]
for ele in x:
for i in range(len(subset)):
currentlist=subset[i];
subset.append(currentlist+[ele])
print(subset)
|
c575e6128c8f352995983c6967e970a10db27520 | phamhoaiThanh/Practical8 | /practical 4/list_exercise.py | 397 | 4 | 4 |
num1 = input ("Number:")
num2 = input ("Number:")
num3 = input ("Number:")
num4 = input ("Number:")
num5 = input ("Number:")
x = max (num1, num2, num3, num4, num5)
y = min (num1, num2, num3, num4, num5)
first_count= (num1)
first_count2= (num5)
print("The first number is" , first_count)
print("The last number is", fir... |
332cc62c4567bb6c6eb3e8e9c9a72c115b2c2f73 | peppermatt94/finance | /simulation.py | 6,953 | 4.03125 | 4 | from numpy import random as rd
from dataclasses import dataclass
import numpy as np
import pandas as pd
@dataclass
class ITO_simulation:
"""
Principle class: it take the pandas dataframe of the stock prices
and the number of days in which the simulation must be perfomed.
ITO processes are extended cla... |
5eedd37d93672f34046e30eff295c3a63b936c79 | Manoj-manu-8/Python-essitionals | /python assignmet 4.py | 1,371 | 4.0625 | 4 | #!/usr/bin/env python
# coding: utf-8
ASSIGNMENT 4:
1.Write a program to print the repeated words index in a given string?
# In[4]:
s="If we are good to someone one day we will have respect for that"
l=s.split()
for i in l:
if (i=="we"):
print(s.index(i))
print(s.rindex(i))
b... |
677c5c33c124c990dc6b54b21988160edba88ecf | olesyat/tictactoe | /tic_tac.py | 3,673 | 3.78125 | 4 | from node_tree import Node, Tree
from copy import deepcopy
class Board:
WINNER = None
def __init__(self):
self.coordinates = [None for i in range(9)]
self.last_value = None
self.last_position = None
def set_mark(self, symbol, coordinate):
self.coordinates[coordinate] = sy... |
c25ba919c1e9ce6c9d324ef33dfdce11a0c40f73 | manaschugani/PythonCC | /Chapter 4/4-11.py | 349 | 3.96875 | 4 | favorite_sushis = ['tempura', 'california', 'cream cheese']
friend_sushis = favorite_sushis[:]
favorite_sushis.append("tempura")
friend_sushis.append('california')
print("My favorite sushis are:")
for sushi in favorite_sushis:
print("- " + sushi)
print("\nMy friend's favorite sushis are:")
for pizza in friend_su... |
f984f5d25d9f0ccebe75f0fb8bccd2eb161e7cd3 | galaxy24/BountyHunter | /app/utils/encrypt.py | 545 | 3.609375 | 4 | # -*- coding: utf-8 -*-
import base64
from hashlib import sha256
def encrypt_password(password):
"""Hash password on the fly."""
assert isinstance(password, str)
if isinstance(password, str):
password = password.encode('UTF-8')
assert isinstance(password, bytes)
result = password
... |
0190ea04522e5a0458f1621f4e38267e07372fd1 | kikivanrongen/RailNL | /classes/classes.py | 1,388 | 3.6875 | 4 | import csv
class Stations():
def __init__(self):
self.names = []
self.x = []
self.y = []
self.critical = []
def stations(self, stations_csv):
"""returns list of all stations with
corresponding coordinates"""
# open csv file with stations
with ... |
9a94d67e6e6e5c6aa0e7d54882acb35b0da74b0b | phyzikhs/matrix-comparison | /xtMx.py | 3,107 | 3.84375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 14 18:55:04 2020
@author: rayhaan
"""
import time
import numpy as np
from functools import reduce
import matplotlib.pyplot as plt
#MATRIX MULTIPLICATION FUNCTION
def matmult(A, B):
C = [[0 for row in range(len(A))] for col in range(len(B[0]))... |
6888cc1eefca41b88c5bd643a1029b16014eb4c4 | comedxd/Artificial_Intelligence | /0-3-IncorrectUseofSelf.py | 293 | 4.0625 | 4 | class Car:
def __init__(): # must pass self object
self.color = "Red" # ends up on the object
make = "Mercedes" # becomes a local variable in the constructor
car = Car()
print(car.color) # "Red"
print(car.make) # would result in an error, `make` does not exist on the object |
4d334c1aff444471050eddec13ef9e1c9a11758e | kupriyanovart/algorithms_and_ds | /recursion/greater_common_divisor.py | 562 | 3.875 | 4 | # Медленный вариант из-за возможной слишком высокой глубины вложенности
# Нахождение НОД методом вычитания
def gcd_v1(a:int, b:int):
if a == b:
return a
elif a > b:
return gcd_v1(a-b, b)
else: # b > a
return gcd_v1(b-a, a)
# Нахождение НОД делением
def gcd_v2(a:int, b:int):
# к... |
6e189833865feec3752b110b5282aae2ec8e2752 | hertacao/Course-Knowledge-Graphs | /exercises/ex1.py | 759 | 3.8125 | 4 | from exercises.ex0 import Graph
class METISGraph:
def __init__(self, graph):
self.nodes = graph.nodes
self.edges = len(graph.edges)
self.neighbors = {}
for edge in graph.edges:
if edge[0] in self.neighbors:
self.neighbors[edge[0]].add(edge[1])
... |
90547459f50458e8049df9598caec6e30c28eda8 | bestgopher/dsa | /linked_list/base.py | 2,183 | 3.953125 | 4 | from linked_list._node import _Node, _DoubleNode
from typing import Optional
from exceptions import Empty
class LinkedListBase:
"""Linked list base object"""
def __init__(self):
self._head: Optional[_Node] = None
self._size = 0
def __len__(self):
"""Return the number of elements ... |
a273bfbe82b1533c3f35c706590b684869b6a401 | Lharp5/comp4106-assignments | /project/generate_data.py | 1,473 | 3.6875 | 4 | from deck import Deck
from hand import Hand
import random
correct_file = 'correct_move.txt'
incorrect_file = 'incorrect_move.txt'
def write_entry(input_file, play):
with open(input_file, 'a') as write_file:
write_file.write(play.to_binary() + '\n')
def generate_data(num_data):
num_left = nu... |
fc72fb2206aa9139b5ac14872d787e16986e8b5b | camillewu90/supervised_learning | /k-NN template.py | 2,157 | 4.03125 | 4 | ## Use knn to predict the iris species
# Import KNeighborsClassifier from sklearn.neighbors
import numpy as np
from sklearn import datasets
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
iris = datasets.load_iris()
iris.keys()
# C... |
edad663704367bb8777dea34002d81ad60b26617 | Aasthaengg/IBMdataset | /Python_codes/p02786/s767421888.py | 107 | 3.671875 | 4 | h = int(input())
num = 1
count = 0
while h > 0:
h = h//2
count += num
num = num*2
print(count) |
3e3ede32ef413909199e90c9d603b725e615e405 | effyhuihui/leetcode | /linkedList/addTwoNumbers.py | 2,104 | 3.6875 | 4 | __author__ = 'effy'
'''
You are given two linked lists representing two non-negative numbers.
The digits are stored in reverse order and each of their nodes contain a single digit.
Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
'''
class ListNode:
def... |
6e2d196941af4fb0e3290702231837658a06c314 | brogan-avery/MyPortfolio-AndExamples | /Python/Databases and Data Manipulation (Pandas, Plottly, etc.)/Precipitation Tracking/createWeatherDBTables.py | 2,614 | 3.84375 | 4 | '''
Author: Brogan Avery
Date: 2020/10/08
Project Title: Weather database table creation
'''
import sqlite3
from sqlite3 import Error
def create_connection(database):
conn = None
try:
conn = sqlite3.connect(database)
return conn
except Error as e:
print(e)
return conn # conne... |
7fc4e7c0dab9398ed27173e3403806f85d21ea01 | takin6/algorithm-practice | /leetcode/graph/1162_as_far_from_land_as_possible.py | 3,445 | 3.515625 | 4 | from typing import List
class Solution:
def maxDistance(self, grid: List[List[int]]) -> int:
# for each land cell,
# do bfs(r, c)
# - expand distance by 1 and check if land exists
# ex) if (r,c)==(0,0) distance 1 is (1,0) or (0,1)
# - ... |
744f199aa497dde2667901abc2d2403b8c6b54a9 | coolharsh55/advent-of-code | /2015/day07/some_assembly_required_part_2.py | 10,429 | 3.796875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
""" --- Day 7: Some Assembly Required ---
This year, Santa brought little Bobby Tables
a set of wires and bitwise logic gates!
Unfortunately, little Bobby is a little under the recommended age range,
and he needs help assembling the circuit.
Each wire has an identifier (some... |
b40eced9a53922b26cbfec94243a03aefa33674c | ManoMambane/Python-PostgresSQL | /A Full Python Refresher/13_dictionaries/friends.py | 230 | 4.1875 | 4 | friends = [
{"name": "Rolf", "age": 24},
{"name": "Adam", "age": 30},
{"name": "Anne", "age": 27},
]
print(friends)
#getting info from list
print(friends[1])
#getting info from list by name
print(friends[1]["name"]) |
963e28d5994070671ba650f79ffb00709b45e406 | define16/Class | /4-1/WIndow Programing/20180321/20180321_3.py | 252 | 3.75 | 4 | score = int(input("1. 이수한 학점을 입력하세요 : "));
avg = float(input("2. 평점을 입력하세요 : "));
if score < 140 or avg < 2.0 :
print("학생은 졸업이 힘들겠습니다.");
else :
print("졸업이 가능합니다");
|
6559045e5b5dd0c7ed727d05ec8f7942ff500989 | XingyuHe/cracking-the-coding-interview | /Chapter8/He87.py | 563 | 3.578125 | 4 | import copy
def permute(orig_list):
if len(orig_list) == 1:
return [[orig_list[0]]]
permutations = permute(orig_list[1:])
new_permutation = []
for permutation in permutations:
for i in range(len(permutation) + 1):
temp = copy.deepcopy(permutation)
temp.insert(... |
020cdfb7a296e54939dc2d473900017ecb88a38b | kbsamet/MLVisualizer | /LinearRegression.py | 1,220 | 3.5 | 4 | from statistics import mean
import numpy as np
from matplotlib.animation import FuncAnimation
import matplotlib.pyplot as plt
class LinearRegression:
def __init__(self,dataset,parameters):
plt.style.use("fivethirtyeight")
plt.title("Click to add points")
self.dataset = dataset
ani ... |
3c3b45c00644efda9f29d51c0fcacddd1d94f92a | mcampbell/uthgard-pjs | /update-population-db.py | 4,346 | 3.6875 | 4 | #!/usr/bin/env python
'''Run through whatever log file and update the database with its values. It
will check to see if this value is already there and insert if not. Deleting
and inserting everything is kind of expensive and unnecessary.
Example log entries:
[2018-01-06T13:22:09-0500] Server Status � Online with 9... |
1f3fcebc17d59a069bb06371584e9fe7bf7cce9b | uragirii/Naruto_Rename | /Naruto_GetNames.py | 2,238 | 3.765625 | 4 | """This file will get the list of the shippuden episode names from the wikipedia page and form the name as SXXEXXX Name """
import urllib.request
url = r'https://en.wikipedia.org/wiki/List_of_Naruto:_Shippuden_episodes'
response = urllib.request.urlopen(url)
source_code = str(response.read().decode("utf-8"))
... |
c19da8227f39d669b0d96ed4ba497e378c9d9465 | DeanHe/Practice | /LeetCodePython/NumberOfWaysToReachaPositionAfterExactlyKSteps.py | 1,555 | 4 | 4 | """
You are given two positive integers startPos and endPos. Initially, you are standing at position startPos on an infinite number line. With one step, you can move either one position to the left, or one position to the right.
Given a positive integer k, return the number of different ways to reach the position endP... |
85368f0f52c3752a31f7ffbf83bd012cfa1a35b2 | LuccaBiasoli/python-cola | /python_colas/set_unicos.py | 248 | 3.59375 | 4 | lista = [1 ,1 ,1 ,4 ,78 ,78 ,4,'foda','mcdonalds','foda','mcdonalds']
print(lista)
print(set(lista))
#///
#set transforma tudo dentro unico
vor = set('Mississipi')
print(vor)
#///
print(set('3 , 4 ,3 ,4'))
print(f'sabia q ia dar isso {set(lista)}') |
d8938421362eedc996bb1ad39c322f45023c6109 | sfechisalin/Facultate | /PLF/Recursivitate.py | 2,014 | 3.515625 | 4 | class Nod:
def __init__(self, e):
self.e = e
self.urm = None
class Lista:
def __init__(self):
self.prim = None
def creareLista():
lista = Lista()
lista.prim = creareLista_rec()
return lista
def adaugaInceput(lista, e):
nod = Nod(e)
nod.urm = l... |
345728961e83e383bfce17d986a1e668ba43cf6b | skp96/DS-Algos | /Grokking/Window Sliding Problems/smallest_subarray_with_given_sum.py | 1,343 | 3.84375 | 4 | """
- Problem: Given an array of positive numbers and a positive number ‘S,’ find the length of the smallest contiguous subarray whose sum is greater than or equal to ‘S’. Return 0 if no such subarray exists.
- Examples:
- Input: [2, 1, 5, 2, 3, 2], S=7
- Output: 2
- Explanation: The smallest subarray with a su... |
193d5e8e3e2c7e9bb72db5311edfea29f072cb46 | sangereaa/xiti | /xiti/8-3.py | 218 | 4 | 4 | a = int(input("Which multiplication table would you like?"))
b = int(input("How high do you want to go?"))
c = 1
print("Here is your table:")
while c <= b:
d = c * a
print(a, "X", c, "=", d)
c += 1
|
edb57d0a55d0fe373706674cb7e1c2a591a70519 | sebbekarlsson/morsetalk | /morsetalk/morse.py | 923 | 3.734375 | 4 | # -*- coding: utf-8 -*-
from morsetalk.alphabet import CODE
from morsetalk.exceptions import MorseEncodeException, MorseDecodeException
def encode_char(char):
if not char:
return ''
char = char.upper()
if char not in CODE:
raise MorseEncodeException(
'<' + char + '> does not ... |
264d1033ed19e0c9871ebfb176cc6cd64b2697f9 | webstersup/password | /passwd.py | 485 | 3.859375 | 4 | #密碼重試程式
#
#在設定預設密碼 password = "a1234"
#使用者最多輸入3次密碼
#不對就顯示出"密碼錯誤!還有_次機會"
#對的話顯示出"登入成功"
password = 'a1234'
i = 2
while i >= 0 :
try_password = input('請輸入密碼')
if try_password == password :
print('登入成功')
break
else :
if i == 0 :
print('密碼錯誤!您已經沒有輸入機會')
break
print('密碼錯誤!還有', i, '次機會')
i = i - 1
|
4fa3d1f73f7c7e10117c96070db05650dbf9248a | guntrox/wowza-keys-import | /wowza-convert.py | 510 | 3.5625 | 4 | #!/usr/bin/env python3
import pandas as pd
import json
import sys
map = {}
def convert(fn):
df = pd.read_excel(fn)
#print(df[['USB Device ID', 'Full License Key']])
for index, row in df.iterrows():
# print(row['USB Device ID'], row['Full License Key'])
map[row['USB Device ID']] = row['Full License K... |
db053446230bea4634fc2fca2aaf5558a50b29b1 | DmitryKizaev/Artezio-Academy-3.0-Hometask | /Hometask1/task1.py | 799 | 4.09375 | 4 | """Homework 1 Task 1"""
# 1. Ensure that the first and last names of people begin with a capital letter
# Given a full name, your task is to capitalize the name appropriately.
# 0 < len(S) < 1000
# The string consists of alphanumeric characters and spaces.
# Note: in a word only the first character is capitalized.
# O... |
b86e77b9afb00c9490aaff1a86a2bffdefd0edc8 | Indian-boult/algoexpert-2 | /Anshul/Array/Smallest Difference.py | 518 | 3.546875 | 4 | a = [-1,5,10,20,28,3] # -1,3,5,10,20,28
b = [26,134,29,15,17] # 15,17,26,134,135
# My solution
def smallestdiff(a,b):
a.sort()
b.sort()
mins=abs(a[0]-b[0])
i = 0
j = 0
for _ in range(len(a)+len(b)-2):
k=mins
if a[i]<b[j]:
mins=min(mins,b[j]-a[i])
if k !=... |
f37ef0a2ab881a0705f0c6cbd7feff408cd29215 | Hearen/AlgorithmHackers | /TangHongyin/populating_next_right_pointers_in_each_node_ii.py | 1,012 | 3.953125 | 4 | # Definition for binary tree with next pointer.
class TreeLinkNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.next = None
class Solution(object):
def connect(self, root):
"""
:type root: TreeLinkNode
:rtype: not... |
3fd5a26e7973f76d1be9252c1937cceeff3d2169 | Ronak912/Programming_Fun | /Bloomberg/MaxDifferenceUnSortedArray.py | 706 | 3.75 | 4 | # Find the maximum difference in an unsorted array with the index of max greater than min. array cant be sorted
def findMaxDifference(inlst):
maxdifference = 0
min_idx, max_idx = 0, 0
for idx, val in enumerate(inlst):
if idx == 0:
continue
if val < inlst[min_idx]:
... |
b1ebd7e11bb8cccd06546c73c3da1bb6f548a3d5 | jkingsman/telepathydev | /misc/badannealing.py | 4,657 | 3.640625 | 4 | #!/usr/bin/env python3
from helpers import getBoardAsList
import random
# all guessers must implement getGuess() which returns a tuple of (guess, boolIndicatingIsSolving) and feedback(guess, bool) to indicate yes or no and
class FitnessGuesser:
def __init__(self):
self.board = getBoardAsList()
se... |
1711d6573e3375d36cb528e91620a86200346a09 | andrew-ocallaghan-ie/MoocWebAppTechAndDjango | /SimpleBrowserServerAndClient/2_simple_server.py | 2,148 | 3.71875 | 4 | from socket import *
"""
This example opens a socket that listens to localhost port 9000.
It can respond to 1 call and queue up another 4.
It continuously trys to accept incoming requests and blocks execition until it does.
Once it recieves a request it prints it and replies with encoded Hello World Html
After execut... |
e389664e5b1ab9ad2a9aa1e862f14f0466b701a2 | rodrez/PythonChallenges | /sumofnth.py | 489 | 3.96875 | 4 | def arith(first_num, step, nth):
"""
Uses the pattern given an returns the sum of the nth number
:param first_num: First integer
:param step: Step increments
:param nth: Times of increments
:return: sum of the nth number
"""
all_num = [first_num,]
saved_num = 9
for i in range(nth... |
15bd90d1ea06953bf7c1921c15f4d1cc7db0c319 | rookie-LeeMC/Data_Structure_and_Algorithm | /leetcode/动态规划/最大正方形.py | 842 | 3.640625 | 4 | # -*- coding:UTF-8 -*-
'''
https://leetcode-cn.com/problems/maximal-square/
'''
def maximalSquare(matrix):
if not matrix: return 0
# 状态定义
# 初始化
row, col = len(matrix), len(matrix[0])
dp = [[0] * col for _ in range(row)]
# 状态转移
ans = 0
for i in range(row):
for j in range(col)... |
15d0843c80e340a7670a83809600d7a25b3b9d63 | trettier/easy_strv2 | /ft_division_str.py | 187 | 3.515625 | 4 | def ft_division_str(a):
b = 0
for i in a:
b += 1
if b % 2 == 1:
c = a[b // 2 + 1:] + a[:b // 2 + 1]
else:
c = a[b // 2:] + a[:b // 2]
return c
|
b715d7a6d442bb136f8ad69c2ea689b05b9a0612 | MonkeyWaffle0/citadelle | /classes/Building.py | 515 | 3.515625 | 4 | from classes.Card import *
class Building(Card):
def __init__(self, color, name, price, value):
super().__init__(color)
self.name = name # Name of the building
self.value = value # Value in points
self.price = price # Price to build it
def __repr__(self):
string = s... |
400d4fe39c4f72b195a02093d55fe1a6716ce527 | fifajan/py-stuff | /scripts/get_mp3.py | 810 | 3.515625 | 4 | #! /usr/bin/python
'''
This script should parse mp3 links from 'url'
(worked on xmusic.me on Jan 11 2015) and write them to 'text_file'.
Then you can download those mp3 files using:
$ wget -i <text_file>
(c) 2015 Alexey Ivchenko aka fifajan (fifajan@ukr.net)
'''
from BeautifulSoup import BeautifulSoup
import urllib... |
60d74c4e794fc2bd1e3ea02abe53d516f5ae61a6 | yatiraj1/optimization | /utils/scrape_table.py | 1,582 | 3.609375 | 4 | import pandas as pd
def scrape_table(soup, identifier, col_range=(0, 1000), href_cols=[]):
"""Scrape tabular data from HTML Pages.
Parameters
----------
soup : soup object
HTML content of web-page
identifier : dict
Dict containing Class/ID selector for table
Fo... |
82317e32f4c348b41b5455dfded4a0df305c7dd5 | emteeoh/deBruijn-Sequences | /scratch/lyndonwords.py | 1,404 | 3.953125 | 4 | def LengthLimitedLyndonWords(s,n):
"""Generate nonempty Lyndon words of length <= n over an s-symbol alphabet.
The words are generated in lexicographic order, using an algorithm from
J.-P. Duval, Theor. Comput. Sci. 1988, doi:10.1016/0304-3975(88)90113-2.
As shown by Berstel and Pocchiola, it takes cons... |
c4d26171bf8ff8e5cfa4b26413d98c7a8dc16320 | alishabry/MADE | /Algo/HW3/bin_search_2.py | 430 | 3.6875 | 4 | def count(t, x, y):
return 1 + t // x + t // y
def bin_search(x, y, n):
left = 0
right = n * (max(x, y) + 1)
if n == 1:
return min(x, y)
while left < right - 1:
mid = (left + right) // 2
if n <= count(mid, x, y):
right = mid
else:
left = ... |
5e6c95b7f5e8604f33b0f4cbbba21d7f11256666 | hwXYZ12/Project-Euler-Python | /TOO LAZY TO USE GIT p96.py | 6,279 | 4.0625 | 4 | import math
import pdb
# represents a 2D matrix of possibility sets of a potential
# Su Doku solution as well as a particular guess for a value
# in addition to the coordinates of that guess
class Guess:
def __init__(self, possibilities, whichCoord, guess):
self.possibilities = possibilities
self.whichCoord = w... |
ca1cca0ffe06f2a1746faef1790e2df810bf9cf5 | ash6899/google-foobar-challenge | /Level2b.py | 3,038 | 3.875 | 4 | # Please Pass the Coded Messages
# ==============================
# You need to pass a message to the bunny prisoners, but to avoid detection, the code you agreed to use is... obscure, to say the least. The bunnies are given food on standard-issue prison plates that are stamped with the numbers 0-9 for easier sorting,... |
ea9ec342a6872122338cf46ad82f2651a1fc9929 | joelehnert/pyfe | /testing.py | 375 | 3.96875 | 4 | x = 1 + 2 * 3 - 4 / 5 ** 6
print(x)
x = 1 + (2 * 3) - (4 / (5 ** 6))
print(x)
##input!!!!!!!
name = input('What is your name?')
print('Welcome,',name,'!')
#hmm, why does this print a space between my name and the exclamation point
#oh, you need to concatanate to eliminate the comma. Let's try below
nam = input('Hell... |
13a8ab85e9c2781175b9eeeb2520e7098a89cc12 | Modrisco/OJ-questions | /Leetcode/Python/0026_Remove_Duplicates_from_Sorted_Array.py | 399 | 3.515625 | 4 | class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
pointer = 0
# replace item on pointer with new item
for num in nums:
if num > nums[pointer]:
... |
28d9a632b5dba92a706b1de1e3f0c4a875423a69 | aishwarya-m-4/SL-Lab-19 | /Python program/AtomicDictionary.py | 692 | 4.28125 | 4 | def AtomicDictionary():
atomic={
'H':'Hydrogen',
'He':'Helium',
'Li':'Lithium',
'Be':'Berilium'
}
#adding unique and duplicate element
a=(input("Enter key:"))
b=(input("Enter value:"))
atomic.update({a:b})
print("Updated Dict is: ", atomic)
c=(input("Enter key:"))
d=(input("Enter value:"))
... |
96dee3cc6ad0fa4ded18393883af565a51d28914 | Huayuehu/sw-design-and-optimization | /lab/lab10/Part I/tree_checker_with_inputfile.py | 2,405 | 3.953125 | 4 | """
This version detect whether the graph based on input.txt is a tree
Next step, I will implement generator and combined with checker
"""
from collections import defaultdict
def cycle_checker(node, parent, visited, loop_node):
visited[node] = True
loop_node.append(node)
for i in graph[node]: # to check... |
94b12e3a8bedd13b309a8d241d181e08c8a16791 | muelljef/372-Project-1 | /chatserve | 5,444 | 3.78125 | 4 | #!/usr/bin/python
from socket import *
import signal
import sys
'''
chatserve <port#>: When the program is called with a port number it will create a socket and listen on
the given port number for a connection from any host. It will only connect to one client at a time.
Once a connection is made t... |
065a8f1fe19f1a356cd81f51237e0c48f6ee1a3a | jmillerneteng/lp3thw | /ex7.py | 497 | 3.828125 | 4 | color = "pinkish with a hint of purple"
print("Maryz lil lamb.")
print("Fleeze was snow, that is white as {}" .format(color))
print("Everywhere that M went.")
print("." * 10) #this is curious
end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end1... |
4c57ba3ed6bdceec3c89a767226e44d671e00015 | PauloViniciusBaleeiro/Uri---Online | /1098.py | 612 | 3.5625 | 4 | I = 0
J1 = 1
J2 = 2
J3 = 3
x = 0
# print('i =>', I)
while (I <= 2):
i = I
# print('x%5', x%5 == 0)
# print('x', x)
if(x==0 or (x%5 == 0)):
# print('inteiro')
print('I={} J={}'.format(int(round(i)), int(round(J1 + i))))
print('I={} J={}'.format(int(round(i)), int(round(J2 + i)))... |
d2f1b0e8af608f5f99353ecdaff3a5da2c7e8530 | mel-haya/42-AI-Bootcamp | /M01/ex00/recipe.py | 2,222 | 3.71875 | 4 | class Recipe:
def __init__(self, name, cooking_lvl,cooking_time,recipe_type,ingredients = [],description=None):
self.name = self._is_valid_name(name)
self.cooking_lvl = self._is_valid_cooking_lvl(cooking_lvl)
self.cooking_time = self._is_valid_cooking_time(cooking_time)
self.ingre... |
6b36a7ff3c348302b7575474a74bb2693d24ddda | antonioravila/Exercicios-CEV-Python | /ex_027.py | 95 | 3.703125 | 4 | nome = str(input("digite seu nome")).split()
nome_separado = nome.split()
print(nome_separado)
|
047b54a72129321c16651619068185fff2c6a9c9 | PavaniVegi/Movie_trailer | /media.py | 680 | 3.53125 | 4 | import webbrowser
# define movie class and it properties
class Movie():
""" Movie class consists the structure of object """
def __init__(self, movie_title, movie_storyline,
poster_img, trailer_youtuber_url):
"""constructer of movie class defines all the key variables"""
... |
27bbad7909ec1025ec163f29d5b1bf2e0947be05 | pradeepsinngh/A-Problem-A-Day | /by-algorithms/sort/easy/001-matrix_cell_dis_order.py | 1,006 | 3.6875 | 4 | # Prob: Matrix Cells in Distance Order
# We are given a matrix with R rows and C columns has cells with integer coordinates (r, c), where 0 <= r < R and 0 <= c < C.
# Additionally, we are given a cell in that matrix with coordinates (r0, c0).
# Return the coordinates of all cells in the matrix, sorted by their distan... |
c7b61e884b5a06e1f134e333c829b91a0f3382f6 | Kaktus994/Algorithms | /Path Sizes/paths.py | 4,022 | 3.515625 | 4 | class UnequalWidthError(Exception):
pass
class Path:
def __init__(self, matrix):
for element in matrix:
if not isinstance(element, list):
raise TypeError(f"Expected matrix (list of lists), got {type(element)} ")
self.matrix = matrix
self.paths = []
self.paths_lenght = []
self.neighbours = []
se... |
e4f21b96b444c4de30869cf7edf3c58f5be2a656 | abdulwasayrida/Python-Exercises | /Exercise 7.5.py | 1,077 | 4.3125 | 4 | #Exercise 7.5 (Continued)
#Geometry: n-sided regular polygon
#Rida Abdulwasay
#1/14/2018
#Import the class Regular Polygon
from RegularPolygon import RegularPolygon
def main ():
#Use default for first polygon
regularPolygon1 = RegularPolygon()
perimeter = regularPolygon1.getPerimeter()
area = regular... |
44796332e20e94c9770ce8227186c4dea7cd9b86 | krzkrusz/untitled | /regular.py | 228 | 3.59375 | 4 | import re
message = "my email is krzysztof.kruszynski@gmail.com"
pattern = "[a-z.0-9]+@[a-z\.]+\.[a-z]{1,3}$" # \d is a digit
m = re.search("[a-z.0-9]+@[a-z\.]+\.[a-z]{1,3}", message)
if m: # would be None if no match is found
print(m.group()) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.