blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
2f84dc3635b64b59f3c19cf036069a34aa2c5e7d | therikshak/FantasyFootball | /DraftYear.py | 346 | 3.65625 | 4 | class DraftYear:
teamName = ''
year = ''
picks = []
def __init__(self, name, year):
self.teamName = name
self.year = year
self.picks = []
# add pick
def add_pick(self, pick_num, pick_round, position, player):
temp = [pick_num, pick_round, position, player]
... |
b9bb7deb73be996ec847225a3c10f9f8c063b7c8 | jglantonio/learning_python | /curso001/03_strings.py | 562 | 4.375 | 4 | #!/usr/bin/env python3
# Strings y funciones para trabajar con ellos
variable = "Tengo un conejo ";
print(variable);
variable2 = "llamado POL";
print(variable2);
print(variable + variable2);
print(variable*2);
# function len
length_variable = len(variable);
print("La variable "+variable+", tiene ",length_variable);
... |
4d2c074afe66f9a13380994d59b80c83c29c6ed3 | fivepandas/panda-python | /full_name.py | 347 | 3.578125 | 4 | first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
print(full_name)
full_name = f"Hell0, {full_name.title()}!"
print(full_name)#f 字符串是是python 3.6 引入的,之前的版本需要使用format
full_name = "{} {}".format(first_name, last_name)
print("Python")
print("\tPython")
print("Languages:\nPython\nC") |
888fd9bf8e6d7215ca56886186a6629a63050f13 | glossywhite/Project_Baczyk_Bury | /Baczyk_bury_projekt.py | 3,010 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 23 11:26:26 2021
@author: szymo
"""
from nltk.tokenize import word_tokenize
from nltk.stem import PorterStemmer
ps = PorterStemmer()
def process_word(word):
word = ps.stem(word)
word = word.lower()
word = word.strip()
return word
if __name__ == '__main... |
767c20e0de12d9682365786062e7edb414fb893b | GurenMK/Read-Write-File | /ReadWrite.py | 1,244 | 3.859375 | 4 | """
Alexander Urbanyak
CS4720(01)
Created: 01-25-2019
Python 3.6
"""
# The program reads a text file "in.txt", converts all letters to uppercase,
# and writes all contents of the read file to "out.txt"
# reads and writes multiple lines
# "out.txt" will be created if it doesn't exist,
# otherwise all its conte... |
ed5276467a97a1f9b3af74eee83f615b4aea6789 | RaginiD/Warm-up-Challenges | /sock_merchant_hashing.py | 596 | 3.765625 | 4 | #!/bin/python
import math
import os
import random
import re
import sys
# Complete the sockMerchant function below.
def sockMerchant(n, ar):
# dict to store socks color and number of pairs
socks_data = {}
for item in ar:
old_count = socks_data.get(item,0)
socks_data[item] = old_count+1
... |
2b20099429be59aa4bcca71df556eb4806aca1f3 | Noor9920/PythonAssignment | /Assignment4.py | 100 | 3.9375 | 4 | n=int(input("The value of n"))
fact=1
for each in range(1,n+1):
fact=fact*each
print(fact)
|
78cfdf23395424fbcad9e4f5248929013f3a2ac7 | Noor9920/PythonAssignment | /Assignment6.py | 90 | 3.8125 | 4 | a=int(input("Enter a No"))
fact=1
for i in range(1,a+1):
fact=fact*i
print(fact)
|
026526ddd9c38e990d966a0e3259edcb2c438807 | arlionn/readit | /readit/utilities/filelist.py | 1,003 | 4.21875 | 4 | import glob
from itertools import chain
def filelist(root: str, recursive: bool = True) -> [str]:
"""
Defines a function used to retrieve all of the file paths matching a
directory string expression.
:param root: The root directory/file to begin looking for files that will be read.
:param recursive... |
e8a3eb0c3ec81c3d341740c6982fbfa39112f4ca | ramesh-anandan/learn-python | /dictionaries.py | 210 | 3.640625 | 4 | my_stuff = {'firstName': 'Ramesh', 'lastName': 'Anandhan', 'address': {'city': 'Bangalore', 'pin': 560043}}
print(my_stuff['lastName'])
print(my_stuff['address']['pin'])
my_stuff['age'] = 35
print(my_stuff) |
af9a36eaf88bc49ccbdf85a869506b9d3d5c587e | ramesh-anandan/learn-python | /decorators.py | 387 | 3.6875 | 4 | def new_decorator(func):
def wrap():
print('before')
func()
print('after')
return wrap
@new_decorator
def func_need_decorator():
print('i need decorator')
func_need_decorator()
# global/locals: Accessing global/local variables from dictionary
def localFunction():
varLoc... |
f81259cfbd65e766de3bf29218a7154d4e2fc7e0 | Daoi/SumOfIntervals | /sum_of_intervals.py | 393 | 3.609375 | 4 | def sum_of_intervals(intervals):
from collections import Counter
interval = []
length = 0
for i in range(len(intervals)):
for j in range(len(intervals[i])):
for x in range(intervals[i][j], intervals[i][j+1]):
interval.append(x)
break
numbers = Counter... |
8350835189b46c5e88273d3145749b1b8d89c7ed | qinxinWu/turtle | /绘制分形树和分形正方形的代码及运行结果/DrawTree.py | 1,790 | 3.53125 | 4 | # !/usr/bin/env python
# coding:utf-8
# Author: Qingxin Wu
import turtle
#绘制分形树的递归方法
#length是指每个树干的长度
def drawFractalTree(length):
#限定递归函数终止的条件为:当传入的树干的长度小于等于10时递归终止即只有大于10才能执行
if length > 10:
#先是画主树干:方向为竖直向上
turtle.forward(length)
#其次,把画笔的方向向右旋转33度,为了接下来画右子树
turtle.right(33)
... |
0d012a23dfd3e68024f560287226171040c2ca67 | EthanReeceBarrett/CP1404Practicals | /prac_03/password_check.py | 941 | 4.4375 | 4 | """Password check Program
checks user input length and and print * password if valid, BUT with functions"""
minimum_length = 3
def main():
password = get_password(minimum_length)
convert_password(password)
def convert_password(password):
"""converts password input to an equal length "*" output"""
fo... |
262d7b72a9b8c8715c1169b9385dd1017cb2632b | EthanReeceBarrett/CP1404Practicals | /prac_06/programming_language.py | 800 | 4.25 | 4 | """Intermediate Exercise 1, making a simple class."""
class ProgrammingLanguage:
"""class to store the information of a programing language."""
def __init__(self, field="", typing="", reflection="", year=""):
"""initialise a programming language instance."""
self.field = field
self.ty... |
4b9e2e7be91d9ed0b3627cfb2ac93b1cc25ed53e | mei1797/tarea-2 | /ejercicio 6.py | 120 | 3.953125 | 4 | n = int(input("Introduce la altura del triangulo (entero postitivo): "))
for i in range(n):
print("*"*(i+1))
|
028e52236ff8d4765bcfabcaf25457cc78901835 | Sourav-1234/Blockchain-Programming | /Module-1/Blockchain.py | 3,279 | 3.640625 | 4 | # Module 1 Create A Blockchain
#Importing necessary libaries
import datetime
import hashlib # Libary use to generate the hash code of secure hash algorithm i.e 256
import json
from flask import Flask ,jsonify
#Building a Blockchain
class Blockchain:
def __init__(self):
self.chain = []
self.create_... |
8aa1cf81834abd2a7cb368ffdb9510ae7f0039e4 | nobleoxford/Simulation1 | /testbubblesort.py | 1,315 | 4.46875 | 4 | # Python program for implementation of Bubble Sort
def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
# Last i elements are already in place
for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if the el... |
3ec9603781aa7c06da5eda3af61af8f0244e697e | juanda2222/playground | /arrays/find_missing_and_repeating.py | 1,630 | 3.921875 | 4 |
"""
Given an unsorted array of size N of
positive integers. One number 'A' from
set {1, 2, …N} is missing and one number
'B' occurs twice in array. Find these
two numbers.
Note: If you find multiple answers then
print the Smallest number found. Also,
expected solution is O(n) time and
constant extra space.
In... |
58e80763a40ced56a528694905d2b45729becd17 | juanda2222/playground | /interview_questions/24_game copy 2.py | 1,052 | 3.546875 | 4 |
# Property always holds: root.val = min(root.left.val, root.right.val)
from itertools import product, permutations
parenthesis = ["(", "(", ")", ")"]+[" "]*6
parenthesis_combinations = set(list(permutations(parenthesis, 6))) # 6 possible positions for the parenthesis
# for each parenthesis combination try eac... |
c1f82edf11f08b802d69e41ddc27344f15feef7e | juanda2222/playground | /python_stackoverflow/next_bigger_number.py | 3,024 | 3.90625 | 4 |
# https://stackoverflow.com/questions/61719835/increasing-itertools-permutations-performance
import itertools
def next_bigger2(n):
num = str(n)
num1 = set(int(x) for x in str(num))
if num == num[0] *len(num):
return -1
#full_set = set(num)
lis = set(int(''.join(nums)) for nums in itertools... |
4156cf132cddb60d49ec6208315a0e206053ec45 | hannahtuttle/Sorting | /src/recursive_sorting/recursive_sorting.py | 3,287 | 4.09375 | 4 | # TO-DO: complete the helper function below to merge 2 sorted arrays
def merge( arrA, arrB ):
# Create an array arr3[] of size n1 + n2.
elements = len( arrA ) + len( arrB )
merged_arr = [0] * elements
# TO-DO
for i in range(0, len(merged_arr)):
if not arrA:
merged_arr[i] = arrB[... |
fa3e3540c5bf171c1f1fd2b69b16d495883f4995 | hiroto-kazama/cs-362_Unit_Testing | /avg_elem.py | 161 | 3.5625 | 4 | def cal_average(a):
avg = sum(a)/len(a)
return avg
"""
userInt = list(map(int, input("Enter elements: ").split()))
print(cal_average(userInt))
""" |
f5690a2f35bb5e7aac15fa49553217ea3efb11a1 | zaleskasylwia/Converter | /zad1.1.1.py | 1,667 | 4 | 4 | #done
def converter_binary(number): #z dziesietnego na binarny
a = []
#print(number)
while number > 0:
a.append(number % 2)
number = int(number / 2)
print_backward(a)
print (" 2")
def converter_decimal(number): # z binarnego na dziesietny
decimal = 0
for digit in str(number... |
5c01f26f3660c86e732bfb63c7f5210e745a6181 | Vanya-Rusin/labs | /Завдання 1.py | 163 | 3.96875 | 4 | from math import sqrt
d=float(input("введіть довжину сторони d: "))
S=d**2/2
P=2 * sqrt(2)*d
print("S=" + str(S))
print("P=" + str(P))
|
9ba1770e3585a53d3a22b801034192427bb124e3 | berglaura/pythonCourse | /ehtoarkkitehti.py | 250 | 3.5 | 4 | luku = int(input("Anna kokonaisluku: "))
if luku > 1000:
print("Luku on suurempi kuin 1000")
elif luku > 100:
print("Luku on suurempi kuin 100")
elif luku > 10:
print("Luku on suurempi kuin 10")
else:
print("Luku on 10 tai pienempi")
|
f08082886a4bbc9ccef1c4fe92f5923d79ac3b2d | Kingdageek/Learn_Python | /Box_Display.py | 524 | 4.09375 | 4 | # Collect sentence to display in centre of the box
sentence = input("Enter a Sentence: ")
screen_width = 80
text_width = len(sentence)
box_width = text_width + 6
margin = (screen_width - box_width)// 2
#Designing our box
print()
print(' ' * margin + '+' + '-' * (box_width - 2) + '+')
print(' '* margin + '|' + ' ' * (... |
5beac375837694d0f0357bd1d2d19289fdb9c9b9 | Kingdageek/Learn_Python | /dark_room.py | 3,347 | 3.8125 | 4 | #dark_room.py
from Guess_game import enter_cmd
def help():
print("There are 4 rooms, Just flow with the game")
print("type 'play' to play 'a dark room'")
print("type 'quit' to quit playing")
print("type 'help' to see this message again")
def play():
while True:
print("You enter a dark room ... |
b6d570d9942e4cad129c3cf3252f3a2c79630c29 | Kingdageek/Learn_Python | /gen_primes.py | 237 | 3.546875 | 4 | # gen_primes.py
import pprint
import math
def gen_primes(n):
primes = [2]
for i in range(3,n):
for k in range(2,int(math.sqrt(i)) + 1):
if i % k == 0: break
else: primes.append(i)
return primes
pprint.pprint(gen_primes(1000))
|
ff54f51ac7d2eecf0faa3a0145462f07e9a2095c | Kingdageek/Learn_Python | /shelve_database.py | 1,872 | 3.921875 | 4 | import shelve
def store_person(db):
"""Query user for details to store in database"""
pid = input("Enter your unique ID: ")
person = {}
person["name"] = input("Enter your name: ")
person["age"] = input("Enter your age: ")
person["phone"] = input("Enter your phone: ")
db[pid] = person
def lo... |
703312ee6d095e5e3990811d98bf6690c1e29f37 | Kingdageek/Learn_Python | /PredatoryCreditCard.py | 1,385 | 3.515625 | 4 | #PredatoryCreditCard.py
from CreditCard import CreditCard
class PredatoryCreditCard(CreditCard):
OVERLIMIT_FEE = 5
SURCHARGE = 1
def __init__(self, customer, bank, account, limit, apr):
super().__init__(customer, bank, account, limit)
self._apr = apr # Annual Percentage Rate
s... |
7d2d55966b1b93149efdec02330bcd4cb17a7fbe | michaelsmirnoff/SF_DAT_15_WORK | /hw/hw1.py | 4,927 | 3.828125 | 4 | '''
Move this code into your OWN SF_DAT_15_WORK repo
Please complete each question using 100% python code
If you have any questions, ask a peer or one of the instructors!
When you are done, add, commit, and push up to your repo
This is due 7/1/2015
'''
#Author:Nick Smirnov
import pandas as pd
import matplotlib.pyp... |
f6b938632305063a193494ad8b3eb0be06791802 | Likkrid/cryptography-summer-2014 | /lista7/ec.py | 3,573 | 3.609375 | 4 | from finite_fields.finitefield import FiniteField
import random
class Point(object):
def __init__(self, curve, x, y):
self.curve = curve
self.x = x
self.y = y
if not curve.contains(x, y):
raise Exception("%s does not contains (%s, %s)" % (self.curve, self.x, self.y))
def __eq__(self, other):
return se... |
f4b9071820ebb88f2b00a01942b3b9f253400d35 | Lyrics2000/lecture2 | /solutions/Strings/AssignVariableToString.py | 237 | 4 | 4 | # assign single variable to string
a = "Hello"
print(a)
#Assign multiple variable to string
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a) |
be2b0b5b397c557001a7636943186c9c2bebd0d4 | finn79426/Algorithm | /Selection Sort/SelectionSort.py | 627 | 3.75 | 4 | import random
def random_list(ran, elements):
return random.sample(range(ran), elements)
def selection_sort(list):
# from small to large
for i in range(0, len(list)-1):
min = 1
for j in range(i+1, len(list)):
if(list[min] > list[j]):
min = j
if(min != i)... |
c367b6aff58bbf529e96b53cea5a122188cef7fe | cursosbit/solucionador_automatico_CT | /var/variable.py | 2,885 | 3.921875 | 4 | ''' Clase para definir ls variable mediante sus atributos'''
class Unidad():
'''Clase para definir las unidades mediante sus atributos'''
def __init__(self, simbolo, nombre, lstunidades):
'''simbolo, símbolo asigndo a la unidad
nombre, identificador de la unidad
lstunidades, unidad... |
ae3f8bfde79ae460511901e3f0153f455afeaf3d | Johnny112F/currency_calculator | /currency.py | 857 | 3.703125 | 4 | """Functions handling currency."""
from forex_python.converter import CurrencyCodes, CurrencyRates, RatesNotAvailableError
rates = CurrencyRates()
codes = CurrencyCodes()
def check_currency_code(code):
"""Is currency code valid?
>>> check_currency_code("USD")
True
>>> check_currency_co... |
b4d3eefb5b74f789a3ae7d99bfd52dff64efb996 | iamkarantalwar/tkinter | /mysqlwithpython(insert)/insertwithmysql(var).py | 759 | 3.78125 | 4 | #insert data with variables
name = input("Enter the name")
email = input("Enter the Email")
password = input("Enter the password")
dob = input("Enter the D.O.B.")
#import the MySql Api
import mysql.connector
#create a bridge between mysql and python
#create the connection
mydb = mysql.connector.connect(
... |
b29b3de7434393fca62ea01898df1015e7a8871f | iamkarantalwar/tkinter | /GUI Sixth/canvas.py | 1,080 | 4.21875 | 4 | #tkinter program to make screen a the center of window
from tkinter import *
class Main:
def __init__(self):
self.tk = Tk()
#these are the window height and width
height = self.tk.winfo_screenheight()
width = self.tk.winfo_screenwidth()
#we find out the center co or... |
443c3d560be29b11764ec609751c86d8fa9eb130 | ValenVictorious/Slot-Saving-Test | /main.py | 1,061 | 3.609375 | 4 | import stuff
import trace_goto
loop = 1
name = input("Name? ")
content = input("content? ")
place = input("place? ")
while(loop < 2):
Next = input("next? ")
if Next == "commands":
print("""commands:
New Save: Create a new save
Veiw Save: Veiw saves
end: end the program""")
if name != "" and conten... |
55abeaf992065b49348262fd31cc660a1f68c3ea | Blaine-Rob5000/STECH-Capstone | /whiteboard.py | 7,617 | 4.34375 | 4 | """Whiteboard projects
Potential whiteboard project questions
created
by: R. G. Blaine
on: April, 9, 2018
"""
# imports
import random
################################################################################
def listFibs(n):
'''Creates and prints a li... |
a8dadea942a0cc4859355eca917b86fe3d253e54 | calanoue/GFIN_Data_Work | /formatting_forecasting_for_new_student_version.py | 9,567 | 3.625 | 4 | """
Formatting and forecasting script for new and final Python student version
"""
import numpy as np
from scipy import stats
from clean_data import CleanData, ExpSmooth
from sqlite3 import dbapi2 as sqlite
# Global variables
VALUE_COLUMN = 5 # First column that holds values
START_YEAR = 1961 # First year in the datab... |
e4680806f90440a2ad2474ae38e3c2d683e47379 | calanoue/GFIN_Data_Work | /merge_countries.py | 1,418 | 3.703125 | 4 | """
Merge a country that has two separate former entities, i.e. Russia and the 'Slavias.
"""
import numpy as np
import sqlite_io
import numpy.lib.recfunctions as nprf
#Global variables
DB = r".\FBS_ProdSTAT_PriceSTAT_TradeSTAT.db3"
TABLE_NAME = "Commodity_Raw_Data"
#Countries to merge with country one being the coun... |
6b0c82e66ebe574a537a970c217c73c26583fa15 | RohinPoloju/HackerRank | /InterviewPrep/strings/sherlock-and-valid-string.py | 1,315 | 3.890625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'isValid' function below.
#
# The function is expected to return a STRING.
# The function accepts STRING s as parameter.
#
def isValid(s):
# Write your code here
char_dict = {}
for char in s:
if char in char_... |
481bd030ef8e07991471f21de973ad7e9d237579 | kevinam99/ML-internship-training | /ML-internship-training-earnestek/python/02-lists.py | 554 | 3.984375 | 4 | list1 = [2,4,5,6,72,17,54,1,3,2,2,44]
print(list1[2])
print(list1[1:3])
print(list1[:3])
print(list1[3:])
print(list1[-1])
print(len(list1))
list1.append(69)
print (list1)
list1.extend([3,4])
'''
list1.extend('yes')#stores as 'y', 'e', 's'
print (list1)
list1.extend(['yes'])#stores as 'yes'
print (list1)
list1.ex... |
46ce3a2346198c0fca61a05d6c0dfe821f336170 | niha-p/Natural-Language-Processing | /Basic NLTK (Word Similarity)/A.py | 431 | 3.75 | 4 | import nltk
import sys
greeting=sys.stdin.read()
print greeting
token_list = nltk.word_tokenize(greeting)
print "The tokens in the greeting are"
for token in token_list:
print token
squirrel=0
girl=0
for token in token_list:
str=token.lower()
if (str=='squirrel'):
squirrel+=1
if (str=='girl'):
girl+=1
p... |
901330d060d7f2b458b05e04ee1eb4ee979146f9 | jaybenaim/python-intro-pt5 | /test.py | 266 | 3.921875 | 4 | def pizza_maker():
print('How many pizzas do you want to order?')
quantity_pizza = int(input())
# order_num = toppings.pizza_order_num()
# toppings.pizza_order_num
ind_pizza = range(1,(quantity_pizza+1))
print(ind_pizza)
print(pizza_maker()) |
4f3a617844b5bce95b1a37c10c86b20fa75c4e1e | yangzhao5566/go_study | /cookbook/第八章/8.4.py | 696 | 4.0625 | 4 | """
创建大量对象时节省内存方法
"""
class Date:
__slots__ = ["year", "month", "day"]
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
"""
当你定义__slots__ 后,Python就会为实例使用一种更加紧凑的内部表示。 实例通过一个很小
的固定大小的数组来构建,而不是为每个实例定义一个字典,这跟元组或列表很类似。 在 __slots__
中列出的属性名在内部被映射到这个数... |
f687a3b60aade360831f0a559bac2fc622194ba0 | yangzhao5566/go_study | /cookbook/第八章/8.5.py | 2,930 | 3.609375 | 4 | """
关于类的私有方法和私有属性
"""
"""
_xx 以单下划线开头的表示的是proected类型的变量。 即保护类型只能允许其本身和子类进行访问
__xx双下划线表示的是私有类型的变量,只能允许这个类本身进行访问,子类也不可以用于命名一个
类属性(类变量),调用时名字被改变(在类FooBar内部,__boo变成_FooBar__boo,如self._FooBar__boo)
"""
import math
class Pub(object):
_name = "protected 类型的变量"
__info = "私有类型的变量"
def _func(self):
print(... |
15a9da7261655dd9e4c5a64aa19467f0a3cba3c7 | JagritiG/Data-Visualization-vol2 | /matplotlib/scatter/scatter.py | 2,821 | 3.609375 | 4 | # Scatter plot using Iris dataset
import pandas as pd
import matplotlib.pyplot as plt
font_param = {'size': 12, 'fontweight': 'semibold',
'family': 'serif', 'style': 'normal'}
# Prepare data for plotting
# load iris dataset from file in Pandas Dataframe
col_names = ['Sepal_length', 'Sepal_width', 'Petal_... |
9fbb5b1f048534d10c2175b8033216fe457133fe | spitis/stable-baselines | /stable_baselines/common/math_util.py | 5,382 | 3.625 | 4 | import numpy as np
import scipy.signal
def discount(vector, gamma):
"""
computes discounted sums along 0th dimension of vector x.
y[t] = x[t] + gamma*x[t+1] + gamma^2*x[t+2] + ... + gamma^k x[t+k],
where k = len(x) - t - 1
:param vector: (np.ndarray) the input vector
:param ga... |
db208265703bbdec3e4ed14b2987ae0ba068561d | jcuartas/MITx-6.00.1x | /Week2/polysum.py | 464 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 11 12:18:09 2017
@author: jcuartas - Juan Manuel Cuartas Bernal
Inputs
n integer
s integer
Output
polysum float
"""
from math import *
def polysum(n, s):
# Calculate area of the polygon
area = (0.25*n*s*... |
be32419b60e322bf07b7fae724bf67aedddf2610 | jcuartas/MITx-6.00.1x | /Midterm Exam/largestOddTimes.py | 840 | 4.09375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 2 04:02:34 2017
@author: jcuartas
"""
def largest_odd_times(L):
""" Assumes L is a non-empty list of ints
Returns the largest element of L that occurs an odd number
of times in L. If no such element exists, returns None """
... |
931eb4a2c91cee8b70a4319af766dc7ce17b6ece | royakash2203/Python_Learning | /Day 1-10/sotc1 calculator.py | 242 | 4.09375 | 4 | n1=int(input("enter the 1st number:"))
n2=int(input("enter the 2nd number:"))
sign=input("enter the operation [+,-,*,/]:")
if sign == "+":print(n1 + n2)
elif sign == "-":print(n1-n2)
elif sign == "*":print(n1*n2)
elif sign == "/":print(n1/n2) |
ffcb969a86f1bfde63159f3fe6913ebc50a4abcb | Kbman99/Python-FAU | /Assignment2/p2.py | 1,002 | 3.75 | 4 | def find_dup_str(s, n):
for index in range(len(s)-n+1):
temp_string = s[index:index+n]
updated_string = s[index+n:]
if updated_string.find(temp_string) != -1 and len(updated_string) != 0:
return temp_string
return ""
program Find_Duplicate_String(s, n):
for i from 0 to l... |
fc7297411e304306ef379e18475ad8353436e889 | Kbman99/Python-FAU | /Assignment2/p3.py | 1,351 | 3.5625 | 4 | import pylab
import math
def compute_interval(min, max, number_of_samples):
while max > min:
sample_points = []
interval_separation = float((max - min)/number_of_samples)
for i in range(number_of_samples):
sample_points.append(round(max - i*interval_separation, 4))
retu... |
3acf680e3f9d80cd772d0e401d95e6a830d5123b | mishaZ-Lab/ooop | /Зверушка.Py | 937 | 3.546875 | 4 | class Critter:
total = 0
@staticmethod
def status():
print('Общее число зверюшек', Critter.total)
def __init__(self, name, hunger = 0, boredom = 0):
self.name = name
self.hunger = hunger
self.boredom = boredom
Critter.total += 1
def talk(self):
prin... |
e5f23cd93a4665b2ea3b9b67f472bb6793ab6959 | ggconstante/ggconstante.github.io | /mrPython/hw5.py | 5,828 | 4 | 4 | # Name: Gingrefel G. Constante
# Date: 02/28/2016
# Class: ISTA 350, Hw5
class Binary:
'''
init has one string parameter with a default argument of '0'. This string can be the empty
string (treat the same as '0'). Otherwise, it should consist only of 0’s and 1’s and should be 16 or less
characters l... |
cb3a8cdc35714d708f5e11c0b8fdeb45c8544e47 | Rodrigocabral144/Projeto_Controle_tv | /aula7_televisao.py | 1,371 | 4.03125 | 4 | class Televisao:
def __init__(self):
self.ligada = False
self.canal = 1
self.volume = 10
def power(self):
if self.ligada:
self.ligada = False
else:
self.ligada = True
def aumenta_canal(self):
if self.ligada:
self.canal +=... |
bd36a8a99fd2d3eae86da3fa0b115bd553f9a618 | eidanjacob/advent-of-code | /2020/6.py | 476 | 3.53125 | 4 | s = 0
with open("./input.txt") as f:
group = set()
first = True
for line in f:
if line != "\n" and line != "":
if first:
first = False
[group.add(c) for c in line if c != "\n"]
else:
newgroup = set([c for c in group if c in line... |
fd9435912655021c274f70ae9220d7e55f750794 | eidanjacob/advent-of-code | /2020/12.py | 1,430 | 3.6875 | 4 | actions = open("input.txt").readlines()
turn = {"E" : { "L" : "N", "R" : "S"},
"N" : { "L" : "W", "R" : "E"},
"W" : { "L" : "S", "R" : "N"},
"S" : { "L" : "E", "R" : "W"}}
current_direction = "E"
current_x = 0
current_y = 0
for action in actions:
a = action[0]
m = int(action[1:])
... |
7db499e4e39bb0f7545f1cd01d983b3790a1207d | andzajan/Adeept_Ultimate_Starter_Kit_Python_Code_for_RPi | /service.py | 1,398 | 3.953125 | 4 | #!/usr/bin/env python
#-----------------------------------------------------------
# File name : 01_blinkingLed_1.py
# Description : make an led blinking.
# Author : Jason
# E-mail : jason@adeept.com
# Website : www.adeept.com
# Date : 2015/06/12
#------------------------------------------------... |
5765384a784ac51407757564c0cbafa06cedb83b | divyaprabha123/programming | /arrays/set matrix zeroes.py | 1,059 | 4.125 | 4 | '''Set Matrix Zeroes
1. Time complexity O(m * n)
2. Inplace
'''
def setZeroes(matrix):
"""
Do not return anything, modify matrix in-place instead.
"""
#go through all the rows alone then
is_col = False
nrows = len(matrix)
ncols = len(matrix[0])
... |
04c2c908a8c25385efd32b14220e9939c94bb010 | divyaprabha123/programming | /arrays/sort_k_arrays.py | 683 | 3.796875 | 4 | import heapq
'''Sorting k arrays
1. Use heap time O(n) space O(n)
'''
def merge_arrays(arrays):
heap = [(lst[0], i,0) for i, lst in enumerate(arrays) if lst]
heapq.heapify(heap)
merge = []
while heap:
min_num, lst_index, ele_index = heapq.heappop(heap)
merge.append(min_num)... |
8d6ae66c36e6bef05464f78e93979a89c279d0b6 | jcurnutt14/FBFriendData | /friendcount.py | 2,100 | 3.875 | 4 | #Program Name: Friendship Paradox
#Author: Jon Curnutt
#Date: 10/15/19
import networkx as nx
G = nx.read_graphml('FrankMcCown-Facebook.graphml')
#Determine number of friends
my_friends = len(G.nodes)
print(f'Total Friends: {my_friends}')
#Determine the average number of friends each friend has
friends_of... |
c3c6955259b4691b202c3c456461362f079c5119 | falcoco/pythonstudy | /ex23.py | 245 | 3.65625 | 4 | L = range(100)
'''
print L[:10]
print L[20:30]
print L[-5:]
'''
print L[:10:2] #pcik one every two numbers
print L[::5] #pick one every five numbers
print L[:] #copy the list
print range(1000)[-5:]
print 'ABCDEFG'[-2:] #see string as list |
47040df315ac09b44047e645f8f988b5a1142342 | falcoco/pythonstudy | /ex7.py | 299 | 4.25 | 4 | age = 7
if age >= 18:
print 'your age is ',age
print 'adult'
#else:
# print 'your age is ',age
# print 'teenager'
elif age >= 6:
print 'your age is ',age
print 'teenager'
else:
print 'kid'
#age = 20
#if age >= 6:
# print 'teenager'
#elif age >= 18:
# print 'adult'
#else:
# print 'kid' |
962d932bddbabc462877308cce22e97594590a0a | falcoco/pythonstudy | /ex9.py | 119 | 3.796875 | 4 | # -*- coding: utf-8 -*-
birth = int(raw_input('Your birth:'))
if birth < 2000:
print '00before'
else:
print '00after' |
5d9305bf6007fa9278894e29bcca9c8b8c0dbae5 | Leejeunghun/Capstan | /11-14/test.py | 2,101 | 3.625 | 4 | from tkinter import *
from tkinter import ttk
import subprocess # 바로 python 실행하기 위해서 사용
def button_pressed(value):
number_entry.insert("end",value)
print(value,"pressed")
def insertNum_on():
txt.insert(100, "On")
subprocess.call('gpio -g write 21 1',shell=True)
def insertNum_off():
txt.insert(100, ... |
7e91ef8f4bce914f08e73ba994e325aaa6cca056 | lisaschubeka/CS50x-Solutions | /Problem Set 7/Houses/import.py | 743 | 3.625 | 4 | from cs50 import SQL
import csv
import sys
def main():
if len(sys.argv)!= 2:
print("Usage: python import.py characters.csv")
sys.exit()
db = SQL("sqlite:///students.db")
with open("characters.csv", "r") as students:
reader = csv.DictReader(students, delimiter=",")
... |
b1f9edecef0578ea8b6ec91147e36ed1e28f2621 | madacoo/aoc | /2017/05/solve.py | 1,148 | 3.625 | 4 | from time import clock
def puzzle_input():
with open("input.txt", "r") as f:
return [int(i) for i in f.read().strip().split()]
def solve(instructions):
"Return the number of steps required to 'escape' the instructions."
i = 0
steps = 0
length = len(instructions)
while (i... |
926c7141c1f6ad007ba57652c1de5c30913d1bbb | chetan1327/Engineering-Practical-Experiments | /Semester 4/Analysis of Algorithm/KMP.py | 1,245 | 3.828125 | 4 | # for proper examples refer https://www.geeksforgeeks.org/kmp-algorithm-for-pattern-searching/
# https://www.youtube.com/watch?v=V5-7GzOfADQ
# uncomment print statements to see how the table is updated
def prefixTable(pattern):
prefix_table = [0]
for i in range(1, len(pattern)):
j = prefix_table[i-1... |
a20cb3c954513dc21d65ab569264c38d1ec07dbc | antuniooh/http-api-without-lib | /databaseUser/ObjectUser.py | 2,223 | 3.875 | 4 | import datetime
class UserObj:
def __init__(self, name: str, phone: str, pokemon: str, image: str) -> None:
""" Create an object of type UserObj, besides that
will be create an ID based on the date of the creation time
:param name: Contact name
:param phone: Contact phone
... |
9a3b9864abada3b264eeed335f6977e61b934cd2 | willzhang100/learn-python-the-hard-way | /ex32.py | 572 | 4.25 | 4 | the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
#first for loop goes through a list
for number in the_count:
print "This is count %d" % number
#same
for fruit in fruits:
print "A fruit of type: %s" % fruit
#mixed list use %r
for i ... |
ffe68ef6fd0c1e21356795a2dc42dc0f26bb3c1c | ananabh/Graph_Algorithm | /Graph_Algorithm/Depth_First.py | 236 | 3.828125 | 4 | def search(graph, visited, current=0):
if visited[current] == 1:
return
visited[current] = 1
print("Visit :", current)
for vertex in graph.get_adjacent_vertices(current):
search(graph, visited, vertex)
|
1bf6bde7716587e3767c5b3f2d8a771c31109019 | ananabh/Graph_Algorithm | /Graph_Algorithm/Dijkstra_Algorithm.py | 1,466 | 3.859375 | 4 | import Graph_Algorithm.priority_dict as priority_dict
def build_distance_table(graph,source):
distance_table = {}
for i in range(graph.numVertices):
distance_table[i] = (None,None)
distance_table[source] = (0, source)
priority_queue = priority_dict.priority_dict()
priority_queue[source] = ... |
f4d5665b4ae72f01abdd3a22863b35102dc45bd3 | VP-Soup/Python-Secure-Parallel-and-Distributed-Computing | /SecretCode.py | 1,182 | 4.09375 | 4 | """
Name: Vicente James Perez
Date: 1/09/2020
Assignment: Module 1: Secret Code
Due Date: 1/10/2020
About this project: Using a dict structure, take user input and translate to "coded" version
Assumptions:NA
All work below was performed by Vicente James Perez
"""
import string
# create reverse alphabet for ... |
a53b9ce0419476bc740adb64ba498d84201a2bbd | helen229/AI_Project_Python | /Mini_max.py | 3,374 | 3.53125 | 4 | import Game_Tree
# from TreeDriver import Node
# from TreeDriver import Tree
class MiniMax:
def __init__(self, game_tree, curChoice):
self.game_tree = game_tree # GameTree
self.root = game_tree.root # GameNode
self.currentNode = None # GameNode
self.successors = [] # L... |
5a34d77e683868d8c9949401771d0bcea5054c69 | bilha-analytics/skoot | /skoot/utils/dataframe.py | 524 | 3.859375 | 4 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import pandas as pd
import numpy as np
__all__ = [
'get_numeric_columns'
]
def get_numeric_columns(X):
"""Get all numeric columns from a pandas DataFrame.
This function selects all numeric columns from a pandas
DataFrame. A numeric col... |
6d284c79a505fcc61f317a33ee6265a52b64bf6d | ZaytsevDmitriy/netology_Iterators.Generators.Yield | /main.py | 1,318 | 3.53125 | 4 |
nested_list = [
['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i']
]
# class FlatIterator:
#
# def __init__(self, my_list):
# self.my_list = my_list
# self.position = 0
# self.position2 = -1
#
# def __iter__(self):
# return self
#
# def __next__(self):
# if self.position < len(self.my_list):
# if s... |
9d90bbd139731a568a40c106aa7c10261ab46d2e | subodhsondkar/vadict_machine_learning | /session.py | 9,139 | 3.609375 | 4 | '''
What is this?
This is a python program for predicting heat generated in some machine according to sensor data provided in the file main.csv. main.csv contains:
1. Time
2. Day_Of_Year
3. TT_16: temperature sensor
4. PYNM_02: temperature sensor
5. TT_11: temperature sensor
... |
749186c75529d26678b30736069c7babb7aa8bd3 | dgilros/TuringNDTMSimulator | /NDTM.py | 5,831 | 3.546875 | 4 | ####
# NDTM.py: a nondeterministic Turing Machine Simulator
# Author: David Gil del Rosal (dgilros@yahoo.com)
####
from collections import defaultdict, deque
class Tape:
# Constructor. Sets the blank symbol, the
# string to load and the position of the tape head
def __init__(self, blank, string ... |
da77c952ce085dc401d65edd7b0bdec7d4899504 | HellLive/Lista-Zumbi | /questao9.py | 458 | 4.03125 | 4 | '''Escreva um programa que pergunte a quantidade de km percorridos por um carro alugado pelo
usuário, assim como a quantidade de dias pelos quais o carro foi alugado. Calcule o preço a pagar,
sabendo que o carro custa R$ 60,00 por dia e R$ 0,15 por km rodado.'''
x=int(input("Qual a quantidade de KM percorrido com o ca... |
065ef683f3667f0da058f83fe29fe8a671c918f9 | yash9168/codeforces-problems | /PY/1stOct_shalin24999.py | 172 | 3.53125 | 4 | n = int(input())
for i in range(n):
str = input()
length = len(str)
if length <= 10:
print(st)
else:
print(st[0], l - 2, st[l - 1], sep="")
|
5d0dc760875c2d5c703c164881a904ed19716979 | wojiushilr/PRML_SVM_ADABOOST_RF | /face_recog/temp3.py | 436 | 3.8125 | 4 | '''
import csv
with open("XXX.csv","w",newline="") as datacsv:
#dialect为打开csv文件的方式,默认是excel,delimiter="\t"参数指写入的时候的分隔符
csvwriter = csv.writer(datacsv,dialect = ("excel"))
#csv文件插入一行数据,把下面列表中的每一项放入一个单元格(可以用循环插入多行)
csvwriter.writerow(["A","B","C","D"])'''
print(list(zip([1, 3, 5], [2, 4, 6]))) |
8244cceeb3f483b05b666a6a268c432426101809 | rapferrer/entry-drawer | /src/random_selector/winning_entry_selector.py | 2,349 | 3.625 | 4 | #!/usr/bin/env python
"""Takes in a list of entrants from a .csv and finds the winner or winners."""
from argparse import Namespace
import logging
import random
from typing import List
from models.entrants_collection import EntrantsCollection
logger = logging.getLogger(__name__)
def find_winning_entries(entrants... |
d6c2b9f271797e580226702c6ec843e00eea3508 | SMinTexas/work_or_sleep | /work_or_sleep_in.py | 428 | 4.34375 | 4 | #The user will enter a number between 0 and 6 inclusive and given
#this number, will make a decision as to whether to sleep in or
#go to work depending on the day of the week. Day = 0 - 4 go to work
#Day = 5-6 sleep in
day = int(input('Day (0-6)? '))
if day >= 5 and day < 7:
print('Sleep in')
elif day >= 0 and d... |
c62a59b69b55dfb757de7342bba9b9a46a899367 | khaloodi/Graphs | /projects/social/social.py | 5,617 | 3.96875 | 4 | import random
class Queue():
def __init__(self):
self.queue = []
def enqueue(self, value):
self.queue.append(value)
def dequeue(self):
if self.size() > 0:
return self.queue.pop(0)
else:
return None
def size(self):
return len(self.queue... |
a7cc600378806c5afab02b2bee30a1fc5ebaa3cd | jhfengyun/Evo-Comp | /timer.py | 871 | 3.578125 | 4 | import logging
from time import time
class Timer:
"""
A class to investigate code runtime.
"""
def __init__(self, seed):
"""
Timer Initialisation
:param seed: The seed of the world being timed
"""
self.logger = logging.getLogger(__name__)
self.logger.set... |
7fa7ce262340b1761172fef53f7ea8690a4ce166 | yujmo/python | /yield/yield.py | 233 | 3.59375 | 4 | def gen():
yield from subgen()
def subgen():
while True:
x = yield
yield x + 1
def main():
g = gen()
next(g)
retval = g.send(1)
print(retval)
g.throw(StopIteration)
main()
|
4abf0f0bd2d6170360ac72b0815fdcba40233dfd | yujmo/python | /python练习题/11/11.py | 358 | 3.6875 | 4 | #!/usr/bin/python2
import re
def words():
file_cache = open("filter_word")
file_read = file_cache.readlines()
file_cache.close()
cache = raw_input("Please input a word:")
if cache and cache !="q":
for i in file_read:
if cache == i[:-1]:
print "freedom"
wor... |
16a79229599922fa4fa255d73e9dd46517e86485 | sahilohe/Even_or_ODD | /even_or_odd.py | 175 | 3.765625 | 4 | def showNumbers(limit):
for i in range(1 ,limit + 1):
if i % 2 == 0:
print(f'{i} EVEN')
else:
print(f'{i} ODD')
showNumbers(10)
|
713be8caaafcd510a7ab9abe8ae3d9ff59f7e037 | denissden/joystick-mouse | /utils.py | 267 | 3.703125 | 4 | def interpolate(val, low, high):
if val <= low:
return 0
if val >= high:
return 1
return (val - low) / (high - low)
def interpolate_power(val, power):
sign = 1 if val > 0 else -1
after = abs(val ** power)
return sign * after
|
d0db003c65b5b4bb5d08db8d23f49b29d15a2d9b | mariaKozlovtseva/Algorithms | /monotonic_check.py | 798 | 4.3125 | 4 | def monotonic(arr, if_true_false=False):
"""
Check whether array is monotonic or not
:param arr: array of different numbers
:return: string "Monotonic" / "Not monotonic" or if True / False
"""
decreasing = False
increasing = False
idx = 0
while not increasing and idx < len(arr)-1:
... |
753f1d9d63eab52182e562bfecc9bd42f7acb0c3 | mariaKozlovtseva/Algorithms | /leet_code/longest_incr_subseq.py | 899 | 3.875 | 4 | def lengthOfLIS(nums: 'List[int]') -> int:
"""
https://leetcode.com/problems/longest-increasing-subsequence/submissions/
Given an integer array nums,
return the length of the longest strictly increasing subsequence.
"""
n = len(nums)
ends_arr = [None] * (n)
ends_arr[0] = 0
length = 1... |
5841f6e9177fd876d1831a4c1b6c7f492db7f299 | mariaKozlovtseva/Algorithms | /stepik_algo/quicksort_bisearch.py | 1,305 | 3.65625 | 4 | def partition(arr):
pivot = (arr[0] + arr[len(arr)//2] + arr[-1]) // 3
ls, gr, eq = [], [], []
for x in arr:
if x > pivot: gr.append(x)
elif x < pivot: ls.append(x)
else: eq.append(x)
return ls, eq, gr
def quicksort(arr):
while len(arr) > 1:
ls, eq, gr = partition(ar... |
d8f7bbe7d88f807fab605333df84486b74e2cb88 | mariaKozlovtseva/Algorithms | /DoubleLL.py | 2,319 | 3.796875 | 4 | class Node:
size = 0
def __init__(self, value):
self.value = value
self.prev = None
self.next = None
class DoubleLinkedList:
def __init__(self):
self.head = None
self.tail = None
def setHead(self, node):
if not self.head:
self.head = node
... |
1f1a00fbb0a7d9b21bfd159b0ae4665af39370d6 | mariaKozlovtseva/Algorithms | /stack_prefix_postfix_notation.py | 2,996 | 3.765625 | 4 | class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items) - 1]
def size(self):
... |
09896d5ccf05e5b341ad50e28fe2ad3f4d248c75 | bets42/42bets | /scripts/send_cmd.py | 2,082 | 3.59375 | 4 | #!/usr/bin/env python -u
"""Send a single command to a 42bets server
Connects to the command port of a server and sends a command, outputting
whatever message is received in response"""
import optparse
import os
import socket
import sys
class TCPCommandSender:
"""Wrapper around TCP client for sending commands"... |
e9696c152599ed1337c59ebace30cf8275ca3876 | suleyman-kutukoglu/guessing-game | /guess-game.py | 1,865 | 3.984375 | 4 | import random
def randomWordFromTxt():
allWords = list()
with open("word_list.txt", "r", encoding="utf-8") as file:
for line in file:
line = line.split()
allWords.append(line[0])
randomWord = allWords[random.randint(0, len(allWords) - 1)]
return randomWord
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.