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
d85e661fcc6f61c320b8502dde6c185d5a50f78a
Struth-Rourke/cs-module-project-algorithms
/moving_zeroes/moving_zeroes.py
787
4.34375
4
''' Input: a List of integers Returns: a List of integers ''' def moving_zeroes(arr): # instantiating an empty, new_arr new_arr = [] # loop over items in the array for i in arr: # if the value of the item in the array is not zero if i != 0: # append the value to the list ...
649ec4c85497261ef93a870830f6d50a9fe5d550
FengXue618/hi
/hi.py
216
3.734375
4
name = input('请输入名字:') height = input('请输入您的身高身高:') weight = input('请输入您的体重:') print('嗨!',name) print('您的身高是:',height, ';您的体重是:', weight)
a968d583d4b1df361bde0473fb808f5c4b88e691
andrecoco/SSC0901_Trabalho01
/scan_ports.py
3,382
3.578125
4
import socket import argparse def _check_port(port, IP): ''' Testa se a porta passada por argumento está aberta no IP alvo. Retorna um booleano que indica se a porta está aberta ou não. ''' soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) soc.settimeout(0.1) code = soc....
3a9aaa5e252c042a99972e7a7146e17a9ddae7e4
parandkar/Python_Practice
/brick_game.py
933
4.15625
4
""" This is a solution to the problem given at https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/bricks-game-5140869d/ Patlu and Motu works in a building construction, they have to put some number of bricks N from one place to another, and starte...
efccbfe53442920f68dba5e07a6de8f05ded48a4
parandkar/Python_Practice
/seat.py
733
4.1875
4
""" This is a solution to the problem given at https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/seating-arrangement-1/ """ # Using dictionaries to deduce the front seats and seat type facing_seats = {1:11, 2:9, 3:7, 4:5, 5:3, 6:1, 7:-1, 8:-3, 9...
625c2fb420c9fb2670a4bf01db08aaa52ccc5080
parandkar/Python_Practice
/count-divisors.py
694
4.1875
4
""" This is a solution to the problem given at https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/count-divisors/ You have been given 3 integers - l, r and k. Find how many numbers between l and r (both inclusive) are divisible by k. You do not need ...
f667235080283f91a309fddd4844ea409719ef13
KevinEca/AnalyseDunesFluviales
/TraitementImage/Point.py
458
3.609375
4
class Point(): def __init__(self, Xpoint, Ypoint): self.CoordonneeX = Xpoint self.CoordonneeY = Ypoint def getXpoint(self): return self.CoordonneeX def getYpoint(self): return self.CoordonneeY def getCoordonnees(self): return s...
a4cfcbfcad47b05b4257e2251ba015f2226761ae
chuene-99/Python_projects
/mostwords.py
410
4.25
4
#program that counts the most common words in a text file. file=open(input('enter file name: ')) list_words=list() dict_words=dict() for line in file: line=line.rstrip() line=line.split() for word in line: dict_words[word]=dict_words.get(word,0)+1 for k,v in dict_words.items(): list_wo...
fdfe2bdae837d1b06840dbf14175d27ad01ba9ae
rednikon/Python
/Docstrings/functions_B.py
927
3.796875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jan 29 21:32:44 2019 @author: veemac Our second module. Calculates volume and area of a box. We define two functions: Volume and Area """ # Pylot: vmcclur1 Vee __author__ = 'vmcclur1' def volume(w, d, h): """Returns the volume of a box with d...
744f607a516a3d874bd33b80c8b599a75e18e2a2
rednikon/Python
/String-Functions/mymodB.py
937
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Feb 9 17:21:10 2019 @author: veemac """ COMMA = ',' SPACE = ' ' BLANK = '' PERIOD = '.' name = "Alexandria Ocasio-Cortez" def initials(name): """Given a name returns the initials. >>> initials('Elon Reeve Musk') 'E.R.M.' >>> initial...
3a43641f7ec1f07e6a90f6f7e83944fa8586424a
rednikon/Python
/String-Functions/mymodA.py
1,051
3.71875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 12 12:48:38 2019 @author: veemac """ """This is my mymodA module in my mynamespack package. It defines some functions that create acronyms. """ BLANK = '' # First, we define two slightly different functions, acronym1 and acronym2. def acron...
3d6db2336c4eeeb4ce337112e89ad992207946f5
Igor-Panarin/Panarin-z-2
/Python_3/Python_3.py
837
3.515625
4
import os def task(file_name): k = 0 if not os.path.exists(file_name): print("There is no file") return False, False with open(file_name, "r") as f: for line in f: for el in line.split(): try: num = float(el) if k ...
cc8234796c577610bd2bb14a2605e3e8196c8362
tatiana-ediger/ds4400-code
/homework2/gradient-descent.py
3,835
4.0625
4
import numpy as np import matplotlib.pyplot as plt import math as m from mpl_toolkits.mplot3d import Axes3D # The function to be graphed def f(x1, x2): return ((-2 * x1 * x1) - (3 * x1 * x2) + (2 * x2 * x2)) * np.sin(x1) # calculates the gradient of a tuple containing two points by returning a tuple with the de...
a20d7bce81bd8d7073d62ab8c7d0535a94b60e69
CiroBarros/OCW-MIT-Introduction-to-Computer-Science-and-Programming-in-Python
/PSET1b.py
962
3.90625
4
# -*- coding: utf-8 -*- """ Created on Fri Sep 11 15:03:28 2020 @author: Ciro Barros """ annual_salary = float(input("Enter your annual salary: ")) portion_saved = float(input("Enter the percent of your salary to save, as a decimal: ")) total_cost = float(input("Enter the cost of your dream home: ")) semi_a...
5e64bf44dcf750d7a2d5c7da057fcf06eb66f004
porkpiie/pythonweek
/tryblock.py
388
4.03125
4
try: no1=int(input("Enter first integer: ")) no2=int(input("Enter second integer: ")) result = no1/no2 print("Result is", result) except ValueError: print("Please enter only numbers: ") except ZeroDivisionError: print("What are you doing? Don't divide by zero") except Exception: print("Fa...
0c87298fdf74c16532b8915f4c3e40cee15f1c55
porkpiie/pythonweek
/wordlistreverse.py
198
3.734375
4
msg=input("Enter you next message: ") word="" i=len(msg)-1 while i >= 0: if msg[i] == " ": print(word) word = "" else: word = msg[i] + word i=i-1 print(word)
fcc372e7653aa7f6a9be6f7bd264580d4c2dd45b
porkpiie/pythonweek
/results3.py
230
3.90625
4
Phy = input("Enter Physics score:") Che = input("Enter Chemisry score:") Mat = input("Enter Maths score:") total= int(Phy)+int(Che)+int(Mat) per=(total/450*100) print("Total score is:",total) print("Percentage is:",int(per), "%")
fdb72f35010db8daa25711780f4dd64abd8f8ab0
porkpiie/pythonweek
/looping1.py
63
3.5625
4
a=1 while a<=10: print("I hate you my friend") a=a+1
a2c58ea778e8581d580dff71681023bb0b2f53e0
porkpiie/pythonweek
/asciicheck.py
319
4.125
4
alpha=input("Enter any letter: ") if ord(alpha)>=65 and ord(alpha)<=90: print("Capital letter") else: if ord(alpha)>=97 and ord(alpha)<=122: print("Lower case") else: if ord(alpha)>=48 and ord(alpha)<=57: print("Digits") else: print("Any other character")
a6c81c911cda7b995456e893b71b400713a8c34d
ry-blank/Module-7
/basic_list.py
878
4.53125
5
""" Program: basic_list_assignment Author: Ryan Blankenship Last Date Modified: 10/6/2019 The purpose of this program is to take user input then display it in a list. """ def make_list(): """ function to return list of user input from function get_input() :return: returns list of user input ...
f6ea760ab1b8649e9a386f6da3f1f729bb49f9b3
megulus/projecteuler
/euler_helper.py
1,868
3.9375
4
''' Gathering some of the functions that will be generally useful to solving the Project Euler problems. ''' # read in a file line by line def get_file_lines(filename): lines = [] try: with open(filename, 'r') as my_file: for line in my_file: lines.append(line.rstrip()) ...
e25b29782e6260d60fbafdcb7edfa7c6b66eed83
FullStackToro/Usuarios_con_cuentas_bancarias
/main.py
2,125
3.796875
4
if __name__ == '__main__': class Usuario: def __init__(self, users, email): self.name = users self.email = email def make_deposit(self, monto, b): b.deposito(monto) print(self.name, '- Cuenta', b.type, '-> Deposito por:', '$', monto) retu...
8d022903c89a5f24d5b99aba8e273ecdce4c2bb2
Hail91/Algorithms
/recipe_batches/recipe_batches.py
1,683
4.125
4
#!/usr/bin/python import math test_recipe = { 'milk': 100, 'butter': 50, 'flour': 5 } # Test for PT test_ingredients = { 'milk': 132, 'butter': 48, 'flour': 51 } # Test for PT def recipe_batches(recipe, ingredients): batches = 0 # Initalize a batches variable to zero while True: # Using a while loop to keep...
1f40a8b00514b824c5801f877ae9ee42776f508d
aCuissot/Hands-On_Machine_Learning_Exercises
/4_Training_Models/4_Models.py
8,976
3.8125
4
import numpy as np import matplotlib.pyplot as plt # Linear Regression print("===== Linear Regression =====") X = 2 * np.random.rand(100, 1) y = 4 + 3 * X + np.random.randn(100, 1) X_b = np.c_[np.ones((100, 1)), X] # add x0 = 1 to each instance theta_best = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y) print(theta...
b8268e00f4f3675fc878d1ec5b7614247d2931bf
aCuissot/Hands-On_Machine_Learning_Exercises
/Keras/2_Functional_API/6_Residual_connection_on_convolution_layer.py
361
3.75
4
import keras from keras.layers import Conv2D, Input # For more info see Deep Residual Learning for Image Recognition pdf in Annexes # input tensor for a 3-channel 256x256 image x = Input(shape=(256, 256, 3)) # 3x3 conv with 3 output channels (same as input channels) y = Conv2D(3, (3, 3), padding='same')(x) # this ret...
89ea5f8682903ced9b8ef55bf6b2b4d6856dbe66
aCuissot/Hands-On_Machine_Learning_Exercises
/Keras/2_Functional_API/2_Multi_input_multi_output_model.py
2,133
3.546875
4
# here a vocabulary of 10,000 words and the sequences will be 100 words long (represented by integers import keras from keras.layers import Input, Embedding, LSTM, Dense from keras.models import Model import numpy as np headline_data = np.random.randint(10000, size=(100, 100)) labels = np.random.randint(10000) additio...
c84bda7be59492dc584a026eef6ad9226f7cb791
thomaswsu/GPS-Analysis
/main.py
6,421
3.625
4
import pandas # open csv files import utc import longlat import movement import os """ Don't forget to install pandas and geopy Usage path should be set to /~/GPS_Analysis/Manual Algorithm To run: python3 -i main.py """ if __name__ == "__main__": f = "" file_name = "" print("Welcome! Make sure your worki...
e1fbb0394458201d27b22d8df48b5df97b5e31c1
ShabnamSaidova/basics
/dogs.py
2,438
4.46875
4
class Dog(): """A simple attempt to model a dog""" def __init__(self, name, age): """Initialize name and age attributes.""" self.name = name self.age = age def sit(self): """Simulate a dog sitting in response to a command.""" print(self.name.title() + " is...
cb5b3c72a8482ce9be3b8b4991527eeada7c27fd
Marcus-Mosley/ICS3U-Unit4-03-Python
/squares.py
1,024
4.40625
4
#!/usr/bin/env python3 # Created by Marcus A. Mosley # Created on October 2020 # This program finds the squares of all natural numbers preceding the # number inputted by the user def main(): # This function finds the squares of all natural numbers preceding the # number inputted by the user # In...
5569b3ebb7178121e73978797d354b54308ca741
IonutPutinica/PythonRepo
/ControlFlow.py
437
3.703125
4
#if statements is_game_over=False p0xposition=0 #player x position e0xposition=3 #enemy0 x position e1xposition=5 #enemy1 x position p0xposition+=2 #increases player x pos by 2 if p0xposition==e0xposition: is_game_over=True #checks if the enemy0 and player position are equal, and, if so, stops the game elif ...
3c6c5c5559bdb2ac4fa4edef4a9e2c44efb5eda6
Nana1208/basic-python
/Tugas-1/Soal-3.py
380
3.796875
4
# x adalah nilai syarat kelulusan x=70 # a adalah hasil ujian teori a=90 # b adalah ujian praktek b=40 if a >= x and b >= x: print("Selamat, anda lulus!") if a >= x and b < x: print("Anda harus mengulang ujian praktek.") if b >= x and a<x: print("Anda harus mengulang ujian teori") if a < x and b < x...
416dbe8ce59d10e427c8dfce56fa78e802e45b06
lleoiu/nsidc0447-scripts
/read_one_month_cmc_swe.py
1,514
3.890625
4
# NSIDC # Sample program to read a single month from the CMC Monthly SWE averages # https://nsidc.org/data/nsidc-0447 # # Requires Python3 and the numpy and matplotlib libraries. # # To run: # python read_one_month_cmc_swe.py import numpy as np import matplotlib.pyplot as plt #Name of the file you wish to read in f...
fee5e804c2e78111a16d70ada0e247895a09557a
Mosfreds/vindinium_rl
/vindinium-python/vindinium/utils/heap_queue.py
955
3.65625
4
import heapq __all__ = ['HeapQueue'] class HeapQueue(object): '''A priority queue implementation (it uses the heapq builtin module). Based on http://www.redblobgames.com/pathfinding/a-star/implementation.html ''' def __init__(self): '''Constructor.''' self._queue = [] def is...
f29722cf52222891613b17941da367e1be925fdb
Mosfreds/vindinium_rl
/vindinium-python/vindinium/ai/minimax/state.py
1,936
3.78125
4
"""Contains State object.""" from . import simulation class State(object): """Represents a game state.""" def __init__(self, game=None): """Create state instance.""" if isinstance(game, State): self.last_move = game.last_move self.parent = game self._game =...
c0965866997cb3e838ca9fe96d3d06a141770b30
venkatesh-sivaraman/SPARCProteinAnalysis
/secondary_structure.py
3,747
3.765625
4
secondary_struct_helix = "helix" secondary_struct_sheet = "sheet" class Strand(object): """Defines a strand of a protein along with its metadata.""" def __init__(self, start, end, ids=[]): self.start = start self.end = end self.identifiers = ids def __repr__(self): return "Strand {}: {}-{}".format(self.ide...
49112217b892b9edbffb49dfc8f2450dc0ee4c3e
iansedano/codingame_solutions
/Skynet_revolution/dijkstra.py
1,792
3.8125
4
nodes = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] links = [[2, 6], [9, 7], [0, 7], [9, 8], [8, 2], [7, 1], [9, 2], [3, 1], [2, 5], [0, 8], [4, 1], [9, 1], [0, 9], [2, 1]] def dijkstra(n1, n2, nodes, links): '''Get shortest distance between two nodes Assumes unweighted linkes (i.e. each link's value is 1) ''' no...
b18eda77ffe0121752bb93beb291eab3184f0df2
Udayin/Flood-warning-system
/floodsystem/flood.py
1,586
4.25
4
# -*- coding: utf-8 -*- """ Created on Tue Jan 24 18:01:03 2017 @author: Rose Humphry """ from floodsystem.utils import sorted_by_key def stations_level_over_threshold(stations, tol): ''' a function that returns a list of tuples, where each tuple holds (1) a station at which the latest relat...
28190f850f3fa962ed4f44ff7b96cef4657bdb69
Udayin/Flood-warning-system
/Task1b.py
587
3.734375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jan 31 11:30:59 2017 @author: udayinadukia """ from floodsystem.geo import stations_by_distance from floodsystem.stationdata import build_station_list stations = build_station_list() def distance(): #Defining Function stations = ...
82f636a96329a840d37293af9387315895d17805
yohanesadityaa/basic_python
/inputuser.py
65
3.5
4
name = input() #kalau int pake , print ("Your name is :" + name)
1cbf3d0ae3da05f9d711570a99ce76ed9b153877
yohanesadityaa/basic_python
/Tugas-2/Soal-1.py
925
3.71875
4
import os nama = [] telepon=[] awal = 0 while True: print ("Selamat Datang!") print("--Menu--") print (" 1.Daftar Kontak\n 2.Tambah Kontak\n 3.Keluar") pilihan = int(input("Masukkan Pilihan\t: ")) os.system ('cls') if pilihan == 2 : os.system('cls') nama1 = input("Nama\t : ") ...
791183576d49dce59ee78edcee7f0d273ff34932
phantomnat/python-learning
/leetcode/graph/997.py
1,250
3.734375
4
# https://leetcode.com/problems/find-the-town-judge/ # easy # graph from typing import List class Solution: def findJudge(self, N: int, trust: List[List[int]]) -> int: # https://leetcode.com/problems/find-the-town-judge/discuss/242938/JavaC%2B%2BPython-Directed-Graph count = [0] * (N + 1) ...
a853d1d40b4cb445c732f580ad52495285cd544e
phantomnat/python-learning
/leetcode/easy/202-happy-number.py
787
3.515625
4
class Solution(object): def isHappy(self, n): """ :type n: int :rtype: bool """ return self.is_happy(n, {n: 1}) def is_happy(self, number, history = {}): if number == 1: return True # if n >= 10: n = number total = 0 w...
dac5c53688717dca28c153672858c8e9eff74457
phantomnat/python-learning
/leetcode/medium/120-evaluate-reverse-polish-notation.py
1,116
3.5625
4
class Solution: def evalRPN(self, tokens): """ :type tokens: List[str] :rtype: int """ num_stack = [] while len(tokens) > 0: t = tokens.pop(0) if t in ['+','-','*','/']: a = num_stack.pop(0) b = num_stack.pop(0)...
de314297b1dc58c231d8862c1ee1ed7a6c1e1e20
philhartmanonic/exercises
/primeFactors.py
594
3.859375
4
n = raw_input('> ') n = int(float(n)) factors = [] settled = [] counter = 0 primes = [] for i in range(2, n): if n % i == 0: factors.append(i) if len(factors) == 0: print "There are no prime factors" else: for i in range(2, n): prime = True for j in range(2, i): if i % j ...
576d32f477c89632fcef3070240fca77e7790009
ivan-marozau/Udacity
/daysBetweenDates.py
1,819
3.578125
4
# By Websten from forums # # Given your birthday and the current date, calculate your age in days. # Account for leap days. # # Assume that the birthday and current date are correct dates (and no # time travel). import time start = time.clock() def isLeapYear(year): if year%4 != 0: return False elif year%100 ...
95bba87d7c02b7648737046f8879aa58bbcf36d5
sanketkothiya/python-programe
/code excercise/new2.py
160
3.734375
4
av=5 x=int(input("enter the canday value ..")) i=1 while i<=x: if i>av: print("out of stock") break print("canday") i+=1; print("bye")
c330e68f24355d447f10544f210bebd187a1714f
sanketkothiya/python-programe
/code excercise/new1.py
153
3.65625
4
x=int(input("enter the number1")) y=int(input("enter the number 2")) z=x+y print('your ans is..') print(z) ch=input("enter the character ")[0] print(ch)
ffc1ae7860c8e5a58281cadd49126ea57280abc9
sanketkothiya/python-programe
/code excercise/new11.py
180
4.09375
4
n=int(input("enter the number")) temp=n r=0 while(n>0): d=n%10 r=r*10+d n=n//10 if(r==temp): print("its palindrop") else: print("its not palindrop")
e0dc7e8dbc4e904a691f6077bc751bd84b02d905
JeeZeh/kattis.py
/Solutions/leftbeehind.py
325
3.6875
4
cont = True while cont: a, b = list(map(int, input().split(" "))) if a == 0 and b == 0: cont = False break if a + b == 13: print("Never speak again.") elif a > b: print("To the convention.") elif a < b: print("Left beehind.") else: print("Undecide...
d933c6780de2eb793cbe5c3ee59fe12fd12505f7
JeeZeh/kattis.py
/Solutions/redrover.py
564
3.5
4
directions = input() complete = False length = len(directions) best_saved = 0 best_count = 0 best_sub = "" start = 0 end = int(length / 2) - 1 while end >= 0: nend = end while nend < length: sub = directions[start:nend] sub_len = len(sub) count = directions.count(sub) saved = co...
57d3c5b6670ba1b84e8c2c83200a9a4364b1e522
piyushsingariya/code-practice
/python/learnthehardway/Ex40.py
435
3.609375
4
class Song(object): def __init__(self, lyrics): self.lyrics = lyrics def sing_me_a_song(self): for line in self.lyrics: print line happ_bday = Song(["Happy birthday to you", "Happy Birthday to you", "Happy Birthday to you", ...
fd5982d54adcca536876f48003c814f73ea227f6
G3Code-CS/Algorithms
/making_change/making_change.py
2,643
4.375
4
#!/usr/bin/python import sys def making_change(amount, denominations): # we can initialize a cache as a list (a dictionary # would work fine as well) of 0s with a length equal to the amount we're # looking to make change for. cache = [0] * (amount + 1) # Since we know there is one way to ...
ee85943cab0f638a70deed17e8f310d5f63aaa2a
rodrigo-montenegro/fullStackPythonYJs
/polimorfismo.py
388
3.53125
4
class Tomate(): def tipo(self): print("Vegetal") def color(self): print("Rojo") class Manzana(): def tipo(self): print("Fruta") def color(self): print("Verde") # Funcion generica que recibe el objeto def funcion(obj): obj.tipo() obj.color() unTomate = Tom...
c56dea73383a332e312cbe833402bd7e39c4deb2
rodrigo-montenegro/fullStackPythonYJs
/listas.py
130
3.578125
4
lista = ["Harry", "Ron", "Hermione"] print(lista) lista.append("Draco") print(lista) lista.sort() print("Lista ordenada:", lista)
b532dfb97a7531093d003d7cb125699f7873f447
georgelembah/python-prewoek
/question3.py
183
3.859375
4
def max_num_in_list(a_list): max = a_list{0} for a in a_list if a > max: max = a return max print(max_num_in_list({1, 2, 3, 4, 5, 6, 7, 8, 9, 10}))
53015b4fc2b2908224be0fa113c6c8c5062b67d6
zwang04/SBitchRecognition
/src/main.py
2,721
3.59375
4
#import speech #import time # #response = speech.input("Say something, please.") #speech.say("You said " + response) # #def callback(phrase, listener): # if phrase == "goodbye": # listener.stoplistening() # speech.say(phrase) # print phrase # #listener = speech.listenforanything(callback) #while listene...
63ad3013c34010cca2206362be71755a198704fb
Magnetixaft/Daily
/CoinFlip.py
431
3.84375
4
#You have n fair coins and you flip them all at the same time. Any that come up tails you set aside. The ones that come up heads you flip again. # How many rounds do you expect to play before only one coin remains? num_rounds = 0 def flipCoin(n): global num_rounds num_rounds +=1 heads = n/2 tails = n/...
2d74ca543ef1164cd29249bfacdf09d990ac5c8a
ChristoffelDoorman/Kernel-perceptron
/kNN.py
2,811
3.6875
4
import numpy as np class kNN: def __init__(self, train_set, test_set, k): self.train_set = train_set self.test_set = test_set self.k = k def calc_distance(self, test_points): """ Calculate all Eucledian distances between training set a...
6be4adaa53477f17c0ff6fb40ac4fbe246b8764c
subreto-roy/Python
/OOP.py
1,231
4
4
class StoryBook: #class VARIable no_of_book=0 discount=0.5 #dander method def __init__(self,name,price,author_name,author_born,no_of_pages): # print('I am being called with instance/object creating') self.name=name self.price=price self.author_name=aut...
d557bd631855504ab945ae614f482cf9ed2dc319
subreto-roy/Python
/Magic method.py
1,174
3.84375
4
class Point2D: def __init__(self,x,y): self.x=x self.y=y def __repr__(self):#programmer/developer jonoi return f'Point2D({self.x,self.y})' def __str__(self):#normal people return f'Class: Point2D,' \ f'x:{self.x},y:{self.y}' def __add__(self...
14f2aa33e4dd708a02d1c2c9577f11e6e60926f8
subreto-roy/Python
/references.py
137
3.71875
4
import copy as cp def f(some_list): some_list.append('ok') x=[1,2,3] s=cp.copy(x) #a copy of the list is made f(s) print(x)
edb6878eae149426083d95d6518e8c3e40a13de8
subreto-roy/Python
/fibonaccy using recursion.py
116
3.90625
4
def fibonacci(n): if n<=1 : return n return fibonacci(n-1)+fibonacci(n-2) print(fibonacci(6))
8b380a261c6f9f71712c56ddd405cc36c49c3e3f
subreto-roy/Python
/printing the odds.py
224
4
4
def print_odd(some_list): new_list=[] for i in range(len(some_list)): if some_list[i]%2!=0: new_list.append(some_list[i]) return new_list a=[1,2,3,4,5,7] print(print_odd(a))
4b1c6c287fa5cc512afe5bd4d8b1589f461ac7eb
subreto-roy/Python
/pattern1.py
210
3.703125
4
row=int (input()) count=0 for i in range (0,row): for j in range(0,row-i-1): print(end=" ") count=count+1 for k in range(0, i+count): print("*", end= "") print(" ")
2f77577b1555b897b9d2aa2bd8bd3557ab0789e0
balapitchuka/python-utilities
/console/split-text-file.py
3,217
3.734375
4
#!/usr/bin/env python3 import os import shutil import sys from typing import List # list to parts, split list # split text file to bunch of parts: # - { text file } { amount of expected parts } # - { text file } { start line :included } { end line :included } def count_amount_of_lines(path_to_file): with open(pa...
de000242afafc8fa391cce60c3ad3a0f3c356c15
balapitchuka/python-utilities
/operator-override.py
571
4.46875
4
# example of overriding operators # operator overriding class Value: def __init__(self, value): self.value = value # - __sub__, * __mul__, ** __pow__, / __truediv__, // __floordiv__, % __mod__ # << __lshift__, >> __rshift__, & __and__, | __or__, ^ __xor__, ~ __invert__ # < __lt__, <= __le__, ==...
37e585267f33ab6d5efcdb2485f02097cbee5ea5
balapitchuka/python-utilities
/decorator/custom-decorator.py
1,867
3.71875
4
# ---------------------------------------- # function without parameters def my_simple_decorator(function): def simple_decorator(): return_value=function() print(f"simple wrapper: {return_value}") return return_value return simple_decorator @my_simple_decorator def summarize2()-...
663f7d2a2603e8ece1218b72b7f9f9a98dabfaa2
balapitchuka/python-utilities
/db-key-value/shelve-example.py
532
3.796875
4
import shelve class Example: def __init__(self, value): self.value = value def __str__(self): return self.value database = shelve.open("my-db-file") database["simple_string"] = "this is simple string into DB" database["int_value"] = 5 database["complex_value"] = Example("this is simple object") ...
af9aa23e13a54925648f76c6b241ccd4b716a7f2
balapitchuka/python-utilities
/functions-built-in/iterable.py
1,769
3.546875
4
#!/usr/bin/env python3 print(">>> all <<<") # --- # True print(all([True,True,True])) # True print(all([1,2,3])) # True print(all(["one", "two", "three"])) # False print(all(["one", None, "two", "three"])) # False print(all([1,0,2,3])) print(">>> any <<<") # --- # True print(any([True,False,False])) #...
5c67f678997b00118ee6cac22d2c66d64b5f955d
balapitchuka/python-utilities
/object-copy.py
253
3.90625
4
# shallow copy a = {1: [1,2,3]} b = a.copy() a[1].append(4) print(a) # {1: [1, 2, 3, 4]} print(b) # {1: [1, 2, 3, 4]} import copy # deep copy a = {1: [1,2,3]} b = copy.deepcopy(a) a[1].append(4) print(a) # {1: [1, 2, 3, 4]} print(b) # {1: [1, 2, 3]}
a326a98def0d0a6ee12a5adb9e9df634831a4e14
balapitchuka/python-utilities
/enum/enumeration.py
950
3.703125
4
import enum print(">>> just a simple static elements") class Furniture(enum.Enum): Table = 1 Chair = 2 Briefcase = 3 print(Furniture.Table) print(Furniture.Chair) import enum print(">>> extends from enumeration") class WriteTools(enum.Enum): # Pencil, Pen = range(2) Pencil = 1 Pen = 2 print(WriteTools.Pen...
0c70bb4f699698b8fe48029d5599e66c5d52c333
verarararaya/Assignments
/python programming/LaiYili_Week2.py
2,675
4.03125
4
# -*- coding: utf-8 -*- # Week 1 - Assessed exercises import math # Q1 Write a for loop to compute the sum of x^2 for x from 0 to 8. What is the # value of this sum? xsum =0 # the start of sum of x^2 for i in range(0,9): xsum = i*i+xsum print(xsum) # Ans:the sum is 204 # Q2 Define a function (addition) that return...
1f1ca977d3e525da5738b486eaae017adafd928a
DamianValle/RL2020
/lab1/problem_3/problem_3.py
1,651
3.53125
4
"""!@brief Lab 1, Problem 3 of the 2020/2021 Reinforcement Learning lecture at KTH. @file Problem 3 solution. @author Martin Schuck, Damian Valle @date 26.11.2020 """ import numpy as np import town as tw import matplotlib.pyplot as plt def main(): town = np.array([[0, 0, 0, 0,], [0, 2, 0, 0...
f676a3b50775acbaf0e5bfd51cb1cb8a0bb86211
chinmaydas96/Data-Structures-and-Algorithms
/1.Algorithmic_Toolbox/week-3/assignment/different_summands.py
470
3.828125
4
# Uses python3 import sys def optimal_summands(n): summands = [] #write your code here high = n low = 1 while (high > 0): if (high <= 2 * low ): summands.append(high) high -= high else: summands.append(low) high -= low low += 1 return summands if __na...
b001708ccb2420979bc683504c002c4f685ac524
chinmaydas96/Data-Structures-and-Algorithms
/1.Algorithmic_Toolbox/week-3/assignment/4.covering_segments.py
825
4
4
# Uses python3 from collections import namedtuple Segment = namedtuple('Segment', ['start' ,'end']) def optimal_points(segments): points = [] # write your code here segments = sorted(segments, key=lambda segment: segment.end) current = segments[0].end points.append(current) for s i...
1fe9f9d739bbe000f39ef64b8dda992c86b4f7e1
chinmaydas96/Data-Structures-and-Algorithms
/1.Algorithmic_Toolbox/week-2/task/5.Huge_Fibonacci_Number.py
730
3.671875
4
# Uses python3 no = input().split(" ") n = int(no[0]) m = int(no[1]) def fib(n): if n < 2: return n a, b = 0, 1 for i in range(n): a, b = b, a + b return a def get_length(m): if m <= 1: return m index, i = 0, 0 a, b = 0, 1 while True: a, b = b, ((a + b...
03be33da2c6c245db64ca2f12a96f8eace8982ce
ValenCardona/Python
/Cadena.py
8,624
3.984375
4
print ("\tValentina Cardona Ligarreto \n\tMisión TIC 2022 \n\tUniversidad El Bosque \n\tMetodos de Cadenas") reiniciar = "si" while reiniciar == "si": print ("\n\t\t Universidad El Bosque - Misión TIC") print ("\n\t\t Aplicacion con metodos de cadenas") cadena = input("Digite una secuencia de caracteres...
6acfbfa8125f6a0c5cabd012e64e755672363a0b
ValenCardona/Python
/Operaciones_basicas.py
1,834
3.921875
4
print ("\tValentina Cardona Ligarreto \n\tMisión TIC 2022 \n\tUniversidad El Bosque \n\tRealizar las operaciones matemáticas basicas: suma, resta, multiplicación, división, residuo y potencia.") numero1 = int(input("\tDigite el primer número: ")) numero2 = int(input("\tDigite el segundo número: ")) numero3 = 5 suma =...
6d5f1c4ee65ac200dd1e86a8a350158a7a5c1d8f
ValenCardona/Python
/Archivos.py
1,842
3.609375
4
print ("\tValentina Cardona Ligarreto \n\tMisión TIC 2022 \n\tUniversidad El Bosque \n\tEjercicios Archivos ") from io import open print ("\n\t\t1. Crear un archivo que inserte diez líneas en un archivo de nombre archivo2.txt ") cantidad = int(input("\n\tDigitela la cantidad de persona que desea ingresar")) archivoTe...
7adf5d98ed01bce7ebfdf2236f592f84df17d7b5
PrimeTimeTeam/Prime-Time-Project
/index_GUI_test.py
193
3.671875
4
def brain(input): list = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53] for x in list: if x == input: return True return False #print (brain(17))
a1049bb53c4840e111bbd84a4a3416ac0a93563d
sharco-code/2DAM
/business-management-systems/python/module_1-4/lab7.py
302
3.875
4
year = int(input("Enter a year: ")) if(year < 1582): print("Año no valido") else: if(year % 4 != 0): print("Año no valido") elif(year % 100 != 0): print("Año bisiesto") elif(year % 400 != 0): print("Año no bisiesto") else: print("Año bisiesto")
8e80042a277109d911670f5be8d4f7a1f2463668
sharco-code/2DAM
/business-management-systems/python/module_1-4/lab4.py
83
4.03125
4
x = float(input("Enter value for x: ")) y = 1/(x+1/(x+1/(x+1/x))) print("y =", y)
d9850e51ecdcc2467c6bb5043497f7dd1f59a711
ellenfurman/mat1
/add.py
109
4.03125
4
num1=int(input("enter integer number: ")) num2=int(input("enter integer number: ")) sum=num1+num2 print(sum)
96bf5d6a36f3c06ab89c6577c862353aee324158
RANJEET16520/InterviewBit
/Arrays/Spiral Order Matrix.py
1,198
3.875
4
# https://www.interviewbit.com/problems/spiral-order-matrix-ii/ ''' Problem: Given an integer A, generate a square matrix filled with elements from 1 to A2 in spiral order. Input Format: The first and the only argument contains an integer, A. Output Format: Return a 2-d matrix of size A x A satisfying the spiral ord...
8cdd86426b8506c3aec5a4d8af17e2b30537124a
RANJEET16520/InterviewBit
/Maths/Excel Column Title.py
461
3.9375
4
# https://www.interviewbit.com/problems/excel-column-title/ ''' Problem: Given a positive integer, return its corresponding column title as appear in an Excel sheet. For example: 1 -> A 2 -> B 3 -> C ...... 26 -> Z 27 -> AA 28 -> AB ''' def Excel(A): if A == 0: return 0 else: ans = "" while A > 0: x = A ...
f0a41ca75cbdb063311136dca240fa3ae7b70120
RANJEET16520/InterviewBit
/Maths/FizzBuzz.py
249
3.921875
4
def FizzBuzz(A): ans = [] for i in range(1,A+1): if i%3==0 and i%5==0: ans.append('FizzBuzz') elif i%3==0: ans.append('Fizz') elif i%5==0: ans.append('Buzz') else: ans.append(i) return ans n = int(input()) print(FizzBuzz(n))
7199960d5d2ed3584949bd41e4205e4fb28782b0
pythoner256/Python-
/算法/希尔排序.py
932
3.78125
4
def func(alist): """ 希尔排序先将列表以一个步长隔断成几个序列,之后将各个序列还是按照插入排序进行排序; """ n = len(alist) gap = n//2 while gap > 0: # 最外层循环控制gap for j in range(gap, n): # 让第一个序列索引从gap步长开始和前面的元素进行判断 i = j while i > 0: if alist[i] < alist[i-gap]: ...
b66120cb2ee3404d3785c854f23984366143684a
pythoner256/Python-
/Python复习整理/review_advance.py
6,511
4.09375
4
# Pyhton 高级编程 不定期更新 """== 和 is 判断两个对象是否相等和是否指向同一个对象""" a = [1, 2] a = b a == b # True 二者元素相同 a is b # True 二者指向同一个对象 a = [1, 2, 3] b = [1, 2, 3] a == b # True 二者元素相同 a is b # False 两个对象并不是指向同一个对象 # 需要注意的是,在Python整型中-6到257这个数值之间是相同的 """深拷贝和浅拷贝""" # 浅拷贝 a_list = [1, 2] b_list = a_list # b_li...
bb16ff5a2253b319db4ee29203e01c767d505dde
pythoner256/Python-
/python standard lib/random.py
461
3.71875
4
import random """random模块""" # random.random 随机产生一个0-1之间的浮点数 # # random.randint(a,b) 随机生成[a,b]之间的一个整数 # # random.randrange(a,b,step) 随机产生的数之间间隔是step,也就是等差 # # # random.sample(range(10),2) 从range(10)中随机产生2个数的列表 # # random.choice(sequence) 从特定序列中随机产生一个元素,这个序列可以是元组,列表,字符串
2bbcea90e037c8465f38d13699a2e4c768aca391
pythoner256/Python-
/Python基础/8.10/super继承.py
609
3.953125
4
class A: def __init__(self, name, age): self.name = name self.age = age class B(A): def __init__(self, name, age, gender, school, professor, about): # 子类__init__方法可以初始化自己的属性,但是要有父类的属性 # super().__init__(name=name, age=age) super().__init__(name, age) # 这里继承必须要写上父类的属性...
dc80c11937f7c56683556b60f211fd3504539c60
Avulaparvathi/pythontraining
/rock paper sc game.py
1,246
4.15625
4
p1=input("enter the choice") p2=input("enter the choice") while True: if p1==p2: print("tie") elif p1=="rock": if p2=="scissors": print("congratulatipns to p1") else: print("congratulation to p2") elif p1=="paper": if p2=="rock": print("congratulations to p1") else: ...
b575e43f3645df3fabf599db8179cf715f7515f0
bobbygos/GaN_interview_program
/interview_program/main.py
844
3.796875
4
import fizzBuzzPlus if __name__ == '__main__': fizzBuzz = fizzBuzzPlus.FizzBuzzPlus() for x in range(100): # Wanted to start at 1. num = x+1 fizzBuzzFlag = False if fizzBuzz.multipleOfThree(num) or fizzBuzz.containsThree(num): # Default is /n. This waits for the endl...
0dfd97b329d8a1ba48ffff5cf7e03ef335be092a
bwbeach/smugmug-to-b2
/smugmug_to_b2/util.py
2,675
3.515625
4
# # File: util # from typing import Callable, Generator, Generic, Iterable, Iterator, Union, TypeVar K = TypeVar('K') T = TypeVar('T') class Reader(Generic[T, K]): """ Holds the current value from an iterable in '.current'. None indicates no more values. advance() moves to the next value. """ ...
9e0fa323565a4e8bc44a52623a50d608690d9370
NickStupich/galcon
/MyBot2.py
7,462
3.65625
4
#!/usr/bin/env python # """ // The DoTurn function is where your code goes. The PlanetWars object contains // the state of the game, including information about all planets and fleets // that currently exist. Inside this function, you issue orders using the // pw.IssueOrder() function. For example, to send 10 s...
e9bae5833dbc6c834ba28605252399bdd18fea97
rukmangadhank/rukman
/alphabets.py
198
3.6875
4
from sys import argv script,num1,num2,num3=argv if (num1 >= num2) and (num1 >=num3): print(num1) elif (num2 >= num1) and (num2>=num3): print(num2) else: print(num3)
e92ea6086f7af8ffcc0bfc2da8c9ff79c9a6fcb9
devkapilbansal/Restaurant-Analysis
/restaurant.py
8,415
3.96875
4
import sys import matplotlib.pyplot as plt import pandas as pd df = pd.read_csv("restaurant.csv", index_col=0) ############################################################# # Funtion to perform Data Visualization on Restaurant Dataset ############################################################# def vi...
2bbc0054bb5fd19bca6902d99c9aafa032425356
sowjanyakandula/Content-Aware-Image-Resizing
/energy_image.py
6,040
3.890625
4
""" This is the primary step in the seam carving algorithm. we find the seam based on the energy of an image. If we run this module in isolation, the energy of an image will be visualized as a grayscale heat map, with brighter spots representing pixels """ import sys from utils import Color, read_image_into_array,...
8bbdb6e9157642e89e718d51a76f674d5fa177be
ethirajmanoj/Python-14-6-exercise
/14-quiz.py
1,062
4.1875
4
# Create a question class # Read the file `data/quiz.csv` to create a list of questions # Randomly choose 10 question # For each question display it in the following format followed by a prompt for answer """ <Question text> 1. Option 1 2. Option 2 3. Option 3 4. Option 4 Answer :: """ import csv score = 0 scor...
55497f19f059c7a12b13501ceb1afe5b05f08df0
isabellagmz/ECE143HW5
/word_processing.py
4,004
4.25
4
# Isabella Gomez A15305555 # ECE143 HW5 # imports: import re def get_average_word_length(words): ''' This function takes in a list of words and computes the average length of the words in the list. :param words: list of words :return: average length of the words in the list ''' # check t...
34294fa5353dd747fa74f228d9360539054a5522
NamanLad/python_codes
/CollegeAssignments/shiftAndAdd.py
970
3.640625
4
# aim is to multiply q and m """ using full adder logic for adding a, b, c sum = a XOR b XOR c carry = ab + c*(a XOR b) """ def add(a, m): c = 0 for i in range(length-1, -1, -1): num1 = int(a[i]) num2 = int(m[i]) sum = num1 ^ num2 ^ c carry = num1 & num2 | (c & (num1 ^ num2)...