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
a82bd7fba196142b95745e0fef2c83054557c2cb
ErenBtrk/Python-Fundamentals
/Numpy/NumpySortingAndSearching/Exercise1.py
407
4.5
4
''' 1. Write a NumPy program to sort a given array of shape 2 along the first axis, last axis and on flattened array. ''' import numpy as np a = np.array([[10,40],[30,20]]) print("Original array:") print(a) print("Sort the array along the first axis:") print(np.sort(a, axis=0)) print("Sort the array along the last ax...
275e3878c56065e3efca85f698bd8ee01fbf262d
ErenBtrk/Python-Fundamentals
/Numpy/numpy-exercises3.py
144
3.640625
4
# 3-Create a numpy array with values increasing by fives between 50-100 import numpy as np np_array = np.arange(50,100,5) print(np_array)
58663499fffaf60cef97fe20896338a49cf40112
ErenBtrk/Python-Fundamentals
/Pandas/PandasDataSeries/Exercise8.py
468
4.3125
4
''' 8. Write a Pandas program to convert the first column of a DataFrame as a Series. ''' import pandas as pd dict1 = { "First Name" : ["Kevin","Lebron","Kobe","Michael"], "Last Name" : ["Durant","James","Bryant","Jordan"], "Team" : ["Brooklyn Nets","Los Angeles Lakers","Los Angeles Lakers","...
234c74c2ffe78d917bda739d3f6dc0870931ea84
Yh199501/isdhw
/03/03.py
406
3.75
4
def zheban(list,x): start=0 if list[0]==x: return 0 end=len(list)-1 while(start==end): if(x==list[start]): return start else: return error if(start<end): middle=start+(end-start)//2 if list[middle]<x: start=middle+1 ...
924527cad45d7f7c910fc4658a0b60b50517dbc3
anshu9/LeetCodeSolutions
/easy/add_digits.py
796
4.21875
4
""" Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. For example: Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. Follow up: Could you do it without any loop/recursion in O(1) runtime? """ def add_digits_...
412666896355872d9db4ffa9a74816d7541ba1e9
georgreen/bootcamp2
/day2/lab/binarySearch.py
1,756
3.78125
4
class BinarySearch(list): def __init__(self,length_list, step_list): ''' input -> length_list : number of elem in list step_list : difference between members of list creates a list with length elements ''' self.extend(list(range(step_list, (length_list * step_l...
d8601e88783790f690dfa9dd73aee6bc2f7d4527
damiangene/Practice-assignments
/2. Control, For, If, While/Firstday.py
900
4.125
4
year1= int(input("What is the first year?")) year2= int(input("What is the second year?")) for year in range(year1,year2+1): #day = R(1 + 5R(Year − 1, 4) + 4R(Year − 1, 100) + 6R(Year − 1, 400), 7) day6 = 6*((year - 1)%400) #print (day6) day4 = 4*((year - 1)%100) #print (day4) day5 = 5*(...
ef4e8286ae8ba62c9d5f5bb90a9978f80b871bda
damiangene/Practice-assignments
/3. Control, For, If, While/Column.py
209
4.03125
4
def input_check(): n = int(input("Select a starting number: ")) if n <= -6 or n >= 2: input_check() else: for numbers in range(n,n+41,7): print (numbers) input_check()
7fc03e29adad04d842ef58b058644ccffbc27349
AnnDing/DemosTensorboard
/embedding_visualization/visual_mnist.py
1,526
3.578125
4
""" A demo to visualize the vectors of MNIST images in tensorboard. We use the projector plugin in tensorboard. 1. create a variable A for the vectors to visualize 2. initialize the variable A, and save it 3. save metadata to record labels for each vectors in A Howto: python visual_mnist.py tensorboard --logdir logs ...
152f4fbb9bb4ed32f0035217154a23fc5f3f37bd
stompesi/MachineLearning
/code/Naive Bayesian/MachineLearningInAction/practice.py
2,980
3.75
4
# 모든 문서에 있는 모든 유일한 단어 목록을 생성한다. def create_vocab_list(data_set): # 비어있는 집합 생성 vocab_set = set([]) for document in data_set: # 연산자 | 는 두 개의 집합 유형의 변수를 합치는 데 사용하는 연산자. # 두 개의 집합 통합 생성 # ex) {'a', 'b', 'c'} | {'c', 'd', 'e'} # -> {'a', 'b', 'c', 'd', 'e'} vocab_set =...
1a6ad96efa774add7d87690272e8140da409ca54
gabewonders/learn-to-code
/python/introducing-python/ex3.py
202
3.75
4
name = raw_input("What is your name? ") years_worked = raw_input("How many years have you worked for Chevron? ") print "Hi my name is %s. I have worked for Chevron for %s years." % (name, years_worked)
5e64d9a12aea6bf9a987b82dc4ec368843833046
ayushvrma/opencvtutorial
/basic operations on img.py
747
3.578125
4
import numpy as np import cv2 img= cv2.imread('messi5.jpg') img2=cv2.imread('opencv-logo.png') print(img.shape) #returns a tupple of rows columns and channels print(img.size) #returns the total number of pixels accessed print(img.dtype) #returns Image datatype b,g,r=cv2.split(img) #to split image into 3 channels im...
6966d510906c2f56f78a88e081f47dead8fb9a81
t-mertz/slurm_utils
/sutils/utils/sort_output.py
714
3.5
4
# This file is part of the SLURM utility # implements a file sorting routine from __future__ import print_function import numpy as np def sort(infilename, outfilename): """Sort a file with lines 'index val1 val2 val3 val4 ...' along ascending index. This can be necessary for example when MPI is handling...
9fb945d19fdf4d09dd5c90721773cb3f33696ff2
PHUICMT/Shift-characters-python-ODDS
/ODDS.py
4,393
3.609375
4
#อันดามัน นพนภาพร [ภูเขา] def enshift_right(str): #เข้ารหัสข้อความ new_text = '' for i in str: t = chr(ord(i) +1) new_text = new_text+t #print(new_text) return new_text def deshift_right(str): #ถอดรหัสข้อความ new_text = '' for i in str: t = chr(ord(i) -1) ...
844a559dfd3eb3b031c6e328a6a5347990a8d47d
juliancomcast/100DaysPython
/Module2/Day19/day19_fileIO.py
1,922
3.5625
4
import this import os print(os.getcwd()) os.chdir('/Users/julian/100DaysPython/Module2/Day19') #decrypt the "Zen of Python" zen = "" for letter in list(this.s): if letter in list(this.d.keys()): zen += this.d[letter] else: zen += letter print(zen) print("=" * 26) #the open() function allows ...
67334c8d4146f1c8ba8580a5c95039a163e4bec2
juliancomcast/100DaysPython
/Module1/Day09/day09_indexing.py
1,121
4.5
4
#specific items can be retrieved from a list by using its indicies quotes = ["Pitter patter, let's get ar 'er", "Hard no!", "H'are ya now?", "Good-n-you", "Not so bad.", "Is that what you appreciates about me?"] print(quotes[0]) print(f"{quotes[2]}\n\t {quotes[3]}\n {quotes[4]}") #slicing uses the format [start:stop:s...
4fe297d8354295929f95c9f78e80dd4c90e131d1
juliancomcast/100DaysPython
/Module1/Day11/day11_augAssign.py
811
4.59375
5
#An augmented assignment improves efficiency because python can iterate a single variable instead of using a temporary one. #There are several types of augmented assignment operators: # += : Addition # -= : Subtraction # *= : Multiplication # /= : Division # //= : Floor Division # %= : Remainder/Modulus # **= : Exponen...
8946097579929b43bfc3d47482f64d26ce8aa7da
hiqua/scripts
/trg
613
3.546875
4
#!/usr/bin/env python3 """ If there is only one argument, try to run rg on it. In case of failure, try to rerun rg on all adjacent transpositions of the string. Useful in case of a simple typo. """ import sys from subprocess import run, CalledProcessError if __name__ == '__main__': if len(sys.argv) == 2: ...
6b036d8879f329ee40aeace04a15863212f13763
vvaldes/ejemplo1
/baseDatosMysql.py
7,326
3.53125
4
#base datos #http://docs.peewee-orm.com/en/latest/peewee/installation.html #pip install peewee # o bien git clone https://github.com/coleifer/peewee.git # cd peewee # python setup.py install #python runtests.py #sudo pip3 install PyMySQL import pymysql import pymysql.cursors con = pymysql.connect('192.168.0.7', 'victo...
35335f8f21d72bb37e2750a3f15c5c9c68ff1be0
husathap/squid
/squid.py
8,718
3.578125
4
# Squid: S-syntax - Quick 'n Dirty # -------------------------------- # By Sathaporn (Hubert) Hu 2014 # Q: What is Squid? # A: It is a preprocessor that allows S-syntax macros to be used in codes # written in many programming languages. To use Squid, give it a rule file, # a file that you want to preprocess and ...
dc853f47647cfa8185eeded8b7b4abd458463413
jpike/PythonProgrammingForKids
/BasicConcepts/Functions/FirstFunction.py
828
4.4375
4
# This is the "definition" of our first function. # Notice the "def" keyword, the function's name ("PrintGreeting"), # the parentheses "()", and the colon ":". def PrintGreeting(): # Here is the body of our function, which contains the block # or lines of code that will be executed when our function is # ca...
80ca82821fb11de416ce34b51597b5f715e635be
jpike/PythonProgrammingForKids
/BasicConcepts/Functions/ProgramFlowWhenCallingFunction.py
528
4.0625
4
# This is the definition for our function. def PrintGreeting(): print("Hello!") # Here is a print statement to print out some text before we call # our function to let us more easily see when our function executes. print("Before PrintGreeting() function call.") # Here is where we call our custom function for the ...
e2443f72f6fa666a40166a58886c8b8bf1da701a
jpike/PythonProgrammingForKids
/Pygame/Pygame6_KeepPlayerOnScreen.py
7,200
3.640625
4
import pygame import random import sys # INITIALIZE PYGAME. pygame.init() # CREATE THE GAME SCREEN. SCREEN_WIDTH_IN_PIXELS = 400 SCREEN_HEIGHT_IN_PIXELS = 400 screen = pygame.display.set_mode( (SCREEN_WIDTH_IN_PIXELS, SCREEN_HEIGHT_IN_PIXELS)) # DEFINE INITIAL PLAYER PARAMETERS. score = 0 player_lives = 10 enemy...
27c652d987b5a0600ce708f932c3c0590ad4fb02
jpike/PythonProgrammingForKids
/Pygame/RectanglePractice.py
3,819
3.984375
4
import pygame import sys # INITIALIZE PYGAME. pygame.init() # CREATE THE GAME SCREEN. SCREEN_WIDTH_IN_PIXELS = 400 SCREEN_HEIGHT_IN_PIXELS = 400 screen = pygame.display.set_mode( (SCREEN_WIDTH_IN_PIXELS, SCREEN_HEIGHT_IN_PIXELS)) # RUN THE GAME UNTIL THE USER CHOOSES TO EXIT. while True: # HANDLE ANY EVENTS ...
5a63befb4bb2b1b00552c54b2416ad8c1da0b99e
jpike/PythonProgrammingForKids
/BasicConcepts/SyntaxErrors/Volume1_Chapter3_SyntaxErrors.py
689
4.125
4
# String variable statements with syntax errors. string variable = 'This line should have a string variable.' 1string_variable_2 = "This line should have another string variable." another_string_variable = 'This line has another string variable." yet_another_string_variable = "This line has yet another string variable....
fc20b0c6c8dd2c54ffc3e4cad2f6b2c86b9f59af
jpike/PythonProgrammingForKids
/Pygame/PygameTemplateWithFixedFrameRate.py
1,249
3.734375
4
import pygame import sys # INITIALIZE PYGAME. pygame.init() # CREATE THE GAME SCREEN. SCREEN_WIDTH_IN_PIXELS = 400 SCREEN_HEIGHT_IN_PIXELS = 400 screen = pygame.display.set_mode( (SCREEN_WIDTH_IN_PIXELS, SCREEN_HEIGHT_IN_PIXELS)) # RUN THE GAME UNTIL THE USER CHOOSES TO EXIT. clock = pygame.time.Clock() while Tr...
330746e985131d3c915c104b98b214cb55b619c8
sangzzz/Data-Structures-Coursera
/week1_basic_data_structures/2_tree_height/tree_height.py
4,329
4.03125
4
# python3 import sys import threading class node: def __init__(self, val=None, val2=[]): self.data = val self.p = val2 # self.m = 0 class linkedlist: def __init__(self): self.head = None def height(k): if len(k.p) == 0: return 0 h = 0 for i in k.p: ...
e507cf39ac3e3628d970f04cd919d3e0e0a85f2a
dmeyers83/TermEstimate
/testconjoint.py
726
3.90625
4
import pandas as pd roles = ["IT Project Manager","Technology Product Manager","Data Scientist", "DevOps Engineer","Software Engineer","Data Engineer","Solutions Architect","Data Analyst","Full Stack Developer","Development Manager","CTO","CIO","Security Engineer","Mobile Application Developer","Senior Web Develope...
3187c91240f4c83ef959bf68b3bb2056cf86414d
razerx100/university
/data structure/Linked_List.py
1,388
3.890625
4
class Linked_List: class Node: def __init__(self, key, value): self._value = value self._key = key self._next = None def __init__(self): self.node_head = None def add_last(self, key, value): if not self.node_head: self.nod...
5641e99794e4ab8f318eae38749b9b5e6d646127
turingwt/magedu_pthon
/magedu_python_exercise/string/test_1.py
1,044
3.640625
4
# sq = ['1', ['2', '2'], '3'] # # print('\"'.join(map(str, sq))) # # print(sq) # sq = 'My name is watson' # # print('\n'.join(sq).splitlines()) # print(sq.rsplit(None, maxsplit=1)[-1]) # print('{} {}'.format(10, 20)) ##################################################### # num1 = input("Please input a number: ").stri...
0ef2b0ae16f02cc3eb5b46d295f5961b4a8c0020
wnsdyd0612/0921
/control01.py
147
4.28125
4
#if -else statement x = 5 if x > 4 or x != 9: print("Output : {}".format(x)) else: print("Output : x is not greater than 4")
4cf02d87043e701ed04156a935e710a10f54e7a0
techacker/Hackerank
/commandlistchallenge.py
1,279
4.21875
4
print('The program performs the given function on a list in a recursive manner.') print('First enter an "Integer" to tell how many functions you would like to do.') print('Then enter the command with appropriate values.') print() print('Enter an integer.') N = int(input()) z = [] def operation(inst, item, ind): if...
68571bcf57eaa90a749cfbeaa39e613e6aeaa7f6
techacker/Hackerank
/calendarModule.py
392
4.125
4
# Task # You are given a date. Your task is to find what the day is on that date. # Input Format # A single line of input containing the space separated month, day and year, respectively, in MM DD YYYY format. import calendar s = input().split() m = int(s[0]) d = int(s[1]) y = int(s[2]) day = calendar.weekday(y,m,d...
d395ee9f2295392adb2d54e0de0f8707b77cea0b
techacker/Hackerank
/sWapCase.py
262
3.90625
4
n = input() swapped = [] for words in n: for i in range(len(words)): if words[i] == words[i].lower(): swapped.append(words[i].upper()) else: swapped.append(words[i].lower()) print(''.join(swapped))
1ad78ed9adf03a027f1e7d91e0e7422359a99ccd
techacker/Hackerank
/designerDoorMat.py
1,101
3.96875
4
#---------------------------------------------------P R O B L E M------------------------------------------------------------ # Mr. Vincent works in a door mat manufacturing company. One day, he designed a new door mat with the following specifications: # Mat size must be NXM. (N is an odd natural number, and M is ...
3215b0ada68e50621452d257cac18e767d0239e6
techacker/Hackerank
/alphabetRangoli.py
811
4.25
4
# You are given an integer, N. # Your task is to print an alphabet rangoli of size N. # (Rangoli is a form of Indian folk art based on creation of patterns.) # # Example : size 5 # # --------e-------- # ------e-d-e------ # ----e-d-c-d-e---- # --e-d-c-b-c-d-e-- # e-d-c-b-a-b-c-d-e # --e-d-c-b-c-d-e-- # ---...
0b0dcbc0b619f5ce51dd55a65a7ede07dfbb5695
Joeshiett/beginner-python-projects
/classes_example.py
633
4.125
4
class Person: # Instantiate class person as blueprint to create john and esther object def __init__(self, name, age): self.name = name self.age = age def walking(self): #defining of behaviour inside of class indentation print(self.name +' ' + 'is walking...') def speaking(self)...
f7d796f095f0ed761815c8d74b2f22adf77a524b
Joeshiett/beginner-python-projects
/palindrome.py
189
4.4375
4
#Code to test to see if a word is a palindrome or not text = input('Input a word: ') if text == text[: :-1]: print('This is a palindrome!') else: print('This is not a palindrome!')
2a4e05fc8d34e7bf22ff9e5bf0b0dae7751435ba
GiorgioBiasuzzi/DisasterResponsePipeline
/train_classifier.py
5,575
3.515625
4
#!/usr/bin/env python # coding: utf-8 # # ML Pipeline Preparation # Follow the instructions below to help you create your ML pipeline. # ### 1. Import libraries and load data from database. # - Import Python libraries # - Load dataset from database with [`read_sql_table`](https://pandas.pydata.org/pandas-docs/stable/g...
06ef66a1760a531c1ceb875031e5fae69be015ef
Perry-Olsson/ctci
/python/linked_lists/check_for_loop.py
917
3.90625
4
from Node import * def checkForLoop(head): current = head nodeMap = {current: True} current = current.next while current is not None: if current in nodeMap: return current nodeMap[current] = True current = current.next return None #no loop def checkForLoopRunner(head): if head.next is...
6aa2327c1de8cf2ff09c6189b578879f53ca7474
valmonten/CodingDojo
/python/oop/animal.py
1,382
3.875
4
class Animal(object): def __init__(self,name,health): self.name=name self.health=health print self.name print self.health def walk(self): self.health-=1 print self.name + " walked" return self def run(self): self.health-=5 print self.na...
1505fd996a162ae55f54c24f642db36228f7f18a
valmonten/CodingDojo
/python/oop/math_dojo.py
791
3.671875
4
class Mathdojo(object): def __init__(self): self.sum=0 def adding(self, *args): running=list(args) for x in running: if isinstance(x, list): for thingy in x: running.append(thingy) else: self....
e40d89b244285fd76d16a6ccd498a38a2a7eefa1
valmonten/CodingDojo
/python/oop/product.py
1,170
3.71875
4
class Product(object): def __init__(self,price,name,weight,brand,cost): self.price=price self.name=name self.weight=weight self.brand=brand self.cost=cost self.status="for sale" def sold(self): self.status="sold" return self def tax_included(se...
d93887a6d8fcfab555b880bfbda05b33f3c70f08
valmonten/CodingDojo
/python/python_fundamentals/type_list.py
663
3.671875
4
def list_type(li): count = 0 sm = 0 bootsandcats = "How to beat box: " if all(isinstance(x, int) for x in li): print "Type is int" for x in li: sm += x print sm elif all(isinstance(x, str) for x in li): print "Type is string" for x in li: ...
c5de22596dfce1a389ccda34fc125994bb54b7ff
isaac-art/LabyrinthMaker
/Cell.py
2,185
4
4
# THIS IS THE CELL CLASS # ADAPTED FROM JAMIS BUCK'S MAZES FOR PROGRAMMERS RUBY CODE class Cell(): def __init__(self, row, column): # init the object with row and column self.row = row self.column = column # the links is initially empty self.links = {} # there surro...
5ff60b76385f8b6befde1e00f0e2a12cb1f90630
julien2424/Learning-Python-ML
/linreg_python/main.py
1,081
3.5625
4
from sklearn import datasets from sklearn import linear_model from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt # linear regression is supervised def get_linreg_model(): # retrieve data boston = datasets.load_boston() # segment data X = boston.data y = boston.t...
deff7d69c06862846e9089310260c4762c4cf086
usac201602491/Proyectos980
/Ejemplos/Pogramacion Basica/Ejercico_2.py
335
3.53125
4
''' def fib(n): if n == 0: return 0 elif n == 1: return 1 else: return fib(n - 1) + fib(n - 2) n = 11 item = fib(n) print(f"El item {n} de la serie de Fibonacci es {item}") ''' a=0 b=1 c=0 sumaT=0 while c<4000000: c=a+b a=b b=c if c%2==0: sumaT = sumaT+c ...
3d872890a5488697cbd3a1ffaaaf656668bf5a4d
usac201602491/Proyectos980
/Ejemplos/POO/POOE1.py
1,013
4.09375
4
# Funcion --> Metodo # Variable --> Atributo # Clase tipo Fecha class Fecha(object): #Constructor def __init__(self, dia, mes, anio): # Crear variables globales dentro de la clase # con la informacion que era local dentro # del metodo constructor self.day = dia self.mon...
b41040278dedcd9e81f0f249ae3c90b1e79e72f2
usac201602491/Proyectos980
/Parciales/Parcial1/Problema1.py
583
3.609375
4
N = 48 # Hasta donde se quiere encontrar el resultado de las sumas def cuadrados(num): respuesta = 0 # Resta de las sumas suma1 = 0 # Suma de valores suma2 = 0 # Suma de valores al cuadrado for i in range(0,N+1): suma1=suma1+i # Suma los valores de ...
5c82c417b07124d723def212c852706c1360b291
usac201602491/Proyectos980
/Tareas/T01/Problema_2.py
827
3.890625
4
print( ''' ============================================== ENCONTRAR LOS PRIMEROS N NUMEROS AMIGOS ============================================== ''' ) while True: try: n = int(input("Introduzca un numero ( N ) : ")) if n <= 0: print("--> ERROR : Debe ingresar un numero mayor a cero ...
ff4d9cc19386fee1db99f84ee517934ef0ed5dc5
andru2400/python_repaso
/python_enfocado_2/main.py
404
3.8125
4
import turtle def main(): window = turtle.Screen() Andres = turtle.Turtle() make_square(Andres) turtle.mainloop() def make_square(Andres): legth = int(input('Tamaño de cuadrado')) for i in range(4): make_line_and_turn(Andres, legth) def make_line_and_turn(Andres, legth): Andr...
5c68b1769c24d48a1de52f69715d682d5960ad1c
D3MON1A/all_in_one_Python
/python_exercises.py
179
3.796875
4
#Write a map function that adds plus 5 to each item in the list. lst1=[10, 20, 30, 40, 50, 60] def addfive(items): return items + 5 lst2=list(map(addfive, lst1)) print(lst2)
92617918fa6a6d88ff46ef44a907358d74ddbe0a
choakpi2/SAB-AvionicsDisplay
/software/PygameTest.py
815
3.578125
4
#Import the Necessary Packages import pygame import DrawTest #Initialize Pygame - Sets up the modules and data structures for Pygame pygame.init() #Create the Display gameDisplay = pygame.display.set_mode((800,600)) pygame.display.set_caption('A bit Racey') #Initialize the clock to be used in FPS calculations clock ...
ceae9ee5d6e36b791f29c590d841f7942c10316f
danielyee517/projects
/coding_problems.py
3,804
3.96875
4
import math # Converts a float string into a floating point number (e.g. "34.575" -> 34.575) def convert_to_float(float_string): result = 0 # Finds the index of the decimal point period_index = float_string.find('.') # If there is no decimal, then simply add digit * 10 ^ power of the place value to the...
643625da65e73c51635cafbe3b183f225f3eaf9f
Rosa-Palaci/computational-thinking-for-engineering
/semana-3/class-11/A01652612-funciones03.py
1,215
4.0625
4
#Actividad Evaluable - Programas que utilizan funciones #Rosa Vanessa Palacios Beltran #A01652612 #Ejercicio ''' INSTRUCCIONES: Define una función que reciba los coeficientes a, b y c de una ecuación cuadrática de la forma ax^2+bx+c=0 y deberá regresar las soluciones x1yx2. **(NOTA: si la ecuación tiene solucione...
7d890451efc7b5a59dbf4e0a774223033e2f8aec
Rosa-Palaci/computational-thinking-for-engineering
/semana-3/class-11/mayores-prueba1.py
1,103
4.125
4
#INSTRUCCIONES: # Define una función que recibe tres números # enteros y regresa los número ordenados de # menor a mayor. # Haz la prueba con dos tercias de números def orden_asc(a, b, c): if a > b and a > c: mayor = a if b > c: medio = b menor = c else: #Signific...
77054ad44389863d8e178756aceaa007251fd17a
Rosa-Palaci/computational-thinking-for-engineering
/semana-2/class-8/A01652612-class-8.py
811
3.640625
4
#Clase-8 #Rosa Vanessa Palacios Beltran #A01652612 #tip tiempo retraso ''' import sys import time def delay_print(s): for c in s: sys.stdout.write(c) sys.stdout.flush() time.sleep(0.10) var = 10 delay_print(f'La variable es {var}') ''' #Formula una pregunta de opcion múltiple al usu...
c129884142aa3dadbc186138b9459a880960c156
Rosa-Palaci/computational-thinking-for-engineering
/semana-3/class-11/class-11.py
492
4.03125
4
#Actividad clase 11 #Rosa Vanessa Palacios Beltran #A01652612 #Ejercicio 1 #Libreria numpy import math def dividir(num, den): if den == 0: #La división no está definida return math.nan else: return num/den #con listas con vector def num #Se necesita repetir 3 veces (se puede usar un ciclofor)...
0dc6502b69c4a1f7f9257657f9f5d870237acda1
Rosa-Palaci/computational-thinking-for-engineering
/semana-2/class-5/A01652612-distintos.py
705
3.84375
4
#Actividad en clase - Estatus de decisión -2 #Rosa Vanessa Palacios Beltran #A01652612 #Ejercicio # 1 a = int(input('Ingresa tu primer número: ')) b = int(input('Ingresa tu segundo número: ')) c = int(input('Ingresa tu tercer número: ')) if((a <= b) and (a <= c)): menor = a if(b <= c): medio = b ...
ca49810c71671c3306817e7ca910c407a9b504a5
Rosa-Palaci/computational-thinking-for-engineering
/semana-2/class-7/A01652612-class-7.py
617
3.890625
4
#Class-7 #Rosa Vanessa Palacios Beltran #A01652612 '''caso comillas print(f'Pero \'supuestamente...') print(f'Pero "supuestamente"...') error print(f"Pero 'supuestamente'...") #imprimir los numeros del 4 al 40, excepto el 5. for num in range(4,41): residuo = num%5 if residuo == 0:#Significa que es multiplo d...
a315753d1b9122af30810896706a0bb99f2a9937
leeylong/pystudy
/ten/regex/c1.py
205
3.90625
4
#正则表达式 # 一种字符串的模式 #应用:快速批量操作同类字符串 #组成 普通字符+元字符 import re a = 'C|C++|C#|Python|Javascript|Python2' r = re.findall('\D',a) print(r)
0df13ebb20f554779ca75ca2693bfb833c7d1473
huhuzwxy/leetcode
/string/67_add_binary.py
863
3.515625
4
# 给定两个二进制字符串,返回其和(二进制字符串)。 # Input: a = "11", b = "1" # Output: "100" # 思路: # 注意进位即可 class Solution: def addBinary(self, a, b): if len(a) < len(b): a = a.zfill(len(b)) else: b = b.zfill(len(a)) c = [0 for _ in range(len(a) + 1)] tmp = 0 for i in rang...
de2d622a95cdee47cedd8be41befb2dd4eaf37b0
huhuzwxy/leetcode
/array/31_next_permutation.py
1,099
3.640625
4
# 给定一个序列,输出其下一个更大序列,若已最大,则从头开始。时间复杂度O(1) # 1, 2, 3 -> 1, 3, 2 # 思路: # 找递增结束的位置,换上比该数大的最小数 class Solution: def nextPermutation(self, nums): i = len(nums) - 1 if nums[i - 1] >= nums[i]: i = i - 1 print(i) if i == 1: m = 0 n = len(nu...
7020287f2c478c4009191fb94ce0d5b8dacd19e5
huhuzwxy/leetcode
/array/1_two_sum.py
921
3.546875
4
# 给定一个数组和一个target,查找数组中相加等于target的两个数,返回其位置 # Input: [2, 7, 11, 15], target = 9 # Output: [0, 1] # 思路: # 哈希表/ 暴力求解 class Solution: def twosum(self, nums, target): dict = {} for i in range(len(nums)): dict[nums[i]] = i y = target - nums[i] if y in dict: ...
059d2b59c3e96dbb3a4076147bb222592a6e30bb
huhuzwxy/leetcode
/sort/75_sort_colors.py
1,706
3.53125
4
#数组中含红白蓝三颜色,将其按红、白、蓝排序,红色为0,白色为1,蓝色为2 #Input: [2, 0, 2, 1, 1, 0] #Output: [0, 0, 1, 1, 2, 2] #思路1: #第一次遍历数组,分别统计0,1,2的个数 #第二次遍历数组,将0,1,2按个数放入数组中 #思路2: #只遍历一次数组实现排序 #设置三个指针,一个指向头j,一个指向尾k,一个遍历i #如果nums[i]==0,将nums[i]与nums[j]交换,i = i + 1, j = j + 1 #如果nums[i]==2,将nums[i]与nums[k]交换,i = i + 1, k = k + 1 #遍历时始终保持i < k,否则尾部...
7ba0954281f856bb66a359bafb97925ec86ee62a
ea3/mc-Ranges-Python
/ranges.py
1,227
3.984375
4
print(range(100)) my_list = list(range(5,10)) print(my_list) even = list(range(0, 10, 2)) odd = list(range(1,10,2)) print(odd) print(even) print("++++++++++++++++++++++++++++") my_string = "abcdefghijklmnopqrstuvwxyz" print(my_string.index('e')) print(my_string[4]) small_decimals = range(0,10) print(small_decimals) p...
2271282187d7125c29cd1c5698ef8c75f77508d7
sophiashuv/UCU_labs_2term
/1_OOP/task2/classroom.py
2,587
3.921875
4
import doctest class Classroom(): ''' Class for classroom representation ''' def __init__(self, number, capacity, equipment): ''' (Classroom, str, int, lst) -> NoneType Create new classroom >>> classroom_016 = Classroom('016', 80, ['PC', 'projector', 'mic']) >>> class...
366c7086642e77173f0d2e5b8fd5e89a89f367b8
sophiashuv/UCU_labs_2term
/4_Винятки, обробка винятків, ієрархія винятків, створення власних винятків. Тестування та зневадження програм./task7/is_sorted.py
390
4.03125
4
def is_sorted(lst): """ (list) -> (bool) The function returns True if the list is sorted and False if not """ if isinstance(lst, list): if len(lst) == 0: return False for i in lst: if not isinstance(i, int): return False if sorted(lst) ...
3358813f2f5a8308dc4c21b142873f5309148091
sophiashuv/UCU_labs_2term
/2_Інкапсуляція. Успадкування. Множинне успадкування. Поліморфізм./task1/exercise2.py
891
3.796875
4
class Animal: def __init__(self, phylum, clas): self.phylum = phylum self.clas = clas def __str__(self): return "<animal class is {}>".format(self.clas) class Cat(Animal): def __init__(self, phylum, clas, genus): super().__init__(phylum, clas) self.genus = genus def sound(self): return 'Meow' ...
ada515c8b7e988947ee79ec1460521a60b181146
lilott8/mit-6x
/Week 9/stdDeviationLength.py
484
3.953125
4
def stdDevOfLengths(L): """ L: a list of strings returns: float, the standard deviation of the lengths of the strings, or NaN if L is empty. """ total = 0.0 length = len(L) if length < 1: return float('NaN') else: lengthList = [] for y in L: len...
b01e980bef4459f14ab55ed620533b9dcb7d138b
lilott8/mit-6x
/week 3/lecture1-p4.py
348
3.859375
4
def gcdRecur(a, b): ''' a, b: positive integers returns: a positive integer, the greatest common divisor of a & b. ''' # Your code here if b == 0: return a else: temp = b b = a % b a = temp return gcdRecur(a, b) print(str(gcdRecur(2, 12))) print(str(gcdRecur(6, 12))) print(str(gcdRecur(9, 12))) ...
cc32fac2c1db4cb55f3eca3e0e88921d840fe023
lilott8/mit-6x
/week 3/lecture1-p3.py
713
3.65625
4
def recurPowerNew(base, exp): ''' base: int or float. exp: int >= 0 returns: int or float, base^exp ''' #accomodate for n^0 if exp == 0: return 1 #all other cases: n^y where y > 1 elif exp % 2 == 1: #base * base^(exp-1) return base * recurPowerNew(base, exp - 1) else: #base^exp = (base^2)^(exp/2) re...
838ef2df7106e15897f747879ff492f253c4d50f
lilott8/mit-6x
/week 3/lecture1-p1.py
516
3.875
4
def iterPower(base, exp): ''' base: int or float. exp: int >= 0 returns: int or float, base^exp ''' i = exp orig = base #accomodate for n^0 if exp == 0: return 1 #accomodate for n^1 elif exp == 1: return orig #all other cases: n^y where y > 1 else: while i > 1: base = base * orig i -= 1 retur...
9cd3ae667a60c8bf96a2ac637838d175e5bf1213
lilott8/mit-6x
/week 7/ProblemSet7/robot.py
5,606
4.0625
4
import math import random class Position(object): """ A Position represents a location in a two-dimensional room. """ def __init__(self, x, y): """ Initializes a position with coordinates (x, y). """ self.x = x self.y = y def getX(self): retu...
3f8cd4a99aeffc1420bf4dd4c9af2f1b487914f7
Jonie23/python-calculator
/calculator.py
2,095
4.375
4
#welcome user def welcome(): print(''' Welcome to Jones's calculator built with python ''') welcome() # calculator() #define a function to run program many times def calculator(): #ask what operation user will want to run operation = input(''' Please type in the calculator operation you will want...
c1d48042f03a38e153876b8f5276b924f132c261
cgkevork/Python
/Fibnum.py
302
3.703125
4
xp=2 x=3 sum =0 while x < 4000000: xn=x x=x+xp xp=xn if (x % 2 ==0): sum = sum + x print('even sum',sum) a, b = 1, 1 total = 0 while a <= 4000000: if a % 2 == 0: total += a a, b = b, a+b # the real formula for Fibonacci sequence print total
be1d3fd41e1225198c2c11d35be52cda609fe28e
cgkevork/Python
/coding-for-journalists-master/8_cleaning/names.py
1,846
3.671875
4
#! usr/bin/python # Quick check to make sure we're getting all of our links before we move on # Let's look at the URL string # What we really care about are the numbers at the end of the link; that's # how the whole setup for the website works. We feed it an ID, it generates # a page. # ...
332bda1023f75fbc719277879880f181903c7b81
jeevaselvi123/hi
/Hangaman/hangaman.py
801
3.703125
4
import random,re country=['russia','canada','china','unitedstates','brazil','australia','india','argentina','kazakhstan','sudan'] str1=random.choice(country) str2='-'*len(str1) str2=list(str2) n=len(str1) print(str1) temp="" n1=3 while n1!=0: ip=input("Enter the letter:") if ip in str1 and ip not in str2: ...
79c2b979c4a452e7ee39e34081af6fdaab1edcef
mpcorps-88/homework
/manorEscape.py
3,679
4.15625
4
# Manor Escape! This program, while simple is a text game intended to simulate an environment # where you must try to escape by making a few simple choices. Each method will have a brief description of what # its purpose is. -S.Johnson August 01, 2017 import random import time #first method to iniate user interactio...
c0d995b48c484784559274ec8f074e697cfc122a
hasan1970/Small-Projects
/Snake.py
3,187
3.6875
4
import pygame import time import random pygame.init() blue=(0,0,255) black=(0,0,0) red=(255,0,0) white=(255,255,255) temp=(10,200,200) dis_width=400 dis_height=300 display=pygame.display.set_mode((dis_width,dis_height)) pygame.display.set_caption("Snake Game") clock=pygame.time.Clock() snake_...
430027b76d916597ca1a9f59178c370b4295d901
isennkubilay/Maximum-Integer
/main.py
446
3.953125
4
from random import randrange num_items = 100 max_value = randrange(1, num_items + 1) print(max_value) num_updates = 0 for i in range(1, num_items): current = randrange(1, num_items + 1) if current > max_value: max_value = current num_updates = num_updates + 1 print(current, "<= Update") else: ...
435017af2f70985b9046541a60e4e5dd073ec5cf
sametkkoserk/MineSweeper_set
/sehir minesweeper.py
3,929
4.3125
4
from swampy.TurtleWorld import* import math import random def turtle_game(): world = TurtleWorld() print('HELLOOOOOO') turtle_1 = Turtle() print('-------- First Turtle---------') name_1 = input('What is the name of Turtle one ?') while name_1 == (""): print("name cannot be em...
d92ed07fc84c097b1f22dcd042383e2197a43194
sahiljuneja/ml-editor
/ml_editor/ml_editor.py
7,751
3.84375
4
import argparse import nltk import pyphen # parse input data def parse_arguments(): """ :return: Text to be edited """ parser = argparse.ArgumentParser( description="Input text to be edited" ) parser.add_argument( "text", metavar="input text", type=str ) ...
2f9f2aee6b07e46825e3bad18e440eab526d349e
nisarg64/Word2Vec-Doc2Vec
/parse_directory.py
665
3.8125
4
from os import walk from os.path import splitext, join def select_files(root, files): """ simple logic here to filter out interesting files .py files in this example """ selected_files = [] for file in files: #do concatenation here to get full path full_path = join(root, file)...
4847b8a3d22047032dca5741807aea22cd5a2e37
Lanavizoli/sae_ihm
/Pacman.py
7,533
3.65625
4
#import Candy #import Playfield class Pacman() : """ Classe pour Pacman. ... Attributes ---------- position : list Renseigne la position du pacman sur le terrain de jeu. jauge : int Renseigne le nombre de points score du pacman joué. Method...
90cd35e0519d6a117da934efb244dfd8692d1291
tosinabase/cs_tasks
/from_children_to_end_node_paths.py
1,857
3.9375
4
# https://www.careercup.com/question?id=5713002834165760 # Given a Start Node and an End Node in a graph. # Report if they are “necessarily connected”. # This means that all paths from the start node lead to the end node. # Report true all paths from start node lead to end node and false if # at least one path does no...
03cfcbf342266a89eeb71fd2f69177edf1144e00
qinyan1994/leetcode
/LeetCode 26. Remove Duplicates from Sorted Array.py
380
3.53125
4
class Solution: """ @param A: a list of integers @return an integer """ def removeDuplicates(self, A): # write your code here k=0 for i in range(1,len(A)): if A[i] != A[k]: k+=1 A[k] = A[i] del A[k+1:le...
1df8567eeb44377dba77925b01ee1ce8750d368a
louis-pham/pham_louis_Assignment1
/question6/q6.py
2,987
3.65625
4
import random import time class Ship(object): def __init__(self, name): self.name = name self.shields = 80 self.hullStrength = 100 self.laserPower = 20 def _chooseShip(self, shipList): #find a ship thats alive and not itself someShip = None while someShip is None: randIndex = random.randint(0, len...
4d7a1ccf22595544dfedd57e7cc2181d18013d5c
milan-crypto/PRACTICE_PYTHON
/Divisors.py
503
4.3125
4
# Create a program that asks the user for a number and then prints out a list of all the divisors of that number. # (If you don’t know what a divisor is, it is a number that divides evenly into another number. # For example, 13 is a divisor of 26 because 26 / 13 has no remainder.) number = int(input("Please choose a n...
ce50d1caccd5127e94769b36df37d30f3b664bb0
victsnet/Geoanalytics-and-Machine-Learning
/SOM-Remote Sensing-Geology/toolbox.py
6,859
3.59375
4
from tqdm import trange import numpy as np import matplotlib.pyplot as plt def window3x3(arr, shape=(3, 3)): r_win = np.floor(shape[0] / 2).astype(int) c_win = np.floor(shape[1] / 2).astype(int) x, y = arr.shape for i in range(x): xmin = max(0, i - r_win) xmax = min(x, i + r_w...
118a0fe6928e7e942347ea35cc2f61efeadf3e00
pankratdodo/python3
/city.py
18,189
3.828125
4
class City(): def __init__(self, name, days, old, kid, money_per_day, price, flight): print("Выберите город:\n•Рим\n•Париж\n•Лондон\n•Токио\n•Пекин\nдля выхода напишите выход\n") self.name = input() if self.name == "выход": exit() self.days = int(input("Введите количеств...
0cc376a069764504b009bb1f3ffcb2ecf787215f
ManoelSCosta/Projetos_Python
/Exercicios_CursoEmVideo/ex031.py
336
3.859375
4
print('{} DESAFIO 31 {}'.format(('='*5), ('='*5))) distancia = float(input('Qual a distância da viagem? ')) if distancia <= 200: precoPassagem = distancia * 0.50 else: precoPassagem = distancia * 0.45 print('A vaiagem será de {}km\nO valor da passagem será R${}'.format(distancia, precoPassagem)) print('B...
5fa421e6453856b69c62fe33530a07ab193ef465
ManoelSCosta/Projetos_Python
/Exercicios_CursoEmVideo/ex030.py
294
3.953125
4
print('{} DESAFIO 30 {}'.format(('='*5), ('='*5))) n = int(input('Informe um número: ')) d = n%2 if n == 0: print('{} é um número neutro'.format(n)) else: if d == 0: print('{} é um numero par'.format(n)) else: print('{} é um número impar'.format(n))
9851cd7008f7e57857b4f0c6df546b062338b7b9
ManoelSCosta/Projetos_Python
/Exercicios_CursoEmVideo/ex028.py
529
3.78125
4
from random import randint from time import sleep print('{} DESAFIO 28 {}'.format(('='*5), ('='*5))) comp = randint(0,5) print('-=-'*20) print('Vou pensar em um número de 0 a 5, tente adivinhar...') print('-=-'*20) sleep(3) usuario = int(input('Em que número eu pensei ')) print('PROCESSANDO...') sleep(3) if ...
c6663969db5ac4d709829ea358476323701abf99
ManoelSCosta/Projetos_Python
/Exercicios_CursoEmVideo/ex044.py
821
3.53125
4
import sys print('\33[7;30;m{} DESAFIO 44 {}\33[m'.format(('='*5),('='*5))) precoProduto = float(input('Informe o Valor do Produto: ')) print('\33[7;30;mFormas de Pagamento Disponiveis\33[m') print('A VISTA = 1\nCARTÃO = 2\n2X NO CARTÃO = 3\n3X OU MAIS NO CARTÃO = 4') formaPagamento = int(input('Insira os números corre...
fe405c425cd99fa10756cd8f85c8da717ea71e99
DBosDavinci/van-input-naar-output
/person.py
372
3.75
4
Name = input('Wat is uw naam?') Address = input('Wat is uw adres?') Code = input('Wat is uw postcode?') Place = input('Wat is uw woonplaats?') print(' ----------------------------------------------------\n' '| Naam :', Name, '\n| Adres :', Address, '\n| Postcode :', Code, '\n| Woonplaats:', Place, '\n --...
eebac37ac5c25acef6ada8ef0b3305eefa376c3c
fabriciodisalvo/Elevator
/elevator.py
5,216
3.84375
4
class Building: def __init__(self, name, number_of_floors): self.name = name self.number_of_floors = number_of_floors self.elevators = [] self.waiting_dict = {} for i in range(int(number_of_floors) + 1): self.waiting_dict[i] = [] def add_passengers(self, pass...
68247317c0145405a949c82d10f08dd4d535bd52
dhirajMaheswari/findPhoneAndEmails
/findPhonesAndEmails.py
1,853
4.4375
4
'''this code makes use of the command line to find emails and/or phones from supplied text file or text using regular expressions. ''' import argparse, re def extractEmailAddressesOrPhones(text, kKhojne = "email"): ''' this function uses the regular expressions to extract emails from the supplie...
04f9b9e623652aff89ff6261069df137c4e48c25
ManishVerma16/Data_Structures_Learning
/python/recursion/nested_recursion.py
226
4.125
4
# Recursive program to implement the nested recursion def nestedFun(n): if (n>100): return n-10 else: return nestedFun(nestedFun(n+11)) number=int(input("Enter any number: ")) print(nestedFun(number))
85d95b3a46de8b55e79a78cae692f57c6b6e030d
Abhi9k/algorithms
/check-if-word-is-valid-after-substitutions/check_if_word_is_valid_after_substitutions.py
738
3.8125
4
def isValid(S): N = len(S) if N < 3 or (N % 3) != 0: return False if N == 3 and S != 'abc': return False s_arr_tmp = [] j = 3 while j <= N: if S[j - 3: j] != 'abc': s_arr_tmp.append(S[j - 3]) j += 1 else: j += 3 if j - 3 < N...