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
4513babc8ea339c4ba1b9d02fe360b9ad431cb3a
kszabova/lyrics-analysis
/lyrics_analysis/song.py
939
4.34375
4
class Song: """ Object containing the data about a single song. """ def __init__(self, lyrics, genre, artist, title): self._lyrics = lyrics self._genre = genre self._artist = artist self._title = title ...
3a8f96cdaa8b0a59d13babb8083b58221d218565
AndOrtegon/GPTO_Python
/input_files/smallcantilever3d/initial_smallcantilever3d_geometry.py
1,697
3.765625
4
# def initial_cantilever2d_geometry(): ## Initial design input file # # *** THIS SCRIPT HAS TO BE CUSTOMIZED BY THE USER *** # # In this file, you must create two matrices that describe the initial # design of bars. # # The first matrix contains the IDs (integer) and coordinates of the # endpoints of the bars (point_m...
ccf647b03c93c0fe35fd0200ea88c567f0d6cc0c
m-nasiruddin/AByteOfPython
/var.py
495
3.75
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Mar 23 11:45:40 2018 @author: osboxes """ i = 5 print(i) i = i + 1 print(i) s = '''This is a multi-line string. This is the second line.''' print(s) i = 5 print(i) i = 5; print(i); i = 5; print(i) i = 5; print(i); s = 'This is a string. \ This co...
3f8d5667a9cf32b977217acd456a0d1ddea561b2
m-nasiruddin/AByteOfPython
/function_local.py
229
3.5
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Mar 23 13:02:48 2018 @author: osboxes """ x = 50 def func(x): print('x is', x) x = 2 print('Changed local x to', x) func(x) print('x is still', x)
b7a25c84d89af353962abcb4b496f25774918315
bcollins5/mis3640
/mypolygon.py
3,007
3.859375
4
'''#import turtle #Excercise 2.1 def square(t): for i in range(4): #we repeat same thing four times t.fd(100) t.lt(90) ''' ''' #Exercise 2.2 def square(t, length): for i in range(4): #we repeat same thing four times t.fd(length) t.lt(90) #Exercise 2.3 def square(t...
822f910b508030057051cde0abdba57473b3ed50
bcollins5/mis3640
/iteration_demo.py
1,624
3.75
4
#Class Session ''' result = 0 for i in range(11): result += i # means: result = result + i print(result) ''' ''' result = 0 for i in range(1,11,2): #for even change to 0 if i % 2 == 1: #for even change to 0 print('current i: ', i) result += i print(result) ''...
eafd2e749b9261a9c78f78e6459846a19094a786
VedantK2007/Turtle-Events
/main.py
2,842
4.34375
4
print("In this project, there are 4 different patterns which can be drawn, and all can be drawn by the click of one key on a keyboard. If you press the 'a' key on your keyboard, a white pattern consisting of triangles will be drawn. Or, if you press the 'b' key on your keyboard, an orange pattern consisting of squares ...
5400c9cfe1695286df6dde7cd63e78198621e940
tanjinadnanabir/InterviewCakeCoding
/permutationPalindrome.py
1,428
4.09375
4
import unittest def has_palindrome_permutation(the_string): # Check if any permutation of the input is a palindrome # Track characters we've seen an odd number of times unpaired_characters = set() for char in the_string: if char in unpaired_characters: unpaired_characters.remove...
bb5272ffd8ad8b4d410f91c3a4b2655a2a37970c
tanjinadnanabir/InterviewCakeCoding
/lastNodeInSinglyLinkedList.py
2,477
4.09375
4
import unittest def kth_to_last_node(k, head): # Return the kth to last node in the linked list if k < 1: raise ValueError( 'Impossible to find less than first to last node: %s' % k ) # Step 1: get the length of the list # Start at 1, not 0 # else we'd fail to count ...
88ea73b19da7b77911ba36026c7c7be2f5b982f3
CAlfanoNerey/computermentorsproj
/lists.py
633
3.828125
4
# def sum_all(t): # #t is a list of numbers # total = 0 # for x in t: # total += x # return total # def cumulative_sum(t): # cumulative_total = 0 # cumulative_sum = [] # for x in t: # cumulative_total += x # cumulative_sum.append(cumulative_total) # return cumula...
fff24306710ef96744e1eb3ebccb85dd3bb09703
sajuptpm/Interview-Prep
/Algorithms_DataStructures/Sorting/Counting_Sort.py
7,454
4
4
""" @author: David Lei @since: 21/08/2016 @modified: Not a comparison sort, so comparison O(n log n) lower bound doesn't apply Visualization: https://www.cs.usfca.edu/~galles/visualization/CountingSort.html How it works: Integer sorting algorithm - it counts the number of objects Applies when element...
f180c185de99e2c5bcf35a3d2b18676931cc570a
Pu-Blic/PruebasPython
/POO_III_super.py
1,286
4.03125
4
class Persona(): def __init__(self, nombre, edad, poblacion): self.nombre=nombre self.edad=edad self.poblacion=poblacion def descripcion(self): print("Nombre:",self.nombre,"\nEdad:",self.edad,"\nPoblacion:",self.poblacion) class Empleado(Persona): def __init__(self, nombre,...
1f7713bf7c0b3b7a20a8071ba8e388c53ba12cca
Pu-Blic/PruebasPython
/Strings.py
928
4.1875
4
myStr ="hola oJEtes" #print(dir(myStr)) print(myStr.upper()) print(myStr.title()) print(myStr.swapcase()) print(myStr.capitalize()) print(myStr.replace("o","0")) oes= myStr.count("o") print (oes) print("El texto tiene" , oes , "oes") print(myStr.split()) #Por defecto Lo separa usando los caracteres en blanco myA...
e0a6e96fe62c314c662315e8f3cb6012e780c3b5
Pu-Blic/PruebasPython
/EntornoGráfico/FormularioLabel.py
839
3.96875
4
from tkinter import * root=Tk() miFrame=Frame(root, width="600", height="400") miFrame.pack() miLabel=Label() miLabel.place(x=5,y=5) #Se una place en lugar de pack para que no redimensione el Frame y la ventana al tamaño del Label miLabel.config(text="Nombre: ") txtNombre = Entry(miFrame) #Entry es como se llaman a l...
66b110a48cb9179330c2b52abb81199e3b652e6f
JuanL-Code/python_3
/complejidad_algoritmica.py
581
4.0625
4
#Calcular el tiempo import time #generar dos implementaciones de factorial, iterativa y recursiva def factorial(n): respuesta = 1 while n>1: respuesta *= n n-=1 return respuesta def factorial_recursivo(n): if n==1: return 1 return n* factorial(n-1) ...
60e890ae84cf2dfe2d6fe631d5944fdc1743d60d
SKCheongBrian/CodingProject
/PigLatin/pigLatin.py
747
3.96875
4
def main(): #initialise consonants and vowels consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'] vowels = ['a', 'e', 'i', 'o', 'u'] userInput = input("Please enter a word: ") lowerInput = userInput.lower() result = "" #crea...
5175a94e1a1c384efeef69540f85cb3944cb901e
xlyuan2018/python_visualization
/plt_2_barplot.py
2,888
3.515625
4
# points 1: use csv.reader to read data row by row, each row in dict type # points 2: split data by some patterns, e.g. ';' # points 3: collect data by collection.counter # points 4: use horizontal bar (barh), data.reverse() import csv import numpy as np import pandas as pd import requests from collections import Cou...
d0fa02395a310d16e0bdc650420396fb01f83509
Pallmal111/Pythonkurs1
/hw_1_1.py
1,542
4.15625
4
# Задача №1 # filename: hw_1_1.py # # Запросить у пользователя имя и фамилию. # Поприветсвовать пользователя с использованием его имени и фамилии. # Запросить День даты рождения (цело число). # Запросить Месяц даты рождения (цело число). # Запросить Год даты рождения (цело число). # Вывести количество прожитых ...
3e4a014b7bb54d92cf9f8c34a9986b497b689921
jonathanpwolfe/machine_learning
/gradient_descent.py
523
3.671875
4
import numpy as numpy import matplotlib.pyplot as pyplot N = 10 D = 3 X = numpy.zeros((N,D)) X[:,1] = 1 X[:5,1] = 1 X [5:,2] = 1 Y = numpy.array([0]*5 + [1]*5) costs = [] w = numpy.random.randn(D) / numpy.sqrt(D) learning_rate = 0.001 for t in range(1000): Yhat = X.dot(w) delta = Yhat - Y w = w - learning...
b95a56108b26a3ddd59a74dcf0e0a7da2de1d5fb
asadurski/snippets
/nltk_based/soundex.py
1,722
3.578125
4
import re def findval(singlechar): # Returns numerical value of character if singlechar.isalpha() and len(singlechar) == 1: if singlechar.lower() in 'bfpv': return '1' elif singlechar.lower() in 'cgjkqsxz': return '2' elif singlechar.lower() in 'dt': ...
baaf87acf617f3d35243a9b0f5a0603981061a1c
Chenyijun13/Coursework
/rentalshop.py
2,574
3.75
4
''' Chenyijun,Part2 ''' from customer import * class RentalShop: def __init__(self): #itialize the car pool self.cars = { "Hatchback":4, "Sedan":3, "SUV": 3 } def print_stock(self): ''' show the available cars ...
ad7cad1920baca00912febb245da5e0302b65d87
rmayherr/python
/arabic_to_roman.py
3,545
3.53125
4
import argparse as ap def converter(number): result = "" number = str(number) roman_values = { 1 : 'I', 5 : 'V', 10 : 'X', 50 : 'L', 100 : 'C', 500 : 'D', 1000 : 'M' ...
eb93c33be269ea1cf3877b8504c02425aa6e7283
rmayherr/python
/timeconversion.py
439
3.765625
4
def timeConversion(s): if (s.split(':')[2][2:] == 'AM'): if (s.split(':')[0] == '12'): return '00' + s[2:-2] else: return s[:-2] else: if (s.split(':')[0] == '12'): return s[:-2] return str(int(s[:2]) + 12) + s[2:-2] print(timeConversion('07:0...
6bb039724f1213cbc953f74072df7767b73b4811
rmayherr/python
/snail.py
1,777
3.921875
4
def snail(matrix): """ Given a 2 dimensional array with values, size can be anything. You have to give back an array so that you travel the array clockwise and moving like a snail's house. """ length_of_matrix = len(matrix) start = 0 counter = 1 result = [] #Check if the array is on...
cdedab7e9400e4a84cf902ef50a1acd7a854f4b2
rmayherr/python
/test2.py~
331
3.890625
4
#!/usr/bin/python3 class Example: """ Test python script """ def __init__(self,name,age): self.name=name self.age=age def write_out(self): print("Hello " + self.name + ".Your age is " + str(self.age)) if "__name__" == "__main__": print("Program name:" + __name__) a=Example("Frank",32) a.write...
8f719280695ac658200268046789953812fff787
rmayherr/python
/list_recursion.py
219
3.734375
4
def list_sum(some_list): if some_list == []: return 0 elif len(some_list) == 1: # base case return some_list[0] else: return some_list.pop() + list_sum(some_list) # recursive case
96923088b9f3d3e923b7867d042bc87e6b7ad12e
FreddMai/EnigmaGui
/PlugBoard.py
671
3.515625
4
from Translator import Translator # The plugboard class. class PlugBoard(Translator): def __init__(self, config): self.config = config.strip().split() self.configDict = {} # Pair the plugboard letters. for pair in self.config: self.configDict[pair[0]] = pair[1] ...
5eb61a6e224d6a447c211b2561f8fa07b1864c38
lyh71709/03_Rock_Paper_Scissors
/03_RPS_comparisons.py
1,742
4.1875
4
# RPS Component 3 - Compare the user's action to the computer's randomly generated action and see if the user won or not valid = False action = ["Rock", "Paper", "Scissors"] while valid == False: chosen_action = input("What are you going to do (Rock/Paper/Scissors)? ").lower() cpu_action = "rock" # Rock ...
68fbf8108a9879a7119844ab8af0f42cf0209d26
sgenduso/python-practice
/src/datetime_methods.py
418
3.65625
4
# import datetime library from datetime import datetime now = datetime.now() print now # 2016-04-25 18:27:59.145463 print now.year # 2016 print now.month # 4 print now.day # 25 print '%s/%s/%s' % (now.month, now.day, now.year) # 4/25/2016 print '%s:%s:%s' % (now.hour, now.minute, now.second) # 18:27:59 print '%s/%s/%s ...
9f087e3abf4746c61e3756fbf95705a72971ff4f
Somanathpy/Amazon_SE_Coding
/reverse_string_sentence.py
340
4.0625
4
str = input("enter a string:") str = str.split() result = [] def word_reverse(word): word = list(word) l = len(word) reverse_word = [] for i in range(0,l): reverse_word.append(word[l-i-1]) return "".join(reverse_word) for word in str: #word = word[::-1] word = word_reverse(word) result.insert(0,word) print...
b230d6d3193078d226373ab200222e7b0514b425
mariamnufal/BehavioralDataAnalysis
/Production code/Python/test_cramer_v.py
1,131
3.609375
4
# -*- coding: utf-8 -*- """ Created on Wed Jun 16 08:23:39 2021 @author: Florent """ import pandas as pd import numpy as np import unittest from functions import cramer_v df_input = pd.DataFrame({ 'name': ["Anna", "Amalric", "Arya", "Barbara", "Bob", "Ben"], 'color': ["blue", "red", "green", "yellow", "blue", "...
20caa893dfd14765fc050677192651700b2349e7
zhengdaying/ARBRT
/ex-5-3.py
232
3.625
4
def isNum(s): try: n=eval(s) except: return False return True s=input("请输入一个字符串:") if isNum(s): print("{}属于".format(s)) else: print("{}不属于".format(s))
7eeade7b9a65e67012286372a00a7f53f3b4edfc
zhengdaying/ARBRT
/ex-2-2.py
434
3.640625
4
SymbolStr=input("请输入货币体系符号:") #美元用“D”,“d”人民币用“R”,“r” if SymbolStr in['R','r']: t=eval(input("请输入货币值:")) D=t/6 print("转换后的货币是:{}D)".format(D)) elif SymbolStr in['D','d']: t=eval(input("请输入货币值:")) R=int(t*6) print("转换后的货币值是:{}R".format(R)) else: print("输入符号错误")
ced55ee757f946247dfa6712bd1357c303fbc8e1
jayanta-banik/prep
/python/queuestack.py
703
4.125
4
import Queue ''' # Using Array to form a QUEUE >>> from collections import deque >>> queue = deque(["Eric", "John", "Michael"]) >>> queue.append("Terry") # Terry arrives >>> queue.append("Graham") # Graham arrives >>> queue.popleft() # The first to arrive now leaves 'Eric' >>> queue....
bd5446c9f6a4ffe3189d6e100070f4d19a0a5bae
jayanta-banik/prep
/python/bfs_search.py
1,389
4
4
#!/usr/bin/env python ''' Breadth First Search Input: tree and value to search for Output: Breadth first search for a specified value in tree ''' class Node(): def __init__(self, val): self.val = val self.left = None self.right = None def bfs(n, person): tree = [] tre...
72bd6afde1669fedf067fcf89a2237aa273c8214
ATLS1300/pc02-graffiti-11-elke-lintukorpi
/PC02_Graffiti_LINTUKORPI_WEEKS.py
1,545
3.765625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Sep 4 14:43:41 2020 @author: elkelintukorpi """ from turtle import * #import the library of commands that you'd like to use colormode(255) # Create a panel to draw on. panel = Screen() w = 750 # width of panel h = 750 # height of panel panel.setup(...
6a9747d5ac43ea964c6ac2680eb23b8baac243c8
janMasangcay/BasicPythonProjects
/test.py
13,152
4.59375
5
##Variable num1 = 1 ##Python Data Types: Integer = 9 Float = 9.01 String = "Dagul" String1 = "3" List = ['Dagul', 'nognog'] Tuple = (1, 2, 3, 'a', 'b', 'c') Dictionary = { 'index1': 'value1', 'index2': 'value2' } Python order of operation: BIDMAS -Bracket -Indices -Division -multiplication -Addition -subtraction B...
cfcf4d6dd3ddb93b8f636ca7f224323496b096ec
dsrlabs/PCC
/CH 5/5_4a_AlienColor_2.py
410
3.9375
4
print() alien_color = ['green'] if 'green' in alien_color: print("The alien color is green, you just earned 5 points for shooting the alien!") else: print("The alien color isn't green. You just earned 10 points!") if 'blue' in alien_color: print("The alien color is green, you just earned 5 points for shooti...
5bce167313c249ba3ae12cb62787711b2d42d07c
dsrlabs/PCC
/CH 5/5_1_ConditionalTests.py
775
4.34375
4
print() color = 'black' #The color black is assigned to variable named color print("Is color == 'black'? I predict True.") #Here, the equality sign is used to determine if the value on each side of the operator matches. print(color == 'black') #Here the result of the equality prediction is printed print("\nIs color =...
1228d627795969c4325f56aec74d589468da8e51
dsrlabs/PCC
/CH 8/8_8_UserAlbum.py
615
4.15625
4
print() def make_album(artist_name, album_title): """Return a dictionary with the album information""" album_info = {'artist_name' : artist_name.title(), 'album' : album_title.title()} return album_info print("\nPlease enter the artist name:") print("Please enter the album title:") print("[enter 'q' at any...
1d86f145ce68ca28fb615b990f72b4ddde489415
dsrlabs/PCC
/CH 8/8_7_album.py
540
4.1875
4
# Thus block of code calls a function using a default # an f-string is used. print() def make_album(name, album_title, tracks =''): """Return a dictionary with the album information""" album_info = {'artist_name' : name.title(), 'album' : album_title.title()} if tracks: album_info['tracks'] = tracks...
3c2e3319644f564138d35e8412b4fa148881171d
dsrlabs/PCC
/CH 3/more_guests.py
1,957
3.59375
4
guest_list2 = ['Delta', 'Ivanhoe', 'Beryl'] message = "Hello" + " " + guest_list2[0].title() + "," + " " + "I would like to invite you to dinner" + "." message2 = "Hello" + " " + guest_list2[1].title() + "," + " " + "I would like to invite you to dinner" + "." message3 = "Hello" + " " + guest_list2[2].title() + "," + "...
28e0623615919eb16d4df81c6c772f89cda0c534
dsrlabs/PCC
/CH 5/5_5a_AlienColor_3.py
392
4.03125
4
#The approach here is to change the color in line 3 to get the proper result print() alien_color = ['yellow'] if 'green' in alien_color: print("The alien color is green. You just earned 5 points!") elif 'yellow' in alien_color: print("The alien color is yellow. You just earned 10 points!") elif 'red' in alien_c...
0c4d35efeba1cdec772f30f538aec4353bb90329
Ivonnelasco01/Assignment-5
/program 2.py
391
4.09375
4
def low_num(): num1 = int(input("Enter 1st number: ")) num2 = int(input("Enter 2nd number: ")) num3 = int(input("Enter 3rd number: ")) min = num1 if min < num2 and min < num3 : min = min elif num2 < min and num2 < num3: min = num2 elif num3 < min and num3 < num2: min ...
acdb4b1e0092ef095936677423fa442f466316d4
srdjankrstic/project-euler
/p012.py
1,662
3.671875
4
#!/usr/bin/python -tt # File: p012.py # Author: Srdjan Krstic (krstic.m.srdjan@gmail.com) # Created: 2012-06-30 17:59 # Description: Project Euler problem 12 import sys import re import math def sieve(n): prime = [False, True] * (n // 2 + 1) prime[1] = False prime[2] = True for i in xrange(3,...
ba6c00905b462ec407002771a59ec12b2532bbcd
yukiiwong/FC-TensorFlow-MNIST-PRACTICE
/fcnn.py
4,839
3.6875
4
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import os from PIL import Image import numpy as np import cv2 #导入mnist数据,'MNIST_data':判断'MNIST_data'文件夹中是否有数据,没有则下载;one_hot:特征提取的一种编码形式 mnist = input_data.read_data_sets('./MNIST_data', one_hot = True) #占位符 x = tf.placeholde...
1b31f1a77fd69abb1b539fc0acc9e971f7ce6f45
cocobaco/project_euler
/prob46.py
1,536
3.609375
4
# -*- coding: utf-8 -*- """ Created on Fri Nov 13 13:23:49 2020 @author: PC1 """ # project euler: https://projecteuler.net # problem 46: Goldbach's other conjecture from time import time from prob3 import is_prime def goldbach_check(num): '''find whether a, b exist such that num == a + 2 * (b ** 2)''' ...
6546d989b759a3cfa54503de8bc7361a00ff7327
cocobaco/project_euler
/prob41.py
2,132
3.546875
4
# -*- coding: utf-8 -*- """ Created on Tue Dec 8 11:28:07 2020 @author: PC1 """ # project euler: https://projecteuler.net # problem 41: pandigital prime from time import time from itertools import permutations from prob3 import is_prime from prob32 import is_pandigital from prob35 import num_to_digitlist, digitli...
fa00ab6e58560d61863db7d61686cafb07a38c8b
cocobaco/project_euler
/prob1.py
651
3.953125
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 13 11:36:05 2020 @author: Admin """ # project euler: https://projecteuler.net # problem 1: multiples of 3 and 5 from time import time def solution(num): summ = 0 for x in range(3, num): if (x % 3)*(x % 5) == 0: summ += x return summ ...
4cbfde75ed0617ca3ac8f27b708904676ff54d11
QuantumCode2000/Woork_Class
/Tarea/Galletas.py
374
3.671875
4
class Galleta: def __init__(self,sabor,color): self.sabor = sabor self.color = color def aumentar_chispitas(self): return "chispas" def __str__(self): return "La galleta es de {} con un color {} ".format(self.sabor,self.color) galleta = Galleta("Chocolate","Cafe") print(gall...
8ad31360beae968e20fc4cf6222a262a215d09ca
justinlee007/traffic-signs
/data_exploration.py
3,730
3.578125
4
import csv import matplotlib.pyplot as plt import data_reader import project_2_lenet def read_signnames(filename="signnames.csv"): # Read signnames.csv and create a list of labels signnames = [] with open(filename, "rt") as csvfile: signreader = csv.reader(csvfile, delimiter=',') for ind...
87896af8383d0c6925eb54ffffcacda570c26b7c
PMiskew/Coding_Activities_Python
/Activity 1 - Console Activity/ConsoleFormulaStage2.py
2,674
3.921875
4
import time import random print("\n\n**************************************") print("Introduction: ") print("\n\tThis calculator will perform two calculations\n") print("\tCalculation 1: Calcate the number of rotations") print("\tof the drive gear for each rotation of the") print("\tmotor gear, given the tooth count ...
3a21e49a519f3120f63a8205759d696f0a98e579
PMiskew/Coding_Activities_Python
/Activity 2 - Event Drive Program/GUIVolCylStepComplete.py
1,324
3.625
4
import tkinter as tk import math #VARIABLES root = tk.Tk() file = open("data.txt","w") #FUNCTIONS def runMe(*args): print("running") #Access Text r = entRadius.get() h = entHeight.get() try: r = float(r) h = float(h) if (r >= 0 and h >= 0): v = calcVolume(r,h) print(v) display.config(stat...
3d177f31578123ad01d5733c178fbd81d89adcdd
PMiskew/Coding_Activities_Python
/Activity 1 - Console Activity/ConsoleFormulaStage1.py
621
4.625
5
#In this stage we will make a simple program that takes in #values from the user and outputs the resulting calculation #Some chnage print("Volume of a Cylinder Formula: ") name = input("Please input your name: ") print("The volume of a cylinder is") print("V = (1/3)*pi*r\u00b2") #Input radius = input("Input radius(...
ebec550e7d1fd66f0d2322b0f4fe7d3995c6a261
johan1a/Algorithms
/sort/merge_sort.py
832
3.71875
4
from random import randint import time def merge_sort(m): n = len(m) if n <= 1: return m left = m[:n/2] right = m[n/2:] left = merge_sort(left) right = merge_sort(right) return merge(left, right) def merge(left, right): result = [] while left and right: if left...
715c0c4655083c4f5b254231bb6aa151b34663d9
x-liu/pythonFun
/helloWorld.py
193
3.5
4
print("Hello Python world!") myName = ['xing','liu'] print(myName) myName[0] = 'Meina' message = f"My first name is {myName[0].title()}, and my last name is {myName[1].title()}" print(message)
fb88aa2145bf3a35d17486e6b69cfb74ee83e8b1
monicador/Python
/diccionario_contar_sumar_pares.py
779
3.8125
4
''' Diseñe un algoritmo que permita contar y sumar los números pares e impares existentes en una serie de 1 a n, siendo n un número digitado por un usuario. A) Imprimir Contador de impares y pares. B) Imprimir Suma de impares y pares. ''' '''def contar_pares_impares(lista): pares, impares = 0,0 for n in l...
7e19a423206e308f45ad04f64a1729141cd2739d
monicador/Python
/while_num_negat.py
302
4.34375
4
''' Diseñe un algoritmo que reciba numeros digitados por el usuario y los imprima en pantalla, el programa debe terminar cuando el usuario digite un numero negativo ''' n = 0 while n>= 0: n = float(input("Digite un numero: ")) if n >= 0: print("El numero digitado es: ", n)
aab38418a78bf0c74208b2c631be1114dccf1f08
monicador/Python
/for2.py
72
3.625
4
for i in range(0,10,2): print("Estamos en la iteracion " + str(i))
6cabde06d7e01776ad48c48432c22ef0c3f2e900
monicador/Python
/2_ciclo_acumulador.py
783
3.6875
4
''' Elaborar un algoritmo que permita acumular la sumatoria de números en una variable teniendo en cuenta que si el numero es mayor que 10 y par se acumula y si el numero es impar y menor que 20 no se acumula. El algoritmo termina cuando la variable acumulada sea mayor o igual a 50. INICIO ENTERO: N, SUMA SUMA = 0 ...
b10fa5a4ad2f1e305a9e60146e7512a51971a5ad
monicador/Python
/funcion_Orden_Superior-04-filter-lamdda.py
1,339
4.6875
5
# FUNCIONES ANONIMAS ''' Habrá ocasiones en las cuales necesitemos crear funciones de manera rápida, en tiempo de ejecución. Funciones, las cuales realizan una tarea en concreto, regularmente pequeña. En estos casos haremos uso de funciones lambda. ------------------------------------------------- lambda argumento : ...
cef91977fdd2325a26844bcc65d06cc3021313ef
chisasy/PythonProject
/day1/print.py
273
3.9375
4
name = "Chisato" print("Hello," + name) print("Hello ", name) print("Hello {}".format(name)) print("{}".format(name)) print("{} hello {}".format(name, 965)) # , = + # ,の後ろはスペース:コーディング規約 # {} .format()で{}のところに()内を表示
406cd7f6f9ae9885ab029edd7221b223ce775c43
zhaobozhen/SimpleGA
/best.py
785
3.609375
4
# 最適解と最適解の遺伝子を探す def best(pop, fit_value): px = len(pop) max_indi1 = [] max_indi2 = [] max_indi3 = [] min_indi1 = [] min_indi2 = [] min_indi3 = [] max_fit = min_fit = fit_value[0] for i in range(1, px): if fit_value[i] > max_fit: max_fit = fit_value[i] ...
97fe484f445dda94021167bc4bfd6525e63c6483
jgonzalezzu/MinTIC2022-UNAB-G63
/CICLO-1/EjerciciosClase/S4/Tuplas.py
1,006
4.0625
4
# Semana 4 - Clase 4 - Tuplas - Ejercicio 1 ''' DEF: Una tupla es una secuencia de valores similar a las listas, pero a diferencia de estas, la tuplas contienen VALORES INMUTABLES, indexados por números enterose i.e. [0], [1], [2], ... , [N]; siendo N un número entero. Estos elementos están contenido entre paréntesis '...
66671cb2cb85ab97e4a7ad28230996ad8b7cef88
jgonzalezzu/MinTIC2022-UNAB-G63
/CICLO-1/AlgoritmosOperadores/Ejercicio2.py
366
3.984375
4
print("Ejercicio 2") ''' calcule la media aritmética de 3 numeros cualesquiera. ''' print('Este programa calcula la hipotenusa de 3 números que ingrese') a = float(input('Ingrese el primer número: ')) b = float(input('Ingrese el segundo número: ')) c = float(input('Ingrese el tercer número: ')) median = (a+b+c)/3 p...
b94a4f71077fadc242175ea1fafac0c1dfacc6f6
jgonzalezzu/MinTIC2022-UNAB-G63
/CICLO-1/EjerciciosClase/S5/Recursividad2.py
330
4
4
# Semana 5 - Clase 2 - Recursividad - Ejercicio 2 #TODO: programa que calcula el n! (factorial) de un valor dado con recursividad def factorial(numero): print('Valor inicial -> ', numero) if numero > 1: numero=numero*factorial(numero-1) print('Valor final -> ', numero) return numero print(fac...
4816b6b785b0901a742a8935c53a6898c12d44da
jgonzalezzu/MinTIC2022-UNAB-G63
/CICLO-1/EjerciciosClase/S3/Listas2.py
588
4.09375
4
lista1 = ['Adrian','Natalia','Carlos','Octavio'] lista2 = ['Fabian','Jose','Fernando'] #TODO: Concatenar las dos listas nueva_lista = lista1 + lista2 print(nueva_lista) #TODO: Emplear el operador * nueva_lista = lista1 * 3 print(nueva_lista) #TODO: Recortar las cadenas lista3 = nueva_lista[2:4] print(lista3) lista3 = n...
aae146ea2a2d4b9b3b4af61c466ea9a685c12f63
jgonzalezzu/MinTIC2022-UNAB-G63
/CICLO-1/EjerciciosClase/S4/DiccionariosYTuplas12.py
1,943
3.96875
4
# Semana 4 - Clase 2 - Diccionarios y tuplas - Ejercicio 12 # TODO: Diccionario con el número como clave y el apellido como valor de la seleccion colombia import os import time def clear(): os.system('clear') #on Windows System clear() jugadores = {} option = 0 while option != 3: try: print('1. Ingresa...
eb25b1c394d1e27f64c691e444e693cc48cf638c
jgonzalezzu/MinTIC2022-UNAB-G63
/CICLO-1/Reto2/Problematica2_while.py
927
3.921875
4
print('Problematica2 - with WHILE loop') #Variable de control de entrada horas = 0 trabajadores = int(1) #Declaración de variables valor_hora = float(input('Ingrese el valor de la hora > ')) total_horas = int(0) #Mensaje de interfaz print('===============================================') print('Para finalizar el regis...
562f08423c858c849765ceab54d8956a63b970d2
jgonzalezzu/MinTIC2022-UNAB-G63
/CICLO-1/EjerciciosClase/S4/DiccionariosYTuplas6.py
284
3.953125
4
# Semana 4 - Clase 2 - Diccionarios y tuplas - Ejercicio 6 #TODO: con la función .items() se lee dato y clave. Item retorna los items diccionario = {'one':'uno','two':'dos','three':'tres'} print(diccionario.items) for clave,valor in diccionario.items(): print(clave,' - ', valor)
5050e8e1948cd2cf6a85f122e9657819493da58f
jgonzalezzu/MinTIC2022-UNAB-G63
/CICLO-1/EjerciciosClase/S4/DiccionariosYTuplas7.py
448
3.8125
4
# Semana 4 - Clase 2 - Diccionarios y tuplas - Ejercicio 7 #TODO: con la función .clear se limpia el diccionario diccionario = {'one':'uno','two':'dos','three':'tres'} # diccionario.clear() lista = ['Color', 'Talla', 'Marca'] # TODO: Crear un diccionario con la lista Color, Talla y Marca. Con valores por defecto igual ...
03b65d62b6d84c9635f28f7f5e75f449bc5336ab
mugbug/algorithms-in-a-whole-new-level
/dynamic_programming/memoization/binomial_coefficient.py
435
3.625
4
def binom(n, k): if k == 0 or k == n: return 1 else: MEMO[n][k] = binom(n - 1, k - 1) + binom(n - 1, k) return MEMO[n][k] MAX = 10 NIL = -1 if __name__ == '__main__': # initialize memoization matrix with NIL MEMO = [[NIL]*MAX]*MAX # print first MAX lines of Pascal's Triangle ...
b480484490c707983c7ccc96047d1b116d99075f
danialahmed2286/python-assignments
/task 4.py
203
3.90625
4
#!/usr/bin/env python # coding: utf-8 # In[3]: A = int(input("enter radius here : ")) print ("The Area of the circle is", (22//7) * (A**2), "sq.meter") input ("press enter for exit") # In[ ]:
33fce5ec3e134a4f888e5c077dc04a822b132a8e
avryjms7/Resume
/gradeCon.py
329
4.28125
4
# grade converter grade = int(input("Enter Student's Grade from 0-100?")) if grade >= 90: print("A") elif grade >= 80 and grade <= 89: print("B") elif grade >= 70 and grade <= 79: print("C") elif grade >= 65 and grade <= 69: print("D") else: print("F") ...
b9a7e300da1131b0ed2eb10c91aff492dcdb2c5b
edunzer/MIS285_PYTHON_PROGRAMMING
/WEEK 2/BONUS_QUESTION.py
218
3.578125
4
import turtle star = turtle.Turtle() star.pencolor("blue") for i in range(5): star.forward(50) star.right(144) star.pencolor("red") for i in range(5): star.forward(50) star.left(144) turtle.done()
93deaa3d236efa015c0525e1328be94642630492
edunzer/MIS285_PYTHON_PROGRAMMING
/WEEK 3/3.5.py
1,278
4.21875
4
# Shipping charges def lbs(weight): if weight <= 2: cost = weight * 1.50 print("Your package will cost: $",cost) elif weight >= 2 and weight <= 6: cost = weight * 3.00 print("Your package will cost: $",cost) elif weight >= 6 and weight <= 10: cost = weight * 4.00 ...
e5e657d5613770c7e96cfcc4cd64810a9816353b
edunzer/MIS285_PYTHON_PROGRAMMING
/WEEK 5/5.16.py
639
3.953125
4
## ODD/EVEN COUNTER import random def generated_random_num(): random_num = random.randint(1,10) return random_num def even_check(number): if (number%2)==0: return True return False def printResults(even_num, odd_num): print(even_num, "were even.") print(odd_num, "were odd.") def nu...
5a615e1e388e6feb6a330c15dfff5250e7e1e66f
edunzer/MIS285_PYTHON_PROGRAMMING
/WEEK 4/4.11.py
259
3.5625
4
## WEIGHT LOSS w_start = int(input("Please enter in your start weight: ")) def chart(w_start): print('Month\t Weight') print('----------------') for m in range (0, 7, +1): w = (w_start-(4*m)) print(m, '\t', w) chart(w_start)
9db99d0bbc24283d36cfc45ae4a18293e24f04f4
willdeardorff/FormalDinnerSeating1
/Formal Dinner Homework.py
1,878
3.65625
4
#family_dinner.py #Jan_19_2020 #Will Deardorff import random # from stackoverflow... def find_nth(haystack, needle, n): start = haystack.find(needle) while start >= 0 and n > 1: start = haystack.find(needle, start+len(needle)) n -= 1 return start student = [] waiter = [] left_over = [] ki...
46ff61c6675eaccb5f09f68dfe8663b0630b96f1
jkurambhatti/jayeshPythonProjects
/anandology/problem.py
1,294
3.640625
4
# def cumsum(l): # for index, value in enumerate(l): # if index == 0: # l[index] = value # else: # l[index] = sum(l[index - 1: index + 1]) # # print l # # cumsum(range(1,5)) # # # def product(l): # k = 1; # for x in l: # k = k * x # # return k # # def ...
704b3f6e7a80987bb0947e3b70b38d4675b7f6e0
jkurambhatti/jayeshPythonProjects
/PythonExperiments/calculator.py
380
3.640625
4
def add(*args): result = 0 for i in args: result = result + i print result def sub(*args): result = 0 for i in args: result = i - result print result def mul(*args): result = 1 for i in args: result = result * i print result def div( n, d ): result = ...
d413b2d2a82c86d820d410548e25ea3cdb8c548a
jkurambhatti/jayeshPythonProjects
/Udacity/take_a _break.py
625
3.5
4
''' the simple udacity project reminds you taking breaks every 2 hour. every 2 hour it plays your favourite palylist video/audio on youtube ''' import webbrowser import time playlist = ["https://www.youtube.com/watch?v=KcUfiGgTkbw", "https://www.youtube.com/watch?v=wZSjyCXCSeU", "https...
dff5aed4a19dfab650804f223bb75feb7f80d3c8
jkurambhatti/jayeshPythonProjects
/anandology/headtails.py
441
3.84375
4
# Problem 19: Implement unix commands head and tail. The head and tail commands take a file as argument and prints its first and last 10 lines of the file respectively. import sys # def head(): # filename = sys.argv[1] # for line in open(filename).readlines()[:10]: # print line.strip() # head() def...
ab292769f2352a54519efe33fa8fa3d4114d4cc2
zhengjingwei/statistical-learning-method
/LinearRegression/linear_regression.py
1,297
3.625
4
import numpy as np import matplotlib.pyplot as plt class LinearRegression(object): """一元线性回归""" def __init__(self, *args, **kwargs): self.max_iter = 1000 self.lr = 1e-2 self.w = 0 self.b = 0 def loss(self, X, Y): X, Y = np.array(X), np.array(Y) ...
578e759839a44eef3ffd9d22d37ca32057c7882d
urimeba/claseAlfas
/ejercicios2.py
2,432
4.0625
4
""" Ejercicio #1 - TRY-CATCH try: haz_algo_si_no_hay_error except Exception as tu_variable_de_error : haz_algo_con_el_error Revisa el codigo y verifica por que marca error. Instancia una sentencia TRY-CATCH para evitar que el programa rompa y manda un mensaje de error personalizado, explicando el problema con...
9b8486be744b3c54136d6c063ebff9719c4dfa51
natioliveira97/PVC
/PD6/src/create_imagedata.py
1,918
3.515625
4
''' Para rodar tem que rodar o programa com o nome do video como argumento (sem .avi) Para fazer um positivo clique e arraste fazendo um triangulo em volta da bola e aperte em 'p' Para fazer um negativo aperte 'n' Para pular o frame aperte outra tecla ''' import numpy as np import sys import cv2 cropping = Fals...
0bab730ca44947051d164e71fdd884a5a8430f90
343829084/leetcode-2
/solutions/092.reverse-linked-list-ii/reverse-linked-list-ii.py
914
3.875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseBetween(self, head, m, n): """ :type head: ListNode :type m: int :type n: int :rtype: ListNode ...
e837d9a77fdf176ef4f8f00019eb14a9955d4efc
343829084/leetcode-2
/solutions/105.construct-binary-tree-from-preorder-and-inorder-traversal/construct-binary-tree-from-preorder-and-inorder-traversal.py
908
3.953125
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def buildTree(self, preorder, inorder): """ :type preorder: List[int] :type inorder: List[int] ...
1380cd6ad6f510b2a8f7e672bf56633615183192
sanchitadhole/Python
/day2.py
917
4.09375
4
# Make Simple Calculator def add(num1, num2): return num1 + num2 def sub(num1,num2): return num1-num2 def mul(num1 , num2): return num1*num2 def divide(num1, num2): return num1/num2 print("please select operation:\n" "1.addition\n" "2.substraction\n" "3.multiplecation\n" "4....
8294cf5fb457523f714f4bfd345756d282ed54f6
svetlmorozova/typing_distance
/typing_distance/distance.py
1,094
4.3125
4
from math import sqrt import click from typing_distance.utils import KEYBOARDS @click.command() @click.option('-s', '--string', help='Input string', prompt='string') @click.option('-kb', '--keyboard', help='What keyboard to use', type=click.Choice(['MAC'], case_sensitive=False), default='MAC') @click....
4b265a94078ece54a24f07b7e78a2e58aa4626aa
mohithpothineni/cspp1-assignments
/m8/Is In Exercise/is_in.py
992
3.984375
4
'''chcecks for a char in a string''' # Exercise: Is In # Write a Python function, isIn(char, aStr), #that takes in two arguments a character and String and #returns the isIn(char, aStr) which retuns a boolean value. # This function takes in two arguments character and String and returns one boolean value. def is_in(ch...
b4cb8953710b6d3404f2c8a2ccf0a342465c0eaf
mohithpothineni/cspp1-assignments
/m11/Integer Division Exercise/integer_division.py
808
3.96875
4
#Exercise: Integer Division Exercise #Modify the code for integer_division so that this error does not occur. def integer_division(x, a): """ x: a non-negative integer argument a: a positive integer argument returns: integer, the integer division of x divided by a. """ if a == 0: retur...
f50164b9a5b648736c5e554a2a0d5ed90608e885
mohithpothineni/cspp1-assignments
/m9/Functions and Objects Exercise-2/functions_and_objects_2.py
634
4.0625
4
'''func and objects 2''' #Exercise : Function and Objects Exercise-2 #Implement a function that converts the given testList = [1, -4, 8, -9] into [2, -3, 9, -8] def inc(num_i): '''takes and input n and increment it by 1''' return num_i + 1 def apply_to_each(list_, func_): '''applies func to entire list an...
253f871201773461c31a334dc32421e4a57ffda9
c-huynh/algorithms2
/homework4/johnsons.py
3,536
4.25
4
""" In this assignment you will implement one or more algorithms for the all-pairs shortest-path problem. Here are data files describing three graphs: g1.txt g2.txt g3.txt The first line indicates the number of vertices and edges, respectively. Each subsequent line describes an edge (the first two numbers are its tai...
284fc1b0e312bfb0a4028d0a0cd401abe7941f5e
c-huynh/algorithms2
/homework4/bellman_ford.py
1,000
3.984375
4
def bellman_ford(graph, n, source): """ Implementation of the Bellman-Ford algorithm. Returns: list of shortest paths to each vertex, (with index corresponding to vertex) if no negative cycles present Returns: None if there are negative cycles """ # initialize all distances from ...
872774c03ec25f0d46475ea53044cb6f5f99d514
c-huynh/algorithms2
/homework3/knapsack.py
1,205
3.875
4
""" The file (knapsack1.txt) describes a knapsack instance, and it has the following format: [knapsack_size][number_of_items] [value_1] [weight_1] [value_2] [weight_2] ... For example, the third line of the file is "50074 659", indicating that the second item has value 50074 and size 659, respectively. You can as...
d727055e2ad18639dbd54f0dc1e73a04525fb1f3
uirasiqueira/Exercicios_Python
/Mundo 2/Aula13.Ex54.py
476
3.84375
4
'''Crie um programa que leia o ano de nascimento de sete pessoas. No final mostre quantas pessoas ainda não atingiram a maioridade e quantas já são maiores''' from datetime import date m=0 x=0 a=date.today().year for c in range (1,8): idade = int(input('\033[33mDigite o seu ano de nascimento:')) if a - idade <...
35d99a242c683446b37534a259c3b42261e1e102
uirasiqueira/Exercicios_Python
/Mundo 3/Aula20.Ex99.py
726
4.0625
4
'''Faça um programa que tenha uma função chamada maior(), que receba vários parâmetros com valores inteiros. Seu programa tem que analisar e dizer qual deles é o maior.''' #Não fiz! from time import sleep def maior(* núm): cont = maior = 0 print('-'*30) print('\nAnalisando os valores passados... ') for...
9ddb428a24ae9cacca8e9ad5cd6631b7b77fea65
uirasiqueira/Exercicios_Python
/Mundo 1/Aula07.Ex11.py
256
3.96875
4
l = float(input('Qual a largura da parede em metros?')) a = float(input('Qual a altura da parede em metros?')) area = l*a tinta = area/2 print(f'A área da parede será de {area} metros quadrado sendo necessário a utilização de {tinta} litros de tinta')
57ce75fb09ccff24fa6e55697c34cf3cd9945484
uirasiqueira/Exercicios_Python
/Mundo 3/Aula21.Ex103.py
991
4.09375
4
'''Faça um programa que tenha uma função chamada ficha(), que receba dois parâmetros opcionais: o nome de um jogador e quantos gols ele marcou. O programa deverá ser capaz de mostrar a ficha do jogador, mesmo que algum dado não tenha sido informado corretamente ''' '''def ficha(lista): print('-.'* 15) nome =...