blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
2626c06833595fd05361b82838fb7495fdeae4f9 | gsimbr/ProjectEuler | /problem_2.py | 396 | 3.859375 | 4 |
def count_even_fibonacci(threshold):
fib_1 = 0
fib_2 = 1
sum_even_fib = 0
while True:
fib_3 = fib_1 + fib_2
if fib_3 > threshold:
break
fib_1 = fib_2
fib_2 = fib_3
if fib_3 % 2 == 0:
sum_even_fib += fib_3
return sum_even_fib
if __na... |
923177e67d9afe32c3bcc738a8726234c5d08ad2 | CTRL-pour-over/Learn-Python-The-Hard-Way | /ex6.py | 758 | 4.5 | 4 | # Strings and Text
# This script demonstrates the function of %s, %r operators.
x = "There are %d types of people." % 10
binary = "binary" # saves the string as a variable
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not) # inserting variables ()
# here's where we print out our variables ^... |
84bd788892b101f438b1ee5e6637901383cb0453 | CTRL-pour-over/Learn-Python-The-Hard-Way | /keywords/numbers.py | 166 | 3.65625 | 4 | #--- numbers: stores integers ----
i = 100
2 + 2 == 4 # True
def math_block():
num = int(raw_input("enter a number >>> "))
a = "1 + 1 = __"
math_block()
|
568c69be02b59df5d2c531bb707be680fc5efa77 | CTRL-pour-over/Learn-Python-The-Hard-Way | /ex29.py | 1,080 | 4.65625 | 5 | # What If
# The if statements, used in conjunction with the > , < operators will print
# the following text if True.
# In other words, ( if x is True: print "a short story" )
# Indentation is needed for syntax purpouses. if you do not indent you will get
# "IndentationError: expected an indented block".
# If you do no... |
46554c75d2000a673d11d628b5921831bec87b74 | CTRL-pour-over/Learn-Python-The-Hard-Way | /ex15.py | 944 | 4.25 | 4 | # Reading Files
# this file is designed to open and read a given file as plain text
# provide ex15.py with an argument (file) and it will read it to you
# then it will as for the filename again, you can also give it a different file.
from sys import argv
# here is how we can give an additional argument when trying to ... |
faaa06b9de53d47b84700c8aa9d9a058007fa7d4 | CTRL-pour-over/Learn-Python-The-Hard-Way | /ex10.py | 488 | 3.796875 | 4 | # What Was That?
# here are some variables with strings including \t, \n and \\ escape sequences.
tabby_cat = "\t I'm tabbed in."
persian_cat = "I'm split\non a line."
backslash_cat = "I'm \\ a \\ cat."
# fat_cat variable creates a vertical list
fat_cat = """
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Gr... |
b762e02cebacd34cb378cf8ba01e2901945cd30b | mmuthumanisha/pythonpro | /l.py | 87 | 3.90625 | 4 | year=int()
if(year%4):
print("is a leap year")
else:
print("is not leap year")
|
abe58ea198fb251577aaf5a3154f5733fdf3aef9 | pinkjacket/numberpython | /program.py | 543 | 4.09375 | 4 | import random
print("-------------------------------------")
print(" GUESS THE NUMBER")
print("-------------------------------------")
print()
number = random.randint(0, 100)
guess = -1
name = input("Name, please. ")
while guess != number:
guess_text = input("Guess a number between 0 and 100: ")
gue... |
d397365d17876b8668222707e765d752ad222675 | riva-digital/ledger | /source/ledger/db_query.py | 5,008 | 3.5625 | 4 | """
db_query
Riva's database query builder
"""
__author__ = "mdhananjay"
def generate_query_str(select_data=[], from_tables=[], where_and=[], where_or=[], where_and_or=[]):
"""
This is an all purpose query generator for pretty much any database.
The format of the tuples in the where_and & the where_or l... |
11fca8dc0ab7182fb7eee799dff5ccb8874b8d1c | zuFrost/Learning-Python-LinkedIn | /Ex_Files_Learning_Python/Exercise Files/Ch2/number_of_digits.py | 662 | 4.09375 | 4 | # Which code snippet can you use to print the number of digits in the number variable?
# You can assume this number is always positive and always less than 10,000.
number = 9999
# if (number>=0):
# print(1)
# elif (number>=10):
# print(2)
# elif (number>=100):
# print(3)
# else:
# print(4)
# if (number<=10... |
b53ed033cf11400411a08a01c4749b47398966c4 | ianmlunaq/python2019-2020 | /quadroots.py | 843 | 3.921875 | 4 | #quadroots.py | CWC | Reference: Amit Saha(Doing Math with Python)
def roots(a,b,c):
D = (b*b - 4*a*c)
print()
print("D = " + str(D))
if(D >= 0):
print("REAL ROOTS")
D = D**0.5
x1 = (-b + D) / (2*a)
x1 = (-b - D) / (2*a)
print("x1 = " + str(x1) + " x2 = " + str(x2))
elif(D < 0):
D = (D * -1)**0.5;
... |
c111caa5edac1264263a13749ecb10c8855fec9f | ntudavid/PythonWorld | /Python_Station/try_tk2_entry_and_text.py | 664 | 3.5 | 4 | import tkinter as tk
window = tk.Tk()
window.title('test window')
window.geometry('500x300') # width x height
e = tk.Entry(window) # show = '*' for passwords
e.pack()
def add():
s = e.get()
t.insert(1.0, s) # row.offset
def insert():
s = e.get()
t.insert('insert', s)
def append():
s = e.get()
... |
d80f1f624f4e41badb56d48861708275b6227f8b | ntudavid/PythonWorld | /Python_Station/runPLA.py | 2,764 | 3.9375 | 4 | '''
Perceptron Learning Algorithm
'''
import numpy as np
import matplotlib.pyplot as plt
def runPLA(num): # num = number of sample points
# target_function: f = [a,b,c] to represent the line: ax+by+c=0
a,b,c = np.random.rand(3)*100-50
f = [a,b,c]
x = np.array([-55,55])
y = eval('(-a*x-c)/b')
... |
9125d42f5cf7be386a8a2790520a1be982e82d40 | ntudavid/PythonWorld | /Python_Examples/python_4.py | 1,113 | 4.09375 | 4 | '''
tutorial (4) - function, recursive function, module
2016/06/15
David Hsu
'''
# factorial: f(n) = n!
# function -> def
def factorial(n):
fact = 1
for i in range(1,n+1):
fact *= i
return fact
def factorialRecursive(n):
if n == 0 :
return 1
else:
return n*factorialRecurs... |
7cd0811d9b9a7b0ba8fbd477615d63f017acfacf | katelyn-dever/Sir_Quiz-A-Lot | /newsqal.py | 11,240 | 3.5 | 4 | ### Sir Quiz-A-Lot desktop application ###
### ITEC 3250 - Katelyn Dever, Elijah Cliett, Brianna Young ###
### Imports ###
import math
import random
# used for GUI
from tkinter import *
from tkinter import filedialog
### GUI Setup ###
root = Tk()
terms = dict()
windowSize = "750x600"
smWindowSize = "400x400"
xsWin... |
8f5434c90e5011c5adf3c512d18614ba496dafb7 | PacktPublishing/Mastering-Python-Design-Patterns-Second-Edition | /chapter10/command.py | 1,910 | 3.625 | 4 | import os
verbose = True
class RenameFile:
def __init__(self, src, dest):
self.src = src
self.dest = dest
def execute(self):
if verbose:
print(f"[renaming '{self.src}' to '{self.dest}']")
os.rename(self.src, self.dest)
... |
6f2354a40fe60b8650068ae2e1383b49ca72e1ca | PacktPublishing/Mastering-Python-Design-Patterns-Second-Edition | /chapter02/exercise_fluent_builder.py | 864 | 3.84375 | 4 | class Pizza:
def __init__(self, builder):
self.garlic = builder.garlic
self.extra_cheese = builder.extra_cheese
def __str__(self):
garlic = 'yes' if self.garlic else 'no'
cheese = 'yes' if self.extra_cheese else 'no'
info = (f'Garlic: {garlic}', f'Extra cheese: ... |
482fea12d58ab30cd7b4121c95b28a4da36e1486 | PacktPublishing/Mastering-Python-Design-Patterns-Second-Edition | /chapter13/iterator.py | 959 | 3.75 | 4 | class FootballTeamIterator:
def __init__(self, members):
# the list of players and coaches
self.members = members
self.index = 0
def __iter__(self):
return self
def __next__(self):
if self.index < len(self.members):
va... |
6412df0a302e2e8dfc6c79bc0787de749f584c96 | mistermusk/NASDAQ-Stock-Prediction-Using-Pandas-and-Numpy | /advanced_stats.py | 2,561 | 3.609375 | 4 | import pandas as pd
import numpy as np
import os.path, time
from urllib.request import urlretrieve
import datetime as dt
import matplotlib.pyplot as plt
################################ Moving Averages ###################################
def moving_Avg(stock_file):
try:
number = int(input("Plea... |
9741da2737040f20a43a623dd4fe98f7d2540841 | minasyan/reverseflow | /reverseflow/arrows/primitive/control_flow_arrows.py | 654 | 3.703125 | 4 | """These are arrows for control flow of input"""
from reverseflow.arrows.primitivearrow import PrimitiveArrow
class DuplArrow(PrimitiveArrow):
"""
Duplicate input
f(x) = (x, x, ..., x)
"""
def __init__(self, n_duplications=2) -> None:
self.in_ports = [InPort(self, 0)]
self.out_po... |
d3c6e63735d52ad672c848ea792620ad8fad2ed2 | Bhavyakadiyala/Home-Activity-Task- | /main.py | 3,225 | 3.75 | 4 | from collections import defaultdict
import heapq
input_file=open("Input.txt","r")
slot_regid={} #stores the registration number of vehicle corresponding to the slot number
reg_no={} #stores registration_number and slot_number as key-value pairs
slot_age={}#Stores slot as key and age as value
ageList=defaultdict(list)#S... |
7d0700a70d505b53f72cbf018b4048f93f11a308 | hondajyh/Sprint_4_data_manipulation_and_tools | /SQLA_2Tbl_12m.py | 4,403 | 4.1875 | 4 | #DEMONSTRATE A 1 TO MANY RELATIONSHIP W/O CORRESPONDING MANY TO 1 RELATIONSHIP
#THIS IS CRUCIAL WHEN WE HAVE SITUATIONS WHERE THE MANY SIDE TABLE OF A 1:MANY RELATIONSHIP
#DOES NOT NECESSARILY HAVE A CORRESPONDING RECORED ON THE 1 TABLE SIDE.
#connect to SQLite DB w/ SQLAlchemy ORM:
from sqlalchemy import cre... |
f356b9b722b00fb85c8e9afbe60e80181a5aba5c | Programacion-Algoritmos-18-2/tarea-03-tutoria-iaortiz | /paquete1/modelo.py | 1,638 | 3.6875 | 4 | #Creación de clase docente
class Docente :
def __init__ (self, n, a):
self.nombre = n
self.ciudad = a
# Metodo get y set para nombre
def agregar_nombre (self, n):
self.nombre = n
def obtener_nombre (self):
return self.nombre
# Metodo get y set para ciudad
... |
a43d4838a307397258ce4bf7da29d105ed6313b5 | MaciejWanat/AutomataDeterminizer | /determinize.py | 3,693 | 3.546875 | 4 | #!/usr/bin/env python3
import sys
import collections
detAutomaton = {}
nonDetAutomaton = {}
acceptStates = set()
detAcceptStates = set()
alphabet = set()
foundState = True
nonDetWalks = False
def prettyPrint(dicto):
print()
for key in dicto:
print(str(key) + " : " + str(dicto[key]))
def prettyPrintO... |
e8faa34e0297ab5fb4a6e68c058747b0d011f468 | HannahMoses/build-a-blog | /main.py | 1,907 | 3.515625 | 4 | #TEMPLATES feb 20 2017,Mon 6:56pm PRESIDENT'S DAY 4430GSWAY Matt6:1verse
import os
import webapp2#rgb(0,234,200) also use rgb(0,234,222
form_html = """
<form >
<body style='background-color:rgb(0,234,200)' >
<h2 style='color:rgb(234,13,156)'> Add a food </h2>
<input type = "text" name="food" ><br><br>
%s
... |
eb2d569e01206cbcb7269945473a28ec5ed9fb47 | sanjib-upreti/IQVIA-Test | /disease_activity.py | 1,506 | 3.796875 | 4 | import feedparser
from datetime import datetime
from time import mktime
from disease_list import disease_list_all, disease_list_small
# disease list created for testing
# initializing the value of days by 2(for testing Module)
days=2
def disease_monitor(days):
try:
if 0 < days <= 30: # putting ... |
7945f90ec505986bbff390dacdfe8a21f28edcdd | Del-virta/goit-python | /lesson3/func.py | 418 | 3.859375 | 4 | def total(a=5, *numbers, **phone_book):
print('a', a)
# проход по всем элементам кортежа
for single_item in numbers:
print('single_item', single_item)
#проход по всем элементам словаря
for first_part, second_part in phone_book.items():
print(first_part,second_part)
print(total(10, ... |
47677a52fd86358fcfea3fe06461d155e7df408a | Del-virta/goit-python | /lesson5/text_length.py | 511 | 3.703125 | 4 | def real_len(text):
t_length = 0
for char in text:
if char in ['\v','\n','\t','\r','\f']:
pass
else:
t_length+=1
return t_length
text = 'Мы думали над тем, как можно все бросить и удететь в космос.\nГде-то там останется семья и друзья. \v а ты сидишь и смотришь... |
ffad24a7368cd7032d28f7a8bde96b75ba0f01b1 | Del-virta/goit-python | /lesson4/coordinates3.py | 559 | 3.703125 | 4 | points = {
(0, 1): 2,
(0, 2): 3.8,
(0, 3): 2.7,
(1, 2): 2.5,
(1, 3): 4.1,
(2, 3): 3.9,
}
def calculate_distance(coordinates):
distance = 0
if len(coordinates) <=1:
return 0
else:
for i in range(len(coordinates)-1):
couple = (coordinates[i],coordinates[i+... |
a10a51dbf22db51031019c4a9fa845cbe34cce0f | Del-virta/goit-python | /lesson8/screencasts/scrncst5.py | 221 | 3.734375 | 4 | import collections
person1 = ('Bob', 'Dou', 25)
Person = collections.namedtuple('Person', ['name', 'surname', 'age'])
person = Person('Jack', 'Watson', 55)
print(person1[0])
print(person.age)
print(person)
print(person1) |
1f4f1946267dc3dc4f634785899b55a634264e2d | Del-virta/goit-python | /lesson8/screencasts/scrncst9.py | 452 | 3.921875 | 4 | squares = []
for i in range(11):
squares.append(i ** 2)
print(squares)
# Using comprehensions
squares_new = [i **2 for i in range(11)]
print(squares_new)
# using function and comprehensions
def func(x):
return x * 2
# with list
dubbled = [func(i) for i in range(11)]
print(dubbled)
# with set
dubbled_set = {... |
a23e8c41a233fc338f09052190a74c9fe17d0561 | Del-virta/goit-python | /lesson8/screencasts/scrncst2.py | 483 | 3.90625 | 4 | import random
from datetime import datetime, timedelta
def main():
starting_date = input('Enter starting date: ')
end_date = input('Enter ending date: ')
starting_date = datetime.strptime(starting_date, "%Y-%m-%d")
end_date = datetime.strptime(end_date, "%Y-%m-%d")
inerval_days = (end_date - star... |
38650ab2af9fb1f6f7b9d91fa82744a37746903a | Del-virta/goit-python | /lesson7/m7t09.py | 241 | 3.734375 | 4 | def all_sub_lists (data):
sub_lists = [[]]
for i in range(len(data)+1):
for j in range(i+1,len(data)+1):
sub_lists.append(data[i:j])
return sorted(sub_lists, key=len)
print(all_sub_lists([4,6,1,3])) |
7658ba056e4e191d6668856e78875e4fce56a202 | Del-virta/goit-python | /lesson2/odd_even.py | 181 | 4.125 | 4 | number = 0
while True:
if number % 2:
print(f"{number} is odd")
else:
print(f"{number} is even")
if number > 20:
break
number = number + 1
|
2de85a372010730f1881ad33cae76b32d92e933c | Del-virta/goit-python | /First practice.py | 473 | 3.921875 | 4 | # Linear equation
print("We are trying to solve linear equation 'ax + b = c'")
a = 3
b = 2
c = 1
print(f"a = {a}, b = {b}, c = {c}")
x = (c - b)/a
print(f"x = {x}")
# Pifagor theorema
print("We are trying to find hypotenuse")
a = int(input('Enter "a" value: '))
b = int(input('Enter "b" value: '))
print(f"a = {a}, b = ... |
3088bf061b059d4af2a3c7bdeb536262bb80dc08 | BlaiseCosico/100DaysOfCode | /CSV-Data-Analysis/ramen.py | 1,663 | 3.546875 | 4 | import os
import csv
from collections import namedtuple, Counter
from typing import List
data = []
Record = namedtuple('Record', ['Review', 'Brand', 'Variety_Style', 'Country', 'Stars', 'Top_Ten'])
def init():
base_file = os.path.dirname(__file__)
filename = os.path.join(base_file, 'data', 'ramen_ratings.csv... |
783eba19b95768cc63c698d5af91ee7a7f4561e9 | mpentler/edinbustrack | /edinbustrack.py | 1,524 | 3.546875 | 4 | # edinbustrack V0.05 - get all of the upcoming services at a particular stop
# (c) Mark Pentler 2017
#
# This uses screen scraping as you appear to have to be a proper developer to
# get access to the Edinburgh City Council's BusTracker API
from bs4 import BeautifulSoup
import requests
def get_bus_times(stop_id): # r... |
21580bb63d57f66c2dd94a8882ebb725af71445c | junzhiwang/cs231n | /assignment1/cs231n/classifiers/softmax.py | 2,535 | 3.625 | 4 | import numpy as np
from random import shuffle
from past.builtins import xrange
def softmax_loss_naive(W, X, y, reg):
"""
Softmax loss function, naive implementation (with loops)
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: A numpy ar... |
cfc7efb3972ee25f68f2f3da0ac4b55269bc6245 | kumararun2002/Dragons-and-Terminators-Game-Python- | /dragons/characters/dragons/dragon.py | 1,316 | 3.921875 | 4 | from ..fighter import Fighter
class Dragon(Fighter):
"""A Dragon occupies a place and does work for the colony."""
is_dragon = True
implemented = False # Only implemented Dragon classes should be instantiated
food_cost = 0
blocks_path=True
is_container=False
# ADD CLASS ATTRIBUTES HERE
... |
835ea6ee01cc4527c3a94285754d6f08c4e6499f | kumararun2002/Dragons-and-Terminators-Game-Python- | /dragons/places/place.py | 3,339 | 4.34375 | 4 | class Place(object):
"""A Place holds fighters and has an exit to another Place."""
def __init__(self, name, exit=None):
"""Create a Place with the given NAME and EXIT.
name -- A string; the name of this Place.
exit -- The Place reached by exiting this Place (may be None).
"""
... |
bd260f44a1128dc5a445b33b9a64d3727b8a0b9a | hupipi96/pyldpc | /pyldpc/ldpc_images.py | 10,715 | 3.578125 | 4 | import numpy as np
from .imagesformat import int2bitarray, bitarray2int, Bin2Gray, Gray2Bin, RGB2Bin, Bin2RGB
from .codingfunctions import Coding
from .decodingfunctions import Decoding_BP_ext, Decoding_logBP_ext, DecodedMessage
from .ldpcalgebra import Bits2i, Nodes2j, BitsAndNodes
import scipy
import warnings
__all_... |
47ebab0595681ce148e3b375e05f966c943cdd76 | pradyotprakash/matasano | /all/challenge15.py | 579 | 3.5 | 4 | def paddingValidation(string, blockSize):
if len(string) % blockSize != 0:
raise Exception("Not PKCS#7 padding!")
lastBlock = string[-16:]
lastChar = lastBlock[-1]
lastCharNum = ord(lastChar)
if lastCharNum == 0:
raise Exception("Not PKCS#7 padding!")
i = lastCharNum - 1
while i >= 0:
if lastBlock[-(las... |
e18d097ce869fbc176141c7ae2b0d8a206c4a715 | code-gauchos/SamC | /BOM.py | 603 | 3.515625 | 4 | import json
import Product
jsonFile = open("./machine.json")
machine = json.load(jsonFile)
print("Let's Build a PC that fits your budget. What setup type would you like? We offer the Budget Gamer, the Mid Ranger, the Power Budget, and the All Out Power.")
products = []
for machineCounter in range(len(machine)):
... |
6a9d9421a0abf10145985ec3f601fcc1d9c7e7ff | Maximusmax30/LesMilies | /les_milies.py | 6,561 | 3.671875 | 4 | # -*-coding:Latin-1 -*
import os # On importe le module os
import pickle
from gestion_compte import *
from function_milies import *
from liste_milies import *
from commandes_milies import *
from characteristique_milies import *
from random import randrange
os.chdir("D:/programme/Python/PROJET/Les Milies")
print("Bienve... |
4d1ab49efc9907e015cb8eb8f45c6678f658c5bd | frogermcs/AIND-Isolation | /game_agent.py | 16,374 | 3.625 | 4 | """This file contains all the classes you must complete for this project.
You can use the test cases in agent_test.py to help during development, and
augment the test suite with your own test cases to further test your code.
You must test your agent's strength against a set of agents with known
relative strength usin... |
eb6e112fbf2a8a3fcf4ac1a137cd6651b322959d | unpsjb-ieee-student-branch/curso-python | /Colab/05-OOP/examples/bravo_1.py | 827 | 3.953125 | 4 | # How to debug
# sears.py
bill_thickness = 0.11 * 0.001 # Meters (0.11 mm)
sears_height = 442 # Height (meters)
num_bills = 1
day = 1
while num_bills * bill_thickness < sears_height:
print(day, num_bills, num_bills * bill_thickness)
day = days + 1
num_bills = num_bills * 2... |
2ca7c4e31ad857f80567942a0934d9399a6da033 | zoeyangyy/algo | /exponent.py | 600 | 4.28125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @Time : 2018/8/16 下午10:27
# @Author : Zoe
# @File : exponent.py
# @Description :
# -*- coding:utf-8 -*-
class Solution:
def Power(self, base, exponent):
# write code here
result = base
if exponent == 0:
return ... |
bce4de78e56bd835490c43ff95d25fadd905ee97 | zoeyangyy/algo | /arrange_min.py | 1,373 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @Time : 2018/8/21 下午10:34
# @Author : Zoe
# @File : arrange_min.py
# @Description :
# class Solution:
# def PrintMinNumber(self, numbers):
# # write code here
# str_li = [str(one) for one in numbers]
# sort = self.quick(st... |
a3ebe6e0f49e7e61fd94455218577b5d5e81dbc5 | itgsod-julia-waldhagen/Uppgift---Filter | /lib/filters.py | 391 | 3.90625 | 4 |
lista = ["Papaya", "Banan", "Apelsin", "Banan", "Druvor", "Melon"]
def filter(lista, x):
newlista = []
for i in lista:
if i == x:
newlista.append(i)
return newlista
print filter(lista,"Banan")
def exclude(lista, x):
for i in range(len(lista)-1,-1,-1):
if lista[i] == x:
... |
36d281d594ec06a38a84980ca15a5087ccb2436a | connor-giles/Blackjack | /hand.py | 847 | 4.125 | 4 | """This script holds the definition of the Hand class"""
import deck
class Hand:
def __init__(self):
self.cards = [] # A list of the current cards in the user's hand
self.hand_value = 0 # The actual value of the user's hand
self.num_aces = 0 # Keeps track of the number of aces that the ... |
a3c08ecf3ee320a6b7a9956dd56d1145826b8e88 | mpumbya/shoppinglist | /test/ntest_bank.py | 732 | 3.65625 | 4 | import unittest
from bank import BankAccount
class AccountBalanceTestCases(unittest.TestCase):
def setUp(self):
self.account_yangu = BankAccount()
def test_balance(self):
self.assertEqual(self.account_yangu.balance, 3000, msg= 'Account balance Invalid')
def test_deposit(self):
sel... |
aa8032e5c37f4954258a53de50d658799af3c5a8 | Shajidur-Rahman/Automatic_Messenger | /main.py | 343 | 3.578125 | 4 | number_of_message = int(input("How many message do you want to send? "))
import pyautogui
import time
message = 0
while message < number_of_message:
time.sleep(2)
pyautogui.typewrite('hello we make song and programming projects. Now i made a project called automatic messenger')
pyautogui.press('enter')
... |
878a1e71286c0a41bfb6a205cd9c70b91ff74bf9 | Fuzzy087/FizzBuzz | /main.py | 580 | 4.0625 | 4 |
primes = []
for possiblePrime in range(2, 100):
isPrime = True
for num in range(2, possiblePrime):
if possiblePrime % num == 0:
isPrime = False
if isPrime:
primes.append(possiblePrime)
print(primes)
for num in range(1, 100):
if num in primes:
prin... |
660681269136d8731f9b01fea37dc16b1ebe577a | i-soo/PS | /BOJ/Steps/Step1/2588-a.py | 317 | 3.75 | 4 | inp1 = int(input()) # int형으로 변환
inp2 = input() # 문자열 그대로 저장
# 문자열의 인덱스를 이용
out1 = inp1 * int(inp2[2])
out2 = inp1 * int(inp2[1])
out3 = inp1 * int(inp2[0])
result = inp1 * int(inp2)
# sep='\n'로 한번에 출력 처리
print(out1, out2, out3, result, sep='\n')
|
b1c3f1c7eba77049582306dbf076a2c75042caa7 | i-soo/PS | /BOJ/Steps/Step5/3052.py | 123 | 3.515625 | 4 | nums = []
for i in range(10):
temp = int(input())
nums.append(temp%42)
num_list = set(nums)
print(len(num_list))
|
3423f54a655e7812a3328e29fee3bc3123a93700 | i-soo/PS | /BOJ/Steps/Step1/2588-b.py | 274 | 3.59375 | 4 | inp1 = int(input())
inp2 = int(input()) # int형으로 변환
# 자릿수 각각을 계산
out1 = inp1*((inp2%100)%10)
out2 = inp1*((inp2%100)//10)
out3 = inp1*(inp2//100)
result = inp1*inp2
# sep='\n'로 한번에 출력 처리
print(out1, out2, out3, result, sep='\n')
|
cf9364dc72547a3058d861b6234668e21d1b681c | KrisAlone2k/matura_inf | /67/67-1.py | 646 | 3.6875 | 4 | #zad 1
print('zad 1')
x = 1
fib = [1,1]
for i in range(2,40):
fib.append(fib[i-2] + fib[i-1])
print('F10',fib[9])
print('F20',fib[19])
print('F30',fib[29])
print('F40',fib[39])
#zad 2
print('zad 2')
def isPrime(x):
i = 2
if x >= 2:
while i < x:
if x%i == 0:
return False... |
6b16f67a76c4951b641d252d40a1931552381975 | by46/geek | /codewars/4kyu/52e864d1ffb6ac25db00017f.py | 2,083 | 4.1875 | 4 | """Infix to Postfix Converter
https://www.codewars.com/kata/infix-to-postfix-converter/train/python
https://www.codewars.com/kata/52e864d1ffb6ac25db00017f
Construct a function that, when given a string containing an expression in infix notation,
will return an identical expression in postfix notation.
The op... |
df1fc547862bf9ec5259c00c39e591857b73b8b3 | Aurelius10/kattisTasks | /hard/completed/0_1sequence/test3.py | 8,524 | 3.546875 | 4 | import sys
import math
def add(x):
return int((x+1)*x/2)
def nCr_list_n2(num):
res_list = []
meas = int(num/2 + 0.5)
res_list = [0]*(meas+1)
res_list[0] = 1
for i in range(1, meas+1):
res_list[i] = res_list[i-1]*(num+1-i)//i
return res_list
def nCr_list_test(num):
res_list = [... |
4bb5d3cdaa0029076e7f1e7cc68b809e51913d1f | anshu3769/KeplerProject | /Backend/data/models.py | 1,729 | 3.5 | 4 | """
This module contains all the models
required by the application.
"""
from sqlalchemy import Column, DateTime, ForeignKey, Integer, String, func
from sqlalchemy.orm import backref, relationship
from .database import Base
class Player(Base):
"""
Class to create a table for storing
a player's person... |
6871c3ff47b4586a2b566ca6f1c4aaa6cb0f5031 | tomomof/kadai | /0726kadai.py | 117 | 3.703125 | 4 | x=4545
print(x)
x_str=str(x)
print("my fav num is", x, ".", "x=", x)
print("my fav num is " + x_str +"."+"x="+x_str)
|
2b5931eade99c213d86c4f5a26eed1ec45dea907 | tianchengcheng-cn/LeetCode | /动态规划/5-最长回文字串.py | 889 | 3.640625 | 4 | """
给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
输入: "babad"
输出: "bab"
注意: "aba" 也是一个有效答案。
"""
class Solution:
def longestPalindrome(self, s: str) -> str:
n = len(s)
# 中心扩展
# 判断边界条件
if n == 0:
return ""
def extend(i: int, j: int, s: str) -> str:
... |
617ad0d0bc92053499ee96aa212c6d9bc14fd38c | tianchengcheng-cn/LeetCode | /双指针/239-滑动窗口中的最大值.py | 1,223 | 3.71875 | 4 | """
给你一个整数数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。
返回滑动窗口中的最大值。
输入:nums = [1,3,-1,-3,5,3,6,7], k = 3
输出:[3,3,5,5,6,7]
解释:
滑动窗口的位置 最大值
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 ... |
810e0a5b90c6973ad04f2fcc20b8fe4451bbec7b | dararod/python-101 | /lista_de_compras.py | 492 | 3.921875 | 4 | lista_de_compras = []
preguntar_de_vuelta = True
while preguntar_de_vuelta:
# obtiene el producto del usuario
item = input("Ingrese producto: ")
# agrega el producto a la lista
lista_de_compras.append(item)
# preguntar si desea continuar
continuar = int(input("Desea agregar otro item?: (0: No/1: Si)"))
... |
82e3e5f9567aca3deda01c7bc8a5157d44c4947f | Akai-Kumako/100knock | /Chapter1/00.py | 80 | 3.578125 | 4 | #00.文字列の逆順
f = reversed(list("stressed"))
a = ''.join(f)
print(a)
|
f0b311eb85eb267e0e4e4ca3da2af2fba1071451 | apugithub/Python_Self | /pandas_intro.py | 795 | 3.921875 | 4 | import pandas as pd
df = pd.read_csv('data/pokemon_data.csv') #Dataframe (the core of pandas)
#print(df) # Print the dataframe
#print(df.info()) #Prints the summary of dataframe
#print(df.head()) # head prints first 5 records + you may specify number inside head too
#print(df['HP'].max()) # displaying the max va... |
81cfaff6e7ed2ac0be013d2439592c4fb8868e63 | apugithub/Python_Self | /negetive_num_check.py | 355 | 4.15625 | 4 |
# Negetive number check
def check(num):
return True if (num<0) else False
print(check(-2))
### The function does check and return the negatives from a list
lst = [4,-5,4, -3, 23, -254]
def neg(lst):
return [num for num in lst if num <0]
# or the above statement can be written as= return sum([num < 0... |
0d4883a8d8d46f1e6b5fb5fd1e9647abac80034e | ftahrirc/Snake1 | /snake.py | 752 | 3.859375 | 4 | import turtle,random
class Cell:
def__init__(self,size,t,x,y):
self.x=x
self.y=y
self.t=t
self.size=size
def draw_square(self):
for side in range(4):
self.t.fd(self.size)
self.t.left(90)
def draw_snake()(self)
for side in range(5):
cell=cell(10,turtle.turtle... |
41f879b9e85bc1dd1fab73cba29e6e5828d6a1be | jurogrammer/studying | /algorithm_study/week3/190129/InJae/[SWEA]1231.중위순회.py | 441 | 3.78125 | 4 | def InorderTraveral(tree,i,N):
if i<=N:
InorderTraveral(tree,i*2,N)
print(tree[i],end="")
InorderTraveral(tree,i*2+1,N)
for t in range(1,11):
N = int(input())
tree = [0 for _ in range(N+1)]
for _ in range(N):
inputValue = input().split(" ")
node, item = inputValu... |
c71ff8bc6ad2d290c7ed03222e46acbc5570f481 | jurogrammer/studying | /Algorithm/[프로그래머스]가장먼노드.py | 1,173 | 3.515625 | 4 | from queue import Queue
#인접행렬로 만들기엔 2만이므로 공간복잡도가 매우 큼. 2만x2만 -> 4백만.
def ConvertEdgeToGraph(edge):
#1번 노드부터 시작, 최대 2만개. 그래프는 인덱스가 u,value가 v
graph = [[] for _ in range(20001)]
#양방향 그래프
for u,v in edge:
graph[u].append(v)
graph[v].append(u)
return graph
def solution(n, edge):
# BFS... |
4419c26eda4759d30d80a8e9681c8164f60414ac | jurogrammer/studying | /Algorithm/[백준]9461.파도반수열.py | 271 | 4 | 4 | '''
https://jurogrammer.tistory.com/6
'''
memo = {1:1,2:1,3:1}
def Wave(n):
if n in memo:
return memo[n]
else:
memo[n] = Wave(n-2)+Wave(n-3)
return memo[n]
n = int(input())
for _ in range(n):
req = int(input())
print(Wave(req)) |
0e5b6c497c37d0e6023ddc712687dc588f85ffd7 | jurogrammer/studying | /algorithm_study/week1/200108/InJae/[SWEA_lesson6_1day]min_max.py | 660 | 3.6875 | 4 | def BubbleSort(input_list): #input : list , output= sorted_list
for i in range(len(input_list)-1,-1,-1):
for j in range(0,i):
if input_list[j]>input_list[j+1]:
temp = input_list[j]
input_list[j] = input_list[j+1]
input_list[j+1] = temp
ret... |
1fcd14f968db19cc71a7409145afa61c6031d728 | gaylonalfano/Python-3-Bootcamp | /__name__variable.py | 1,067 | 3.546875 | 4 | '''
A "dunder" variable. Special properties represented by __name__ variable.
When run, every Python file/module has its own __name__ variable. If the file is
the main file being run, its value is "__main__". Otherwise, its value is the file name.
***check out say_hi.py and say_sup.py for example***
Basically, the _... |
8f27badfdef2487c0eb87e659fac64210faa1646 | gaylonalfano/Python-3-Bootcamp | /card.py | 767 | 4.125 | 4 | # Card class from deck of cards exercise. Using for unit testing section
# Tests: __init__ and __repr__ functions
from random import shuffle
class Card:
available_suits = ("Hearts", "Diamonds", "Clubs", "Spades")
available_values = ("A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K")
def _... |
6bcb51fae80c295f98d6004344c5ffec1028f602 | gaylonalfano/Python-3-Bootcamp | /infinite_generators_get_multiples.py | 649 | 4.21875 | 4 | # def get_multiples(number=1, count=10):
# for i in range(1, count+1):
# yield number*i
#
# evens = get_multiples(2, 3)
# print(next(evens))
# print(next(evens))
# print(next(evens))
# print(next(evens))
# GET_UNLIMITED_MULTIPLES EXERCISE:
def get_unlimited_multiples(number=1):
next_num = number
... |
d3aab6c3a00102b36f6eea2c25e5bd4015217d9b | gaylonalfano/Python-3-Bootcamp | /deck_of_cards_class_project.py | 9,080 | 4.21875 | 4 | '''
Introduction
Your goal in this exercise is to implement two classes, Card and Deck .
Specifications
Card
Each instance of Card should have a suit ("Hearts", "Diamonds", "Clubs", or "Spades").
Each instance of Card should have a value ("A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K").
Card 's... |
c68446d2fa042a3c279654f3937c16d632bf2420 | gaylonalfano/Python-3-Bootcamp | /decorators_logging_wraps_metadata.py | 2,667 | 4.40625 | 4 | """
Typical syntax:
def my_decorator(fn):
def wrapper(*args, **kwargs):
# do stuff with fn(*args, **kwargs)
pass
return wrapper
Another tutorial example: https://www.youtube.com/watch?v=swU3c34d2NQ
from functools import wraps
import logging
logging.basicConfig(filename='example.log', level=lo... |
0fa247aef355f85a8a00d44357933f418038c91d | gaylonalfano/Python-3-Bootcamp | /debugging_pdb.py | 1,790 | 4.1875 | 4 | '''
Python Debugger (pdb) -- To set breakpoints in our code we can use pdb by inserting this line:
def function(params):
import pdb; pdb.set_trace() - Usually added/imported like this inside a function
*Rest of code*
Usually placed right before something starts breaking. Allows you to see a preview of what h... |
1f60486620945a344e4de43c3644a16ce1886b49 | gaylonalfano/Python-3-Bootcamp | /say_hi.py | 945 | 3.9375 | 4 | '''
Here's what happens you import something:
1. Tries to find the module (if it doesn't find it, it throws an error).
2. But if found, it runs the code inside of the module being imported
So, in the example with say_hi and say_sup, when you import say_sup into the say_hi file,
it will run the code in the say_sup modu... |
9c309fa1bc6df7bf3d6e6b7ed047df45eb670316 | gaylonalfano/Python-3-Bootcamp | /sorted.py | 1,583 | 4.5625 | 5 | '''
sorted - Returns a new sorted LIST from the items in iterable (tuple, list, dict, str, etc.)
You can also pass it a reverse=True argument.
Key difference between sorted and .sort() is that .sort() is a list-only method and returns the
sorted list in-place. sorted() accepts any type of iterable. Good for sorted on ... |
f6c7ea3bf3080757bd268ee0b701e6c29c0d584f | gaylonalfano/Python-3-Bootcamp | /interleaving_strings_zip_join.py | 686 | 4.3125 | 4 | '''
Write a function interleave() that accepts two strings. It should return a new string containing
the two strings interwoven or zipped together. For example:
interleave('hi', 'ha') # 'hhia'
interleave('aaa', 'zzz') # 'azazaz'
interleave('lzr', 'iad') # 'lizard'
'''
def interleave(str1, str2):
return ''.jo... |
e02c57c26c880e076aae5b89ad58ebc5c774b541 | gaylonalfano/Python-3-Bootcamp | /any_all_genexp_sysgetsize.py | 2,594 | 4.0625 | 4 | '''
all - Return True if all elements of the iterable are truthy (or if the iterable is empty)
'''
all([0, 1, 2, 3,]) # False
all([char for char in 'eio' if char in 'aeiou']) # True
all([num for num in [4, 2, -1, 10, 6, 8] if num % 2 == 0]) # False
# Do all first letters start with 'c'?
people = ['Charlie', 'Cas... |
a5668f587fe9b9b26b70afd0e7bf97bc317c35b3 | gaylonalfano/Python-3-Bootcamp | /polymorphism_OOP.py | 1,806 | 4.3125 | 4 | '''
POLYMORPHISM - A key principle in OOP is the idea of polymorphism - an object can take
on many (poly) forms (morph). Here are two important practical applications:
1. Polymorphism & Inheritance - The same class method works in a similar way for different classes
Cat.speak() # meow
Dog.speak() # woof
Human.speak(... |
01f789624331400198854db00783dd92238b33ec | gaylonalfano/Python-3-Bootcamp | /RockPaperScissors.py | 3,615 | 4.375 | 4 | # # Now adding a computer player (random pics)
# from random import randint
#
# player = input('Player: Enter rock, paper, or scissors: ').lower()
# computer = randint(0, 2)
# if computer == 0:
# computer = 'rock'
# elif computer == 1:
# computer = 'paper'
# else:
# computer = 'scissors'
#
# print("...rock.... |
3b95bdfc9e342ab8269671b0d7410d311fdcba43 | gaylonalfano/Python-3-Bootcamp | /try_except.py | 3,737 | 4.5 | 4 | '''
In Python, it is STRONGLY encouraged to use try/except blocks to catch exceptions
when we can do something about them. Let's see what that looks like.
Most basic form:
try:
foobar
except NameError as err:
print(err)
'''
'''
WHEN TO USE TRY/EXCEPT VS. RAISE:
You would want to use try-except when you wan... |
79c42425fad9a2049934a8208d0b8cf9ca9b0a08 | gaylonalfano/Python-3-Bootcamp | /custom_for_loop_iterator_iterable.py | 1,648 | 4.4375 | 4 | # Custom For Loop
'''
ITERATOR - An object that can be iterated upon. An object which returns data,
ONE element at a time when next() is called on it. Think of it as anything we can
run a for loop on, but behind the scenes there's a method called next() working.
ITERABLE - An object which will return an ITERATOR when... |
1c99eb986dc4930076e17100b281bcc2f21c2c8b | gaylonalfano/Python-3-Bootcamp | /generator_expressions.py | 778 | 3.796875 | 4 |
# g = (yield num for num in range(1, 10)) WRONG! DON'T NEED TO ADD YIELD
# g = (num for num in range(1,10))
# print(g) # <generator object <genexpr> at 0x104005780> GENERATOR EXPRESSION
# print(next(g))
#
# def nums():
# for num in range(1,10):
# yield num
#
# f = nums()
# print(f) # <generator ob... |
2e9cde6ddaf45706eb646ec7404d22a851430e3f | gaylonalfano/Python-3-Bootcamp | /dundermethods_namemangling.py | 1,096 | 4.5 | 4 | # _name - Simply a convention. Supposed to be "private" and not used outside of the class
# __name - Name Mangling. Python will mangle/change the name of that attribute. Ex. p._Person__lol to find it
# Used for INHERITANCE. Python mangles the name and puts the class name in there for inheritance purposes.
# Think of hi... |
e25847f26dc7c05266590c808073ab6b9828705a | SamiFatmi/python-programming-SAMI-FATMI | /Labs/Labb-3/shapes.py | 38,556 | 4.53125 | 5 | import math
import matplotlib.pyplot as plt
class Shape:
""" This class will be parent to the classes 'Rectangle' and 'Circle', it will contain the
coordinates of the 2D shapes
"""
def __init__ (self,x:float,y:float)->None:
self.x= x
self.y= y
@property
def x(self):
... |
ea96c085e2d906bc42fe62c5c399b26fd6ea40f9 | ElYannu87/learnthehardway | /ex15.py | 281 | 3.625 | 4 | # import sys
# from sys import argv
# naming script
# script, filename = argv
# open the file
filename = input("Filename?")
txt = open(filename, 'w')
line4 = input("Line4: ")
# print and read file
print(f"Here's your file {filename}")
txt.write(line4)
txt.write("\n")
txt.close()
|
39d442135370452b86ee1a1fa0bfa5997620c83a | ElYannu87/learnthehardway | /ex19.py | 1,095 | 3.796875 | 4 | def cheese_and_crackers(cheese_count, boxes_of_crackers):
print(f"Your have {cheese_count} cheeses!")
print(f"You have {boxes_of_crackers} boxes of crakcers!")
print("Man that's enough for a party!")
print("Get a blanket. \n")
def cookies_and_milk(cookie_count, milk_count):
print(f"You have {cookie... |
d1c15339e17f6c7faf3666be0b62c4d55a311ac1 | kshannon/dse-241 | /exercise_2/utils/data_shape_ex2.py | 1,030 | 3.6875 | 4 |
# coding: utf-8
# Was a .ipynb file that we converted to a .py. temp1.json can be renamed.
# Import libraries
import json
import pandas as pd
import numpy as np
# Read json file into pandas data frame
df = pd.read_json('exercise2-olympics.json')
df.head(5)
# Dataframe to take who are the top 10 countries by meda... |
ac2082c2807c70d039c3335abc5461b945ef1788 | sathiiii/Hackerrank-Solutions | /Dynamic Programming/Equal.py | 1,893 | 3.6875 | 4 | '''
Problem Statement: Christy is interning at HackerRank. One day she has to distribute some chocolates to her colleagues.
She is biased towards her friends and plans to give them more than the others. One of the program managers hears of this and tells her
to make sure everyone gets the same number. To ... |
6f189295fa8c97662f91d6482e330d33d379c51c | fenning-research-group/Python-Utilities | /FrgTools/frgtools/imageprocessing.py | 8,248 | 3.578125 | 4 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
from PIL import Image
import affine6p
from skimage.transform import resize as skim_resize
import cv2
def adjust_brightness(img, value):
'''
adjust image brightness on a 0-255 scale
example:
img_brighter = adjust_brightness(i... |
28a3d57dc9f488b89e738b0e6717b6cdac4e1e23 | aolovely/NguyenTienThanh-Fundamentals-c4e13 | /Session05/HomeWork/Exercise2.py | 337 | 3.921875 | 4 | numbers = [1, 6, 8, 1, 2, 1, 5, 6]
def TimeNumber(n):
count = 0
for i in range(len(numbers)):
if numbers[i] == n:
count += 1
return count
number = int(input("program to count number occurrences in a list \n enter a number? "))
print("{0} appears {1} times in my list".format(number, Time... |
3561e9569974ab7a02fddb59d62416fc1f223283 | aolovely/NguyenTienThanh-Fundamentals-c4e13 | /Session05/HomeWork/Exercise4.py | 239 | 3.921875 | 4 | def rabbit(month):
if month == 0:
return 1
if month == 1:
return 2
else:
return rabbit(month - 1) + rabbit(month - 2)
for i in range(5):
print("month {0}: {1} pairs of rabbit".format(i, rabbit(i)))
|
481c1694ddaa1e5c99c1fd2d7f6b64a5c0ca6293 | aolovely/NguyenTienThanh-Fundamentals-c4e13 | /Session03/Game1.py | 218 | 3.59375 | 4 | n = int(input("enter: "))
count = 1
while True:
if (n//10) != 0:
count +=1
n //=10
else:
break
print(count)
# while True:
# count +=1
# n //=10
# if n == 0:
# break
|
f93ea5e58432cda7ea42779f8ce1ecf0b018f8a6 | aolovely/NguyenTienThanh-Fundamentals-c4e13 | /Session05/HomeWork/Exercise2WithFunctionCount.py | 205 | 4.09375 | 4 | numbers = [1, 6, 8, 1, 2, 1, 5, 6]
number = int(input("program to count number occurrences in a list \n enter a number? "))
print("{0} appears {1} times in my list".format(number, numbers.count(number)))
|
5ac518feb75960ec562952e50027cbd7c1fb8746 | DiogoRibeiro7/Data-Cleaning | /convert_cat2num.py | 233 | 3.5625 | 4 | def convert_cat2num(df):
# Convert categorical variable to numerical variable
num_encode = {'col_1' : {'YES':1, 'NO':0},
'col_2' : {'WON':1, 'LOSE':0, 'DRAW':0}}
df.replace(num_encode, inplace=True) |
30cb891b8e30026399bef6f9dc4db0d3ea021487 | henryneu/pycharm | /cn/edu/modu/iter_tool.py | 540 | 3.8125 | 4 | # -*- coding:utf-8 -*-
#Author: Henry
import itertools
natuals = itertools.count(1)
ns = itertools.takewhile(lambda x: x <= 10, natuals)
for n in ns:
print(n)
# cs = itertools.cycle('ABC')
# for c in cs:
# print(c)
# 重复输出10个A
np = itertools.repeat("A", 10)
for p in np:
print(p)
# 把一组迭代对象串联起来
for c in it... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.