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 |
|---|---|---|---|---|---|---|
4bb0736d12da8757a76839f242d902fb08afc461 | vamsikrishna6668/python | /class2.py | 559 | 4.3125 | 4 | # w.a.p on class example by static method and static variables and take a local variable also print without a reference variable?
class student:
std_idno=101
std_name="ismail"
@staticmethod
def assign(b,c):
a=1000
print("The Local variable value:",a)
print("The static ... |
2435e4af4414429c2bc3b66ee1475829799b01d6 | seraht/AmazonScraper | /Scraping/laptop_features_class.py | 2,267 | 3.546875 | 4 | """
Define an OOP Features, with the corresponding attributes and functions for the features of the laptop
Authors: Serah
"""
from Createdb import connect_to_db
from datetime import datetime
import config
from Logging import logger
import sys
sys.path.append('../')
DB_FILENAME = config.DB_FILENAME
class Features:
... |
8425d06717614c9e3d0a34e0c253cf1f6eebf8d3 | svi-lab/general_programs | /slice_of_pie.py | 3,391 | 3.53125 | 4 | import numpy as np
from warnings import warn
def slice_of_pie(matrix, phi_1, phi_2, r_1=0, r_2=np.inf, center=False):
"""isolates the sclice of an image using polar coordinates
Prerequisites: numpy
Parameters:
matrix:2D ndarray: input matrix as 2D numpy array (your input image)
r_1:float: ... |
3a5908b10e1eb651085ac4dee75e344b8bb9cc83 | singzinc/PythonTut | /basic/tut2_string.py | 785 | 4.3125 | 4 |
# ====================== concat example 1 ===================
firstname = 'sing'
lastname = 'zinc '
print(firstname + ' ' + lastname)
print(firstname * 3)
print('sing' in firstname)
# ====================== concat example 2 ===================
foo = "seven"
print("She lives with " + foo + " small men")
# ======... |
57d256f05332980e76360dc99e3f2693905a8b60 | giacomofi/DijkstraAlgorithmR | /heapdijkstra.py | 2,818 | 3.515625 | 4 | from graph import Graph
from node import Node
import time
class HeapDijkstra:
def __init__(self):
pass
nodeLinkAndCost = []
heaps = []
finalHeap = []
def createGraph(self):
nodes = []
g = Graph(nodes)
f = open("GeneratedGraph.txt", "r")
lines = f.readlin... |
9e59cf888a34263475acad0a8dd3543d5352a105 | gbmhunter/AdventOfCode2017 | /day12/day12.py | 1,361 | 3.65625 | 4 | connections = []
with open('input.txt', newline='') as file:
for line in file:
connPrograms = line[line.index('>') + 2:]
connPrograms = [x.strip() for x in connPrograms.split(',')]
connPrograms = list(map(int, connPrograms))
connections.append(connProgram... |
bb3d93729ebf17b23e6af471a3165371da9715fc | gbmhunter/AdventOfCode2017 | /day5/day5.py | 973 | 3.640625 | 4 |
input = open('input.txt')
inputLines = input.readlines()
instrList = []
for line in inputLines:
instrList.append(int(line))
canExit = False
index = 0
steps = 0
while True:
if index < 0 or index >= len(instrList):
break
instr = instrList[index]
# print('instr = ' + str(instr))
# Increme... |
cb8589722606e8fa69a9db8c49f7a55080f8a8cc | talhaibnaziz/projects | /pi3ddemos/CollisionBalls.py | 1,902 | 3.65625 | 4 | #!/usr/bin/python
from __future__ import absolute_import, division, print_function, unicode_literals
""" Example of using the loop control in the Display class with the behaviour
included in the pi3d.sprites.Ball class
"""
import random
import sys
import math
import demo
import pi3d
MAX_BALLS = 25
MI... |
1a8b164a526e8a1cde7fc6617f1caf31f95c7cb3 | antoniogi/HPC | /Python/TACC_HPC/3_matplotlib/bars_color.py | 590 | 4.03125 | 4 | #!/usr/bin/env python
#
# Creates and displays a bar plot. Changes the bar color depending on
# the y value
#
#
# agomez (at) tacc.utexas.edu
# 30 Oct 2014
#
# ---------------------------------------------------------------------
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(5)
yvals = [-100, 200, ... |
21edae2f34df0c3b13ec7a37bdbfcfce357fe524 | jgramm/altfactsbot | /textToMarkov.py | 5,144 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 11 15:35:37 2017
@author: James
"""
import re
import random
def textTo2GramMarkov(text, wordsTo=dict(), count=0):
#text = re.sub(r'\W+', '', text)
#words = text.split()
words = "".join((char if char.isalpha() else " ") for char in text).split()
... |
efc04c2b1660461fb8321fa29699e5d73ffd6285 | oliviervos/python_workbook_174_Solution | /IntroductionToProgramming/E14.py | 169 | 3.734375 | 4 | height_us = map(float,raw_input("please input your height with feet and inches, sep by ,").split(','))
print "your height in cm is", 2.54*(height_us[0]*12+height_us[1])
|
79b4b968d475c29c3a99f4a85724ca9a3d05f4c9 | oliviervos/python_workbook_174_Solution | /IntroductionToProgramming/E13.py | 1,132 | 3.6875 | 4 | # the solution in the book is optimal but too simple, here we give the optimal dynamic programming solution
coins = input("input a number of cents in integer\n")
pennies = 1
nickels = 6 #in order to make it harder, we make nickles to be 6
dimes = 10
quarters = 25 #limit the denominations to only 4 types
from ... |
590b4ee6898e35551b8059ef9256d307a8bcce59 | markvakarchuk/ISAT-252 | /Python/Rock, Paper, Scissors - Linear.py | 1,891 | 4.1875 | 4 | import time
import random
# defining all global variables
win_streak = 0 # counts how many times the user won
play_again = True # flag for if another round should be played
game_states = ["rock", "paper", "scissors"]
#printing the welcome message
print("Welcome to Rock, Paper, Scissors, lets play!")
time.slee... |
b47c6a6383e857ea7ca8e93cc0c24f43a59c7516 | piyushsharma161/Detect-and-count-differnet-products | /training/copy_dir.py | 1,122 | 3.515625 | 4 | import os, shutil
import argparse
'''
Creating the output directory if not already exists
Doing the copy directory by recursively calling my own method.
When we come to actually copying the file I check if the file is modified then only we should copy.
'''
parser = argparse.ArgumentParser()
def copy_dir(src, dst, s... |
c07f63c3755581aca8eb2c7adf3024aaf422ea60 | eclansky/scriptPlayground | /looping.py | 301 | 3.9375 | 4 | #looping
#for loops
#Make a for loop that prints out dictionary stuff
#items returns list of dictionaries key:value pairs
# dict.items format
# Putting sep separator equal to empty string makes it delete the spaces between
for name, price in menu_prices.items():
print(name, ':', price, sep='')
|
51d1da533af29e0a438cfa46ab22b85054e3eeb4 | alexng96/ECE143Team6 | /analysis_modules.py | 3,095 | 4.40625 | 4 | import pandas as pd
def make_pandas(fname):
"""Makes a pandas dataset from the given csv file name. Changes data-types of numeric columns
Arguments:
fname {string} -- the csv files with CAPE data
"""
assert fname == 'engineering.txt' or 'humanities.txt' or 'socialSciences.txt' or 'ucsd.txt', "... |
3a784950aad8f17238f9aa4ca346ae1491f77b92 | rebondy/barbot | /algorithm.py | 5,373 | 3.75 | 4 | Margarita = ["Tequila", "Cointreau", "Lime Juice"]
MintJulep = ["Wiskey", "Angostura Bitters", "Sugar Syrup"]
PlantersPunch = ["White Rum", "Lime Juice", "Sugar Syrup", "Angostura Bitters"]
Cosmopolitan = ["Vodka", "Cointreau", "Lime Juice", "Cranberry Juice"]
Vodkatini = ["Vodka", "Vermouth"]
Fitzgerald = ["Lemon Juic... |
2f0f16f52d149b8420c44326c81b66f24be427e3 | rudrut/developing-python-applications-2020 | /Week7_tasks.py | 4,921 | 3.65625 | 4 | #----------------------------------------------------------------
#Task 1
#class Complex:
# def __init__(self, real = 0, imaginary = 0):
# self.real = real
# self.imaginary = imaginary
#
# def getReal(self):
# return self.real
#
# def getImaginary(self):
# return se... |
92d4b3e00f461d9582d502d56ae028f3297f6c90 | arqcenick/SRMNIST | /contrib_homework.py | 7,549 | 3.5 | 4 | # CS 559 homework template
# Instructor: Gokberk Cinbis
#
# Adapted from
# https://www.tensorflow.org/get_started/mnist/pros
# License: Apache 2.0 License
#
# Homework author: <Your name>
#########################################################
# preparations (you may not need to make changes here)
##################... |
cb8efd3255f3b5a4c19a93b4efb02de49c4c0a84 | Clay190/Unit-5 | /warmup13.py | 265 | 3.640625 | 4 | #Clay Kynor
#11/16/17
#warmup13.py
from random import randint
words = []
for i in range(1,21):
num = randint(1,100)
words.append(num)
words.sort()
print(words)
print("The maximum is", words[19])
print("The minimum is", words[0])
print("Sum", sum(words))
|
58e95dd1b6f235ea6b2e4817724b1b8590666005 | brunalimap/house_rocket | /notebooks/aula_python01.py | 3,308 | 4 | 4 | import pandas as pd
df = pd.read_csv('data/kc_house_data.csv')
# Para verificar o dataset
#print(df.head())
# Para verificar os tipos das variáveis das colunas
#print(df.dtypes)
# Primeiras Perguntas dos CEO
# 1- Quantas casas estão disponíveis para comprar?
# Estratégia
# 1. Selecionar a coluna 'id'
# 2. Contar ... |
4c3c113d6b9546ec9eba9f289524f25313aa0a25 | jbbang3/thinklikeCS | /Ch10List.py | 1,498 | 3.6875 | 4 | def middle(t):
return t[1:-1]
def cumsum(x):
newt=[]
for i in range(len(x)):
print(i)
newt+=[sum(x[:i+1])]
return newt
def nested_sum(t):
summed=0
for i in range(len(t)):
summed+=sum(t[i])
return summed
letters=['a', 'b', 'c', 'd']
print(middle(letters))
number=[1... |
3bb12286fa514a14083d77e90a9bf443dff65d4d | AngeloBradley/Data-Structures-w-Python | /SLinkedList.py | 13,616 | 4.0625 | 4 | from LinkedList import LinkedList
from Node import Node
import sys
class SLinkedList(LinkedList):
def __init__(self):
LinkedList.__init__(self)
#==================================#Private Helper Functions#==================================
def insertion_handler(self, newdata, pointer1, ... |
0fd48c88aaa2783327154f9189d9b07e16b5f7e8 | Teakmin/algorithm | /solving/fibonacci.py | 179 | 3.71875 | 4 | def fib(n):
if n == 0 or n==1 : return n # fib(0) = 1, fib(1) =1
return fib(n - 1 ) + fib(n - 2) # fib(n) = fib(n-1) + fib(n-2)
print(fib(5))
print(fib(4))
print(fib(3)) |
388bd00a1e22c4b91ddddfb08eed5c05c61f4607 | justinyates887/tkinter-practice | /hello.py | 450 | 3.9375 | 4 | #tkinter is built into python
from tkinter import *
#To use a widget, or window, you have to declare it from tkinter
root = Tk()
#you can then add a label to the widget
myLabel = Label(root, text='Hello World')
#The pack function is a primitive way to get the widget to appear on screen
myLabel.pack() #Now the window... |
7ca6661867b207e89b504eabf422334c6c5c9d58 | thouzeauhernan/Phyton | /index.py | 5,583 | 3.625 | 4 | from sqlite3.dbapi2 import Row
from tkinter import ttk
from tkinter import *
import sqlite3
print("hola mundo")
class producto:
db_nombre = 'baseDatos.db'
#
def __init__(self,window):
self.wind=window
self.wind.title('nueva aplicacion')
#crear un frame
frame = Lab... |
c3f3e836042df5e06d1f19b26fda1197726d2030 | mikofski/poly2D | /polyDer2D.py | 2,204 | 4.25 | 4 | import numpy as np
def polyDer2D(p, x, y, n, m):
"""
polyDer2D(p, x, y, n, m)
Evaluate derivatives of a 2-D polynomial using Horner's method.
Evaluates the derivatives of 2-D polynomial `p` at the points
specified by `x` and `y`, which must be the same dimensions. The
outputs `(fx, fy)` will ... |
d3be3d7e395eafc7174e41ec2a9e995616374be0 | PacktPublishing/Raspberry-Pi-Making-Amazing-Projects-Right-from-Scratch- | /Module 1/Chapter 1/prog4.py | 106 | 3.65625 | 4 | def fib(n):
a,b = 0,1
for i in range(n):
a,b = b,a+b
return a
for i in range(0,10):
print (fib(i))
|
8e3cc0cdc15f9e761c8056591532dd2409b6fd5b | PacktPublishing/Raspberry-Pi-Making-Amazing-Projects-Right-from-Scratch- | /Module 1/Additional code files/Additional_Programs_Part_1/prog2.py | 398 | 3.609375 | 4 | # Fractal Koch
import turtle
def koch(t, order, size):
if order == 0:
t.forward(size)
else:
for angle in [60, -120, 60, 0]:
koch(t, order-1, size/3)
t.left(angle)
def main():
myTurtle = turtle.Turtle()
myWin = turtle.Screen()
myTurtle.penup()
myTurtle.backward(... |
8e44b4f33e8737c96f56d1b20c70c8ba3488d83f | andutzu7/Lucrare-Licenta-MusicRecognizer | /Music Recognizer/Metrics/BinaryCrossentropy.py | 1,870 | 4 | 4 | import numpy as np
from .Loss import Loss
class BinaryCrossentropy(Loss):
"""
The class computes the binary crossentropy by applying the formula.
Sources: * Neural Networks from Scratch - Harrison Kinsley & Daniel Kukieła [pg.407-412]
"""
def forward(self, y_pred, y_true):
"""
... |
19dafbf700ec73673dd5fddd2b12472785a14467 | andutzu7/Lucrare-Licenta-MusicRecognizer | /Music Recognizer/Metrics/MeanAbsoluteError.py | 1,462 | 4.03125 | 4 | import numpy as np
from .Loss import Loss
class MeanAbsoluteError(Loss):
"""
The MAE class computes the loss by calculating the average of the absolute value of the errors
(the average squared difference between the estimated and actual values)
Sources: * Neural Networks from Scratch ... |
e49bdaefea94b60748c118015eb75b1980bc3cc3 | charlesepps79/ch_3 | /shrinking_guest_list.py | 3,716 | 4.25 | 4 | # 3-7. Shrinking Guest List: You just found out that your new dinner
# table won't arrive in time for the dinner, and you have space for
# only two guests.
# Start with your program from Exercise 3-6. Add a new line that prints
# a message saying that you can invite only two people for dinner.
guests = ['Ted Bundy'... |
fb9b534920888e4d9ce1cb440a260bb6927cf11e | GeeksHubsAcademy/2020-hackathon-zero-python-retos-pool-4 | /src/kata2/rpg.py | 1,274 | 3.96875 | 4 | #!/usr/bin/python
import random
import string
def RandomPasswordGenerator(passLen=10):
resultado = ""
letras = string.ascii_letters
digitos = string.digits
signosDePuntuacion = string.punctuation
# Generamos una contrseña simplemente de letras
n = 0
while n < passLen:
resultad... |
a61402a1392632c8b661e1feb93249f0f8e782ec | Nionchik/Nionchik.github.io | /PhitonLessons/Condition.py | 261 | 3.78125 | 4 | money = 2000
if money >= 100 and money <= 500:
print('КУПИ ЖВАЧКУ')
else:
print('НЕ ПОКУПАЙ ЖВАЧКУ')
if money >= 1000 and money <= 2000:
print('Купи игрушку')
else:
print('Не покапай игрушку')
|
cc739faec2db174882aa754012daa6d07c1dcbcc | Nionchik/Nionchik.github.io | /PhitonLessons/Domashka2_Else & If.py | 249 | 3.796875 | 4 | money = 490
if money >= 100:
print('Ты нормально обепеченный человек')
else :
print('Ты очень беден или богат')
if money >= 500:
print('Ты слишком богатый человек')
|
7e7cb661a3ff5ab152b247b74217e0e5edb7a74c | serhatarslan1/Denemeler | /Bilet ücreti.py | 550 | 3.703125 | 4 | #25.02.2018
__author__ = "Serhat Arslan"
while True:
print("Öğrenci (1)")
print("Tam (2)")
print("65 Yaş Üzeri(3)")
print("-------------------")
print
seçim= input("Bilet Türü Seçiniz:")
if seçim=="1":
print("Öğrenci bilet ücretiniz 1.75 TL.")
elif seçim=="2":
... |
43bd9e4306c3e31a78795005e12a57bb63e06751 | JakeBednard/CodeInterviewPractice | /7-1_MergeTwoSortedLinkedList.py | 1,311 | 4.09375 | 4 | """Merge 2 prior sorted linked list into linked list"""
class node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def print_linked_list(head):
temp = []
while True:
temp.append(head.value)
head = head.next
if head is None:
br... |
4f6c341cb5903f526d9780af9d1aa2f8b2b87e35 | JakeBednard/CodeInterviewPractice | /6-1B_ManualIntToString.py | 444 | 4.125 | 4 | def int_to_string(value):
"""
Manually Convert String to Int
Assume only numeric chars in string
"""
is_negative = False
if value < 0:
is_negative = True
value *= -1
output = []
while value:
value, i = divmod(value, 10)
output.append((chr(i + ord('0'))))... |
3eb362415223db72994bcd38fd329f08624ca2ad | zhuyidiwow/Learning-Python | /course3/assign_week5.py | 364 | 3.71875 | 4 | import urllib
import xml.etree.ElementTree as ET
url = raw_input("Enter url: ")
data = urllib.urlopen(url).read() # read the xml to a string
tree = ET.fromstring(data) # make a tree with that string
count_lst = tree.findall(".//count") # find all count tags and return a list
total = 0
for count in count_lst:
t... |
0e4e3032733e0e07094344c896c907161ef70ddd | sptechguru/Python-Core-Basics-Programs | /ifelse.py | 171 | 3.96875 | 4 | var1 = 355
var2 = 35
var3 = int(input())
if var3 > var1:
print("Greater Number is")
elif var3 == var1:
print("Equal Numbers")
else:
print("Less Number is ")
|
1c6b1d582a9b2ec6ff7ac5bfa5d4fa9a00e57de8 | sptechguru/Python-Core-Basics-Programs | /oops/opps.py | 259 | 3.71875 | 4 | class Person:
def __init__(self,first_name, last_name, age):
print("Init Method")
self.name= first_name
self.last = last_name
self.age = age
p1 = Person('santosh','pal',24)
print(p1.name)
print(p1.last)
print(p1.age)
|
02f83da16ff3445b8d2776f3db483110aff7b4a0 | sptechguru/Python-Core-Basics-Programs | /string.py | 222 | 3.9375 | 4 | mystr = "Santosh is good Boy"
# print(len(mystr))
# # print(mystr[10])
print(mystr.upper())
print(mystr.lower())
print(mystr.count("0"))
print(mystr.find("is"))
print(mystr.capitalize())
print(mystr.replace("is" ,"are")) |
5573f3eeb4a16263a4204b4ef1058858646b9873 | sptechguru/Python-Core-Basics-Programs | /oops/multipleinhertance.py | 1,101 | 4.1875 | 4 | import time
class phone:
def __init__(self,brand,model_name,price):
self.brand = brand
self.model_name = model_name
self.price = price
def full_name(self):
return f"{self.brand}{self.model_name} {self.price}"
# multiple inheritance in class phone is Dervive Class & Main Cl... |
7cb34e5485d3bb69e8479f85ce08880cf9acd73e | Nathan-Patnam/Bioinformatics-AssignmentsandProjects | /Peptide Encoding/PeptideEncoding.py | 10,797 | 4.21875 | 4 | # function that takes in a single amino acid either in its 3 letter or one letter form and returns all of the possible codons that map to that amino acid
import itertools
def peptideEncoding():
aminoAcid = str(input("Please enter either a 3 letter or 1 letter amino acid sequence"))
aminoAcid = aminoAcid.upper... |
6305d8b2f7033d5b7895f02cb0f9ed8b5edafe9e | andrewbom/Automation-Car-Sharing-System | /agentpi/database_utils.py | 2,955 | 3.90625 | 4 | import sqlite3
from sqlite3 import Error
class Database_utils:
def __init__(self, connection=None):
self.database_name = 'agentpi_db'
self.con = self.sql_connection()
self.sql_initialize()
def sql_initialize(self):
self.sql_table()
self.sql_insert_data()
... |
462ab3ed06b932739727251a1660d1658d71e63d | thomasrmulhern/event_generator | /op_data_gen.py | 11,270 | 3.640625 | 4 | import pandas as pd
import numpy as np
from random import choice
import datetime
import string
def create_file(num_rows):
#TODO: Write code to dump straight to a csv rather than creating a pandas dataframe
'''
Description: Create a pandas df that will hold all the data and ultimately
output to json. ... |
b9da92ef59f3a2568f255889f9ad078fc7adc44e | coderliuhao/DataScienceBeginner | /python_advanced/some_builtin_module/thread_priority_queue.py | 2,068 | 3.796875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2020/9/3 下午5:11
# @Author : liu hao
# @File : thread_priority_queue.py
"""python的queue模块提供同步的线程安全队列类,包括FIFO(先入先出)队列Queue
LIFO(后入先出)队列LifoQueue,优先级队列priorityQueue"""
"""useful methods in queue method
1 queue.qsize() return length of queue
2 queue.empty() whether... |
678a1fdeea549523ac4f965bdd47bf67352fa867 | dspruell/scripts | /utils/jjdecode/jjdecode-file.py | 1,389 | 3.75 | 4 | #!/usr/bin/env python3
#
# Decode jjencoded file using jjdecode module.
#
# <https://github.com/crackinglandia/python-jjdecoder>
#
# Copyright (c) 2019 Darren Spruell <phatbuckett@gmail.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provi... |
f9522ba0b82fc6032c66db240cab133cb8192a02 | Kim-house/Lesson-1 | /encapsulation.py | 767 | 4.0625 | 4 | # class Computer:
# def __init__(self):
# self.__maxprice = 900
# def sell(self):
# print("Selling Price: {}".format(self.__maxprice))
# def setMaxPrice(self, price):
# self.__maxprice = price
# c = Computer()
# c.sell()
# # change the price
# c.__maxprice = 1000
# c.sell()
# #... |
0af3c908c726ef19b620caf23c2acd770d44b5a5 | Kim-house/Lesson-1 | /lesson2.py | 187 | 3.609375 | 4 | x=4
print ((x<6) and (x>2))
print ((x<6) & (x>2))
print (x>6) or (x<2)
print ((x>6) | (x<2))
a = [1, 2, 3]
b = [1,2,3]
print (a)
print (b)
print (a == b)
print (1 in a)
print (4 not in b) |
5024d194462c7b6a0fc33aebaf49bca19c9642e4 | upekshaa/puzzle_solver | /puzzle_tools.py | 5,640 | 3.765625 | 4 | """
Some functions for working with puzzles
"""
from puzzle import Puzzle
from collections import deque
# set higher recursion limit
# which is needed in PuzzleNode.__str__
# you may uncomment the next lines on a unix system such as CDF
# import resource
# resource.setrlimit(resource.RLIMIT_STACK, (2**29, -1))
import s... |
b070ec7bba67bf6ade44913ec99b59b914a59cdb | Azab007/Data-Structures-and-Algorithms-Specialization | /algorithms on strings/week1/suffix_tree/suffix_tree.py | 1,222 | 3.71875 | 4 | # python3
import sys
from collections import deque
from collections import defaultdict
def build_trie(text):
trie = defaultdict(dict)
i = 0
patterns = [text[i:] for i, _ in enumerate(text)]
for pattern in patterns:
v = 0
for symbol in pattern:
if symbol in trie[v]:
... |
7d26e6913a4b0024fa1082e5f3ea7c9ff0cbc50b | Azab007/Data-Structures-and-Algorithms-Specialization | /algorithms on strings/week2/suffix_array/suffix_array.py | 572 | 4.21875 | 4 | # python3
import sys
from collections import defaultdict
def build_suffix_array(text):
"""
Build suffix array of the string text and
return a list result of the same length as the text
such that the value result[i] is the index (0-based)
in text where the i-th lexicographically smallest
suffix of text sta... |
847ce21722b4237ffc0ca03f5bb6fb7f5b319f47 | Azab007/Data-Structures-and-Algorithms-Specialization | /algorithm toolbox/week2_algorithmic_warmup/6_last_digit_of_the_sum_of_fibonacci_numbers/fibonacci_sum_last_digit.py | 651 | 4 | 4 | # Uses python3
import sys
import unittest
def fibonacci_sum_naive(n):
if n <= 1:
return n
previous = 0
current = 1
sum = 1
for _ in range(n - 1):
previous, current = current, previous + current
sum += current
return sum % 10
def get_fibonacci_last_digit_fast(n):
... |
17daf1b70f5135d5117c97e024322d3689eefc6e | Azab007/Data-Structures-and-Algorithms-Specialization | /algorithm toolbox/week2_algorithmic_warmup/7_last_digit_of_the_sum_of_fibonacci_numbers_again/fibonacci_partial_sum.py | 630 | 3.828125 | 4 | # Uses python3
def get_fibonacci_last_digit_fast(n):
if (n <= 1):
return n
f = [0,1]
for i in range(2,n+1):
f.append((f[i-2] + f[i-1]) % 10)
return f[-1]
def fibonacci_sum_fast(n):
n = (n + 2) % 60
c = get_fibonacci_last_digit_fast(n)
if c == 0 :
c = 9
retur... |
6ffc5c38b51f1665cb27f987bebc51005df8a9af | saraben6/tictascii | /tictascii/ticlib/players.py | 1,540 | 3.84375 | 4 |
import random
from .exceptions import MarkerOutOfRange, MarkerExists
class Player(object):
def __init__(self, marker):
self.marker = marker
self.games_won = 0
def increment_wins(self):
self.games_won += 1
def get_wins(self):
return self.games_won
def make_a_move(se... |
8b94f093e253caaccfbb16840192d95657bf69e4 | ikailash19/guvi | /beginpgm52.py | 359 | 3.859375 | 4 | numer1=int(input())
if numer1==1:
print("One")
elif numer1==2:
print("Two")
elif numer1==3:
print("Three")
elif numer1==4:
print("Four")
elif numer1==5:
print("Five")
elif numer1==6:
print("Six")
elif numer1==7:
print("Seven")
elif numer1==8:
print("Eight")
elif numer1==9:
print("Nine")
elif numer1==0:
print(... |
96d7879af212c0651d753f442bccc52c8886c2d4 | ikailash19/guvi | /beginpgm54.py | 64 | 3.859375 | 4 | numer1=int(input())
print (numer1 if numer1%2==0 else numer1-1)
|
81f431a16062a3eae5be9788e8f1b52d08085b53 | ikailash19/guvi | /playerpgm43.py | 68 | 3.703125 | 4 | arr,ar=map(str,input().split())
print("yes" if ar in arr else "no")
|
63c0824145f1f4b350ae060f28a90e7e4da1893a | ikailash19/guvi | /beginpgm71.py | 98 | 3.828125 | 4 | arr=list(input())
ar=list(map(str,arr))
ar.reverse()
if arr==ar:
print("yes")
else:
print("no")
|
cbc8b8b708a11ddcc9711b2d33a4d8f838a436a8 | spandangithub2016/Python | /trip.py | 617 | 3.8125 | 4 | def hotel_cost(nights):
return 140*nights
def plane_ride_cost(city):
if city=="Charlotte":
return 183
elif city=="Tampa":
return 220
elif city=="Pittsburgh":
return 222
elif city=="Los Angeles":
return 500
def rental_car_cost(days):
cost=40*days;
... |
27b24ddcce76385c3616b51897e55d01acdadca1 | spandangithub2016/Python | /inheritance.py | 479 | 3.5625 | 4 | class parent:
def func(self,a,b):
self.a=a
self.b=b
def view(self):
print "this is super class"
print "a=",self.a," and b=",self.b
class child (parent):
def view(self):
print "this is child class"
print "a=",self.a," and b=",self.b
def only(self... |
2acae9e81e1b4e4d9eb804b9972febbfee484cf3 | nirajbawa/python-programing-code | /13_pytthon.py | 965 | 3.8125 | 4 | # practice set
# 2.
# while(True):
# name = raw_input("inter your name")
# mark = input("enter your marks")
# phone = input("enter your number")
# try:
# mark = int(mark)
# phone = int(phone)
# template = "the name of th student is {}, his marks are {} and pho... |
c4b070167650e5804d5203337a1e26d656ea6978 | nirajbawa/python-programing-code | /4_python.py | 1,270 | 3.953125 | 4 | #pratice set
# 1. make list of 7 fruit using user input
#user input
# f1 = raw_input("Enter fruit Number 1 ")
# f2 = raw_input("Enter fruit Number 2 ")
# f3 = raw_input("Enter fruit Number 3 ")
# f4 = raw_input("Enter fruit Number 4 ")
# f5 = raw_input("Enter fruit Number 5 ")
# f6 = raw_input("Enter fruit Numb... |
ac886fd8959715ebc061ba29118debb608ddf14c | SSeanin/data-structures-and-algorithms | /structures/tree.py | 4,118 | 3.8125 | 4 | class Node:
def __init__(self, data):
self.data = data
self.children = []
def add_child(self, data):
self.children.append(Node(data))
class StrictNode:
def __init__(self, data):
self.left_child = None
self.middle_child = None
self.right_child = None
... |
1b6ea806ee13af70efeaa04e2b15456ca396fb9a | guyincognito-io/cryptopals | /set1/challenge8.py | 264 | 3.546875 | 4 | import helper
with open("8.txt", "rb") as f:
for line in f:
ciphertext = line.strip()
if helper.checkForECBEncryption(ciphertext.decode('hex'), 16):
print "Found possible ECB Encrypted ciphertext: "
print ciphertext
|
6b0808ea4b78e02e0d6e792206bee00af8ad8d24 | zingkg/arkham-horror-assistant | /minify_xml.py | 275 | 3.5 | 4 | #!/usr/bin/python
import sys
def main(argv):
file = open(argv[0])
line = file.readline()
while line != '':
if not '<!--' in line:
print(line.strip(), end='')
line = file.readline()
if __name__ == '__main__':
main(sys.argv[1:])
|
8a69b86370d2b9f0961d97e27595e0d56c1a2654 | KhaledAbuNada-AI/Python-Course | /Numbers.py | 523 | 3.828125 | 4 | from math import *
number1 = 5
number2 = -3
my_list = [1, 10, 15, 100]
# Operations
print((number1 + number2) * 2)
print(number1 * number2)
print(number1 - number2)
print(number1 / number2)
print(number1 % number2)
# Numbers math
print(abs(number2))
print(pow(number1, 2))
# Numbers Max, Min
print(max(my_list))
print(... |
918a92d75f0bbf33e42246adc0d9624e6428a886 | KhaledAbuNada-AI/Python-Course | /Strings.py | 517 | 3.71875 | 4 | text = "\"Data Structuring\" is Very Important\n" \
" for any Programmer who wants to become\n" \
"a \"Professional\" in the field"
#Lower , Upper Strings
lower_text = text.lower()
upper_text = text.upper()
print(upper_text)
print(lower_text.islower())
print(text.isupper())
# Index Strings
index_text = ... |
bb95c7251ca5c6699244ea651deed2d7aaf749e3 | hoobui/mypython | /def.py | 288 | 3.609375 | 4 | # def gen_fib():
#
# s = int(input('please input a num: '))
# fib = [0,1]
# for i in range(s):
# fib.append(fib[-1] + fib[-2])
# print(fib)
#
# gen_fib()
# print('-' * 50)
# gen_fib()
# import sys
# print(sys.argv)
def pstar(n=30):
print('*' * n)
pstar(12)
|
b8b604b9aa550500df7a0057333de126e9c0115f | nuggy875/tensorflow-of-all | /5. linear regression.py | 1,682 | 3.640625 | 4 | # 5. linear regression
# 선형 회귀에 대하여 알아본다.
# X and Y data
import tensorflow as tf
# 학습을 할 data
#x_train = [1, 2, 3]
#y_train = [1, 2, 3]
# 그래프 빌드 #
# placeholder 사용
X = tf.placeholder(tf.float32, shape=[None])
Y = tf.placeholder(tf.float32, shape=[None])
# 계속 업데이트 되는 값은 Variable : trainable variable
# random_norma... |
eba2ffaeaf9b38da5f9ae60b785f406070267873 | nuggy875/tensorflow-of-all | /7. gradient descent algorithm.py | 1,147 | 4.125 | 4 | # 7. gradient descent algorithm
# 경사 하강법 이해를 목적으로 한다.
import tensorflow as tf
# 그래프 빌드 #
# 데이터
x_data = [1, 2, 3]
y_data = [1, 2, 3]
# 변하는 값
W = tf.Variable(tf.random_normal([1]), name='weight')
# 데이터를 담는 값 'feed_dict'
X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)
# Our hypothesis for linear model X * ... |
467bf2b94016e26a7c4e92a5a7fdc2623818a9aa | concpetosfundamentalesprogramacionaa19/practica220419-iancarlosortega | /problema2.py | 521 | 3.828125 | 4 | """
Problema 1 del laboratorio 1
autor @iancarlosortega
"""
#Declaracion de las variables por teclado
x = input("Ingrese la variable x: \n")
y = input("Ingrese la variable y: \n")
z = input("Ingrese la variable z: \n")
#Operacion para encontrar el valor de m
m = (float(x)+(float(y)/float(z)))/(float(x)-(float(y)/f... |
a483b1b0862163e0fbd84a837361b52608ca4c5e | adamhowe/Selection | /Revision exercise 2.py | 200 | 4.125 | 4 | #Adam Howe
#Revision exercise 2
#30/09/2014
age = int(input("Please enter your age: "))
if age >= 17:
print("You are old enough to drive")
else:
print("You are too young to drive")
|
21ae49cdd1d8966dab16659f9ccd70ff0f28e459 | shashikdm/Deep-Neural-Network | /DNN.py | 6,851 | 3.75 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 15 07:19:27 2018
@author: shashi
"""
import numpy as np
import matplotlib.pyplot as plt
#Class for trainer
class DNN:
def __init__(self, layers, neurons, X_train, y_train, learning_rate = 0.01, iterations = 5000, activation_hidden = "relu", acti... |
25293e5fc75005831882e6dcc66cfb43d04f74bc | jvpersuhn/Pythonzinho | /Aula19/Exercicio1.py | 1,416 | 3.734375 | 4 | # Aula 19 - 04-12-2019
# Lista com for e metodos
# 1 - Com a seguinte lista imprima na tela (unsado a indexação e f-string)
cadastroHBSIS = [ 'nome', ['Alex' ,'Paulo' ,'Pedro' ,'Mateus' ,'Carlos' ,'João' ,'Joaquim'],
'telefone',['4799991','4799992','4799993','4799994','4799995','4799996',... |
0d280f685edb91eb846721c56525aff826e53bcd | jvpersuhn/Pythonzinho | /Aula4/Arquivo.py | 998 | 3.578125 | 4 | import os
def escrever():
if not os.path.isdir('Dados'):
os.mkdir('Dados')
nome = input('Digite o nome: ')
idade = input('Digite a idade: ')
arquivo = nome + ',' + idade + '\n'
f = open('Dados/Aluno.txt','a')
f.write(arquivo)
f.close()
def ler_tudo():
f = open('Dados... |
e6dbeb843c51beb815314ee4afa57553328a295d | kaushal087/hangman | /isWordGuessed.py | 574 | 3.75 | 4 | ##############################################################
from imports import *
def isWordGuessed(secretWord,lettersGuessed):
for w in secretWord:
if w not in lettersGuessed:
return False
return True
##############################################################... |
c85c8d5d4fd42761939cf23b76eedd680b9e8df6 | Naveen1331/DSA_Algorithms | /array.py | 148 | 4.0625 | 4 | arr = [11, 22, 33, 44, 55]
print("Array is :", arr)
res = arr[::-1] # reversing using list slicing
print("Resultant new reversed array:", res) |
cfc5bdca05d896c71b3323bd0dd1e69632d7c418 | taras18taras/Python | /Prometheus/Python/5.3 (prometeus).py | 743 | 3.84375 | 4 | def super_fibonacci(n, m):
# за умовою перші m елементів - одиниці
if n<=m:
return 1
# інакше доведеться рахувати
else:
# ініціалізуємо змінну для суми
sum = 0
# і додаємо m попередніх членів послідовності, для розрахунку кожного з них рекурсивно викликаємо нашу функцію
... |
8249802cd86228639448f3564468a76d98b7e32c | taras18taras/Python | /Простые числа.py | 583 | 4.03125 | 4 | #Написать функцию is_prime, принимающую 1 аргумент — число от 0 до 1000, и возвращающую True,
# если оно простое, и False - иначе
def is_prime(number):
"""Эту функцию можно сильно оптимизировать. Подумайте, как"""
if number == 1:
return False # 1 - не простое число
for possible_divisor in range(2... |
c11e4094d06bf9532751d48952f1893bee903d12 | vazgenzohranyan/battleship | /utils.py | 3,464 | 3.609375 | 4 | import numpy as np
def find_neighbour(pos, board):
i,j = pos
for n in range(i - 1, i + 2):
for m in range(j - 1, j + 2):
if m in range(10) and n in range(10) and [i, j] != [n, m]:
if board[n][m] == 1:
... |
0f43f2db6e2f5157c833faf3c49247ce40e28f35 | juannlenci/ejercicios_python | /Clase03/tabla_informe.py | 2,119 | 3.609375 | 4 | #Informe.py
import csv
camion = []
precio = {}
costo_total=0.00
ganancia=0.00
balance=0.00
def leer_camion(nombre_archivo):
'''
Se le pasa el nombre del archivo a leer y devuelve
una lista con nombre, cajones y precio
'''
camion =[]
lote = {}
with open (nombre_archivo, "rt") as f:
... |
fb6dbaed129890aa171757a61785cf8084a32168 | juannlenci/ejercicios_python | /Clase07/informe.py | 2,425 | 3.609375 | 4 | #!/usr/bin/env python3
#%%Informe.py
from fileparse import parse_csv
def leer_camion(nombre_archivo):
'''
Se le pasa el nombre del archivo a leer y devuelve
una lista con nombre, cajones y precio
'''
with open(nombre_archivo, encoding="utf8") as file:
camion = parse_csv(file, select=["... |
6dcd8553477affaecb3e2f97f06af531129f9c04 | iuliarevnic/Gomoku | /helpers.py | 19,656 | 4.25 | 4 | '''
Created on 23 dec. 2018
@author: Revnic
'''
def checkRows(matrix):
'''
Function that checks whether there are 5 consecutive elements of 1 or 2 on any row of a given matrix
input: matrix
preconditions:-
output: 0 or 1 or 2
postconditions: If there are such 5 elements of 1, the fun... |
5cf606c2bc4fe03967952f96b4a42b2a41b846f4 | derickdev6/pybasic | /number_guesser.py | 597 | 3.71875 | 4 | import random
def run():
lifes = 5
rand_number = random.randint(0, 100)
while True:
if lifes == 0:
print('You lost :(')
break
print('Try to guess')
chosen = int(input(': '))
if rand_number > chosen:
lifes -= 1
print('> - Lifes... |
9f556c096bdca4d5a5657485875b17b2bbadfec5 | uoshvis/scrapy-examples | /src/xpath_examples/first_node.py | 1,396 | 3.59375 | 4 | from scrapy import Selector
def example_node():
# https://www.zyte.com/blog/xpath-tips-from-the-web-scraping-trenches/
# the difference between //node[1] and (//node)[1]
# //node[1] selects all the nodes occurring first under their respective parents.
sel = Selector(text="""
<ul class="list">
... |
241396d6059ddf3b6bdb521cd0c26f311d2ad4d6 | StefaRueRome/LaboratorioFuncionesRemoto | /potencia.py | 175 | 3.8125 | 4 |
def a_power_b(a,b):
prod=1
for i in range(0,b):
prod=prod*a
return prod
a=int(input("Ingrese la base: "))
b=int(input("Ingrese la potencia: "))
print(a_power_b(a,b)) |
4d74e0f3212ef18edd0fcc5b556d852baa403c4b | samp830/CS61A | /hw/hw01/quiz/quiz01.py | 983 | 4.0625 | 4 | def multiple(a, b):
"""Return the smallest number n that is a multiple of both a and b.
>>> multiple(3, 4)
12
>>> multiple(14, 21)
42
"""
lcm = max(a,b)
while lcm % min(a,b) != 0:
lcm = lcm + max(b,a)
return lcm
def unique_digits(n):
"""Return the number of unique digi... |
0aa845bb1209f9edb325fd573291d06afa48ee5c | alephramos/Hackwords | /hackwords.py | 375 | 3.640625 | 4 | # -*- coding: utf_8 -*-
import pandas as pd
import sqlite3,random
mypath = "Files/"
df = pd.DataFrame()
connection = sqlite3.connect('words.db')
cursor = connection.cursor()
query="select word,frecuency,length(word) as len from hackword order by frecuency desc"
df = pd.read_sql_query(query,connection)
print(df.sort(... |
74a6e558d7e5f7958973ebf3114e85bbfddb243d | alexescalonafernandez/service-locator | /service_locator/ioc.py | 5,218 | 3.96875 | 4 | from enum import Enum
class Singleton:
"""
Decorator for add singleton pattern support
@author: Alexander Escalona Fernández
"""
def __init__(self, decorated):
"""
:param decorated: class to convert to singleton
"""
self._decorated = decorated
def instance(... |
61fd094bc05f18dadbfb7a90ea641ae943504d44 | moldabek/WebDevelopment | /week8/lab7/5.functions/c.py | 88 | 3.53125 | 4 | def xor(a,b):
return a^b
a = [int(i) for i in input().split()]
print(xor(a[0],a[1]))
|
c181197fae9dcf631399298063c953dc071b271a | moldabek/WebDevelopment | /week8/lab7/1.input-output/a.py | 82 | 3.71875 | 4 | from math import sqrt
n = int(input())
m = int(input())
print(sqrt(n**2 + m**2))
|
0aca92e95b1a6d7260776caf897432ceabe3a2f8 | moldabek/WebDevelopment | /week8/lab7/2.if-else/c.py | 118 | 3.859375 | 4 | n = int(input())
m = int(input())
if n == 1 and m == 1 or n != 1 and m != 1:
print("YES")
else:
print("NO")
|
01aaf5aec0ca74fdfec8f95d7137979737c313a4 | JMH201810/Labs | /Python/p01320g.py | 1,342 | 4.5 | 4 | # g. Album:
# Write a function called make_album() that builds a dictionary describing
# a music album. The function should take in an artist name and an album
# title, and it should return a dictionary containing these two pieces of
# information. Use the function to make three dictionaries representing
# differe... |
64a30bf626d62b29ae78c9ac9435dc1ca5c929f3 | JMH201810/Labs | /Python/p01320L.py | 568 | 4.15625 | 4 | # l. Sandwiches:
# Write a function that accepts a list of items a person wants on a sandwich.
# The function should have one parameter that collects as many items as the
# function call provides, and it should print a summary of the sandwich that
# is being ordered.
# Call the function three times, using a di... |
a8da0ec50d16d15d4dca89edc8b794c440994bf5 | JMH201810/Labs | /Python/p01310i.py | 813 | 3.875 | 4 | # Pets:
# Make several dictionaries, where the name of each dictionary is
# the name of a pet. In each dictionary, include the kind of animal
# and the owner's name. Store these dictionaries in a list called pets.
# Next, loop through your list and as you do print everything you know
# about each pet.
Suzy ... |
ae64e924773c4243da27404de13e74ce2e973b56 | JMH201810/Labs | /Python/p01310j.py | 631 | 4.59375 | 5 | # Favorite Places:
# Make a dictionary called favorite_places.
# Think of three names to use as keys in the dictionary, and store one to
# three favorite places for each person.
# Loop through the dictionary, and print each person's name and their
# favorite places.
favorite_places = {'Alice':['Benton Harbor'... |
d6c1fa3d43547d59fa10a9e6d1e51e169dac8a18 | JMH201810/Labs | /Python/p01210i.py | 924 | 4.875 | 5 | # Pizzas: Think of at least three kinds of your favorite pizza. Store these pizza
# names in a list, and then use a for loop to print the name of each pizza.
pizzaTypes = ['Round', 'Edible', 'Vegetarian']
print("Pizza types:")
for type in pizzaTypes:
print(type)
# i. Modify your for loop to print a senten... |
e86600435612f88fbf67e3e805f0e21e6f0f51f8 | 23-Dharshini/priyadharshini | /count words.py | 253 | 4.3125 | 4 | string = input("enter the string:")
count = 0
words = 1
for i in string:
count = count+1
if (i==" "):
words = words+1
print("Number of character in the string:",count)
print("Number of words in the string:",words) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.