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
028ab999ef30435a85fd6c81f95a5c99c7f7e721
kckani/pythontut
/tuple.py
410
3.984375
4
# A tuple is a collection which is ordered and unchangeable. Allows duplicate members. # create a tuple fruits = ('apples', 'oranges', 'grapes') # using a constructor # fruits2 = tuple(('apples', 'oranges', 'grapes')) #single value needs traling comma fruits2 = ('apples',) # get a value print (fruits[1]) # can not chan...
ce933393f86b982b9223461f3937a962ea46f880
DYasser/Memory_Python
/Remember.py
16,338
4.03125
4
#Nabil Yasser #Python3~ from random import * import time def RESTART(): variables = {'x1':1, 'x2':2, 'x3':3, 'x4':4, 'x5':5, 'x6':6, 'x7':7, 'x8':8, 'x9':9, 'x10':10, 'x11':11, 'x12':12, 'x13':13, 'x14':14, 'x15':15, 'x16':16, 'x17':17} lost = 0 lost1 = 0 lost2 = 0 lost3 = 0 p=1 ...
8369dabbbe5680471488c495cf5a9b8599e11ea8
orbache/pythonExercises
/exercise1.py
541
4.40625
4
#!/usr/bin/python __author__ = "Evyatar Orbach" __email__ = "evyataro@gmail.com" '''Exercise 1 Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old. ''' from datetime import datetime year = datetime.now()...
3bd707a6c0b5a2ffb1657ae2ac8465452aa30d6d
orbache/pythonExercises
/exercise14.py
747
4.5625
5
#!/usr/bin/python __author__ = "Evyatar Orbach" __email__ = "evyataro@gmail.com" '''Exercise 14 Write a program (using functions!) that asks the user for a long string containing multiple words. Print back to the user the same string, except with the words in backwards order. For example, say I type the string: My n...
3a438b6ae720851f4fc983569f844584cd59a9e4
skumartd/PythonIntro
/Day1/SampleCode.py
186
3.828125
4
x = 34 - 23 # A comment. y = "Hello" # Another one. z = 3.45 if z == 3.45 or y == "Hello": x = x + 1 y = y + " World" # String concat. print(x) print(y) t=str(z)+y print(t)
d680f29d9d093655b0dcc922776c775be7c49e71
brunoleej/study_git
/ML,DL, RL/Deep Learning/keras/keras40_mnist4_lstm.py
1,799
3.796875
4
# 주말 과제 # LSTM 모델로 구성한 input_shape = (28*28,?) # (28*28,1) # (28*14,2) # (28*7,4) # Module import import numpy as np import tensorflow as tf from tensorflow.keras.datasets import mnist # preprocessing (x_train,y_train),(x_test,y_test) = mnist.load_data() print(x_train.shape,x_test.shape) # (60000, 28, 28) (10000, 2...
9f88b19eba4cac6565e8f3256fdd65b2caeef659
brunoleej/study_git
/Pytorch/ANN/Sigmoid_function.py
242
3.671875
4
import numpy as np import matplotlib.pyplot as plt def sigmoid(x): return 1 / (1 + np.exp(-x)) x = np.arange(-5.0, 5.0, 0.1) y = sigmoid(x) plt.plot(x,y) plt.plot([0,0],[1.0,0.0], ":") plt.title('Sigmoid Function') plt.show()
a2d28dea1a54f73a6acccc5e914ca7a7541b80e1
brunoleej/study_git
/Basic/Algorithm/Basic/Multiple Inheritance/Multiple Inheritance3.py
1,781
4.0625
4
# 아래 코드는 최상위 클래스 메소드를 두 번 호출하게 되는 문제점이 있음 (심화) ''' # 클래스 선언 class Person: def __init__(self): print('I am a person') class Student(Person): def __init__(self): Person.__init__(self) print('I am a student') class Worker(Person): def __init__(self): Person...
aa3219491259c0b1f3111b5acaa50b2a44e56b3c
brunoleej/study_git
/Basic/Algorithm/Basic/Comprehension/List Comprehension/List_comprehension.py
839
4.0625
4
# python Comprehension # 다른 Sequence로 부터 새로운 Sequence (Iterable Object)를 만들 수 있는 기능 # List Comprehension # 사용법 # [출력표현식 for 요소 in 입력 Sequence [if 조건식]] # 입력 Sequence는 Iteration이 가능한 데이터 Sequence 혹은 컬렉션 # [if 조건식]에서 []은 리스트 괄호가 아니라, 옵션이라는 뜻, 즉 조건이 있을때만 넣으면 된다는 뜻임 # 예 : 종류가 다른 데이터에서 정수 리스트만 가져오기 dataset...
c8a45d8ad4bae3b6dc6746928b51ea3a184ca421
brunoleej/study_git
/Mathematics/Data science/Mathmatics/04/inverse_function.py
428
3.75
4
import numpy as np import matplotlib.pyplot as plt def f1(x): return x ** 2 def f1inv(x): return np.sqrt(x) x = np.linspace(0, 3, 300) plt.plot(x, f1(x), "r-", label="함수 $f(x) = x^2$") plt.plot(x, f1inv(x), "b-.", label="역함수 $f^{-1}(x) = \sqrt{x}$") plt.plot(x, x, "g--") plt.axis("equal") p...
b20ffb7fa174f23ff0a341d20d9d14070cb4222a
brunoleej/study_git
/ML,DL, RL/Machine Learning/Preprocessing/Pandas_OneHot_encoding.py
165
3.84375
4
import pandas as pd df = pd.DataFrame({'item':['TV','냉장고','전자레인지','컴퓨터','선풍기','선풍기','믹서','믹서']}) print(pd.get_dummies(df))
c8ee7940d0e3e1b6303b62f25113e706dc6a6734
brunoleej/study_git
/ML,DL, RL/Deep Learning/keras/keras31_split.py
349
3.5625
4
# 분석 import numpy as np dataset = np.array(range(1,11)) size = 5 def split_x(seq,size): aaa = [] for i in range(len(seq)- size + 1): subset = seq[i : (i + size)] aaa.append([item for item in subset]) print(type(aaa)) return np.array(aaa) data = split_x(a, size) print('================...
23d14208af86e6bed8cbe9f2672da4a3af15b25a
brunoleej/study_git
/Basic/Algorithm/Basic/Polymorphism/polymorphism1.py
961
3.921875
4
# 다형성(polymorphism) # 같은 모양의 코드가 다른 동작을 하는 것 # 키보드의 예로 # push(keyboard): 키보드를 누른다는 동일한 코드에 대해 # ENTER, ESC, A 등 실제 키에 따라 동작이 다른 것을 의미함 # 다형성은 코드의 양을 줄이고, 여러 객체 타입을 하나의 타입으로 관리가 가능하여 유지보수에 좋음 # Method Override (메소드 재정의)도 다형성의 한 예입니다. # 클래스 선언 class Person: def __init__(self, name): self...
c8cf7a7c6b5a999bcad80cc8a3ab48492a2aabf4
brunoleej/study_git
/Basic/Algorithm/Basic/OOP/Public_private_protected_ex.py
1,311
4.15625
4
# 원 클래스 생성하기 # attribute : 원 반지름, 원 이름 # method # 1. 원 이름 리턴 메소드 # 2. 원 넓이 리턴 메소드 # 참고(원 넓이 식) : 3.14 X 원 반지름 **2(원 반지름의 제곱) # 3. 원 길이 리턴 메소드 # 참고(원 길이 식) : 2 X 3.14 X 원 반지름 # 생성자에서만 attribute 값 설정 가능 # attribute는 private으로 설정 ...
ab421ab88e4ed3a260bf2da6883c9f57f7340681
brunoleej/study_git
/Basic/Matplotlib/04. Matplotlib Legend/02_legend_position1.py
273
3.53125
4
import matplotlib.pyplot as plt plt.plot([1, 2, 3, 4], [2, 3, 5, 10], label='Price ($)') plt.xlabel('X-Axis') plt.ylabel('Y-Axis') # plt.legend(loc=(0.0, 0.0)) # under plt.legend(loc=(0.5, 0.5)) # middle # plt.legend(loc=(1.0, 1.0)) # top plt.show()
26f3ae950569562b07bb42ac67badaf35a2193db
brunoleej/study_git
/Basic/Matplotlib/05. Axis Range/04_axis_range.py
254
3.703125
4
import matplotlib.pyplot as plt plt.plot([1, 2, 3, 4], [2, 3, 5, 10]) plt.xlabel('X-Axis') plt.ylabel('Y-Axis') x_range, y_range = plt.xlim(), plt.ylim() print(x_range, y_range) axis_range = plt.axis('scaled') print(axis_range) plt.show()
357a6b0ffdf73627d8fd7a5d5e14e3316fdb8ef7
brunoleej/study_git
/Mathematics/Data science/Mathmatics/02/operate_vector_matrix.py
331
3.828125
4
import numpy as np # 배열 생성 x = np.array([10, 11, 12, 13, 14]) y = np.array([0, 1, 2, 3, 4]) # 덧셈 print(x + y) # [10 12 14 16 18] print(x - y) # [10 10 10 10 10] # 행렬 덧셈 print(np.array([[5,6],[7,98]]) + np.array([[10,20],[30,40]]) - np.array([[1,2],[3,4]])) ''' [[ 14 24] [ 34 134]] '''
5dfef0d956d0559c7472d2aa3358f2f49ea47bea
brunoleej/study_git
/Basic/Algorithm/Linked List/Linked_list_Good_Bad.py
995
3.78125
4
# 3. 링크드 리스트의 장단점 (전통적인 C언어에서의 배열과 링크드 리스트) # 장점 # - 미리 데이터 공간을 미리 할당하지 않아도 됨 # - 배열은 **미리 데이터 공간을 할당** 해야 함 # 단점 # - 연결을 위한 별도 데이터 공간이 필요하므로, 저장공간 효율이 높지 않음 # - 연결 정보를 찾는 시간이 필요하므로 접근 속도가 느림 # - 중간 데이터 삭제시, 앞뒤 데이터의 연결을 재구성해야 하는 부가적인 작업 필요 node = head while node.next: ...
fcd74bfcba32d22be9058cd6d6b93fb75e0faaee
brunoleej/study_git
/ML,DL, RL/Deep Learning/keras/keras32_split3_LSTM.py
2,606
3.796875
4
# 과제 및 실습 / LSTM # EarlyStopping, preprocessing all in # 데이터 1 ~ 100 # x y # 1 2,3,4,5 6 # ... # 95,96,97,98,99 100 # predict를 만들 것 # 96,97,98,99,100 -> 101 # ... # 100,101,102,103,104 -> 105 # 예상 predict는 (101,102,103,104,105) import numpy as np a = np.array(range(1, 101)) size = 6 # ...
e3fe674aa8fa2cb7cd1fb377660f9dddcda29f72
saurabhchris1/Algorithm-and-Data-Structure-Python
/Depth_First_Search/Depth_First_Search.py
1,475
3.6875
4
# Depth first search both recursive and iterative(Using Stacks) class Node: def __init__(self, data=None, children=None): self.data = data self.children = children def dfs(self): self._dfshelper(self) def _dfshelper(self, node): print (node.data) if node.children ...
1d70db077c874f75b3911d94f58428037734fa66
saurabhchris1/Algorithm-and-Data-Structure-Python
/Bubble_Sort/Bubble_Sort_Iterative_Optimized.py
644
4.3125
4
# Bubble Sort Iterative Optimized # Print i,j will help you figure out calculations def bubble_sort_iterative(num_arr): len_arr = len(num_arr) flag = True for i in range(len_arr): if not flag: break flag = False for j in range(len_arr - i - 1): print(i, j) ...
9ec7935108efec5030d99d8a191f72493254f09a
vinnymarcondes/python
/Exercícios de estudo/triangulo.py
363
4.03125
4
a = float(input("Digite o valor a: ")) b = float(input("Digite o valor b: ")) c = float(input("Digite o valor c: ")) if a >= b + c or b >= c + a or c >= a + b: print("Triângulo inexistente.") elif a == b and b == c: print("Triângulo equilatero.") elif a == b or b == c or c == a: print("Triângulo isósceles.") ...
9929fda9ded1d571c0275a78c377669d4a9f6e5f
vinnymarcondes/python
/URI/URI1001.py
125
3.78125
4
A = int(input("Insira o valor de A: ")) B = int(input("Insira o valor de B: ")) Soma = A + B print ("X = {}".format(Soma))
845cd8440cd3b2aa8efa6d150fec83c72d2baf46
vinnymarcondes/python
/Exercícios de estudo/PH.py
170
3.859375
4
PH = float(input("Digite o valor do PH: ")) if PH < 7.0: print("Solução ácida") elif PH == 7.0: print("Solução neutra") else: print("Solução básica")
38fdeb4071d4308c3ae66015d264505283344b4b
vinnymarcondes/python
/Exercícios de estudo/par e impar.py
131
4
4
a = int(input("Digite um número: ")) if(a % 2 == 0): print(a, "é um número par") else: print(a, "é um número ímpar")
6fb0991163f4d360176b1b344718fee3787b8e79
Emanoel580/ifpi-ads-algoritmos2020
/lista condicionais 2b/fabio_2b_02_sexo.py
248
3.671875
4
def main(): letra = str(input('diga uma letra: ')) sexo(letra) def sexo(valor1): if valor1 == 'F': print('F - Feminino') elif valor1 == 'M': print('M - Masculino') else: print('Sexo invalido') main()
3fa1b3871e6f58c1100b5664c36ac13bfa1dcc52
Emanoel580/ifpi-ads-algoritmos2020
/lista condicionais 2a/fabio_2a_22_hora_jogo.py
1,233
3.78125
4
def main(): hora_inicio = int(input('hora inicio: ')) minuto_inicio = int(input('minutos iniciais: ')) hora_fim = int(input('hora final: ')) minutos_fim = int(input('minutos finais: ')) duracao_jogo(hora_inicio, hora_fim, minuto_inicio, minutos_fim) def duracao_jogo(valor1, valor2, valor3, valor4)...
22d2883940cbe07f53d4875575cbb515b057e787
Emanoel580/ifpi-ads-algoritmos2020
/lista condicionais 2a/fabio_2a_06_triangulos.py
735
4.09375
4
def main(): num = int(input('1° angulo: ')) num_2 = int(input('2° angulo: ')) num_3 = int(input('3° angulo: ')) forma_triangulo(num, num_2, num_3) def forma_triangulo(a, b, c): if a + b + c == 180: soma = a + b + c print('formam um triangulo !') if a < 90 and b < 90 and c <...
272dad919afc1bf7c4358f3c4db51201ac1f5930
Emanoel580/ifpi-ads-algoritmos2020
/Lista 03 Repetição for/for_03_06.py
133
3.953125
4
# tabuada de multiplicação num = int(input(" numero p/ a tabuada: ")) for n in range(1, 11): print(f'{num} x {n} = {num*n}')
96fb4a3b221a50e575e96626da67f23b14d4cc90
Emanoel580/ifpi-ads-algoritmos2020
/lista condicionais 2a/fabio_2a_15_horas_aula.py
811
3.859375
4
def main(): print('-=' * 20) horas_aula = int(input('horas de aula do professor1: ')) custo_hora = float(input('o valor por horas do professor1:')) horas_aula2 = int(input('horas de aula do professor2: ')) custo_hora2 = float(input('valor por horas do professor2: ')) preco_hora(horas_aula, custo...
45a25a7bdc2362507b76129fea60dee33c55b50f
Emanoel580/ifpi-ads-algoritmos2020
/lista condicionais 2a/fabio_2a_02_maior_menor.py
339
4.03125
4
def main(): a = int(input('1° numero: ')) b = int(input('2° numero:')) menor_maior(a, b) def menor_maior(x, y): if x == y: print('iguais') elif x > y: print('o primeiro n° {} é maior do que {} '.format(x,y)) else: print('o segundo n° {} é maior do que {}'.format(y, ...
8de7e84b494d983ef8e8cd53d92bd8d313e1c527
Emanoel580/ifpi-ads-algoritmos2020
/Lista 03 Repetição for/fabio_q24_for.py
456
3.75
4
n = int(input('n° habitantes:')) salario = float(input('salario: ')) filhos = int(input('filhos:')) cont = 1 media_filho = 0 salario_ate_mil = 0 for cont in range(n): media_salario = (salario * n) / n media_filho = filhos / n if salario <=1000: salario_ate_mil = (salario / 1000) * n print('media ...
2ac83d0f3bfe73efed164e0f58765643f05fac3e
vanderveldenmd/MiscLeetCode
/MaximumLengthofRepeatedSubarray.py
1,809
3.703125
4
class Solution: def findLength(self, nums1: List[int], nums2: List[int]) -> int: if nums1 == nums2: #The trivial case where the two are equal return len(nums1) else: maximum = 0 #Storage used to find the longest subarray #This next section of code in...
42d013acda60a2aff5c7cc7c04e4b64f7df038a7
vanderveldenmd/MiscLeetCode
/IsomorphicStrings.py
1,875
4.0625
4
#This uses dynamic programming where the cipher will be stored by an array. If there are more than one letters trying to substitute the program will know there is an #issue and return false. Then, the program will check the cipher to look for duplicates which would also indicate there is an issue in the solution. clas...
f7f9295edd7b010a5899b5fe7bc1ff66f84d33d6
pg42876/AAB
/Aulas/Aula 2/SuffixTree.py
2,210
3.6875
4
# -*- coding: utf-8 -*- class SuffixTree: def __init__(self): self.nodes = { 0:(-1,{}) } # root node self.num = 0 def print_tree(self): for k in self.nodes.keys(): if self.nodes[k][0] < 0: print (k, "->", self.nodes[k][1]) else: ...
ecb59f191c3e067acd7776cce1f49e9f9380c223
happymao/alien_invasion
/bullet.py
1,148
3.796875
4
import pygame from pygame.sprite import Sprite class Bullet(Sprite): ''' create a class for manage buller ''' def __init__(self, ai_settings, screen, ship): ''' create a bullet on the position of ship ''' super(Bullet, self).__init__() # otherwise Super __init__() will be over written ...
5270f1e5b8d4285e401d440476bc077ee89b0315
Themis404/completed_tasks
/task_twelve/task_twelve.py
1,092
4.5625
5
''' 2. В одном файле в каждой строке записаны координаты пар точек. Каждая координата отделена от другой пробелом. Например, строка вида 3 6 -2 4 означает, что координаты первой точки (3;6), второй - (-2;4). Во второй файл требуется построчно записать наибольшее и наименьшее расстояние между точками ''' import math d...
5e6438887f1623fc1a378fc902c1024dde67f18c
FoteiniRodi/Crash-Course-on-Python-by-Google
/Week5_5.1ObjectOrientedProgramming.py
17,226
4.125
4
#%% """ Google's Crash course on Python, Week 5: Object-oriented Programming (OOP) 5.1 Object-oriented Programming Theory from Google What is Object-oriented Programming Python uses a programming pattern, called object-oriented programming, to explain concepts to a computer. Python OOP models these concepts b...
b71c8353038c7cac83a834e5b047cc735648b371
abelar96/PythonPrograms
/HW2.py
425
4.21875
4
##Diego Abelar Morales def distance(s, h): return s * h speed = int(input("What is the speed of the vehicle in mph?: ")) hours = int(input("How many hours has it traveled: ")) print("Hours Distanced Traveled") print("------------------------------") for time in range(1, 1 + hours): distance(...
033ec6d5082b56389d6921865ea3fe92e77d743d
DerSchinken/PasswordCardGenerator
/PasswordCardGenerator/GUI/gui.py
2,631
3.65625
4
from PasswordCardGenerator import PasswordCard from tkinter import filedialog, messagebox from tkinter import * from tkinter.ttk import * from os import path, remove from random import randint app = Tk() app.run = app.mainloop app.title("Password Card Generator") app.iconphoto(False, PhotoImage(file="assets/img/Logo.p...
891a63e00ee2094a05ba7fa25f89f4a0339d20ee
Vaishnav95/bridgelabz
/object_oriented_programs/inventory_2.py
500
3.828125
4
"""Create a JSON file having Inventory Details for Rice, Pulses and Wheat with properties name, weight, price per kg. """ import json file = open("inventory.json", 'r') data = json.load(file) file.close() for key in data: for value in data[key]: price = 0 weight = 0 price += int(value['pri...
b66c2aab4e1b2707cbfb7105900d15b92ebcde91
Vaishnav95/bridgelabz
/data_structures_util.py
17,566
4.15625
4
""" This is a Util class for data structures which contains all the functions performing the mentioned tasks. Author: Vaishnav Goregaonkar Date: 17/12/2019 """ class Node: """Creating a Node class with reference initially set to None Parameters: data = the value contained in the node """ def...
81c36116f85b01b93766a9da64c926e525d3731c
Vaishnav95/bridgelabz
/data_structures/cash_counter_queue.py
378
3.703125
4
"""Simulate Banking Cash Counter This is a Program which creates Banking Cash Counter where people come in to deposit Cash and withdraw Cash. Have an input panel to add people to Queue to either deposit or withdraw money and dequeue the people. Maintain the Cash Balance. """ from data_structures_util import Queue queu...
0d58826718124173c580fddc80ab18717d8db13e
Vaishnav95/bridgelabz
/testing_programs/vending_notes.py
758
4.40625
4
''' Find the Fewest Notes to be returned for Vending Machine a. Desc -> There is 1, 2, 5, 10, 50, 100, 500 and 1000 Rs Notes which can be returned by Vending Machine. Write a Program to calculate the minimum number of Notes as well as the Notes to be returned by the Vending Machine as a Change b. I/P -> read the Change...
de3f20a97b1f6ad9a4f09553914f7a0b4b55ee54
Vaishnav95/bridgelabz
/algorithm_programs/sort_merge.py
700
4.15625
4
''' Merge Sort ​ - ​ Write a program to do Merge Sort of list of Strings. a. Logic -> ​ To Merge Sort an array, we divide it into two halves, sort the two halves independently, and then merge the results to sort the full array. To sort a[lo, hi), we use the following recursive strategy: b. Base case: If the subarray le...
6c802e64c761ee9de46c355b25dad866c867ded1
Vaishnav95/bridgelabz
/logical_programs/tic_tac_toe.py
630
4.25
4
''' Cross Game or Tic-Tac-Toe Game a. Desc -> Write a Program to play a Cross Game or Tic-Tac-Toe Game. Player 1 is the Computer and the Player 2 is the user. Player 1 take Random Cell that is the Column and Row. b. I/P -> Take User Input for the Cell i.e. Col and Row to Mark the ‘X’ c. Logic -> The User or the Compute...
6783d9d94eaa6705608e94ca13f64eea7094ea4a
Vaishnav95/bridgelabz
/object_oriented_programs/stock_account.py
1,709
3.921875
4
"""Stock account management @Purpose: Print a stock report with value of each stock @author: Vaishnav Goregaonkar @date: 27/12/2019 """ class Share: """This class contains info about the stocks owned by an individual """ def __init__(self, name, price, number): self.name = name ...
897e72cbb6d1596829f5dc4efef99799fa875f79
CaMeLCa5e/Dailyfall2015
/list_verify.py
276
3.71875
4
#! usr/bin/env python already_emailed_list = ["x", "z"] # import open(newlist.txt,'r') as needs_to_be_checked: needs_to_be_checked = ["x", "y","z", "L"] for item in needs_to_be_checked: if item in already_emailed_list: pass else: print '"'+item+'",'
6c9159342e3323fe19e6f861104a30b99829ad5d
mrchary/oreilly-python-1
/Exercises/greeting.py
160
4.03125
4
# # greet someone # first = input("Please enter your first name: ") last = input("Please enter your last name: ") print ("I am please to meet you,",first,last)
d264c5fb456b55e2e6ec387ef4f491f8aadc2c4a
mrchary/oreilly-python-1
/Exercises/input_counter.py
479
3.90625
4
#!/usr/local/bin/python3 word_set = set() word_dict = {} while True: s = input("Enter text: ") if not s: print("Finished") break else: for punc in ",?;.": s = s.replace(punc, " ") words = s.lower().split() for word in words: previous_size = len(word_set) word_set.add(word) ...
c7978c2ebe8157836f68dbdafb83ee8d3e78c3f7
maxcastan/p-3
/tickers.py
2,525
3.53125
4
''' command to run->python3 tickers.py numtickers tickers.txt py file to extract valid tickers from nasdaq website authors: Paulina Scarlata and Max Castaneda ''' import requests import sys,os from iex import Stock import lxml.html def save_tickers(n): ''' Args: n: number of tickers to prin...
43d222b563bfa6a2ebf8f17284035023f37d3acb
RookieDay/py_example
/py_exercises/exercise_26/pyaudio_module/np_shape.py
484
3.875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/11/9 # @Author : RookieDay # @Site : # @File : np_shape # @Github : https://github.com/rookieday # @Software: PyCharm Community Edition import numpy as np c = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]]) print(c) print(c.shape) c.shape = 4,3 pr...
b1ab33304721427afc5cc51e36fc0f1c3ab902a4
RookieDay/py_example
/spider_ways/sqlite3_test.py
928
3.765625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/11/15 # @Author : RookieDay # @Site : # @File : sqlite3_test # @Github : https://github.com/rookieday # @Software: PyCharm Community Edition # 参考 # http://www.runoob.com/sqlite/sqlite-python.html import sqlite3 # 连接到SQLite数据库 # 数据库文件是test.db # 如...
b14035beb5a3e961f75bb0b050b0ffc42440e87f
RookieDay/py_example
/test/propertytest.py
1,044
3.71875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/10/14 15:44 # @Author : RookieDay # @Site : # @File : propertytest.py # @Software: PyCharm Community Edition # 只允许对Student实例添加name和age属性 # __slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称 # Python内置的@property装饰器就是负责把一个方法变成属性调用的 class Student(obje...
5f3b122a4d059cb9ebea2d09ebe828dce33f9505
helish88/casino-bot-for-discord
/src/casino.py
5,901
3.5
4
import random import typing as t from types import TracebackType from collections import Counter from dataclasses import dataclass from src.enums import ScoreChances @dataclass(frozen=True) class Container: board: t.List[str] # board with emojis multiplier: int # multipli...
a7261fb413999c29ef7d40d1a3723e3ccf847f4c
tbnsok40/Algorithm
/BAEKJOON/[baek] 16460.py
565
3.890625
4
name, gender_pref, max_dist = input().split() max_dist = int(max_dist) # if gender_pref == 'MF' or 'FM': # gender_pref = 'MF' answer = [] for _ in range(int(input())): partners_name, gender, dist = input().split() dist = int(dist) if ((gender_pref == gender) or (gender in gender_pref)) & (max_...
2765613fa17ef4175253abe92823954d67837a84
tbnsok40/Algorithm
/BAEKJOON/[baek] 11728.py
1,095
3.984375
4
# def mergeSort(original_list): # if len(original_list) < 2: # return original_list # mid = (len(original_list) // 2) # list1 = original_list[:mid] # list2 = original_list[mid:] # return merge(mergeSort(list1), mergeSort(list2)) # # def merge(list1, list2): # i = 0 # j = 0 ...
b3a26c56d18f363bfb1cba242bff0d33a3363414
cod3baze/initial-python-struture
/solo_learn/handle_files/readin.py
293
4.1875
4
#Para recuperar cada linha em um arquivo, você pode usar o método # readlines para retornar uma lista na qual cada elemento é uma linha no arquivo. file = open("textos.txt", "r") #print(file.readline()) #file.close() # ou usando um loop FOR for line in file: print(line) file.close()
9f2c92d68d7c2bfb325b3e437681c380768c6761
cod3baze/initial-python-struture
/solo_learn/handle_files/working File.py
595
3.90625
4
#É uma boa prática evitar o desperdício de recursos, certificando-se de que os arquivos estejam # sempre fechados depois de serem usados. Uma maneira de fazer isso é usar try e finally. try: file = open("textos", "r") print(file.read()) finally: file.close() #Uma maneira alternativa de fazer isso é usando ...
f2784c8cc19167c649f41b9f077b127c8eb04cbe
svshriyansh/python-starter
/ex2fiborecur.py
244
4.15625
4
def fib(n): if n == 1: return 0 elif n == 2: return 1 else: return fib(n-1) + fib(n-2) m = int(input("Enter the number to find its fibonacci: ")) for Num in range(1, m+1): print(fib(Num),end=' ')
77fdf3a3913e0f9ef183ee080f07d94b22855a1d
ASKJR/udemy-projects
/python3-basic/media-aluno.py
1,437
3.765625
4
# total de aulas = 20 # Aprovado mínimo 70% de presença && média >=6 nome = input('Digite seu nome: ') # validação input while True: p1 = input('Digite a nota da P1: ') try: p1 = float(p1) if p1 >= 0 and p1 <= 10: break else: print('Nota deve ser ente 0-10') ...
baca1b3c23ad07a3996835ada15fafa89c2bda9e
nishu959/pepcodingbitmanipulation
/reducento1inminimumsteps.py
362
3.90625
4
n = int(input()) c = 0 while(n!=1): if ((n&1)==0):#or if(n%2==0) n = n //2 #n = (n>>1) can also be used elif(n==3): c += 2 break elif((n & 3)==1):# or if(n%4==1) n = n - 1 elif((n&3)==3):# or if(n%4==3) n = n +1 c += 1 print(c) #print(64>>1,64<<1) #>> used f...
f1a67e63a0aef70a065084291d6c6a7f9f488d04
RachelElysia/everyone-pairs-once
/pair-up.py
3,297
3.78125
4
import random # Example: # Input: ['Rachel', 'Hunter', 'Alicia', 'Nan', 'Elizabeth', 'Ilana', 'Jen', 'Yvonne'] # Output Example: # Round 1: {{'Rachel', 'Hunter'}, {'Alicia', 'Nan'}, {'Elizabeth', 'Ilana'}, {'Jen', 'Yvonne'}) # Round 2: {{'Rachel', 'Alicia'}, {'Hunter', 'Nan'}, {'Elizabeth', 'Jen'}, {'Ilana', 'Yvonne'...
e024ab5891a5fa310c0b35d61a796460b252c1a5
xiaoxingyu3618/2
/day05/exercise01.py
267
3.625
4
""" 在控制台中录入西游记喜欢的人物 """ list_person = [] while True: str_input = input("请输入西游记中喜欢的人物:") if str_input == "": break list_person.append(str_input) for item in list_person: print(item)
3b910f9bbb806aa93dac92ceb1aca1902a94d047
xiaoxingyu3618/2
/day16/exercise05.py
497
3.734375
4
""" """ class MyRange: def __init__(self, number): self.number = number def __iter__(self): return MyRangeIterator(self.number) class MyRangeIterator: def __init__(self, end_value): self.end_value = end_value self.__number = 0 def __next__(self): if self.__...
cf88c48be0003d58d7e5789b6eb7547e3ec80805
xiaoxingyu3618/2
/day04/exercise01.py
186
3.609375
4
""" 在控制台中获取一个整数,如果是偶数赋值为偶数 """ number = int(input("请输入一个整数:")) state = "奇数" if number % 2 else "偶数" print(state)
ee97eb09110af5920b87231b7de26c9523af1d28
xiaoxingyu3618/2
/day04/demo04.py
454
3.984375
4
count = 0 while count < 3: str_score = input("请输入成绩:") if str_score == "": break #不会执行else语句 score = int(str_score) if score > 100 or score < 0: print("输入有误") count +=1 elif score >= 90: print("优秀") elif score >= 80: print("良好") elif score >= 60: ...
4a7acb70a85d7db53e536639423ca96e01979d20
xiaoxingyu3618/2
/day03/exercise01.py
303
3.671875
4
""" 选择语句 调试 """ price = float(input("请输入商品的单价:")) count = int(input("请输入商品的数量:")) money = float(input("请输入金额:")) result = money - price * count if result >= 0: print("应找回:" + str(result)) else: print("所付金额不足")
896b15e7430a79490aeae0edd7b23ef292bf6d74
xiaoxingyu3618/2
/project_mouth01/student_manager_system.py
3,335
4.09375
4
""" 学生信息管理系统 """ class StudentModel: """ 学生数据模型 """ def __init__(self, name="", age=0, score=0, id=0): self.name = name self.age = age self.score = score self.id = id class StudentManagerController: __init_id = 1000 def __init__(self): self._...
b6d376675a3a492976eeafc193a8fa9bec9ff56f
xiaoxingyu3618/2
/day17/exercise01.py
545
3.859375
4
list01 = [3, 4, 55, 6, 7] def my_enumerate(iterable_target): for index in range(len(iterable_target)): yield (index, iterable_target[index]) for index, element in my_enumerate(list01): print(index, element) def my_zip2(*args): # 根据星号元组形参args第一个参数的长度生成索引len(args[0]) for i in range(len(args[...
bf24693840bf985e9eed593a3a77221f6d280312
lioralehrer/appleseeds
/week9/python/ex-2-speaking-python/Intersection.py
218
3.859375
4
def intersection(list1,list2): list3 = [i for i in list1 if i in list2] return list3 list1 = [4, 9, 1, 17, 11, 26, 28, 54, 69] list2 = [9, 9, 74, 21, 45, 11, 63, 28, 26] print(intersection(list1, list2))
97009c0b45b68e67bc7b658e6c1f396eacc613d1
nkatz01/Python-exercises
/RecursionSum.py
1,133
3.53125
4
Houses = [1, 2, 3, 4] def IterativeSum(i): Total = 0 while (i<4): Total += Houses[i] i = i+1 return Total; #print(Houses[0]) #print(IterativeSum(0)) def SumRecursive(i): if (i==0): return Houses[i]; else: #the sum of A[0],...,A[i] #is the sum of elements A[0],...,A[i-1] and A[i] return SumR...
0dfcd75d105d585ced421972befb67a8bb17e346
nkatz01/Python-exercises
/analyseString.py
535
4.09375
4
#Nuchem Katz 11.12.2017 #This program gete the first character of a string, The last character #The middle character (if the length is odd),) #The middle two characters (if the length is even string=input("Enter string : ") print(string[0],string[-1]) if len(string)%2==0: midleftpointer=int(len(string)/2)-1 ...
430d49187ec7b32578fb816244c23dd08a56d37a
nata1y/cleanco
/cleanco/classify.py
1,685
3.8125
4
""" Functions to help classify business names by country or type, based on legal terms. Examples of use: >> # check name for its possible business type(s) >> classification_sources = typesources() >> matches("MyCompany Ltd", classification_sources) ['Limited'] >> >> # check name for its possible jurisdictions, usual...
0276d89b33d3d01d708dcf7d3e1ee51f989989e8
dshinzie-zz/exercism
/python/roman-numerals/roman_numerals.py
496
3.984375
4
def numeral(arabic_input): CONVERSION = { 1: 'I', 4: 'IV', 5: 'V', 9: 'IX', 10: 'X', 40: 'XL', 49: 'XLIX', 50: 'L', 90: 'XC', 100: 'C', 400: 'CD', 500: 'D', 900: 'CM', 1000: 'M' } roman = '' f...
960ce48017ee9c7730a4e6471349ec2683d3167c
rahulb246/leetcode-may-challenge
/week-1/isCousins.py
1,560
4.09375
4
# In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1. # Two nodes of a binary tree are cousins if they have the same depth, but have different parents. # We are given the root of a binary tree with unique values, and the values x and y of two different nodes in the tree. #...
ae6420bb386942a1b94bebf777617f4451d6d214
CVHS-TYM/Marpaung_Story
/Learning/whiletest.py
85
3.671875
4
i = 0 t = int(input()) while i != 6: i += 1 if i == 3: continue print(i)
c56b8017f80e221e17ba0e6440a02bcc3e12d66c
CVHS-TYM/Marpaung_Story
/Learning/Starting Tutorials/addsix.py
97
4
4
x = float(input("Give me a number: ")); print("The number "+str(x)+" plus six equals "+str(x+6));
63b7555419eed642b75d9f7fff0e9cd9484446df
Simonanilgeorge/orm-test
/class.py
331
3.953125
4
class Student: def __init__(self,name,age,address): self.name=name self.age=age self.address=address def insert(self,name): print(self.__dict__) print(name) # @classmethod student=Student("Simon",24,"abcdsd") # student.insert("test name") print(student.__dict__....
ba8519681671f04491b2c54a7cc4f1c744fa85d5
boettcherb/JetBrains-Academy-Projects
/Medium/Numeric Matrix Processor/numericmatrixprocessor.py
6,268
3.5625
4
class Matrix: def __init__(self, rows, cols, matrix=None): self.rows = rows self.cols = cols if matrix is None: self.matrix = [[0 for _ in range(cols)] for _ in range(rows)] else: self.matrix = matrix def __getitem__(self, item): return self.matri...
b1868258cb8eed6f7df9368a6837063bad52ff55
boettcherb/JetBrains-Academy-Projects
/Easy/Bill Splitter/billsplitter.py
781
3.96875
4
import random n = int(input("Enter the number of friends joining (including you):\n")) if n > 0: print() print("Enter the name of every friend (including you), each on a new line:") names = [input() for _ in range(n)] bill = int(input("\nEnter the total bill value:\n")) print('\nDo you want to use ...
72036dca9ced8611341358a84347f90a6b5efb6e
devzgabriel/python-calculator
/Parte Matricial da Calc.py
3,308
3.671875
4
qtd_lin_A = int(input('Quantas Linhas na Matriz A (máx 5):')) qtd_col_A = int(input('Quantas Colunas na Matriz A (máx 5):')) matrizA = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] for l in range(0, qtd_lin_A): for c in range(0, qtd_col_A): matrizA[l][c] = int(input(f...
7c52d557460eda863495599f64adb32ff78431bb
simple5510/Leetcode
/Leetcode/236.Lowest Common Ancestor of a Binary Tree.py
2,874
3.9375
4
''' Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itse...
36763f6208aea6d9641949418e0fc0376bb101bc
simple5510/Leetcode
/Leetcode/6. ZigZag Conversion.py
972
4
4
""" 将字符串 "PAYPALISHIRING" 以Z字形排列成给定的行数: P A H N A P L S I I G Y I R 之后从左往右,逐行读取字符:"PAHNAPLSIIGYIR" 实现一个将字符串进行指定行数变换的函数: string convert(string s, int numRows); 示例 1: 输入: s = "PAYPALISHIRING", numRows = 3 输出: "PAHNAPLSIIGYIR" 示例 2: 输入: s = "PAYPALISHIRING", numRows = 4 输出: "PINALSIGYAHRPI" 解释: P I ...
afdc61fd1667c4d6939dd242cb775bb9e101b2f7
simple5510/Leetcode
/Leetcode/102.Binary Tree Level Order.py
2,095
3.96875
4
''' Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its level order traversal as: [ [3], [9,20], [15,7] ] ''' # Definition for a binary tre...
2c8d2f1e1a5fc600825d06fc7eedd153af107445
Natarajshanmugam/Problems_nataraj
/cat_mouse.py
227
3.71875
4
##https://www.hackerrank.com/challenges/cats-and-a-mouse/problem ##x,y,z=1,3,2 ##x,y,z=1,2,3 ##x,y,z=85,66,80 a,b=0,0 a=abs(x-z) b=abs(y-z) if(a<b): print("cat A") elif(a>b): print("cat B") else: print("mouse C")
2bd927349bcc570a0c4fac5bd926ceb2b8cf7947
azurrosenlov/Fingrid_analysis
/Wind_generation_airflow.py
1,438
3.71875
4
import requests import datetime import json import os ''' Function that extracts yesterdays date, formats the datetime input and connects to the Fingrid API-service. Returns the data from the API-service and the date (as the time variable). ''' def wind_generation(): variableId_wind = 75 api_code = {'x-api-k...
a2380c2f8ea772778259ae69c8851a5ebffffb8e
itodotimothy6/CTCI
/Arrays-&-Strings/1.4/solution.py
1,566
4.25
4
# Given a string, write a function to check if it is a permutation of a # palindrome. A palindrom is a word or phraze that is the same forwards and # backwards. A permutation is a rearrangement of letters. A palindrome does not # need to be linited to just dictionary words. # Note: a maximum of one character should ha...
eb0cd8880288e151938e894de7b04cdaeafc0840
RagazziMoscow/4_json
/pprint_json.py
990
3.6875
4
import json import os.path # Загружает содержимое json - файла def load_data(filepath): if(os.path.exists(filepath)): with open(filepath, "r") as json_file: list = json.loads(json_file.read()) else: list = None return list def pretty_print_json(data): format_data = json.d...
f2ce02fe4a649be8b2646c34427984151f68b8be
23devanshi/pandas-practice
/Automobile Dataset/Exercises.py
2,191
4.34375
4
# Exercises taken from : https://pynative.com/python-pandas-exercise/ import pandas as pd import numpy as np #pd.display df = pd.read_csv('D:/Python tutorial/Pandas Exercises/1 Automobile Dataset/Automobile_data.csv') df.shape #: From given data set print first and last five rows print(df.head()) print(df.t...
fa61c68de2ff1470106346a77f276052d3981114
btarcahn/natstupid
/prototype-01/search/artifacts.py
1,831
4.03125
4
import json from enum import Enum class Stack: """Lightweight representation of a stack data structure. Reference: https://runestone.academy/runestone/books/published/pythonds/BasicDS/ImplementingaStackinPython.html """ def __init__(self, n=0): self.__items = [] def is_empty(self): ...
fc29559a765aa002c659627362b57e9d5c6748af
x-jeff/Python_Code_Demo
/Demo11/drop_nan.py
637
3.671875
4
import pandas as pd import numpy as np df=pd.DataFrame([["Tim","M",24,169,100],["Jack","M",np.nan,177,np.nan],["Jessy","F",21,162,np.nan],["Mary","F",23,159,87]]) df.columns=["Name","Gender","Age","Height","Weight"] df["Salary"]=np.nan print(df) #舍弃含有缺失值的行/列 #舍弃含有缺失值的行 print(df.dropna(axis=0,how="any"))#默认参数 #舍弃含有缺失值...
f1b54284583b0504c1ad7eb994198432efeb9157
x-jeff/Python_Code_Demo
/Demo9/numpy_demo.py
248
3.765625
4
import numpy as np a=[1,2,3] b=[2,3,4] #print(a*b) #error for k,v in zip(a,b): print(k*v) for k,v in zip(a,b): print(k,v) c=[k*v for k,v in zip(a,b)] print(c) import numpy as np a=np.array([1,2,3]) b=np.array([2,3,4]) print(a+b) print(a*b)
a2b05a057766e31f09a0833082684fc3491de4bb
x-jeff/Python_Code_Demo
/Demo12/12.1.create_class.py
1,187
4.09375
4
class Employee: 'class information' empCnt = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCnt += 1 # self.empCnt=1 def displayCnt(self): print("Total Employee %d" % Employee.empCnt) def displayEmp(self): prin...
0704b8a36877f5bbfd5ea2ead13628c8a6d3f85e
x-jeff/Python_Code_Demo
/Demo15/time_format.py
908
3.625
4
from datetime import datetime from datetime import timedelta from time import mktime import pandas as pd # 输出现在的时间 current_time = datetime.now() print("current time : ", current_time) print(type(current_time)) # 将时间转换成字符串 print(current_time.strftime('%Y-%m-%d')) # 将字符串转换成时间 print(datetime.strptime('2020-08-19', '%Y-...
bcec15a522763cbb1ffa8c86d7039daab7479f11
x-jeff/Python_Code_Demo
/Demo43/PCA_demo.py
602
3.578125
4
from sklearn.decomposition import PCA from sklearn.datasets import load_iris from matplotlib import pyplot as plt iris = load_iris() X = iris.data y = iris.target print(X.shape) pca = PCA(n_components=2) pca.fit(X) X_reduced = pca.transform(X) print(X_reduced.shape) plt.scatter(X_reduced[:,0], X_reduced[:,1], c=y) ...
37ab1b76a62ec291da99c0d506950dd4266d6154
pseudo11235813/Random-Python-Ciphers
/cryptoMath.py
1,072
3.984375
4
#some usable math functions def gcd(a,b): # function that returns the greatest common divisor or two integers while a!= 0: a,b = b % a , a return b def modularInverse(a,b): # fucntion that returns the modular inverse of two integers, this function is used when decrypting a code that's been decrypted...
ddf23def27bf7f1fa42fc75734abffec93907230
renatomak/linguagem-python
/teste.py
86
3.671875
4
print('Primeiro Programa') 3 + 5 a = 2 b = 3 dictio = {'nome': 'Renato', 'idade': 20}
01ad99a561a9d1e625a02abd725fbf8dd3ebce4d
jiaojihua/python
/matplotlib/3d-qumian.py
859
3.703125
4
import pandas as pd #读取表单 df = pd.read_excel('abc.xls',sheet_name=0) #可以通过sheet_name来指定读取的表单,其值可以是索引,也可以是表单名 data = df.head()#默认读取前5行的数据 #读取指定行 data = df.iloc[0].values[3] #0表示第一行,这里读取数据并不包含表头 #读取指定的多行,数据会存在嵌套的列表里面 data = df.iloc[[1,2]].values #读取指定的行列 data = df.iloc[1,2] #读取第一行第二列的值 #读取指定的多行多列值 data = df.loc[[1,2],['个...
3286b98702b8eaebb9392679b8f6b7b663bad191
avp/lunarlockout
/bfs.py
921
3.53125
4
from logger import log_result from state import State from collections import deque import time def run_bfs(start_dict, start_name): print("running bfs") start_state = State(start_dict) visited = {} visited[start_state] = True q = deque([start_state]) q.append(start_state) start_time = time.time() popp...