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 |
|---|---|---|---|---|---|---|
b487c1ad1b5acc72cb0fc003c30187fdefc1a341 | ElmelundJC/KEA_python_semester_4 | /2._data_structures/exercises.py | 1,299 | 4.0625 | 4 | # Sort a list
# Create a list of strings with names in it. (l = [‘Claus’, ‘Ib’, ‘Per’])
names = ['Claus', 'Ib', 'Per']
# Sort this list by using the sorted() build in function.
sorted_names = sorted(names)
print(sorted_names)
# Sort the list in reversed order.
sorted_names_reversed = sorted(names, reverse=True)
prin... |
e2deb685e56008ae47cec92eab1095b343877f17 | JacobFischer/CS5400-Puzzle | /src/board.py | 11,317 | 3.96875 | 4 | from pieces import Piece, Alligator, Turtle, Tree, Boat, Goal
# used to print things to console all pretty like
_str_mapping = {
None.__class__: " .",
Alligator: "A#",
Turtle: "T#",
Tree: "C#", # because they are Cyprus Trees or whatever
Boat: "B@", # will be replaced with an arrow
Goal: " G"... |
1cb2d9eb696059ca5ef5e4ea2d8b48f69671061f | mbonnemaison/Learning-Python | /Leetcode/009_Palindrome_Number (Leetcode).py | 1,448 | 3.828125 | 4 | """
Palindrome number (Leetcode problem #9)
Given an integer x, return true if x is palindrome integer.
An integer is a palindrome when it reads the same backward as forward.
For example, 121 is palindrome while 123 is not.
Example 1:
Input: x = 121
Output: true
Example 2:
Input: x = -121
Output: false
Explanation: F... |
572eb584fb562b811de2b73c517ed4fffbf5c8e2 | mbonnemaison/Learning-Python | /First_programs/boolean_1.py | 730 | 4.15625 | 4 | """
def list_all(booleans):
Return True if every item in the list is True; otherwise return False
list_all([]) = True
list_all([True]) = True
list_all([False]) = False
list_all([True, False, True]) = False
raise Exception("TODO")
"""
def list_all(booleans):
for bools in booleans:
if not isinstance(bools, b... |
f5bcc93172ba0577ba9f663e9526c382c0300e61 | samism/Projects | /Numbers/pi.py | 102 | 3.578125 | 4 | from math import *
n = raw_input('Enter how many decimals of pi: ')
pie = str(math.pi)
print pie[:n] |
0c62c55cd1b6b60c32e26c9690d1a04c99b15ef1 | alexwlchan/alexwlchan.net | /src/_files/2015/readinglist.py | 1,037 | 3.59375 | 4 | #!/usr/bin/env python
"""
readinglist.py
~~~~~~~~~~~~~~
This script gets a list of all the URLs in Safari Reading List, and
writes them all to a file.
Requires Python 3.
See https://alexwlchan.net/2015/11/export-urls-from-safari-reading-list/
"""
import os
import plistlib
INPUT_FILE = os.path.join(os.environ['HOM... |
9899b27cb3a14c516af1fdf7516970c14689d592 | perodriguezl/weather_calculator | /calculations_helper.py | 3,484 | 3.671875 | 4 | import math
class calculations_helper:
'''
Instance designed to contain all the reusable calculation methods -- Expected 9/9 methods to be testeables
'''
def __init__(self):
'''
@param self:
@return:
'''
self.full_cicle = 360
self.half_cicle = 180
... |
5a6cf4c11ef1e556159db78c65450a5b0320e100 | meistalampe/MTEC | /WorkingFolder/MTEC/cut_segment.py | 3,105 | 3.578125 | 4 | import os
from typing import List
from empatica_data_extraction import *
def main():
"""
A function that reads a data file, stores its contents into a list and extracts the time segment, specified by two
timestamps as specified by the user. Afterwards the segment is saved into a new file.
"""
# ... |
2205eee999f0175dbb14cc40d239bd819fc83baa | KarenAByrne/Python-ProblemsSets | /fib.py | 1,159 | 4.21875 | 4 | # Karen Byrne
# A program that displays Fibonacci numbers.
def fib(n):
"""This function returns the nth Fibonacci number."""
i = 0
j = 1
n = n - 1
while n >= 0:
i, j = j, i + j
n = n - 1
return i
# Test the function with the following value. My name is Karen , so the first and l... |
9c55add6e0ef7035b49ac749ca1b6a1365a4000d | dumbPy/Intro_to_ML-EE769- | /Assignment_1/train.py | 12,205 | 3.578125 | 4 |
# coding: utf-8
# # Intro to Machine Learning Assignment 1 Report
#
#
# Importing all the Dependencies here
# In[49]:
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.metrics import accuracy_scor... |
c17dbc0dd48d6447907183800835423a7c48ffb5 | galatea-associates/fuse-test-data-gen | /src/multi_processing/pool_tasks.py | 6,148 | 3.96875 | 4 | """ Pool Manager functionality for both create and write parent processes.
The create parent process executes the 'parent_process' method of the Creator
class, which prepares a batch of 'create jobs' then calls the 'run_create_jobs'
method of this module to run them over a pool of child processes.
The write parent pr... |
8964c25ea2491fbd680e0376afdc5d92f3c99f67 | vasu-negi/Network-Data-Streaming | /Assignment 3/ActiveCounter.py | 1,068 | 3.75 | 4 |
import random
class ActiveCounter:
# this will initialize the variables as well as check for any wrong input and raise appropriate Error
def __init__(self):
self.number = 0
self.exp = 0
#This function will increment the counter
#The counter is only incremented based on the proba... |
c5bbd592dd2432c3e9d98fa09fdc826db8fed385 | duynamrcv/robot_vision | /inverse_image.py | 628 | 4.0625 | 4 | import cv2
import numpy as np
def inverse_image(gray):
'''
Convert the gray image to it's inverse image
gray - input image must be gray scale
'''
h, w = gray.shape
# print("{} {}".format(w,h))
mask = 255*np.ones([h,w], dtype=np.uint8)
i_img = mask - gray
return i_img
if __name__ ==... |
c8cd572bde563d3cebd748dde843402cd1fb2077 | camaral82/Python_Self_Study_MOSH | /Dictionary.py | 506 | 4.28125 | 4 | """24/09/2020 - Thursday
Dictionary Exercise
Type a sequence of numbers and at the end
transcript each element.
In case of typing a character, show ! """
digits_mapping = {"1": "One", "2": "Two", "3": "Three",
"4": "Four", "5": "Five", "6": "Six",
"7": "Seven", "8": "Eight", "9"... |
330a69ccb3e98e6b6072d41b633b2b281ae59edb | gump334/BlackCloudGeeks | /main.py | 932 | 3.5 | 4 | import requests
from bs4 import BeautifulSoup
import schedule
import time
# web scrape resource to fetch current info from a website
r = requests.get('https://weather.com/weather/today')
soup = BeautifulSoup(r.text, 'html.parser')
today_temp = soup.select('.today_nowcard-temp > span ')
current_temp = today_temp[0].cont... |
69c187c260ea1ea47b2e74ce7525d117b92f64c2 | cookiebrains/udemy-bootcamp-py | /projects/project_12.py | 856 | 4.0625 | 4 | import random
num = random.randint(1, 100)
def guess_the_number(mode):
times = 1
if mode == 'easy':
times = 10
if mode == 'hard':
times = 5
guess = 0
while guess != num:
print(f'You have {times} attempts remaining to guess the number. ')
guess = int(input('Make a g... |
8b1d353922504a699f0431290550289e5e315a25 | ClemRiviere/JEVCCM | /GameObjects/Callais.py | 4,422 | 3.84375 | 4 | import math as Math
class Case :
def __init__(self, x,y) :
self.x = x
self.y = y
self.heuristique = None
self.cost = None
self.parent = None
def __eq__(self,case) :
if not case:
return False
return self.x == case.x and self.y == case.y
def distance(self,case) :
return Math.sqrt(Math.pow(case.x ... |
d227c6c8db8de4e1c53f4c34f559c4a8e9aeb69c | faizmomin/PolyPaint | /testing.py | 617 | 3.828125 | 4 | # Allows user to select 4/6 colours.
# importing tkinter module
from tkinter import *
from tkinter import colorchooser
colour_Base = ["#ffffff","#ffffff","#ffffff","#ffffff","#ffffff","#ffffff"]
# choose_color(): Gets a colour in #HEX format
# colourNum (int) is one of the 6 colours
def choose_color(colourNum):
c... |
72663f0656ad734acee538dc6aa8f8d67256d49a | saileshkhadka/SearchingAlgorithm-in-Python | /LargestElementfromlistinLinearTime.py | 2,475 | 4.1875 | 4 | # Problem Description
# The program takes a list and i as input and prints the ith largest element in the list.
# Problem Solution
# 1. Create a function select which takes a list and variables start, end, i as arguments.
# 2. The function will return the ith largest element in the range alist[start… end – 1].
# 3. Th... |
189a89fb0d3b429f134bee72e3764026d0ed37f5 | Bringer-of-Light/kaggle | /Titanic/code/s1/preprocess.py | 4,508 | 3.5625 | 4 | from include import *
from plotfunc import *
# get titanic & test csv files as a DataFrame
train = pd.read_csv(r"../input/train.csv")
test = pd.read_csv(r"../input/test.csv")
full = train.append( test , ignore_index = True )
titanic = full[ :891 ]
del train , test
print ('Datasets:' , 'full:' , full.shape , 'titan... |
b011727792f7594f4a2da53d970b2a5bb7e9c105 | bruna-nb/gestao-de-anuncios | /model/cliente.py | 3,497 | 3.796875 | 4 | class Cliente():
"""
Classe usada para definir clientes
(Explicação mais detalhada...)
Atributos
---------
nome : str
Nome do cliente
telefone : str
Telefone do cliente
email : str
E-mail do cliente
codigo : int
Código do cliente
Métodos
---... |
5cb2f68fac9c6fd35a91bcbbc42ca6ae8dafac87 | kiri182/PracticePython | /08.py | 809 | 3.984375 | 4 | """
Rock beats scissors
Scissors beats paper
Paper beats rock
"""
import random
import sys
game = {'1': 'Rock', "2": 'Scissors', "3": 'Paper'}
def playgame():
computer_input = random.randint(1, 3)
player_input = input(
'Type the number. Rock:1, Scissors:2, Paper:3? : ')
player = game[player_inpu... |
9cf28e2b217e7e0bcabfce080072641ab436ea62 | zygoloid/wf10 | /wf10.py | 13,367 | 3.53125 | 4 | import curses
import random
import math
import os
import time
numAngles = 8
keys = {}
class Key(object):
def __init__(self, code):
keys[code] = self
self.pressed = False
def __bool__(self):
return self.pressed
def wrap(x, y):
x %= y
if x < 0: x += y
return x
erase = False
centre = (0, 0)
def a... |
60b9f563c153f11d6bdc037dcb8c173cb4699ca0 | sloanehawk/TheTechAcademyPythonCodingProjects | /drill2.py | 913 | 3.96875 | 4 | #Drill 2
#This script will use sqlite3 to create a database, and read from a supplied list of file names
#and add only the files from the list that end with a ".txt" file extension
import sqlite3
conn = sqlite3.connect('drill2.db')
with conn:
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS tbl... |
4215a1db4779d76595bab3fcaea2010257b2559a | equilibrium360/PythonSnippets | /generators/generator_snippet.py | 208 | 3.828125 | 4 |
def square_numbers_with_generator(nums_list: list):
for x in nums_list:
yield x*x
if __name__ == '__main__':
gn = square_numbers_with_generator([1, 2, 3])
for i in gn:
print(i)
|
579d15c31fb768b0f8de89735baf9b6dd6c32a2c | 1acson2/AlephCero | /Estacionamiento.py | 716 | 3.578125 | 4 | from Cola import Cola
from Tubo import Tubo
class Estacionamiento(Cola):
def generar(self):
nuevo = Tubo()
self.encolar(nuevo)
def destruir(self):
self.desencolar()
def estacionar(self,vehiculo):
return ticket
def retirar(self,placa,ticket):
def existe(self,p... |
dca796a534f07efee42d017761c7c77e87b785eb | andrewjuarez/wallbreakers-hw | /week3/is_subsequence.py | 620 | 3.609375 | 4 | # https://leetcode.com/problems/is-subsequence/description/
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
if s == t:
return True
try:
index = 0
for char in t:
if char == s[index]:
index +=1
... |
8698907742b85d6bf1abf769a86eb3fff0abb4fe | andrewjuarez/wallbreakers-hw | /week1/reverse_words_in_a_string_iii.py | 283 | 3.671875 | 4 | # https://leetcode.com/problems/reverse-words-in-a-string-iii/description/
class Solution:
def reverseWords(self, s: str) -> str:
words = s.split(" ")
s = ""
for i in range(len(words)):
s += words[i][::-1] + " "
return s[:-1]
|
76064df862bccc18a4a9732160d158b1809e1953 | sampathl/basics | /leet code/reverseString_recursive.py | 256 | 4.03125 | 4 | def reverseString(s):
if len(s)==1:
#print("--",s)
return s
elif len(s)>1:
#print(s[-1],s[:-1])
s[:-1]=reverseString(s[:-1])
s.insert(0,s.pop())
return s
print(reverseString(['h','e','l','l','o'])) |
6d923b528b55185d601b6d2560037a5b19561ffc | gabastil/pyDocs | /Scan.py | 3,362 | 4.1875 | 4 | # Name: Scan.py
# Author: Glenn Abastillas
# Date: 8/21/2015
# Purpose: Allows the user to:
# 1.) Count the number of directories and subdirectories, etc., in a directory.
# 2.) Count the number of files in a directory and its subdirectories.
#
# To see the script run, go to the bottom of this page.... |
2975c30e12493516fbdfbfa2f5f88859f972eb8a | gabastil/pyDocs | /SpreadsheetPlus.py | 6,434 | 3.5625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Name: SpreadsheetPlus.py
# Version: 1.0.0
# Author: Glenn Abastillas
# Date: September 21, 2015
#
# Purpose: Allows the user to:
# 1.) Load a spreadsheet into memory.
# 2.) Transpose columns and rows.
# 3.) Find a search term and ret... |
53e092df9f6c1626f359e32cf01e441881126bbc | linda1212/PythonCode | /hello_py3.py | 594 | 3.859375 | 4 | #!/usr/bin/python
year = "2017"
date = "07"
list = ['a',756,2.23,'tom']
print(list)
print(list[0])
print(list[1:3])
var1 = 1
var2 = 2
print(year*2);
a1 = True;
a2 = False;
if(a1 and a2):
print('all true')
else :
print('not all true')
pass
pass
pass
num = 3
if num == 3 :
print('num is 3')
elif num == 2:
... |
3f07333fe11b65981a4d530cc59ff45e42fe8225 | ssaroonsavath/python-workplace | /conversion/conversion.py | 977 | 4.25 | 4 | '''
Created on Jan 20, 2021
The objective is to make a program that can complete different conversions
'''
#Use input() to get the number of miles from the user. ANd store
#that int in a variable called miles.
miles = input("How many miles would you like to convert?")
#Convert miles to yards, using the following:... |
7116ec0fbd12d2c7c69668bb0b72bb579116c5c3 | StevenSLXie/AcaMail | /mailBasic.py | 2,352 | 3.6875 | 4 | # Import smtplib for the actual sending function
import smtplib
import imaplib
import email
# Import the email modules we'll need
from email.mime.text import MIMEText
# The sendMail function provides a simple way to send the content of a .txt file as
# the body of a email. Several to be done: 1) options for typing ... |
7686831590125c15617128a0115e1a23b084d528 | mayanderson/python-selenium-automation | /hw3_algorithms/algorithm_2.py | 298 | 4.15625 | 4 | def longestWord():
sentence = input('Please enter a sentence with words separated by spaces:')
words = sentence.split()
if len(words) == 0: return ""
if len(words) == 1: return words[0]
longest = ""
for word in words:
if len(word) > len (longest): longest = word
return longest |
d1e6ea2f071bf4897e13b77f881e6db0614509f8 | allorapdx/project-1 | /guessing_game.py | 2,976 | 3.71875 | 4 | """
--------------------------------
Python Web Development
Project 1 - Number Guessing Game
Version 2.0
--------------------------------
"""
import random
high_score = []
number_of_attempts = 0
level = 'easy'
random_number = 0
number_range = '1 and 10'
#Display a welcome message to the player.
def menu():
prin... |
9d7dee0606fd14a746eec44386f38fb29fc02781 | stancodestore/SEJSandbox | /Inv_assistant/SQLite_Tool.py | 1,550 | 3.953125 | 4 | import sqlite3
from sqlite3 import Error
def create_DB(db_file):
""" create a database connection to a SQLite database """
conn = None
try:
conn = sqlite3.connect(db_file)
print(sqlite3.version)
except Error as e:
print(e)
finally:
if conn:
conn.close()
... |
658408212c2953a13931535581cbd34f9f446d83 | chokrihamza/opp-with-python | /try_except.py | 496 | 4.125 | 4 | try:
print(x)
except:
print("there is no value of x")
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
try:
f = open("demofile.txt", 'w')
f.write("Hello th... |
5bed094bafe0408a3ea268b2f1343cd82b59643c | dgapitts/mongo_m101p_vagrant | /m101p/hw2/dave_upsert.py | 2,240 | 3.515625 | 4 | import pymongo
import sys
# establish a connection to the database
connection = pymongo.Connection("mongodb://localhost", safe=True)
db = connection.dgapitts
students = db.students
def using_upsert():
print "updating with upsert"
try:
# lets remove all stuff from students
#students.remove({... |
73155a78e9a81f0498d3ed649e28efbd761d7eaa | Jokhanan/Carbon-Footprint-Tracker | /Program Directory/EventClass.py | 1,349 | 3.859375 | 4 | #--------------------------------------------------------------------------------------------------------
# Name: Event Parent Class (EventClass.py)
# Purpose: Parent Class for all event objects
#
#
# Author: Nisarg Shah
# Created: 4-Jan-2018
# Updated: 17-Jan-2019
#---------------------------------------------... |
00ddfa438d1670a66621534671a95e40d5d94f82 | masknugget/mypyqt | /cores/treedict.py | 1,866 | 3.765625 | 4 | from collections import OrderedDict
################################################################################
### TreeDict-key sorted dict
################################################################################
class TreeDict(OrderedDict):
def __init__(self, arr, reverse=False):
self._reve... |
d51308e309dc2401e063fbcd95561b86f59b3256 | EvgenyDD/BSUIR-STP-LABs | /2.Native_types.py | 2,230 | 3.890625 | 4 | '''
Types
1. Logic
2. Nums
3. Strings
4. Byte
5. Lists [a, b, c, d, a] - not mutable
6. Tuples (a, b, c, d, a) - mutable
7. Unions {a, b, c, d}
8. Dicts {a: b, c: d}
'''
import fractions
import math
def is_it_true(anything):
return True if anything else False
print('Logical type')
size = 0
print('size is ' + str... |
7ddab1a480e5e4ab6d33ce0bec4039a590547973 | Rohankrishna/Python_Scripting_Practice | /even_odd.py | 383 | 4.15625 | 4 | from math import sqrt
n = int(input("enter a number "))
check = int(input("Enter the number with which we want to check "))
if n % 4 == 0:
print("It is an even number and also a multiple of 4")
elif n%2==0:
print("It is an even number")
else:
print("It is an odd number")
if(n%check==0):
print(n, " is evenly divis... |
24b3424ae2a5af010eed5ffff3d13097bbfbcebb | Rohankrishna/Python_Scripting_Practice | /array_elements_sum.py | 121 | 3.53125 | 4 | ar=[]
sum=0
ar=list(map(int,input("Enter the elements you want to enter: ").split()))
for i in ar:
sum+=i
print(sum) |
a3899c4116f0fac62b3988db6ee38189b1ac472e | Rohankrishna/Python_Scripting_Practice | /divisors.py | 185 | 4.03125 | 4 | num = int(input("Enter the number for which we want divisors : "))
n = num/2 +1
divisors=[num,]
for i in range(1,n):
if num%i==0:
divisors.append(i)
divisors.sort()
print(divisors)
|
b62daa2a87474ab6bdbb49a216b887aebec88d9b | lqrz/autonomous_agents_2 | /models/field.py | 8,008 | 3.703125 | 4 | from __future__ import division
import numpy as np
import random
from models.predator import Predator
from models.prey import Prey
from models.state import State
class Field(object):
"""
Models the environment:
Responsibilities:
- Maintaining a list of agents
- coordination of the steps in an epis... |
010791d9f7c1001e7e43ccc1e19e766632678f5a | antoniovl/usr-tools | /randpwd.py | 2,695 | 3.90625 | 4 | #!/usr/bin/env python
"""
Simple generator of random passwords.
Generates a string alternating a consonant and a vowel, making the password
pronounceable.
"""
import sys
import random
import argparse
CONS = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'r',
's', 't', 'v', 'w', 'x', 'y', 'z']
VO... |
a503a913b8e5bc1a49b07f93a5672654b48dfb6e | MuhammedSert01/AlgoritmaAnalizi | /fibonacci.py | 216 | 3.859375 | 4 | def fib(n):
f=[0, 1]
for i in range(2, n+1):
f.append(f[i-1] + f[i-2])
return f[-1]
n = int(input("Kac elemanli fibonacci dizisi olsun? :"))
print("{}.fibonacci sayisi: {}".format(n, fib(n)))
|
4653e2a004cbea9cf2a8ce1620cc5fbbc3a86120 | Johnny-QA/Python_training | /Python tests/exercise.py | 2,190 | 3.78125 | 4 | ###### EXERCISE 6
### Task 1
class Store:
def __init__(self, name):
self.name = name
self.items = []
def add_item(self, name, price):
self.items.append({
'name': name,
'price': price
})
def stock_price(self):
total = 0
for item i... |
5b3e624ac2be2ade91eba0530b7dc932369faaef | Aditya7799/171IT204_Sem4 | /DAA/Lab7/problem1.py | 291 | 3.59375 | 4 | def maximalsubset(l):
l=sorted(l,key=lambda x:x[1])
subset=[]
for i in l:
if(len(subset)==0):
subset.append(i)
elif(subset[-1][1]<=i[0]):
subset.append(i)
return subset
def main():
l=[(1,3),(2,8),(2,5),(3,7),(4,8),(4,6),(6,12),(7,10)]
a=maximalsubset(l)
print(a)
main() |
980b7a7e9e0eb54fdb5e45109285da68ca5dafec | brownd0g/Financial-Independence-Calculator | /Financial Independence Calculator.py | 2,070 | 4.375 | 4 |
# This function is used to make sure user inputs a valid number for each question
def validInput(question):
UI = input(question)
# The following will run until a positive real number is entered
while True:
try:
num = float(UI)
while num < 0:
num = float(input(... |
43f1302eb024cdbdde1e734d0207e7225ee99850 | tcharding/self_learning | /pthw/ex3.py | 188 | 3.8125 | 4 | # numbers
print ("I will now count chickens:")
print ("Hens", 23 + 6 / 2)
print ("Roosters", 500 - 36 * 6)
print ("is it true that 3 > 2")
print (3 > 2)
print ("what is 3 + 2: ", 3 + 2)
|
58e67c3453ac23f8c6773f1819e3b689b19f42f3 | nshaibu/Algorithms | /python/doubly_linked_list.py | 2,386 | 3.71875 | 4 | '''
Created on Jul 31, 2017
@author: nafiu
'''
import sys
class Node(object):
'''
Doubly linked list
'''
def __init__(self, params=None):
self.data = params
self.next = params
self.prev = params
def set_data(self, param):
self.data = param
def set_next(self, ... |
4e05bb8f771a06fe21d0fda5116ee8fc99dff322 | dbuscaglia/hackerrank_practice | /fib.py | 674 | 3.515625 | 4 | class fib(object):
previous_results = {
1: 0,
2: 1,
}
@classmethod
def set_initials(cls, first, second):
cls.previous_results[1] = first
cls.previous_results[2] = second
@classmethod
def modified(cls, number):
if number == 1:
return cls.prev... |
7ace11efc4b69b3bcfdd4adf0c03fb3bcf68ec42 | chinese-soup/realnames | /dump_to_db.py | 1,316 | 3.5625 | 4 | #!/usr/bin/env python3
import csv, sqlite3
try:
con = sqlite3.connect("../sql/hltvdownload.sqlite3")
#con.set_trace_callback(print)
except Exception as e:
print("Database connection error.")
print("Deleting old values.")
cur = con.cursor()
cur.execute("""DELETE FROM realnames;""") # don't commit this un... |
362a29c452107bb469d9bc5c482c0351db026442 | JMGONB/Mirepositorio | /mi_proyecto_agosto/src/utils/folders_tb.py | 782 | 3.515625 | 4 | # Función genérica para abrir, crear, leer y escribir archivos
import pandas as pd
import urllib
from bs4 import BeautifulSoup
# Función para abrir el dataset. Esto pasa el archivo CSV (separado por comas) y transformo en un DataFrame
def read_open(name):
csv_df=pd.read_csv(name,sep=";")
return csv_df
... |
174b33d6647238211d365e3a4cd048c3590a96bb | blackbeam/pycc | /doc/Codingstyle.py | 1,487 | 3.546875 | 4 | ''' This one line outlines the module content
Here we see the detailed Discription of the Module:
Make clear how to comment and structure your code so that other can read and use it.
Have a look at the content of https://github.com/alnkpa/pycc/wiki/Coding-style
'''
# import in the beginning
import sys
class OurClass... |
575c5faa6c2bd295fb234ca7088f0f29acfddd5b | juanfranco97/data_scientist | /introduccion_data_scientist_con_python/cursos/Curso_de_Introducción_al Pensamiento_Computacional_con_Python/enumeracion.py | 236 | 4 | 4 | numero=abs(int(input('introducce un numero ')))
respuesta=0
while respuesta**2 < numero:
respuesta +=1
if respuesta**2 == numero:
print(f'la raiz cuadrada es {respuesta}')
else:
print(f'{numero} no tiene raiz entera') |
39cd5fcc6d4fd9d1749c7efd61feed2b3890a1be | juanfranco97/data_scientist | /introduccion_data_scientist_con_python/cursos/Curso_de_Introducción_al Pensamiento_Computacional_con_Python/cajanegra.py | 862 | 4.03125 | 4 | """Importamos la libreria de unittest."""
import unittest
def suma (num_1, num_2):
return (num_1+num_2)
"""Creamos una clase para los test, en este caso se llamara
CajaNegraTest, y como parámetro."""
class CajaNegraTest(unittest.TestCase):
"""Definimos la funcion que generara el test."""
def t... |
4fb35443fb21ae32945cf2265a0dfa88f5e211a1 | juanfranco97/data_scientist | /introduccion_data_scientist_con_python/masterclass-facundo/manejo_de_fechas.py | 569 | 3.71875 | 4 | import datetime
my_day = datetime.date.today()
print(my_day)
my_day1 = datetime.datetime.now()
print(my_day1)
my_day2 = datetime.date(1999, 12, 23) #crear objetos tipo fecha personalisados
print(my_day2)
my_timestamp = datetime.date.fromtimest(13124214))
print(my_timestamp)
my_day3 = datetime.date.t... |
0598d2455360e7d0ec943e8b90e46a7131ff8949 | younesk93/python-challenge | /PyBank_2.py | 2,956 | 3.78125 | 4 | # Import os module and csv file reader
import os
import csv
# Know the current working directory
Current_Path = os.getcwd()
Current_Path
#'/Users/Younes/Desktop/CLASSWORK/LearnPython/Useful-Repository-master/Resources/PyBank'
# Assign variables
total_months = 0
total_revenue = 0
this_month_revenue = 0
prev_reve... |
1c31729585fe4266315aa4175fc8e20511fe7ee7 | Matthmul/Python2020 | /Zestaw_11/Zadanie_11_1.py | 1,641 | 3.578125 | 4 | import random
import numpy as np
class RandomListNumbers:
def __init__(self, size=10):
self.size = size
self.int_number_list = list(range(0, self.size))
def rand_numbers(self):
random.shuffle(self.int_number_list)
return self.int_number_list
def rand_sorted_numbers(self):... |
c164b305375a334168d0f39cbf4a6a61dd3a066b | Matthmul/Python2020 | /Zestaw_5/Zadanie_5_2.py | 3,417 | 3.671875 | 4 | import math
def add_frac(frac1, frac2):
nominator = frac1[0] * frac2[1] + frac1[1] * frac2[0]
denominator = frac1[1] * frac2[1]
gcd = math.gcd(nominator, denominator)
return [nominator / gcd, denominator / gcd]
def sub_frac(frac1, frac2):
nominator = frac1[0] * frac2[1] - frac1[1] * frac2[0]
... |
c0ed179dda7518746bf80ccea4fc8a46071232a1 | Matthmul/Python2020 | /Zestaw_9/Zadanie_9_7.py | 1,602 | 3.8125 | 4 | class Node:
"""Klasa reprezentująca węzeł drzewa binarnego."""
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
def __str__(self):
return str(self.data)
def bst_max(top):
if top is None:
raise ValueErro... |
075fa25b21ac79d40359b98a46acd5f6b6536bc6 | Matthmul/Python2020 | /Zestaw 3/Zadanie 3.5.py | 355 | 3.53125 | 4 | def fun(lengt):
line = ''
for i in range(lengt):
line += '|'
for j in range(4):
line += '.'
line += '|\n'
for i in range(lengt + 1):
line += str(i)
num_of_space = 5 - len(str(i + 1))
line += " " * num_of_space
print(line)
if __nam... |
2c7883d2c464936c5fb2bfc6d6e62ccab313b6ce | ggsbv/pyWork | /compareDNA/AminoAlign.py | 1,526 | 4.21875 | 4 | #findLargest function finds and returns the largest DNA string
def findLargest(AA1, AA2):
largest = ""
if len(AA1) >= len(AA2):
largest = AA1
else:
largest = AA2
return largest
#align function compares two amino acid sequences and prints any differences (mutations)
def... |
d247e34ecf8ecd2bfcb21b0cdb26c100a88fb42e | ggsbv/pyWork | /compareDNA/translateFunctionV2.py | 1,460 | 3.703125 | 4 | def translate(dna):
dna = dna.upper()
start = 0
output = []
slcListI = ["ATT","ATC","ATA"]
slcListL = ["CTT","CTC","CTA","CTG","TTA","TTG"]
slcListV = ["GTT","GTC","GTA","GTG"]
slcListF = ["TTT","TTC"]
while start < len(dna)-2:
currentCodon = dna[start:start+3]
... |
ae3dc05fcf15db0da3b238b8c2cb26a7311d5e67 | laxmikant4644/Online-competitive-programming | /code vita/anagram_b.py | 848 | 3.546875 | 4 | def main():
def check(w,a):
return ''.join(sorted(list(w)))==''.join(sorted(list(a)))
line=raw_input()
line_list=line.split(' ')
line_list[-1]=line_list[-1][:-1]
printed=[]
while len(line_list)>1:
word=line_list[0].lower()
if word in printed:
del lin... |
e7c0faf8127f813db4bd4599198c8f6eda8ff552 | alexjohnlyman/Python-Exercises | /Inheritance.py | 1,003 | 4.21875 | 4 | # Inheritance
# Is an "is a" relationship
# Implicit Inheritance
class Parent(object):
def implicit(self):
print "PARENT implicit()"
def explicit(self):
print "PARENT explicit()"
def altered(self):
print "PARENT altered()"
class Child(Parent):
def implicit(self):
pri... |
15c50d10d407abe7aede0843cded8e3678771049 | katzperwozniak/DataExtractor | /dataextractor/dataextractor.py | 9,659 | 3.796875 | 4 | import pandas as pd
import numpy as np
import re
import csv
class extractVars:
"""
Class for extracting new variables out of datastream file
This class is created to extract 'conversion duration' - users time since
first visit till first conversion, 'visits frequency' - number of visits on
partic... |
08b01d241ef2e00852f19201efbd826b39bbdcb8 | ee2008/script | /python_test/tt.py | 778 | 3.546875 | 4 | #!/nfs/pipe/Re/Software/bin/python2.7
import sys
people=['adam', 'LISA', 'barT']
def name(x):
if not x[0].isupper():
head=x[0].upper()
else:
head=x[0]
s=x[1:len(x)]
if s.isupper():
tail=s.lower()
else:
tail=s
print head+tail
map(name,people)
#def fib(max):
# n, a, b = 0, 0, 1
# while n < max:
# ... |
cc87c3ae6a3b867f6772e93db1b3ca67e176295b | LinuxLibrary/Python | /Programs/PS-Programs/Path/01-GettingStarted/03-Functions/Students1.py | 379 | 3.65625 | 4 | students = []
def get_students_titlecase():
students_titlecase = []
for student in students:
students_titlecase =student.title()
return students_titlecase
def print_students_titlecase():
students_titlecase = get_students_titlecase()
print(students_titlecase)
def add_student(name):
students.append(name)
s... |
8b7039b2a5691d3d67922299d5002e11e4895054 | LinuxLibrary/Python | /MyPyStore/programs/CC_Progs/CC-07/CC-07.1/CC-07.1.04_Check_it_twice.py | 126 | 3.65625 | 4 | #!/usr/bin/python
board = []
#def battleship:
for i in range(0,5):
level = ["O"] * 5
board.append(level)
print board
|
844f5b1e7a19914e67cb325179dc42f84eeae327 | LinuxLibrary/Python | /MyPyStore/programs/CC_Progs/CC-07/CC-07.1/CC-07.1.06_Printing_pretty.py | 207 | 3.734375 | 4 | #!/usr/bin/python
board = []
#def battleship:
for i in range(0,5):
level = ["O"] * 5
board.append(level)
def print_board(board):
for i in board:
print " ".join(level)
print_board(board)
|
0428185f451411f7ba5024ca0140de0a677795bb | LinuxLibrary/Python | /MyPyStore/programs/CC_Progs/CC-08/CC-08.0/CC-08.0.13_For_your_lists.py | 221 | 4.0625 | 4 | #!/usr/bin/python
numbers = [7, 9, 12, 54, 99]
print "This list contains: "
for num in numbers:
print num,
# Add your loop below!
print "\nThis list contains sqares : "
for num in numbers:
print num ** 2,
print
|
298ab47829b2875bca88208e9d87d2d1ceb8a96f | LinuxLibrary/Python | /Py-4/py4sa-LA/programs/04-Classes.py | 864 | 4.28125 | 4 | #!/usr/bin/python
# Author : Arjun Shrinivas
# Date : 03.05.2017
# Purpose : Classes in Python
class Car():
def __init__(self):
print "Car started"
def color(self,color):
print "Your %s car is looking awesome" % color
def accel(self,speed):
print "Speeding upto %s mph" % speed
def turn(self,direction):
pri... |
0aa23aa8e0db2e17486f085f3df4d9d9500a89f4 | LinuxLibrary/Python | /MyPyStore/programs/CC_Progs/CC-07/CC-07.0/CC-07.0.03_Appending_to_a_list.py | 80 | 3.71875 | 4 | #!/usr/bin/python
n = [1, 3, 5]
# Append the number 4 here
n.append(4)
print n
|
b9a94cfdd2b184452976eb19ca115ce681dcaed3 | LinuxLibrary/Python | /MyPyStore/programs/MY_Progs/05._life2.py | 653 | 3.703125 | 4 | #!/usr/bin/python
# Author:
print "----- Life Expectency v0.99-----"
name = raw_input("What is your name? ")
print name,
age = input("What is your age? ")
print name,
expect = input("To what age do you expect to live? ")
# extending life2.py to incorporate conditional testing
timeleft = expect - age
print name,
answ... |
fc65bcedd2e12eed75fe1e5fdb2b1a51ac176a8c | LinuxLibrary/Python | /Programs/PS-Programs/Path/02-Fundamentals/07-ExceptionHandling/02-Exceptions.py | 327 | 3.65625 | 4 | #!/usr/bin/env python3
'''A module for demonstrating exceptions.'''
import sys
def convert(s):
'''Convert to an integer.'''
try:
x = int(s)
print("Convertion succeeded! x =", x)
except (ValueError, TypeError) as e:
print("Conversion error: {}"\
.format(str(e)),
file=sys.stderr)
raise # Re-raise ex... |
2b0ec779066d68bf8b8b4b8462aec53f55c92b6f | LinuxLibrary/Python | /Programs/PS-Programs/Path/01-GettingStarted/04-Classes/Classes1.py | 371 | 3.984375 | 4 | students = []
class Student:
school_name = "My School"
def __init__(self, name, student_id=332):
student = {"name": name, "student_id": student_id}
students.append(student)
def __str__(self):
return "Student " + self.name
def get_name_capitalize(self):
return self.name.capitalize()
mark = Stu... |
0dc68fd5e50095dc40b6c095dad84b70bc1c18b4 | LinuxLibrary/Python | /Py-4/py4inf/4-db-py/programs/test2.py | 229 | 3.96875 | 4 | #!/usr/bin/python
import sqlite3
name = raw_input("Please input name: ")
conn = sqlite3.connect('test.db')
cur = conn.cursor()
cur.execute('''SELECT name FROM Users WHERE name = ?''', (name, ))
row = cur.fetchone()
print row
|
e2b9d59382d40cfa999c6d5cadf20523db82d3db | Mayurpotdar14/Python-Sample-codes | /Mayur_Python_code/Assign5_Integral.py | 118 | 3.96875 | 4 | j = 2
num = int(input('Enter the number: '))
for x in range(1, num+1):
print(j,"**",x," = ", j*x,"(",j,"**",j*x,")",) |
7f11b2559f02c730514a6e0d66f1706fe2b5d1bd | Mayurpotdar14/Python-Sample-codes | /Mayur_Python_code/first_last_array_element_addition.py | 287 | 3.765625 | 4 | val = [1,4,9,40,1,3,5,7,12]
print("List is : ",val)
length = len(val)
print("Length of String is: ",length)
mid_val = 1+((len(val) - 1 )// 2)
print("Middle index position is :",mid_val)
for i in range(int(len(val)/2)):
print(val[i] + val[-i-1]," ", end = '')
print(val[mid_val - 1]) |
8d4f1c168a198d80f5fd618023459fe1b9cda407 | brookstawil/LearningPython | /Notes/7-9-14 ex5 Problem Make a purchase from 1-99 cents.py | 843 | 3.671875 | 4 | #7/9/14
#Problem: Make a purchase from 1-99 cents
#Compute the minimum number of coins for the change from 1$
cost = int(input("How many cents does it cost?"))
change = 100 - cost
print (change,"cents is your change")
#quarters
quart_amt = change // 25
remainder = change % 25
#print (remainder)
#print ("You get back... |
2774729159c10dc8b6d54f2f19498d2f594fd049 | brookstawil/LearningPython | /Notes/7-10-14 ex1 Fun with formatting floating point.py | 455 | 3.703125 | 4 | # 7/10/14
# Fun with formatting floating point
print(3.1415926)
print()
a = 1.2
b = 1.23
c = 1.234
d = 1.2345
#Justified the ouputs left
print(a)
print(b)
print(c)
print(d)
#catinating a string multiple times
print ("Yo "*10)
#Justifying to the center (Decimals align)
print (" "*2, a)
print (" "*2, b)
print (" "*... |
0c7a90f2fa619eea57110c5250c046e2188b4d72 | brookstawil/LearningPython | /Assignments/TawilBrooks_assign4.py | 971 | 3.84375 | 4 | #7/22/14
#Brooks Tawil assignment 4
#This program deals out random cards from a consistently fresh deck and also gives you how many face cards were dealt
import random
#sets up a counter for the amount of face cards
face_amt = 0
for num in range(0,53):
#Determines suit
suit = random.randint(1,4)
#Give... |
97b7f50d9511e5acd7a86947b8bc5a367f4b589d | brookstawil/LearningPython | /Notes/7-16-14 ex1 Problem Square root calculator.py | 935 | 4.3125 | 4 | #7/16/14
#Problem: See how many odd integers can be subtracted from a given number
#Believe it or not this actually gives the square root, the amount of integers need is the square root!!
#number input
num = int(input("Give me a number to square root! "))
num_begin = num
#Loops through the subtractions
#defines the s... |
2af694a25d9f9174581cd14f3eafad232b278f83 | brookstawil/LearningPython | /Notes/7-14-14 ex6 Letter grades.py | 525 | 4.125 | 4 | #7-14-14
#Letter grades
#Input the grade
grade = input("What is the grade? ")
grade = grade.upper()
#Long way
#if grade == "A":
# print ("A - Excellent")
#else:
# if grade == "B":
# print("B - good!")
# else:
# if grade == "C":
# print("C - average")
# else:
# pri... |
798919ee34ea03bf0941eb6cd0d672f1af49ccdd | brookstawil/LearningPython | /Notes/7-9-14 ex3 Fun with Operators on Integers.py | 678 | 4.09375 | 4 | # 7/9/14
# Fun with Operators on Integers
#inputs ONLY give back strings so we must convert it to integers with 'int'
input_age = input("Type your age")
age = int(input_age)
print("Your age is", age)
age_next_year = age + 1
print("Your age next year will be ",age_next_year)
twice_age = age * 2
print ("2x your age ... |
3979fe1f8b34766d1240ebe1dfbc1cbea7befd77 | brookstawil/LearningPython | /Notes/7-31-14 ex2 Write a message on the turtle screen.py | 860 | 3.5625 | 4 | #7/31/14
#Write a message on the turtle screen one at a time
from turtle import *
def home_turtle(xpos,ypos):
pu()
goto(xpos,ypos)
pd()
def forward_turtle():
pu()
setx(xcor() + 10)
pd()
def main():
speed("fastest")
home_turtle(-200,200)
msg1 = "Error, please try again.\n"
m... |
0dedfad6210ca78804a4bd80490e62297e0b47b7 | brookstawil/LearningPython | /Notes/7-22-14 ex4 Problem Make star pyramid.py | 622 | 4.0625 | 4 | #7/22/14
#Problem: Make a pyramid of stars!
num_lines = int(input("Stories do you want your pyramid to be? "))
#Number of stars per line, to be added on to in the loop
stars_per_line = 1
#Defines a counter for how many lines are used, to be added onto in
lines_counter = 1
#how many spaces
amt_spaces = num_lines - ... |
ec1f9eb074b9429219c410c902a440cea069377e | brookstawil/LearningPython | /Notes/7-31-14 ex1 Determine whether a number (N) is prime.py | 958 | 4.1875 | 4 | #7/31/14
#Determine whether a number (N) is prime or not
#We only have to check numbers up to the integer square root of N.
import math
#This determines whether n is prime
#INPUT - a number to check
#OUTPUT - Ture if it is prime or False if is is not
def is_prime(n):
is_it_prime = True #We start with an assumpt... |
c9f5cdd00d217884afe417d90e582d955f0edfc8 | kniers/Capstone | /Content/foyer/martini.py | 1,460 | 3.78125 | 4 | import eng
# The martini is handed to you by a server when you enter the foyer. It isn't needed for anything, but holding blocks the billiards quest
class Martini:
name = 'martini'
aliases = ['dry martini', 'cocktail']
def look(self):
return "It's a dry martini that was handed to you by a ... |
4b3a11d6ab7dde17cc1ea9458a0600f35e49c99a | kniers/Capstone | /Content/gardens/pinkFlower.py | 1,864 | 3.53125 | 4 | import eng
class PinkFlower:
name = 'pink flower'
#type = 'Item'
visible = True
aliases = ['flowers', 'flower', 'pink flowers']
descriptions = {'desc': "It's a pink flower growing on a bush. It's the kind of flower you'd stick on your formalwear to add a little color.",
'takePF': "You won't just take one, bu... |
e89dc391af63ab99630bfda553557d92fb55447b | kniers/Capstone | /Content/library/booknathaniel.py | 2,160 | 3.5 | 4 | import eng
class Booknathaniel:
name = 'Nathaniel Winston'
#type = 'Item'
visible = True
aliases = []
descriptions = {'desc': "Adventures of Nathaniel Winston - 1905 to 1911. It's an old black leather bound book. ",
'descHaveBook': "There is a gap where the book was. You see a silver button at the ba... |
467071602c8a091476001d28283e4ee83b01e302 | kniers/Capstone | /Content/masterBedroom/gown.py | 2,076 | 3.5 | 4 | import eng
class Gown:
name = 'gown'
#type = 'Item'
visible = False
aliases = ['dress']
descriptions = {'desc': "What's this? A beautiful red gown with a yellow sash. Great for cocktail parties!",
'wearingDesc': "You're dressed in a gown, so you're safe to move around the party - just don't act weird... |
345ca09e311e8093662232a46cbd376c4697099a | humbertodias/humbertodias.github.io | /computer science/python/Sorting Algorithms/MergeSort.py | 1,245 | 4.03125 | 4 | """ gets the data using merge sort and returns sorted."""
def mergeSort(data):
for j in range(1, len(data)):
j *= 2
for i in range(0,len(data),j):
data_1 = data[i:i+(j/2)]
data_2 = data[i+(j/2):j-i]
l = m = 0
while l < len(data_1) and m < len(data_2):
if data_1[l] < data_2[m]:... |
5c2379218d346798dff59be18f339fe429fe567e | raytroop/leetcode365 | /merge_sort.py | 730 | 3.671875 | 4 | # http://wuchong.me/blog/2014/02/09/algorithm-sort-summary/
def merge_sort(ary):
if len(ary) <= 1 : return ary
num = len(ary)//2 #二分分解
left = merge_sort(ary[:num])
right = merge_sort(ary[num:])
return merge(left,right) #合并数组
def merge(left,right):
'''合并操作,
将两个有序数组left[]和right[]合并成... |
911212e6dc5a9cbae5007d09e37a685e1c375c7f | StellaLX99/sorting | /sorting.py | 5,496 | 4.28125 | 4 |
#!/bin/python3
'''
Python provides built-in sort/sorted functions that use timsort internally.
You cannot use these built-in functions anywhere in this file.
Every function in this file takes a comparator `cmp` as input which controls how the elements of the list should be compared against each other.
If cmp(a,b) retu... |
5f7eb22b350332e0cc108248d876df303ddc984c | tp6fu6m3/NTU-Courses | /計算機容錯/hw1/p2.py | 576 | 3.734375 | 4 | import matplotlib.pyplot as plt
def bigTruck (rate) :
result = rate**18 + 18*(1-rate)*(rate**17) + 18*17*0.5*((1-rate)**2)*(rate**16)
return result
def smallTruck (rate) :
result = rate**4 + 4*(1-rate)*(rate**3)
return result ;
b = []
s = []
r = []
for i in range(1,1000,1) :
#... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.