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
c2c711c85fadceddd47c403ecd3007e0857ed823
ParkJinWoo1/Python
/Python01/com/test03/rand02.py
422
3.90625
4
# -*- coding:utf-8 -*- import random # 1부터 45 사이의 숫자 6개를 중복 없이 만들어서 리스트로 리턴하는 lotto()함수 만들기 # main 함수에서 호출하여 출력하자 def lotto(): lotto = set() while len(lotto) <= 6: ran = random.randint(1, 45) lotto.add(ran) result = sorted(lotto) return result if __name__ == '__main__': ...
8aa3d166e597384b03af2bc3dc58b83582b11b9f
ParkJinWoo1/Python
/Python00/start.py
299
3.796875
4
''' (문자열 값) REPL : Read Eval Print Loop Interactive shall (대화형 프로그래밍 환경) ''' # 주석 # 변수 = 값 a= 10 b= 20 # 출력 print(a) print(b) print(a + b) # 문자 출력 print('a') print("b") print('a' + "b" + 'cd') # print('a'+ a) # 타입이 달라서 + 불가
c2215797ceff8c4dcf5747ed08ae72d8289cbd85
ParkJinWoo1/Python
/Python01/com/test03/mtest02.py
241
3.65625
4
# -*- coding:utf-8 -*- def func01(x,y): return x + y def func02(x, y): return (x + y, x - y) if __name__ == '__main__': a = func01(1, 3) print(a) b= func02(4, 7) print(b) c, d = func02(5, 3) print(c, d)
9b3f76d0f3659b1b5d9c4c1221213ea6fbbc2a5b
arloft/thinkpython-exercises
/python-thehardway-exercises/ex4.py
892
4.34375
4
my_name = "Aaron Arlof" my_age = 40 # sigh... my_height = 70 # inches my_weight = 152 # about my_eyes = 'blue' my_teeth = 'mostly white' my_hair = 'brown' print "Let's talk about %s." % my_name print "He's %d inches tall" % my_height print "He's %d pounds heavy" % my_weight print "Actually, that's not too heavy." prin...
85d6c3f2854c6ecbf629ce22ceffe1e74f2444eb
arloft/thinkpython-exercises
/python-thehardway-exercises/ex2.py
311
3.703125
4
# A comment, thes are notes you put into your program to read later # Anything after the pound sign (on the same line) is ignored by python print "i could have code like this." # the comment after it is ignored # you can also use a comment to 'disable' some code # print "This won't run" print "This will run."
94419017d19789016381c741c8446c3908c644b3
mdegregori1/Graphs
/projects/ancestor/ancestor.py
2,033
3.78125
4
# essentially, looking for the longest path possible between starting_node and ancestors from graph import Graph from util import Queue def earliest_ancestor(ancestors, starting_node, parents=False): # must keep track of node and its ancestor, call in queue and graph # after, must create graph -> loop through...
fda058f3e817ba5d21a183087d45c4a987f5bfdc
nitrons/Writy
/app.py
826
3.828125
4
from tkinter import * from tkinter import ttk from tkinter import filedialog # your code goes between window and window.mainloop window = Tk() window.title('Writy') window.configure(background = 'gray1') # function for saving file def save(event): with open('text.txt', 'w') as file: file.write(text1.get("1.0",'en...
8824eea0fe2c3e35614e03a38fd16082732d7e21
aldairespiritu19/Python-Projects
/Abstraction.py
426
3.75
4
from abc import ABC, abstractmethod class Basketball(ABC): def Points(self, amount): print("Your points amount in the first quarter: ",amount) @abstractmethod def total_points(self, amount): pass class Scoring(Basketball): def total_points(self, amount): print('Your total...
34dd1eb23b78a9de93547fa72cb32d2b0091d78a
pettybai/my_practice
/senior/context.py
1,734
4.03125
4
# 什么是上下文?其实我们可以简单地把它理解成环境 # 进程上下文指的是一个进程在执行的时候,CPU 的所有寄存器中的值、进程的状态以及堆栈上的内容等,当系统需要切换到其他进程时,系统会保留当前进程的上下文,也就是运行时的环境,以便再次执行该进程。 # 上下文管理器协议,是指要实现对象的 __enter__() 和 __exit__() 方法 from math import sqrt, pow class Point(object): def __init__(self, x, y): print('init') self.x, self.y = x, y def __ent...
4d865fdb57bc91e125c5e8034966982c79019cce
pettybai/my_practice
/function/decorator.py
1,448
3.71875
4
########################### # 装饰器就是一个返回函数的高阶函数,一种高阶函数的用法 # 装饰器其实就是一个语法糖,存在参数传值的顺序 # def print_func_name_first(func): def wrap(): print(func.__name__) return func return wrap def runtime(): import time start = time.time() def decorator(func): def wrap(*args, **kwargs): ...
7f097848244c4d1f3510309310c7e75db71d839d
pettybai/my_practice
/operation/thread_local.py
2,146
3.890625
4
# 很简单的构想 # 同一线程会进行内存共享 # 意味着对变量做修改会影响其他线程 # 那怎么将线程和变量绑定呢?局部变量,全局字典绑定,ThreadLocal # 局部变量 from threading import Thread, current_thread, local # def echo(num): # print(current_thread().name, num) # # # def calc(): # print(current_thread().name + 'is running') # local_num = 0 # for i in range(10000): # ...
29068efd77bff8bda17c5026f2a067b38873e51f
slwpsn/pyt2
/lesson1_task5.py
774
3.96875
4
# Пользователь вводит две буквы. Определить, на каких местах алфавита они стоят, и сколько между ними находится букв. # Блок-схемы — https://drive.google.com/file/d/11mGcB9Poc0QZqxjVP14_TOXe0RAnMXTu/view?usp=sharing a = input('Введите первую букву на латинице: ') b = input('Введите вторую букву на латинице: ') alpha...
4f7af138ed16b25e1be312763159b7643ecc63dc
andrijana-kurtz/Udacity_Data_Structures_and_Algorithms
/project4/student_code.py
1,814
3.59375
4
from heapq import heappush, heappop, heapify from math import sqrt def calc_euc_dist(a, b, intersections): a = intersections[a] b = intersections[b] return sqrt((a[0] - b[0])**2 + (a[1] - b[1])**2) class PathIsec: def __init__(self, no): self.no = no self.previous = None self.c...
c4d6ef81f598c2f0277bb734bfd90316be19043b
andrijana-kurtz/Udacity_Data_Structures_and_Algorithms
/project3/problem_5.py
2,914
4.21875
4
""" Building a Trie in Python Before we start let us reiterate the key components of a Trie or Prefix Tree. A trie is a tree-like data structure that stores a dynamic set of strings. Tries are commonly used to facilitate operations like predictive text or autocomplete features on mobile phones or web search. Before w...
69221b1ff0e2c1951a093abc0b095f4f16023b4c
navarrs/16811-robo-math
/hw2/code/q3.py
3,367
4.03125
4
# @author Ingrid Navarro # @andrewid ingridn # @date October 15, 2020 # # @brief Newton's method on finding roots # @notes # # Includes --------------------------------------------------------------------- import numpy as np from enum import Enum import matplotlib.pyplot as plt # # Problem impl...
03d52796292acc21d931c5e898a366db75acf112
Kwabena-Kobiri/Breast-Cancer-Analysis-with-AI
/GUI.py
2,483
3.5625
4
#IMPORT TKINTER MODULES FOR BUILDING UI from tkinter import * from PIL import ImageTk, Image from tkinter import filedialog from tkinter.filedialog import askopenfilename #PROVIDE FUNCTIONS TO BE USED IN UI def selectImage(): global canvas canvas = Canvas(root, width = 300, height=300) canvas...
8ec108d9e7689393dce6d610019da91cd693dfd7
ottoman91/ds_algorithm
/merge_sort.py
1,124
4.375
4
def merge_sort(list_to_sort): #base case: lists with fewer than 2 elements are sorted if len(list_to_sort) < 2: return list_to_sort # step 1: divide the list in half # we use integer division so we'll never get a "half index" mid_index = len(list_to_sort) / 2 left = list_to_sort[:mid_index] right = l...
5983a91db3ea0a57cf7407dfb26d3f292e8de46d
CursosIE/IE-0217-II-16-G8
/Lab0/suma.py
499
3.828125
4
#!/usr/bin/python ## @package suma # Script para sumar. # import sys import math ## Esta función suma los elementos de una lista. # @param data la lista. # @return el resultado de la suma. def sumar(data): result = 0.0; for i in data: result = result + i return result if __name__ == "__main__"...
9abc0a18f0340132c518e9881dfdf5687e90b1d8
tasyaulfha/belajarPython
/code_reuse.py
170
3.59375
4
# REPLACE THIS STARTER CODE WITH YOUR FUNCTION june_days = 30 print("June has " + str(june_days) + " days.") july_days = 31 print("July has " + str(july_days) + " days.")
ca09af9a21e6241736a2d9c633620adec09e8f9d
Alfie-Lambert/escape-the-paperclip-factory
/the-game.py
1,957
3.9375
4
print("\n") print("Escape the Paperclip Factory") print("\n") print("Your eyes open slowly. The concrete feels cold upon your cheek. \nYou realise that you're in some kind of office.\nA voice rings out across the speakers:") name = input('"WHAT IS YOUR NAME?"') health = 100 print('"Welcome to the game {0}!"'.format(...
fc189102c8a0235e913de4a5ba2ae70c53957533
Mazumsad/Python-Programs
/Connect_Four.py
4,372
4
4
""" A game of connect-4 Versus the computer Author: Oscar A. Nieves Updated: August 9, 2021 """ from random import randint # Class stack (for each column) class Stack: def __init__(self): self._list = [] def __len__(self): return len(self._list) def push(self, element): ...
a11b789813d884aaf1e8e995f9ce5f3ac0880feb
Mazumsad/Python-Programs
/Arbitrary_Random_Numbers.py
996
3.546875
4
# Arbitrary probability distribution # # Generates random numbers according to an arbitrary probability distribution # p(x) defined by the user on a domain [a,b] # # Author: Oscar A. Nieves # Last updated: July 30, 2021 import matplotlib.pyplot as plt import numpy as np import math as mt plt.close('all') #np.random....
7401e6460fd30d979cbcab55e69e3544206a9ce1
ZHKO1/leetcode
/1.py
457
3.5625
4
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ itemArray = range(len(nums)) dit = {} for i in itemArray: if (nums[i] in dit): print(dit) retu...
91a162ad3eb32d477e95cc7dd69a9bedde840af9
ZHKO1/leetcode
/55.jump-game/55.py
779
3.71875
4
def canJump(nums): """ :type nums: List[int] :rtype: bool """ if len(nums) == 0: return False if len(nums) == 1: return True index = 0 jumpFarthest = index + nums[index] if(jumpFarthest == 0): return False newjumpFarthest = 0 for index in range(1, len(...
cf6f4380774caf1bddcd3ce7808f1eaf65a0b4d3
ZHKO1/leetcode
/45.jump-game-ii/45.py
757
3.5
4
class Solution: def jump(self, nums): """ :type nums: List[int] :rtype: int """ if(len(nums) == 1): return 0 index = 0 jumpNumber = 1 jumpFarthest = index + nums[index] newjumpFarthest = 0 for index in range(1,len(nums)): ...
3e8da4477c78bb1c94649d11a6cb3d1d4ec78628
IagoRodrigues/PythonProjects
/Python3_oo2/prob_novo2.py
1,484
4.03125
4
class Funcionario: """ Vou criar um mixin Mixins sao classes extremamente especificas que sao herdadas para agregar um funcionamento para as classes que as herdarem. No caso vou criar um mixin para escrever o nome do funcionario: 1) Defino que meus funcionarios tem o atributo nome """ ...
aff17011358732c5e05f8795f23ffe2b160d4c04
IagoRodrigues/PythonProjects
/jogos/forca_4.py
1,526
3.765625
4
import random def jogar(): print("*********************************") print("***Bem vindo ao jogo da Forca!***") print("*********************************") arquivo = open("palavras.txt", "r") # Abro o arquivo palavras para leitura palavras = [] # Crio uma lista de palavras for linha in arq...
d7a97cdf17638e92d14fab42dfce81e4ff9636fa
IagoRodrigues/PythonProjects
/Python3_oo2/modelo.py
1,822
4.15625
4
class Filme: def __init__(self, nome, ano, duracao): # Atributos privados são marcados usando __ no inicio do nome self.__nome = nome.title() self.ano = ano self.duracao = duracao self.__likes = 0 # Posso criar getters usando uma função com o mesmo nome do atributo ...
eb7f3fbcca0e9259861dfa9cb0534692717832d1
IagoRodrigues/PythonProjects
/exercicios/Invillia_bonus.py
526
3.8125
4
comp_pista = int(input("Comprimento da pista: ")) nro_voltas = int(input("Numero de voltas do GP: ")) reabast_desej = int(input("Reabastecimentos desejados: ")) consumo_do_carro = int(input("Consumo do carro: ")) tamanho_corrida = nro_voltas * comp_pista; tamanho_em_km = tamanho_corrida / 1000; consumo_total = taman...
81bd22182402690d8e36142d4f24f0f5d5bf0195
IagoRodrigues/PythonProjects
/exercicios/LPE_1_Ex2.py
345
4.0625
4
print("==================================") print("=========Cálculo de média=========") print("==================================") valor_A = int(input("Valor A: ")) valor_B = int(input("Valor B: ")) valor_C = int(input("Valor C: ")) media = ((valor_A + valor_B + valor_C) / 3) print("A média entre estes números é {:...
360c614adb12feb3928b8fd60e6e5b9f0c083c54
Vikash-8090-Yadav/python_projects
/random_guessing_game(GUI).py
1,941
3.640625
4
from tkinter import * import random root = Tk() root.geometry("399x410") root.configure(bg = "cyan") root.title("NUMBER_GUESSING") number = 0 x1 = random.randint(1,100) print(x1) x = StringVar() y =StringVar() def show(): global number l1.configure(text = "u have "+str(number)+"of 5 chnaces") s = e.get() l4....
b4505d0b7b4b1b9a2bbaebbd49ca261054ef935b
DIdaniel/coding-training
/3-countLetters/demo.py
275
4.125
4
# -*- coding: utf-8 -*- # 인풋 : string 넣는 input 만들기 # string function # 아웃풋 : STRING has STRING.LENGTH characters say = input('What is the input string? : ') def smthString(say) : print(say + ' has ' + str(len(say)) + ' characters' ) smthString(say)
03dc6d2c4223efe10b69acd3cc6b8bbda5732fc8
noltron000-coursework/data-structures
/source/recursion.py
1,182
4.40625
4
#!python def factorial(n): ''' factorial(n) returns the product of the integers 1 through n for n >= 0, otherwise raises ValueError for n < 0 or non-integer n ''' # check if n is negative or not an integer (invalid input) if not isinstance(n, int) or n < 0: raise ValueError(f'factorial is undefined for n = {n}...
1f6878f1a62be6110158401c6e04d0c8d46a5d8b
noltron000-coursework/data-structures
/source/palindromes.py
2,633
4.3125
4
#!python def is_palindrome(text): ''' A string of characters is a palindrome if it reads the same forwards and backwards, ignoring punctuation, whitespace, and letter casing. ''' # implement is_palindrome_iterative and is_palindrome_recursive below, then # change this to call your implementation to verify it p...
d5f36665dea2f4492d5f1522fa4ddbafc508db52
FifiTeklemedhin/ToDoListApp
/MaxHeapTutorial.py
2,888
3.59375
4
# modified from https://gist.github.com/pavlin-policar/63e237b5e0b9c8dc1b47b0e4f780a88f class MaxHeap: def __init__(self, collection=None): self._heap = [] if collection is not None: for el in collection: self.push(el) def push(self, value): self._heap.appen...
0c608e98db7340f7ba9f0f7fd016631ba118832f
21350010/Week6
/week6.3.4.py
228
4
4
grade= int(input("Enter Marks: ")) letterGrade = "F" if grade >= 90 : letterGrade = "A" if grade >= 80 : letterGrade = "B" if grade >= 70 : letterGrade = "C" if grade >= 60 : letterGrade = "D" print(letterGrade)
ac8e6616fe97a418e310efd5feced4ffde77a8cd
themeliskalomoiros/bilota
/stacks.py
1,696
4.46875
4
class Stack: """An abstract data type that stores items in the order in which they were added. Items are added to and removed from the 'top' of the stack. (LIFO)""" def __init__(self): self.items = [] def push(self, item): """Accepts an item as a parameter and appends it to the en...
994247baf36ffebae449b717429bd937ba770b60
paolithiago/Python-Paoli
/GraficoLinhaValores_Mes(Mod3Sigmoidal).py
607
4.3125
4
#2. REVISÃO MODULO 3 - VISUALIZAÇÃO DE DADOS import matplotlib.pyplot as plt # IMPORTA BIBLIOTECA MATPLOTLIB data = ['set','ago','jul'] # CRIA UMA LISTA COM OS MESES print(saldo_lista) # IMPRIME A LISTA COM OS TRES SALDOS(EX ANTERIOR) prin...
045ec01b388b08e2afbe457209bafaff7e876f86
name-3652/no_01
/daily/No_1480.py
1,328
4.0625
4
''' 1480. 一维数组的动态和 给你一个数组 nums 。数组「动态和」的计算公式为:runningSum[i] = sum(nums[0]…nums[i]) 。 请返回 nums 的动态和。   示例 1: 输入:nums = [1,2,3,4] 输出:[1,3,6,10] 解释:动态和计算过程为 [1, 1+2, 1+2+3, 1+2+3+4] 。 示例 2: 输入:nums = [1,1,1,1,1] 输出:[1,2,3,4,5] 解释:动态和计算过程为 [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1] 。 示例 3: 输入:nums = [3,1,2,10,1] 输出:[3,4,6,16...
8c60bd6b650667ba11cc774b919670d798b22370
peiqiaoWang/Leetcode
/027. Remove Element .py
436
3.609375
4
class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ k = 0 size = len(nums) for i in range(size): if nums[k] == val: nums.pop(k) k -= 1 ...
6d112e6fa46126d73db476c213ac5ffb3d35a1cb
rnzucker/MadLib
/madlib.py
4,867
3.53125
4
"""Playing around with Python text modules to do MadLibs This will read a PDF file. It will produce a version with random words removed, that can be filled out for fun. It will also produce a version with words replaced with the same part of speech: adverb, adjective, verb, or noun. TextBlob doesn't seem to work well ...
4f7dcfb634334e7fa35825b4dc7d95e394507e27
schari2509/coderspack
/Python/task5.py
334
4
4
#Months months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] m = input("Enter month : ") for i in range(12): if m == months[i]: print("No. of days : ", days[i]) ...
42a87d6d8834d4d11f1aff4996662787a4a52414
latygindenis/arcanoid
/ball.py
4,237
3.640625
4
# -*- coding:utf-8 -*- from pygame.sprite import Sprite, collide_rect from pygame import image import random class Ball(Sprite): go_right = True go_left = False go_down = True go_up = False Vel_y = 1.0 def Intersect(x1, x2, y1, y2, db1, db2): if (x1 > x2 - db1) and (x1 < x2 + db2) an...
b5c5a3d0c0b9fc1152c6c5a286c22747f1f6d934
0ushany/learning
/python/python-crash-course/code/5_if/practice/5_alien_color#3.py
670
3.953125
4
# 外星人颜色#5 alien_color = 'green' if alien_color == 'green': print("You got 5 goat!") elif alien_color == 'yellow': print("You got 10 goat!") else: print("You got 15 goat!") print("------------------------------") alien_color = 'yellow' if alien_color == 'green': print("You got 5 goat!") elif alien_c...
4022fb87a259c9fd1300fd4981eb3bd23dce7c1f
0ushany/learning
/python/python-crash-course/code/5_if/practice/7_fruit_like.py
406
4.15625
4
# 喜欢的水果 favorite_fruits = ['apple', 'banana', 'pear'] if 'apple' in favorite_fruits: print("You really like bananas!") if 'pineapple' in favorite_fruits: print("You really like pineapple") if 'banana' in favorite_fruits: print("You really like banana") if 'lemon' in favorite_fruits: print("You really l...
c44e89c9eabd07f1dbef07419b5be820d1d885f1
0ushany/learning
/python/python-crash-course/code/3_list/practice/6_add_guest.py
395
3.765625
4
# 添加嘉宾 guest = ['oshany', 'shane'] print(guest[0], guest[1] + " just come here to have fun") print("I got a big table to eat dinner") guest.insert(0, 'osy') guest.insert(1, 'newberxy') guest.append('0shany') print(guest[0], guest[1], guest[2], guest[3], guest[4] + " have fun now!!") # 这里使用了insert()方法插入了字符串 # 使用了ap...
6b4a0658e4d7dc0cb631ab87a5a1f63424f070ef
0ushany/learning
/python/python-crash-course/code/9_class/14_randint.py
383
3.59375
4
# 骰子 from random import randint x = randint(1, 6) class Die(): def __init__(self, sides=6): self.sides = sides def rool_die(self): for i in range(1, 11): print(randint(1, self.sides)) print("6 side:") die = Die() die.rool_die() print("\n10 sides:") die10 = Die(10) die10.rool_di...
8f8884ac60b976804e3d24668b0905733a2af294
0ushany/learning
/python/python-crash-course/code/7_input_while/8_deli.py
361
3.890625
4
# 熟食店 sandwich_orders = ['apple', 'banana', 'pear'] finished_sandwiches = [] while sandwich_orders: current_sandwich = sandwich_orders.pop() print("I made your " + current_sandwich + " sandwich\n") finished_sandwiches.append(current_sandwich) print("All the sandwich made are this") for sandwich in finish...
421b373009c576651836246c68752a9541345d74
0ushany/learning
/python/python-crash-course/code/9_class/6_iceCreamStand.py
578
4.0625
4
# 冰淇淋小店 class Restaurant(): def __init__(self, restaurant_name): self.restaurant_name = restaurant_name def describe_restaurant(self): print("This restaurant is " + self.restaurant_name + "\n") def open_restaurant(self): print("We are open for guest now!") class IceCreamStand(Rest...
a250c91776f7861d845f18bce5835d8c3d177bf5
karrdenas/Ftask
/main.py
518
3.828125
4
import random import string btns_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] def ansbut(a): but + str(a) = random.choice(buttons) buttons.remove(but) print(but) for a in range(3): ansbut(a) ''' but1 = random.choice(btn_list) btns_list.remove(but1) print(but1) but2 = random.choice(btn_li...
48a37c12509288f77b004c2e919844e176b9c94c
luksflas/python_stuff
/coursera w/ej2f.py
226
3.765625
4
def bisiesto(x): if x%4==0 and (not(x%100==0) or x%400==0 ): texto ='es bisiesto.' else: texto ='es un anno NO bisiesto.' return texto x = int(input('Introduzca un anno entre 1600 y 2500:')) print(x,bisiesto(x))
500d2e4daea05e14d3cedad52e0fae2d1ca4fe92
harjothkhara/computer-science
/Intro-Python-I/src/08_comprehensions.py
1,847
4.75
5
""" List comprehensions are one cool and unique feature of Python. They essentially act as a terse and concise way of initializing and populating a list given some expression that specifies how the list should be populated. Take a look at https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions for m...
8fb980a3ed11e84bd308321f833621eb6ed3f52a
harjothkhara/computer-science
/Intro-Python-I/lecture_day2.py
1,253
4.0625
4
def double(x): # being copied return x * 2 num = double(10) val = double('something') double(2) print(num) # 20 print(val) # 'somethingsomething' # define a doubling function, that doubles every element in a list def double_list(li): # li is being passed by reference, pointer for i in range(0, len(li...
23d8562ec8a10caa237d4544bb07cfefbb6fcd7f
harjothkhara/computer-science
/Sprint-Challenge--Data-Structures-Python/names/binary_search_tree.py
2,610
4.1875
4
class BinarySearchTree: # a single node is a tree def __init__(self, value): # similar to LL/DLL self.value = value # root at each given node self.left = None # left side at each given node self.right = None # right side at each given node # Insert the given value into the tree ...
51f36aa8b8c78974dcfba5ac4ecd61d69cefd2b9
harjothkhara/computer-science
/Intro-Python-I/avg.py
2,457
3.890625
4
# Return the "centered" average of an array of ints, which we'll say is the mean # average of the values, except ignoring the largest and smallest values in the array # centered_average([1,2,3,4,100]) -> 3 sum([2, 3, 4]) / 3 # centered_average([1,1,5,5,10,8,7]) -> 5 sum([1, 5, 5, 8, 7]) // 5 # centered_average([-10...
3bc4b5b53b1c1a22eccd79ada8cd9c978c60035c
dovanhuong/Algorithm_For_RL
/03 min_tree/min_tree.py
1,965
3.65625
4
import numpy as np from collections import deque import matplotlib.pyplot as plt class min_tree(): def __init__(self, buffer_size): self.tree_index = buffer_size - 1 # define min_tree leaf node index. self.array_tree = [0 for i in range((buffer_size * 2) - 1)] # set min_tree size (double of buffer ...
491612359adb50f8e5cad740c5a4fc0027a1d034
kjamaal/samples
/python/bsearch.py
339
3.75
4
import sys #requires sorted list l def bsearch(l, term): first = 0 last = len(l)-1 while first <= last: mid = (first+last)//2 if l[mid] == term: return l[mid] else: if term < l[mid]: last = mid-1 else: first = mid+1 print(bsearch(sys.argv[1].split(',...
52ebc8af37012ecf52a9b8706f2793ea30b20c69
ElijahLiY/chordsearching
/note2chord.py
839
3.65625
4
def note2chord(note0,note1,note2): def note2num(a): for i in range(11): notename=['do','#do','re','#re','mi','fa','#fa','sol','#sol','la','#la','si'] if notename[i] == a: break return i num1st = note2num(note0) num2nd = note2num(note1) num3rd ...
8b4e51f543261feb2934c5a1b581de984779806f
EelcoHoogendoorn/Escheresque
/escheresque/geometry.py
13,918
3.59375
4
"""geometry class The geometry class combined the topology of a single fundamental triangle, with a set of coordinates for the primal vertices From this, metric properties on the sphere are computed, such as the primal-dual transfer operators, as well as the multigrid transfer operators """ import numpy as np import...
7f9539a4623210c6630fac5161da35eaed84bb0c
gloomysun/pythonLearning
/1-基础/1_基础类型和变量.py
479
3.796875
4
print('i\'m ok') # 使用r''表示内部默认不转义 print(r'i\'m ok') #使用'''...'''表示多行内容 print(''' hello python i'am ok ''') #boolean print(True) print(not True) print(3>2) a = 'ABC' b = a a = 'XYZ' print(b) print(10/3) print(10//3) print("==============练习======================") n = 123 f = 456.789 s1 = 'Hello, world' s2 = 'Hello...
5f34c9b5adbff6649c054934000561501041e3cd
gnfka0828/sammosummo.github.io
/assets/scripts/ripple-sounds.py
5,900
3.53125
4
"""Synthesize, plot, and play ripple sounds. """ import numpy as np import sounddevice as sd import matplotlib.pyplot as plt from scipy.interpolate import interp1d from scipy.io import wavfile a0 = 1e-5 # reference amplitude sr = 44100 # sample rate def ripple_sound(dur, n, omega, w, delta, phi, f0, fm1, l=70):...
9fa63b60043d5684455ac79c54e332daaf490778
ReubenDomacasse/ICTSTS11VX
/Tentamen/0918901_opdracht1-001_v1.py
867
3.671875
4
# Tentamen versie :BMFWRDZN # Gegevens :Reuben Domacasse 0918901 23-10-2017 # Opgave :1-001 # Inleiding: De inhoud van een voorwerp met een diameter van 33 cm wordt berekend met de formule: 1/8 x 3,14 x (33^4) / 5 # Opdracht: Schrijf een programma dat deze berekening uitvoert. # Eisen: ...
7ddbcfd7cc98e8b1c81282d05ccde5eccb33dc74
alejotalice/Ejercicios-de-python-alejo-talice
/alejotalice-5.py
108
4.03125
4
nombre = input("cual es tu nombre?") print(nombre.upper() + " tiene " + str(len(nombre)) + " letras")
b90cb6ea61f871e8e696432cc57d579db7e79353
menosbel/python-excercises
/guia1/ejercicio9.py
302
3.6875
4
num1 = input('Ingrese un numero entero: ') num2 = input('Ingrese otro numero entero: ') num3 = input('Ingrese otro numero entero: ') num4 = input('Ingrese otro numero entero: ') num5 = input('Ingrese otro numero entero: ') lista_numeros = [num1, num2, num3, num4, num5] print(lista_numeros)
93620ec9c2a36243d69573783ef4899ee90eb1a0
menosbel/python-excercises
/guia2/ejercicio8.py
195
4.1875
4
decimal = 0 for i in range(3): binario = input("Ingrese un número binario: ") for bit in binario: decimal += decimal + int(bit) print(decimal + 1) decimal = 0
3804475cdfb4ddda2db9289599c83f9c34fcaf60
menosbel/python-excercises
/guia2/ejercicio3.py
320
4.03125
4
number_1 = input('Ingresar un numero: ') number_2 = input('Ingresar otro numero: ') number_1 = int(number_1) number_2 = int(number_2) if number_1 < number_2: print(number_2 - number_1) elif number_1 > number_2: print(number_1 + number_2) elif number_1 == number_2: print(number_1 * number_2)
f267c6864d8f75be5202d7b097d11430dba513c6
menosbel/python-excercises
/guia2/ejercicio6.py
1,118
3.953125
4
# opcion dos. mas optima despues de ver la solucion operacion = int(input(''' Seleccione la operacion que desea realizar: 1- Suma 2- Resta 3- Multiplicacion 4- Division 5- Terminar programa Que desea ...
386cbe1db55cb4fbee189104113d68d67e58fe52
julianlin/user_account_app
/database/database.py
1,891
3.8125
4
import os import sqlite3 import csv from typing import List DB_NAME = 'user_account_app.db' class Database: def __init__(self): if os.path.exists(DB_NAME): os.remove(DB_NAME) self.create_user_table() self.insert_user_rows_from_csv() def create_user_table(self) -> None: query_str = """ ...
d53cdffa568dc81f1fa888d7321145043fb11ab3
banshchikov/Karatsuba-Multiplication
/Karatsuba_multiply.py
936
3.734375
4
# https://en.wikipedia.org/wiki/Karatsuba_algorithm # z2 = x0y0 # z0 = x1y1 # z1 = (x0 + x1)*(y0 + y1) - z2 - z0 # result = z2*B^2m + z1*B^m + z0 import math def multiply(x, y): if x < 10 or y < 10: return x * y nX = int(math.floor(math.log10(x))+1) nY = int(math.floor(math.log10(y))+1) n ...
894f9a2ef6b13fefdc6470d1f277600c224465c4
ShreeramAthreya/Data-structures-and-Algorithms---Coursera-Specialization-UCSD-
/Algorithmic toolbox/Week 2/assign_2_1.py
289
3.640625
4
def calc_fib(n): if n<2: if n==1: return 1 else: return 0 else: f = [0]*(n+1) f[0] = 0 f[1] = 1 for i in range (2,n+1): f[i] = f[i-2]+f[i-1] return f[i] n = int(input()) print(calc_fib(n))
351d2efea51e37e7d89c2468b996da726abe5bbd
salay/sf-wdi-51-assignments
/siri-salay/week-8/playwithpy.py
1,183
4.09375
4
from random import shuffle # a list of state dictionaries states = [ { "name": "Washington", "capital": "Olympia" }, { "name": "West Virginia", "capital": "Charleston" }, { "name": "Wisconsin", "capital": "Madison" }, { "name": "Wyoming", "capital": "Cheyenne" }] print("Hey friend! Wel...
e801b19dced51e97038136881f9adc2450fbc2b4
analaura09/pythongame
/p10.py
421
3.5625
4
import run() real = float(input(' Quanto dinheiro voce tem? ')) dolar = real/ 3.27 print(' Com R${} voce pode comprar U${}'.format(real,dolar)) opçao = int(input('deseja repetir esse exercicio[1] \ndeseja voltar para o mundo 1[2] \ndeseja sair do jogo[3]')) if opçao == 1: import p10 p10.run() if opçao ==2: ...
5ec0a218b3f61e6f3f7bb7551b9ef1cbf899802a
analaura09/pythongame
/fase3.py
637
3.5625
4
while True: import webbrowser print('=====================================') print('=== BEM VINDO A FASE 3 DO MUNDO 1 ===') print('=== OS DESAFIOS DESSA FASE SAO ===') print('esse desafio é uma introduçao do seu curso de python!') print('Segue abaixo o link do video:') webbrowser.open('https...
1520f670797fc2508ff49a8b105a2de33694ec3b
analaura09/pythongame
/p86.py
314
3.640625
4
lista = [] print('\n') for l in range(1,4) : for c in range (1,4) : lista.append(int(input(f'diga um valor para a posição({l},{c}) = '))) print('=–'*21) for p,n in enumerate(lista) : print(f' [{n:^5}]',end = '') if p == 2 : print('') elif p == 5 : print('') print('\n')
624b9d369b87a61469b7575e3bc51809f42236d0
analaura09/pythongame
/fase16.py
1,030
3.921875
4
while True: print('======================================') print('=== BEM VINDO A FASE 16 DO MUNDO 3 ===') print('=== OS DESAFIOS DESSA FASE SAO ===') print('72. numero por extenso \n73. tuplas com times \n74. maior e menor valores em tuplas') print('75. analise de dados em uma tupla \n76. lista de...
fdadb17ca679fe8bd403de71b07aab64dd3ec200
analaura09/pythongame
/p55.py
227
4
4
for c in range (1,6): list = [] list.append(float(input('digite o peso de uma pessoa: '))) ordem = list.sort() print(' o maior peso lido foi de {}'.format(list[5])) print(' o menor peso lido foi de {}'.format(list[0]))
0d30e6125fdc68729d89894f820e321b213a1815
analaura09/pythongame
/p25.py
401
3.59375
4
import run() nome = str(input(' Digite um nome: ')).strip() print(' Seu nome te Silva?{}'.format('silva'in nome.lower())) opçao = int(input('deseja repetir esse exercicio?[1] \ndeseja voltar para o mundo1? [2] \ndeseja sair do jogo?[3]')) if opçao == 1: import p25 p25.run() if opçao ==2: import mundo1 ...
6f4b1fe81cec0a46e90bc44e7715ac2823a31825
analaura09/pythongame
/p33.py
578
3.625
4
def run() n1 = int(input(' Digite um valor: ')) n2 = int(input(' Digite outro valor: ')) n3 = int(input(' Digite outro valor: ')) list=[n1,n2,n3] print(list) print('o maior numero é {} e o menor numero é {}'.format(list[2], list[0])) opçao = int(input('deseja repetir esse exercicio?[1] ...
35674a72f5ba8ea31282168b77bcf5f940a0b514
analaura09/pythongame
/p105.py
784
3.6875
4
import run() def notas(*n,sit=False): '''> funçaopara analisar notas e situaçoes de varios alunos''' r = dict() r['total'] = len(n) r['maior'] = len(n) r['menor'] = len(n) r['media'] = len(n)/len(n) if sit: if r['media'] >= 7: r['situaçao'] = 'boa' elif r['m...
5d8bfc60b0c8e6ab2fb9ebb413d388e4eaa9a183
analaura09/pythongame
/p81.py
389
3.984375
4
val=[] while True: val.append(int(input('digite um valor:'))) resp=input('quer continuar? [S/N]') if resp in 'Nn': break print('-='*30) print(f'voce digitou {len(val)} elementos') val.sort(reverse=True) print(f'os valores em ordem decrescente sao {val}') if 5 in val: print('o valor 5 faz parte d...
08e7c054ec0b709b6930b517927d6692b8c137d3
analaura09/pythongame
/fase4.py
631
3.703125
4
while True: print('=====================================') print('=== BEM VINDO A FASE 4 DO MUNDO 1 ===') print('=== OS DESAFIOS DESSE MUNDO SAO ===') print('1. Deixando tudo pronto \n2. Resposta ao usuario') opçao = int(input('qual desafio você escolhe(digite o numero 1 ou 2)?')) if opçao == 1:...
36060408ec5d38ad18c62922791f3139b146d661
analaura09/pythongame
/p103.py
558
3.734375
4
import run() def ficha(jog='<desconhecido>', gol =0): print(f'o jogador {jog} fez {gol} gol(s) no campeonato') n = input('nome do jogador:') g = input('numeros de gols:') if g.isnumeric(): g=int(g) else: g=0 if n.strip()== '': ficha(gol=g) else: ficha(n,g) opçao = int(input('deseja repetir esse exe...
e86918e0400cabfd3aa04f86f9738a5404fac342
analaura09/pythongame
/p63.py
386
3.828125
4
# Desafio 63 - Sequência de Fibonacci v1.0 print ("Desafio 63, Sequência de Fibonacci v1.0") n=int(input("Quantos números você quer mostrar: ")) t1=0 t2=1 print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") print("{} → {}".format(t1, t2), end='') cont=2 while cont < n: t3= t1+ t2 print (" → {}".format(t3), e...
3cef477926b5149e61770e55c934370796bf23f2
analaura09/pythongame
/fase9.py
794
3.890625
4
while True: print('=====================================') print('=== BEM VINDA A FASE 9 DO MUNDO 1 ===') print('=== OS DESAFIOS DESSA FASE SAO ===') print('22. analisando um texto \n23. separando os digitos de um numero \n24. primeiras letras de um texto \n25. procurando string \n26. primeira e ultima ...
5a179067df89d0b3282fb1cdc8b037f73b24e8eb
genshang/data-scrape
/app.py
826
3.578125
4
import urllib2 from bs4 import BeautifulSoup web_page = "https://finance.yahoo.com/quote/FB?p=FB" #created a variable and assigned it the website from yahoo finance FB (getting the website) page = urllib2.urlopen(web_page)# .urlopen is a function, web_page is the vessel for the website # print(page) soup = BeautifulS...
b55df48b2b868ef1f92e6d919a7b96de0bfee5d8
shinyamagami/get_the_kinetic_energy_from_feet_and_pound
/get_the_kinetic_energy_from_feet_and_pound.py
3,555
4.59375
5
# Shin Yamagami # Oct 15th, 2015 # # This program calculate the kinetic energy of a moving object from # a distance and mass inputted by a user. # explain what this program will do def print_description(): print('This program calculate the kinetic energy of a moving object from\n' 'a distance and mass in...
16f90df94d646823c872053fa2656ec3635d5401
ongxx107/Python
/ongxx107_5A.py
2,209
3.984375
4
#Ren Jeik Ong labSection23 hw5a import math import random data = int(input("How many data? ")) value =str(input("Input data values: ")) value = value.split(" ") if(len(value) == 1): print("Empty List, no data points entered") else: for i in range(0,len(value)): value[i] =float(value[i]) average ...
e1ed8ce9cabb0d901de3ad92ba9605c599a051d2
drunkinlove/graphs
/BFSearch.py
1,545
3.8125
4
def BFS(adj, dist, parent, color, source): for v in adj.keys(): color[v] = 'white' dist[v] = float('Inf') parent[v] = None color[source] = 'gray' dist[source] = 0 parent[source] = None Q = [] # This is a queue Q.append(source) while Q: u = Q.pop(0) ...
49e4c6e85a28647c59bd025e34ac9bae09b05fc8
rtorzilli/Methods-for-Neutral-Particle-Transport
/PreFlight Quizzes/PF3/ProductFunction.py
445
4.34375
4
''' Created on Oct 9, 2017 @author: Robert ''' #=============================================================================== # (5 points) Define a function that returns the product (i.e. ) of an unknown set of # numbers. #=============================================================================== def mathProd...
83e274d5e60edd944558633b33237ff4a7a22853
chenyin01/CodeCourse
/machinelearningplus/numpy/yi_solution.py
25,104
4.125
4
import numpy as np """ 1. Import numpy as np and see the version Difficulty Level: L1 Q. Import numpy as np and print the version number. """ # print(np.__version__) """ 2. How to create a 1D array? Difficulty Level: L1 Q. Create a 1D array of numbers from 0 to 9 Desired output: #> array([0, 1, 2, 3, 4, 5, 6, 7, 8, ...
75822093c169ba48926b3783bc4719d9103560f6
rustamlinabi/Python---SoloLearn-Assignments
/Einstein riddle.py
5,144
3.703125
4
""" Einstein's Riddle Einstein's Riddle is a logic puzzle. It is often claimed that only 2% of the population can solve the puzzle. It has several variants, one of them is this: 1. There are five houses. 2. The Mathematician lives in the red house. 3. The Hacker writes in Python. 4. Brackets (code editor) is...
b6164347a3fb42aa601077f2a8742a5849d1a11f
nikolaj74-hub/lessons
/lesson2.3.py
674
3.515625
4
while True: m = int(input('Введите месяц числом от 1 до 12')) e = 0 r = 12 if m >= e or m < r: win = [1, 2, 12] sprig = [3, 4, 5] sam = [6, 7, 8] aut = [9, 10, 11] if win.count(m) == 1: print('Зима') else: if sprig.count(m) == 1: ...
335b5c7ee20102750c5ca4e77c0540a53d588116
nikolaj74-hub/lessons
/za7.py
440
3.78125
4
from functools import reduce print(reduce(lambda a, b: int(a) * int(b), range(1, 1+int(input('введите номер эл'))))) ############################################################################################### from math import factorial def fact(): for el in {factorial(int(input('введите номер эле...
3b19e3fab39325f3547214d6519aa41f3eb662d2
nikolaj74-hub/lessons
/zaz2.py
1,299
3.546875
4
# 2) Создайте собственный класс-исключение, обрабатывающий ситуацию деления на нуль. # Проверьте его работу на данных, вводимых пользователем. При вводе пользователем нуля в # качестве делителя программа должна корректно обработать эту ситуацию и не завершиться с # ошибкой. class Error(Exception): def __in...
22b2642a6eee05af3331b7dd7770cb763f6991a4
nikolaj74-hub/lessons
/lesson2.3.v1.py
1,222
3.75
4
while True: m = int(input('Введите месяц числом от 1 до 12:')) e = 0 r = 12 if m >= e or m < r: # проверка введенного числа месяца a_dict = {'win': [1, 2, 12]} b_dict = {'spr': [3, 4, 5]} c_dict = {'sum': [6, 7, 8]} d_dict = {'aut': [9, 10, 11]} for v in a_d...
bfd97ec81a9ea987a72dd5a01e06ed9c37d29007
Zhengrui-Liu/FireAlarmingSysCDA
/src/main/python/programmingtheiot/cda/emulated/HvacEmulatorTask.py
2,208
3.640625
4
##### # # This class is part of the Programming the Internet of Things project. # # It is provided as a simple shell to guide the student and assist with # implementation for the Programming the Internet of Things exercises, # and designed to be modified by the student as needed. # import logging import programmin...
f4eee2a0530dd690a7a4ea9c1293635add5ec749
Zhengrui-Liu/FireAlarmingSysCDA
/src/main/python/programmingtheiot/data/SensorData.py
1,627
3.78125
4
##### # # This class is part of the Programming the Internet of Things project. # # It is provided as a simple shell to guide the student and assist with # implementation for the Programming the Internet of Things exercises, # and designed to be modified by the student as needed. # from programmingtheiot.data.BaseIo...
4ca4ce5288866d34fb15d782df4ef0fa94cf7f34
wblong/python-note
/py01/py01.py
523
3.8125
4
#! coding:utf-8 import sys import unittest class IterTest(object): def __init__(self): self.a=0 self.b=1 def __iter__(self): self.a,self.b=self.b,self.a+self.b return self.b def next(self): self.a,self.b=self.b,self.a+self.b return self.b def main(): p...
c051402f31eb18b0cfa72e91abaec35ab9e846f2
giorgiopizz/python
/bocconi_ex/es2.py
311
3.6875
4
##funzione ricorsiva def soldi(x,r,n): if(n==0): return x elif(n>0): return soldi(x+r*x,r,n-1) ##funzione matematica """ import math def soldi(x,r,n): if(n==0): return x elif(n>0): return x*pow(1+r,n) """ print(soldi(input("x?\n"),input("r?\n"),input("n?\n")))
a741b7f5085de903357270b84851c1f925fcc6af
RicharVe947/Rotamundos_Test
/ejercicio.py
817
3.921875
4
# -*- coding: utf-8 -*- """ Hacer una función llamada "separador" que me regrese: ¿Cuántas letras mayúsculas hay en el string "source"? ¿Cuántas letras minúsculas hay en el string "source"? ¿Cuántos símbolos hay en el string "source"? """ """Regreasa una lista con el numero de letras mayusculas, minusculas y simbo...