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
36dbbf2f8409b92bd179c8ffe82fff84c68e627d
rishabkatta/Donald-Knuth-Conjecture
/factroot.py
4,621
4.0625
4
''' @author-name: Rishab Katta This program uses python version 2 ''' import math import Queue import sys class Node: ''' Node Class is used to represent each node in the Tree. The Value of each node in the tree is calculated by performing factorial, square root and floor operations starti...
a73d47ed2c37a448adea378d7af9979a9dc12015
vuwvuwpl/python_udemy_learning-ai
/newral_network/machine_learning.py
5,561
3.734375
4
# coding: UTF-8 import math import matplotlib.pyplot as plt # シグモイド関数 def sigmoid(x): return 1.0/(1.0+math.exp(-x)) # ニューロン class Neuron: input_sum = 0.0 output = 0.0 def setInput(self, inp): self.input_sum += inp def getOutput(self): self.output = sigmoid(self.input_sum) ...
deb0941c46090ce100108522fc20ad99f78f6f1e
SuperTrampAI/Chapters
/doc/Two.py
1,048
3.765625
4
# -*- coding: utf-8 -*- # @Time : 2020/5/17 16:02 # @Author : Marko Li 'lxh800109@gmail.com' # @Site : # @File : Two.py # @Software: PyCharm # __create_data__=2020/5/17 16:02 # @Description: add Description one='全局变量' def main(): print("start") # one='外层嵌套变量' # if elif else 语句 age = 18 # ...
1af963fa34baccf6c1130861225b912d42b787ec
RainysLiu/Learn-Test
/old_test/装饰器实现单例.py
317
3.921875
4
def Singleton(cls): ins = {} def singleton(*args, **kargs): if cls not in ins: ins[cls] = cls(*args, **kargs) return ins[cls] return singleton @Singleton class A(object): a = 1 def __init__(self, x=0): self.x = x a1 = A(3) a2 = A(2) print(a1) print(a2)
dcee80352c93df7f9dccfef14c15ea31dd7bfe88
databooks/databook
/deepml/pytorch-examples02/nn/two_layer_net_module.py
1,980
4.21875
4
import torch """ A fully-connected ReLU network with one hidden layer, trained to predict y from x by minimizing squared Euclidean distance. This implementation defines the model as a custom Module subclass. Whenever you want a model more complex than a simple sequence of existing Modules you will need to define your...
cd7668a66a7eab16b41c713358ec3fb31ac8ee63
Freddiekins/PythonStudy
/homework2/9.py
348
3.828125
4
# 定义一个函数,函数接收一个数组,并把数组里面的数据从小到大排序 # (冒泡排序, 也可以直接使用相关的函数); import random def sort(list): print("原数组:", list) list.sort() print("排序后:", list) list = [] for i in range(10): list.append(random.randint(0, 100)) sort(list)
95afd19c17de39c7f24dfdabc1b294b8acf4e026
Freddiekins/PythonStudy
/homework3/2.py
331
3.8125
4
# 写一个程序,从input.txt中读取之前输入的数据,存入列表中,再加上行号打印显示;格式如下 import os path = os.getcwd() f = open(path + "/homework3/input.txt") list = f.readlines() for i in list: i = i.strip() for i in range(len(list)): print(i+1, end="") print("."+list[i], end="")
7fdb52673f61605a146cd3add9e5ae3bbd385600
Freddiekins/PythonStudy
/exe6/5_fight.py
1,250
3.578125
4
from human import human from dog import dog import random class fight(object): def __init__(self, human, dog): self.human = human self.dog = dog def fight(self): mark = random.randint(0, 1) while len(self.human) and len(self.dog): if mark == 0: d =...
39dc430c700d054a8587c8244de42c630e7139aa
Freddiekins/PythonStudy
/homework2/4.py
615
3.734375
4
# 写函数,统计字符串中有几个字母,几个数字,几个空格,几个其他字符,并返回结果; def strScan(str): letter = 0 num = 0 char = 0 space = 0 for i in str: if i.isdigit(): num = num + 1 elif i.isalnum(): letter = letter + 1 elif i.isspace(): space = space + 1 else: ...
29aafe0285e98e8e1de8b32debf56239e6d3bcd3
Freddiekins/PythonStudy
/practice/4.py
481
3.734375
4
# 一个文件内容的如下,请按照行读取文件的内容, 将分数排序后输出到另外一个文件中: f = open("read.txt", encoding='utf-8') data = f.readlines() f.close() list1 = data[1].split() list2 = data[2].split() list3 = data[3].split() list = [list1, list2, list3] list.sort(key=lambda score: score[2]) f = open("new.txt", mode="w") f.write("姓名 学号 成绩\n") for i in ...
45b0f6b870a1b0cea9045b3b71c4626b9e758971
Freddiekins/PythonStudy
/homework3/6.py
621
3.875
4
# 对一篇英文文章,进行词频统计,输出前10个出现频率最高的单词; import os def getText(): path = os.getcwd() f = open(path + "/homework3/text.txt") text = f.read() text = text.lower() for i in text: if i.isalnum() is False and i.isspace() is False: text = text.replace(i, " ") return text dict = {} t = ...
9a5c0c3e11e3a1e8f211fa5697e81ce16f0a8d5a
Orelavant/Mountain-Test-1
/MountainMatrix.py
4,737
3.65625
4
""" Mountain Matrix """ import numpy as np import math as math import random as rand import matplotlib.pyplot as plt from matplotlib.pyplot import figure def main(): # Initializing rows = 5 columns = 9 mount_matrix = np.zeros((rows, columns)) # Creating mountain drop_ones(mount_matrix) ...
8e7838966b1c3b4573c001f3c97cfc0db35a6ee4
lpython2006e/student-practices
/4_Tran_Thi_Nhu_Huong_LOCAL/bai3.4.py
1,575
3.578125
4
"""Update previous one, allow to enter multiple classmate, at end, allow to save to file as CSV format""" from datetime import datetime import re import csv def _check_valid_name(a): list = ["Huong", "Thach", "Dung", "Thien"] if a not in list: return False else: return True def _check_va...
2ec0019b6c59154df7a28488c8e3acb39692a3ae
lpython2006e/student-practices
/14_Tran_An_Thien/Bai_2.1.py
288
4.09375
4
# Write a function that returns the largest element in a list. list_large = ['sfsg', '123', 'sdjjgd'] print("max list: ", max(list_large)) # list1, list2 = ['C++','Java', 'Python'], [456, 700, 200] # print ("Max value element : ", max(list1)) # print ("Max value element : ", max(list2))
6224237e95526be40e503636b43c25e7efb8c1c4
lpython2006e/student-practices
/15_Nguyen_Tu_Giang/bai-2.1.py
190
4.21875
4
# Write a function that returns the largest element in a list. def largest_ele(ele): ele.sort() result = ele[len(ele) - 1] return result print(largest_ele([1, 10, 5]))
75e8edfa8f01a8605e6f8fb37fecfe5f23d1ce2f
lpython2006e/student-practices
/12_Nguyen_Lam_Manh_Tuyen/2.7.py
610
4.1875
4
#Write three functions that compute the sum of the numbers in a list: using a for-loop, a while-loop and recursion. # (Subject to availability of these constructs in your language of choice.) def sum_with_while(lists): list_sum = 0 i = 0 while i < len(lists): list_sum += lists[i] i += 1 ...
2dd9f273f1443e2f985d2ae977aadd30bffae8e4
lpython2006e/student-practices
/5_Pham_Ngo_Tien_Dung/2.5.py
452
3.96875
4
# Write a function that computes the running total of a list. def totalList(number, myList): tong = 0 for i in range(number): x = int(input("myList[" + str(i) + "]= ")) myList.append(x) print("myList = ", myList) for item in myList: tong += item print("tong c...
2e20b953d82be98668208fe1cd18d044480bc80e
lpython2006e/student-practices
/9_Phan_Van_Quan/bai3_1.py
319
4
4
#Write a program that allow user enter a file name (path) then content, allow user to save it # import os # os.mkdir("test.txt") file_name = input("Nhap vao file_name dang .txt ") file = open(file_name, 'w+') file.write("Hello is is comment") file.flush() file.close() file_2 = open(file_name,'r') print(file_2.read())
319377b53a9c8cb567b2d5981a589b8656ce3e7d
lpython2006e/student-practices
/14_Tran_An_Thien/Bai_2.4.py
338
4.09375
4
# Write a function that returns the elements on odd positions in a list. def return_odd_position_element(list_a): c = [] for i in range(1, len(list_a), 2): c.append(a[i]) return c a = [41, 19, 74, 107, 12309, -82, 64, 39, 501, 124, 70, 1111] odd_element_list = return_odd_position_element(a) print(...
aee5a03a92e3a6c22b45572d699dd11ccda175d7
lpython2006e/student-practices
/12_Nguyen_Lam_Manh_Tuyen/1.4.py
355
4.0625
4
#Write a program that asks the user for a number n and prints the sum of the numbers 1 to n start=1 print("Please input your number") end=input() sum=0 while end.isdigit()==False: print("Your input is not a valid number, please try again") end=input() for i in range(start,int(end)+1): sum=sum+i print("Sum f...
e89abb4cac99c0ab9cfbba645999894ab4760ccd
lpython2006e/student-practices
/8_Tran_Vu_Ngoc_Thach/bai 1.9.py
512
4.09375
4
"""Write a program that prints the next 20 leap years (enter year or if not, get current year as default)""" import datetime now = datetime.datetime.now() string = input("input the year") if string: actual_year = int(string) else: actual_year= now.year total = 20 i= 0 print ("List of next 20 leap years:") whi...
251cd6f1aeb21b7b67400998ef96b9ddf304a427
lpython2006e/student-practices
/9_Phan_Van_Quan/bai3_3.py
1,480
4.0625
4
#Write a program that allow user to enter classmate (name, Birthday, Email), # validate if enter values are valid format (limit length apply), else ask user to enter again per field # nhap name #limit length apply import re limit_name = 7 limit_birthday = 8 limit_emall = 30 def check_input_name(list_input): if(le...
b2c73a750653b98ec18668d59309bba5dc3f1a94
lpython2006e/student-practices
/9_Phan_Van_Quan/bai2_9.py
216
4.15625
4
#Write a function that concatenates two lists. [a,b,c], [1,2,3] → [a,b,c,1,2,3] def concatenates(list_1,list_2): return list_2 + list_1 list_3 = ['a','b','c'] list_4 = [1,2,3] print(concatenates(list_3,list_4))
fe3a3d9d4f36f0f06b4644040e9569b43e92418a
lpython2006e/student-practices
/8_Tran_Vu_Ngoc_Thach/bai3.5.py
260
3.875
4
"""Write a program that read the CSV and print to console as a table (row and column should be aligned, border using – and |)""" import csv from prettytable import from_csv file = "huong.csv" with open("huong.csv", "r") as fp: x = from_csv(fp) print(x)
86696980175f5ff13f0508f5cb4b62cdae6d9ebc
lpython2006e/student-practices
/4_Tran_Thi_Nhu_Huong_LOCAL/bai4.2_rework.py
2,108
4.0625
4
"""Create a program to enter student information, store it as list of student and allow to search students by their name (partial)""" class Student: def __init__(self, name: str = None, nickname: str = None, birthday: str = None, class_number: int = None): self.name = name, self.nickname = nicknam...
820baad5f24cfc52195fbf11f5c74214812a1b76
lpython2006e/student-practices
/12_Nguyen_Lam_Manh_Tuyen/1.3.py
308
4.25
4
#Modify the previous program such that only the users Alice and Bob are greeted with their names. names=["Alice","Bob"] name=() while name not in names: print("Please input your name") name = input() if name=="Alice": print("Hello",name) elif name=="Bob": print("Hello",name)
209fcdefc9bc9b8f11e148809cb705ef0ad668fc
lpython2006e/student-practices
/9_Phan_Van_Quan/bai3_4.py
2,011
3.6875
4
#Update previous one, allow to enter multiple classmate, at end, allow to save to file as CSV format import re import csv limit_name = 7 limit_birthday = 8 limit_emall = 30 first_name = [] last_name = [] birthday = [] email = [] def check_input_name(list_input): if(len(list_input[0]) < limit_name and len(list_in...
56dbe18f5cd493157d153647e82cc9b94fcb8f6c
Bhaveshsadhwani/Test
/ASSESSMENT/Que14 .py
281
4.3125
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 10 16:25:08 2017 @author: User """ num = input("Enter a positive number:") if (num > 0) and (num &(num-1))==0: print num,"is a power of 2" else: print num,"is not a power of 2 "
a656dde5560ca810e0f56b7134177b55c020407f
Bhaveshsadhwani/Test
/ProblemStatement/Question 17.py
221
3.734375
4
# -*- coding: utf-8 -*- """ Created on Mon Oct 09 16:52:15 2017 @author: User """ a= 'H1e2l3l4o5w6o7r8l9d' count = 0 for each in a: if count % 2 == 0: print(each), count+=1 else: count+=1
dc43594df19d3c287aa52ae322d724c9be2f4bbe
Bhaveshsadhwani/Test
/que19.py
324
3.5625
4
# -*- coding: utf-8 -*- """ Created on Wed Oct 11 16:49:08 2017 @author: User """ class Demo: def __init__(self,string): self.string=string def __print__(self): print self.string objectD1=Demo("Hello") objectD2=Demo("BBye") objectD1.__print__() objectD2.__print...
d2625609d625f5d12a14962e47e4c0cc603742e7
Niagara1000/Python_Fundamentals
/person.py
316
3.609375
4
class Person_2: def __init__(self, name, age): self.name = name self.age = age #your code here self.pets = [] def birthday(self): self.age += 1 #your code here def add_pet(self, pet_type, pet_name): self.pets.append((pet_type, pet_name))
9756641ff51e60a1b12d2ba7fbb5190b1b1bb124
WifiTheHuman/Insect-Tracking-Drone-Control-System
/src/tx_swarm.py
3,088
3.578125
4
""" tx_swarm.py Transmitter drone swarming logic (mothership) With the input of a target location (currently from target_positions_gps.txt), outputs the desired drone location """ import time import swarming_logic from gps import GPSCoord # assign the drone a number drone_num = 0 drones = [GPSCoord(-43.520508, 172...
636dfe4d1f9bf218fa7ea4637ffa64c61755b8a7
vicdoz/advent_of_code_2019
/01_12_2019/part2.py
548
3.53125
4
def calcule_fuel(mass: int): fuel_calculated = (int(mass / 3) - 2) if fuel_calculated > 0: fuel_calculated += calcule_fuel(mass=fuel_calculated) else: fuel_calculated = 0 return fuel_calculated assert calcule_fuel(14) == 2 assert calcule_fuel(1969) == 966 assert calcule_fuel(100756) ==...
4ff98dc017eda7df9a80c19e72fab899eac3b044
YuhaoLu/leetcode
/1_Array/easy/python/rotate_array.py
1,677
4.125
4
""" 0.Name: Rotate Array 1.Description: Given an array, rotate the array to the right by k steps, where k is non-negative. Could you do it in-place with O(1) extra space? 2.Example: Input: [1, 2, 3, 4, 5, 6, 7] and k = 3 Output: [5, 6, 7, 1, 2, 3, 4] 3.Solution: array.unshift ...
94183b3fa7b6febb9fac0cd7a99be3d9ee608935
YuhaoLu/leetcode
/1_Array/easy/python/buy_n_sell_stock.py
1,626
3.859375
4
""" 0.Name: Calculate the sum of the increasing subarrays 1.Description: Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may not engage in multiple transactions at the same time. 2.Example: Input: [7, 1, 5, ...
8244b2c89489b52681b49174ee7889ec473cf6d7
YuhaoLu/leetcode
/4_Trees/easy/python/Symmetric_Tree.py
2,166
4.53125
5
""" 0.Name: Symmetric Tree 1.Description: Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center) 2.Example: Given linked list: 1 / \ 2 2 / \ / \ 3 4 4 3 Input: root =...
160c6d9a7e48a31889177cb867e3580d7469f136
C-MTY-TC1028-031-2113/tarea1-basicos-ArturoDuCas
/assignments/04PEMDAS/src/exercise.py
360
3.6875
4
def main(): from math import sqrt print (str(round(2*(3/4)+4*(2/3)-3*(1/5)+5*(1/2),4))) print (str(round((2*35+4*sqrt(36**3)-6*49),4))) print (str(round((4**3+2*5**2)/(4*4),4))) print (str(round((2*(4+5)**2+4*(4-5)**2)/(4*5**2),4))) print (str(round((sqrt((4+5)**2+2**(4+5))/(2*4+2*5)**2),4))) ...
98ce3fdbc1a984e94b2a3ffb884a3a252fa552f7
GunSik2/deeplearning
/src/01.base/b.basic_operation.py
1,190
3.65625
4
import tensorflow as tf # ---------------- # Basic constant operations a = tf.constant(2) b = tf.constant(3) # Launch the default graph. with tf.Session() as sess: print("a=2, b=3") print("Addition with constants: %i" % sess.run(a+b)) print("Multiplication with constants: %i" % sess.run(a*b)) # ---------...
818b51ace77159159c9429c700aa8c6cf8955501
BSanau/data-analysis-pipeline
/SRC/f_createpdf.py
2,839
3.640625
4
from fpdf import FPDF from SRC.var_text_report import texto def situation (country, owner): if country == "Ghana" and owner == "Government": txt = texto["Situation1"] elif country == "Ghana" and owner == "Private": txt = texto["Situation2"] elif country == "Spain" and owner == "Government...
6aa5c7746b2b5b274a16d2b1e1c0d670af5a383e
iloeng/ReadBooks
/01-编程小白的第一本Python入门书/BetGamePy3.py
1,983
4
4
# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: BetGamePy3 Description : 赌点儿钱吧! Author : Liangz date: 2018/9/6 ------------------------------------------------- Change Activity: 2018/9/6: -----------------------------------...
44720d42dc157afb6e26cecdf576d7a4a4392586
komantnick/list_of_python_labs
/PythonLab3/gentest.py
2,057
3.734375
4
def calc(): history = [] while True: x, y = (yield) if x == 'h': print(history) continue result = x + y #print (result) yield result history.append(result) c = calc() print(type(c)) # <type 'generator'> next(c) # Необходимая инициация. М...
1df94c11e36c23bd17752519659f96de91f7ea97
johnerick89/iCube_tasks
/task2.py
735
4.375
4
def get_maximum_value_recursion(weight,values,capacity, n): ''' Function to get maximum value Function uses recursion to get maximum value ''' if n==0 or capacity == 0: return 0 if weight[n-1]>capacity: return get_maximum_value_recursion(weight,values,capacity, n-1) else...
d2daa33003d3f150815a8522dc2a7efbd93b32fa
wanyuxing/Python_learning
/2048_Final.py
6,419
3.515625
4
""" Clone of 2048 game - Henry Wan. This program can only run on http://www.codeskulptor.org """ import poc_2048_gui import random # Directions, DO NOT MODIFY UP = 1 DOWN = 2 LEFT = 3 RIGHT = 4 # Offsets for computing tile indices in each direction. # DO NOT MODIFY this dictionary. OFFSETS = {UP: (1, 0), DOWN: (-1, ...
8c995e574d906da60bcb829024c6943c7413a751
wanyuxing/Python_learning
/Graph_degree.py
1,918
4
4
""" Degree distributions for graphs, there are 3 contant graphs represented by dictionary """ EX_GRAPH0 = {0: set([1, 2]), 1: set([]), 2: set([])} EX_GRAPH1 = {0: set([1, 4, 5]), 1: set([2, 6]), 2: set([3]), 3: set([0]), 4: set([1]), 5: set([2]), 6: set([])} EX_GRAPH2 = {0: set([1, 4, 5]), 1: set([2, 6]),...
6c9b4ba0a343ab3f99eb66204e165d7ce4a48786
FatChicken277/holberton-system_engineering-devops
/0x16-api_advanced/0-subs.py
593
3.75
4
#!/usr/bin/python3 """This module is in charge of making the connection with the api and return the number of subscribers of a given subreddit.""" import requests def number_of_subscribers(subreddit): """This method returns the number of subscribers of a given subreddit""" headers = {"user-agent": "1637-h...
62e7a8865c3d4b0ac0e5e4408117bbac018cffdb
Tonynovtop/Learning-Python
/cal_statisticalpha.py
969
3.828125
4
input_str = """The First-ever Open-water Beluga Sanctuary will Welcome to Adorable Whales in June,Adorable beluga whales are a pupular attraction to aquariums around the world,but like many other wild animals,they also risk losing their habitats due to human intervention such as population growth,new buildings along th...
033d300c6f0950c4d880b078ba8a029aa54c28ae
Tonynovtop/Learning-Python
/merge_result.py
1,289
3.78125
4
# 合并结果 # 两个文件的统计已经在各自的机器上完成了, # 并且结果以字典的方式保存,现在需要合并这两个结果字典,得到一个完整的统计结果 # 两个文件的结果字典如下: # { # "a":10, # "b":21, # ... # "z":18 # } import random import string def generate_2_dict(): # 产生两个字典 a = dict() b = dict() for x in string.ascii_lowercase: # 从a-z的字符串中得到字典的键 temp_num = random.rand...
7cac553480088b7bf613799900690ce9388e7447
erijpkema/slurm-jobinfo
/pynumparser.py
14,702
3.703125
4
#!/usr/bin/python2 # # Works with either Python v2.7+ or v3.3+ # """ This module provides two classes for use in parsing string form of numbers and number sequences: NumberSequence and Number. 1. pynumparser.NumberSequence * Simple parsing for intuitive representation of number sequences. * Optional lower and/o...
8637e0046caedf4817bbcd71cee5eda0dfb33834
jtpio/algo-toolbox
/python/mathematics/pandigital.py
870
4.09375
4
import string def is_pandigital(n, b=10, zeroless=False, unique=False): """ Return True if the number n is pandigital in base b. Parameters ---------- n: int or string The number to test. b: int The base to choose, defaults is 10. zeroless: bool Zero is a forbidden digi...
986022e9efaf3be0de6a1276905b6857c56f6efb
jtpio/algo-toolbox
/python/data_structures/priority_queue_test.py
735
4.09375
4
import random from priority_queue import PriorityQueue # Test the priority queue returns the elements in ascending order of priority pq = PriorityQueue() N = 20 ordered = list(range(N)) shuffled = list(range(N)) random.shuffle(shuffled) for x in shuffled: pq.add(x, x) popped = [] while not pq.is_empty(): po...
951e6870e1c504e5e17122f8cb7a8600d13115bc
jtpio/algo-toolbox
/python/mathematics/cycle_finding.py
1,154
4.21875
4
def floyd(f, start): """ Floyd Cycle Finding implementation Parameters ---------- f: function The function to transform one value to its successor start: The start point from where the cycle detection starts. Returns ------- out: tuple: - mu: int Position at ...
9b06db392f6b98bb0fc220b4978cb0345486b3ad
turtelneck/Python-Projects
/text-based-game/nice-mean-game.py
3,013
4.21875
4
# # Python: 3.9.0 # # Author: Rhodri def start(nice=0,mean=0,name=""): # get user's name name = describe_game(name) nice,mean,name = nice_mean(nice,mean,name) def describe_game(name): """ check if this is a new game or not. If it is new, get the user's name. If it is not a...
4a035f88413cb95964e554e9f18890a2293d55e5
iamnickson/astar
/astar_geo.py
7,719
3.71875
4
from math import sqrt import matplotlib.pyplot as plt import heapq import numpy as np from geo_coords import * from obstacle import * from numba import jit # example of image on map plot: http://scitools.org.uk/cartopy/docs/latest/matplotlib/advanced_plotting.html # adapted from: https://www.laurentluce.com/posts/solv...
bad75a540ecbfe4bf96a6c5d0bfb13da4ee8ff2c
lxw-mesoor/wikipedia-scripts
/lib/priority_queue.py
1,474
3.984375
4
#!/usr/bin/env python2 # coding: utf-8 class MinPriorityQueue(object): """ Maintain a structure that pops out the smallest one. Currently the internal structure is only a list """ def __init__(self, sortkey=None): self.sort_ = lambda x: sortkey(x) if sortkey is not None else x self....
553d803455b31f609bdcb98f739f4826b5b48b5b
andreghislandi/Projeto-ProWay-Treinamento
/main.py
20,105
3.734375
4
from tkinter import * from tkinter import messagebox import sqlite3 root = Tk() root.title("Gerenciador de Treinamento") #criar funcao query def query(): #criar database conn = sqlite3.connect("dados_treinamento.db") #criar cursor da database c = conn.cursor() #fazer a query c.execute("S...
977481ae8df75902d911823ae4c366080e5f0125
binhle3920/search-project-ai
/SOURCE/data.py
681
3.890625
4
import os """ The function get maze will return a 2D array, maze size (m x n) and pos of pacman (x, y) This is a coordinate and each element hold a value, present it is empty (0), wall (1), monster (3) or food (@) Ex maze: 0 0 1 0 0 0 1 2 0 0 3 0 0 0 0 0 --> maze[2][2] will be 3 """ def string_to_numbe...
34e067181f4f6ef2d8f934c61da25e9c104c624f
hysapphire/leetcode-python
/src/103.二叉树的锯齿形层次遍历.py
1,039
3.53125
4
# # @lc app=leetcode.cn id=103 lang=python3 # # [103] 二叉树的锯齿形层次遍历 # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None from collections import deque class Solution: def zigzagLevelOrder(...
1ed7588908647a16c53b3f690aa18a147c854839
hysapphire/leetcode-python
/src/257.二叉树的所有路径.py
858
3.609375
4
# # @lc app=leetcode.cn id=257 lang=python3 # # [257] 二叉树的所有路径 # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def binaryTreePaths(self, root: TreeNode) -> List[str]...
495629e7a5b0b91ada17b55e85d5bd792db18a4b
hysapphire/leetcode-python
/src/234.回文链表.py
991
3.640625
4
# # @lc app=leetcode.cn id=234 lang=python3 # # [234] 回文链表 # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def isPalindrome(self, head: ListNode) -> bool: if not head: retur...
6ccd5be6c988b512123cb3a13564130a0a5cc105
hysapphire/leetcode-python
/src/125.验证回文串.py
889
3.5
4
# # @lc app=leetcode.cn id=125 lang=python3 # # [125] 验证回文串 # # @lc code=start class Solution: def isPalindrome(self, s: str) -> bool: s = "".join(ch.lower() for ch in s if ch.isalnum()) left = 0 right = len(s) - 1 while left < right: if s[left] != s[right]: ...
59a0fbd0ec7c01154fa5d653ebf35ee667159c0c
williambrunos/Python-For-ML
/Class_3/Oficina/main.py
2,205
3.59375
4
import numpy as np import numpy.ma as ma def discover_day_of_week(number): if number > 7: number = number % 7 if number == 1: return 'Domingo' elif number == 2: return "Segunda" elif number == 3: return "Terça" elif number == 4: return "Quarta" elif numb...
1947d4f1bdbcbc54ca8ffbbaaa984b8b91bb837f
BrenoAlv/Projeto-Programa-o-
/q15.py
2,677
4.5
4
#Jogo de Pedra, papel e tesoura: nesse jogo cada jogador faz sua escolha (1 –Tesoura, 2 – Pedra, 3 – Papel), # e vence aquele que escolher um objeto que seja capaz de vencer o outro.Faça que leia a opção de objeto do primeiro jogador # a opção de objeto do segundo jogador e informe qual jogador venceu(ou se houve emp...
de40865ca539e67fd17dad698e001918a790da2e
BrenoAlv/Projeto-Programa-o-
/q7.py
1,191
3.921875
4
peso = float(input('Olá vamos calcular o seu IMC, Por favor, me informe o seu peso atual: ')) alt = float(input('Agora me informe sua altura atual: ')) calc_imc = peso / (alt**2) if calc_imc <= 18.5: print('Seu peso atual é de {}Kg, Sua altura atual é de {}m, Seu IMC é de {:.2f}, Você está bem abaixo do peso id...
cd31a589b79c5825cb92341682ae4434b567d30e
SeanEmac/customer-churn
/src/churn.py
9,734
3.671875
4
from sklearn.metrics import roc_curve from sklearn.model_selection import train_test_split import pandas as pd import matplotlib.pyplot as plt import matplotlib.ticker as mtick import tensorflow as tf tf.get_logger().setLevel('ERROR') """ I have done some ML tasks like this in College but only with scikit-learn,...
7fd85d758f91a52b84f3ce75de540fb216f7df11
vanshvmehta/List-Operations
/BubbleSort.py
472
4.03125
4
""" To sort a list using bubble sort """ from random import randint def bubble(): i = 0 while i < 10: for j in range(0, 10 - 1): if l[j] > l[j + 1]: l[j], l[j + 1] = l[j + 1], l[j] i += 1 print('Sorted List: ', l) while True: l = [randin...
9f02659587cf86dfa48843172934910156623e7e
AhmedMorsy95/News-Aggregator
/api.py
317
3.640625
4
from abc import abstractmethod, ABC class api(ABC): # abstract class which any API added must inherit and implement the abstract methods in it. # This way adding a new API can be generic and easy. @abstractmethod def search(self): pass @abstractmethod def list(self): pass
da79cd419b4e71cb127111c3337c6f1459792e56
Hwesta/project-euler
/euler_006_difference_sum_squares_vs_square_sums.py
377
3.5625
4
# Project Euler Problem 6 # Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. # Holly Becker # Done 2008-12-25 def main(max): squaresum=(max*(max+1)/2)**2 sumsquare=0 for i in range(max+1): sumsquare+=i**2 difference = squaresum-sumsquar...
d73cc193848b102bd003c6328665289c6e4c6823
mvered/ME106
/Week3Assignment-VeredM-countdown.py
552
4.375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Week 3 Assignment - Wellstone ME 106 - Part II Created on Sat Aug 11 12:46:54 2018 @author: mvered """ countdownMessage = ' more days until the election!' lastDayMessage = ' more day until the election!' electionDayMessage = 'Today is election day!' daysLeft = inpu...
16c6a35c0c71400c3052610cb33e62b74de3ca22
vishwanathsingh/SA
/Model.py
791
3.78125
4
import sqlite3 database = 'example.db' def connect(): conn = sqlite3.connect(database) return conn def create_table(table, column_tuples): c = connect() columns = _get_sql_string(column_tuples) c.execute("CREATE TABLE " + table + " " + columns) c.close() def save(table, values_dict): conn = connect() colu...
07cadb72fbfa9713608dddd0824eef95d0223ac5
zkn-1020/gy-2006
/guoya/one.py
5,262
3.65625
4
# a = 10 # b = 20 # print(a + b) # # a,b,c = [1,2,3,] # print(a) # print(b) # print(c) # # x,y,*z = (1,2,3,4,5) # print(x) # print(y) # print(z) # # a = 10 # b = 20 # print(a) # print(b) # # print(a+b) # print(a-b) # print(a*b) # print(a/b) # print(a%b) # print(a**b) # print(a//b) # # print(a==b) # print(a!=b) # print(...
5d827eb6c43edf12e8a212bd435b6fff9b40c10e
siddharthabishnu/Rotating_Shallow_Water_Verification_Suite
/src/DGSEM_Rotating_Shallow_Water/LinkedListClass.py
2,594
3.78125
4
""" Name: LinkedListClass.py Author: Sid Bishnu Details: This script contains functions for forming a linked list class with integer data. """ class Record: def __init__(myRecord,listData=0,key=0,PointerToNextRecord=None): myRecord.listData = listData myRecord.key = key myRecord.next ...
f8a686c2dc19c0beb4182370fb0ed8a8c3a79b61
joelveneale/numberguess
/numberguess_oop/Models/Difficulty.py
2,100
3.984375
4
import random class Difficulty: input = '' value = 0 valid = False random_number = random.randint(0, 100) min_max = list(range(0, 100)) count = 10 level = '' def reset_difficulty(self): self.input = '' self.value = 0 self.valid = False def set_difficulty(s...
54cbcc33b4b5d78c5401251e47a1aefce4b3ce31
retropleinad/DnD-Calculator
/calculations/damage.py
3,013
3.734375
4
from collections import deque # The damage dice has 20 sides D20 = 20. # Class to take attacks and saves and calculate average damage class AttackHandler: # Stores attacks and saves in appropriate deques def __init__(self, armor_class=15, turns=10): self.attacks = deque() self.sa...
6f07c8fa8f7bf8f0a945613e48c5a76aadc028b3
nodicora/planarity
/planarity/planarity_functions.py
780
3.671875
4
"""Functional interface to planarity.""" import planarity __all__ = ['is_planar', 'kuratowski_edges', 'ascii', 'write', 'mapping'] def is_planar(graph): """Test planarity of graph.""" return planarity.PGraph(graph).is_planar() def kuratowski_edges(graph): """Return edges of forbidden subgraph of non-plan...
57fa6892c9c72deeecddc089a6e92ba2e8eb12a8
hayley01145553/Web_Scraping_Project
/NationalParkVisitation/NationalParkVisitation/spiders/np_visitation_spider.py
4,356
3.515625
4
from scrapy import Spider from NationalParkVisitation.items import NationalparkvisitationItem # for문 이름 # for문 입장료 # 이름, 입장료를 zip으로 묶어서 튜플로 되고 이거를 List에 넣음 # 만든 최종 리스트를 가지고 item에 넣어서 yield class NPVisitationSpider(Spider): name = "np_visitation_spider" allowed_urls = ['https://www.nps.gov'] start_urls = [...
1467865f5d75cb32fec93a4fb858e8bbc3ef20c4
cuddlywhiskers/HarvardCS50
/PSet7/houses/roster.py
1,196
3.78125
4
from sys import argv, exit from cs50 import SQL import csv # compile codes def main(): check_arg() get_students() # Check arg def check_arg(): # Check for number of arguments if len(argv) != 2: print("Usage: python roster.py name") exit(1) # Check whether name of house.is in cur...
adf51d9291d86d2a5fef668c47c113b558724325
SG-20/PYTHON
/Ex10_loop_random_name.py
261
3.921875
4
import random people=[] for x in range(0,8): person=input("Type the name of a person: ") people.append(person) index=random.randint(0,7) random_person=people[index] print("Picking a random person: ", random_person)
fbbff52ca2c230af867d0ad82c54d1f3f2bd54ef
SG-20/PYTHON
/EX01.km2miles.py
118
4.03125
4
km=float( input("Type the number of kilometers: ") ) miles=km/1.609344 print(km, "km = ", round(miles,4), "miles")
5c7eb9110825e838d5fdfab5fe365e3fc6012fe0
geshem14/my_study
/Coursera_2019/Python/week9/week9task1_1_test.py
2,286
3.859375
4
from sys import stdin from copy import deepcopy # week 9 task 1 # https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/ # albda/klass """ текст задания тут 79 символ=>! Реализуйте класс Matrix. Он должен содержать: Конструктор от списка списков. Гар...
554bf1141d384fee9d97ca42d9e3d24d2a8f12a8
geshem14/my_study
/Coursera_2019/Python/week3/week3task22.py
449
4.03125
4
# week 3 task 22 """ текст задания тут 79 символ=>! Дана строка. Удалите из этой строки все символы @. """ string = input() # строковая переменная для ввода search_string = "@" # искомая строка string = string.replace(search_string, "") # колво вхождений пробела print(...
bdefd91888caad7f05e8899fe88d2b6e6886e71b
geshem14/my_study
/Geekbrains_2019/Python/Intensiv_16102019/new.py
1,373
3.5
4
# https://geekbrains.ru/lessons/51092 import sys import copy a = [15, 574.2, 'hello', True, "world"] print(type(a)) # type # getter # setter? a[0] = 13 print(a) # mutable # immutable print(type(a[0])) print(type(a[1])) print(type(a[2])) print(type(a[3])) print(dir(a)) a.append('cool') print(a) a.remove('cool') p...
104b6b05bd01b2b0cee8fdbfa5f58abfce1cba58
geshem14/my_study
/Coursera_2019/Python/week4/week4task11.py
1,109
4.15625
4
# week 4 task 11 """ текст задания тут 79 символ=>! Дано действительное положительное число a и целое неотрицательное число n. Вычислите aⁿ, не используя циклы и стандартную функцию pow, но используя рекуррентное соотношение aⁿ=a⋅aⁿ⁻¹. Решение оформите в виде функции powe...
ff2c2f984035f5f3d4994da9e2c2654bab625a32
geshem14/my_study
/Coursera_2019/Python/week3/week3task15.py
1,259
4.125
4
# week 3 task 15 """ текст задания Дана строка. Если в этой строке буква f встречается только один раз, выведите её индекс. Если она встречается два и более раз, выведите индекс её первого и последнего появления. Если буква f в данной строке не встречается, ничего не выводите. При решении этой задачи нельзя использоват...
fb8107dc38efd43cb3a07145a6b3fc9d95811c16
geshem14/my_study
/Coursera_2019/Python/week3/week3task10.py
3,478
3.859375
4
# week 3 task 10 """ текст задания Даны действительные коэффициенты a, b, c, при этом a != 0. Решите квадратное уравнение ax²+bx+c=0 и выведите все его корни. Формат ввода Вводятся три действительных числа. Формат вывода Если уравнение имеет два корня, выведите два корня в порядке возрастания, если один корень — выведи...
57e867be37c2fe851173aca72e9a8e65e1a8d023
geshem14/my_study
/Coursera_2019/Python/week2/week2task1.py
426
4
4
# week 2 task 1 """ текст задания Напишите программу, которая считывает два целых числа A и B и выводит наибольшее значение из них. Числа — целые от 1 до 1000. """ a = int(input()) b = int(input()) max = b # это переменная для максимального значения if a > b: max = a print(max)
06627824be30157b0259b3b28c74eb3d1bfa6013
geshem14/my_study
/Coursera_2019/Python/week9/week9task1_3_test.py
2,573
3.890625
4
from sys import stdin from copy import deepcopy # week 9 task 3 # https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/ # 9Vl6a/oshibki-transponirovaniie class MatrixError(BaseException): def __init__(self, c_matrix1, c_matrix2): self.matrix1 = c_matrix1 self.matrix2 = c_mat...
0bf6ccbcf81fde22edc6fb0ed7af72317050ca53
geshem14/my_study
/Coursera_2019/Python/week3/week3task16.py
832
4.125
4
# week 3 task 16 """ текст задания тут 79 символ=>! Дана строка, в которой буква h встречается минимум два раза.Удалите из этой строки первое и последнее вхождение буквы h, а также все символы, находящиеся между ними. """ string = input() # строковая переменная для ввода...
4803471f9a118dc56d4996bf5c850706e6258d17
geshem14/my_study
/Coursera_2019/Python_Advance/week2/week1learning.py
1,547
4.75
5
# week 2 learning # video 1. Lists and Tuples """ поиск медианы случайного списка. Медиана - это значение в отсортированном списке, которое лежит ровно посередине, таким образом, половина значений - слева от него, и половина значений --- справа """ import random import statistics numbers = [] numbers_size = random.ran...
d85819e6099949bb137714322ce858c417712129
geshem14/my_study
/Coursera_2019/Python/week9/week9task1_2_test.py
1,551
4.09375
4
from sys import stdin from copy import deepcopy # week 9 task 2 # https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/ # cTJex/dobavit-umnozhit class Matrix: def __init__(self, listOfLists): self.matrix = deepcopy(listOfLists) def __str__(self): str1 = '' for ...
8804e14d9bd6e481e8b65b3f7a1e76c31f91e1e0
geshem14/my_study
/Coursera_2019/Python/week5/week5task15.py
765
4.03125
4
# week 5 task 15 """ текст задания тут 79 символ=>! Найдите количество положительных элементов в данном списке. Формат ввода Вводится список чисел. Все числа списка находятся на одной строке. Формат вывода - Выведите ответ на задачу. """ def IsPositiveNum(a): if int...
e63ac64dfe94effb0dd4276462873f6ab4e1df28
artemmarkaryan/ugly_algorithms
/20.02/lift_rides.py
777
3.71875
4
from random import randint import pprint pp = pprint.PrettyPrinter().pprint def main(): max_weight = 10 passengers = [1, 2, 3, 4, 5, 6] # max_weight = randint(10, 20) # passengers = [randint(1, 10) for _ in range(randint(10, 20))] passengers_sorted = sorted(passengers) selected = {} rides...
cee10c74a970ce8a3db71279c41376ea6f2b919f
Kenom/Estudos
/PYTHON/sistemapesquisa.py
4,473
3.84375
4
# Código criado por Wesley Maia # # Voltado totalmente a estudo de Python # import sys import os import pickle import smtplib from datetime import date with open("data.txt", "rb") as file: # open file data.txt , list names "database" register_name = pickle.load(file) "register_name = ['Wesley','Maia','Silva...
588398aafad3c52549e15de2d979c3d175e2bc23
XharlieB/batch9
/main.py
869
3.671875
4
from alumno import Alumno def start(): add() guardarAlumnos = [] def add(): preguntaQueHacer = input('Que deseas hacer? \n (1) Agregar un alumno. \n (2) Ver alumnos. \n (3) Salir \n ') if preguntaQueHacer == '1': def camposNecesarios(): nombreUsuario = input('Ingresa el nombre(s) de tu Alumno: ') nombr...
755e5e4ce68c3f83a86c63f8ffc6cbb509edf8d9
Iansdfg/Leetcode2ndTime
/95. Unique Binary Search Trees II.py
707
3.671875
4
class Solution: def generateTrees(self, n): """ :type n: int :rtype: List[TreeNode] """ if n == 0: return [] return self.findTree(1, n) def findTree(self,left, right): if left > right: return [None] res = [] for i in range(...
58038145023ff2fb47af5e02bb9c5980919894a6
MamadTvl/Bank-Multi-Threading
/src/employee.py
3,018
3.640625
4
import random from queue import Queue import time class Employee(Queue): def __init__(self, unique_id, name, bank): self.id = unique_id self.name = name code = str(random.randrange(1, 231)) self.color = u"\u001b[38;5;" + code + "m " + code.ljust(4) self.bank = bank ...
680f614780e1d9fa07c676f04e711f0f6cc029df
amandamb/GameLabs
/pong.py
5,624
3.765625
4
import pygame, sys # Constants SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 PADDLE_WIDTH = 10 PADDLE_HEIGHT = 100 PADDLE_START_X = 10 PADDLER_START_X = SCREEN_WIDTH - (2 * PADDLE_WIDTH) PADDLE_START_Y = 20 BALL_SPEED = 10 BALL_WIDTH_HEIGHT = 16 PADDLE_SPEED = 20 SOUND_FILE = "button-6.wav" pygame.init() screen = pygame.dis...
8ae56dffc3f2c66e98650408661a29ceeaaa530f
dhawal55/Python_for_Nordies
/ARS_fizzbuzz.py
411
4.0625
4
def fizzBuzz(): ''' prints 'fizz' if valueToCheck is evenly divisible by 3 'buzz' if evenly divisible by 5, 'fizzbuzz' if both. ''' for valueToCheck in xrange(1,100): retVal = '' #start with empty string if valueToCheck % 3 == 0: retVal += 'fizz' if valueToCheck % 5 == 0: retVal += 'buzz' if retVa...
b96e6428eab9765403e15ae493c199eec0c010e4
sravanth-janga/DSA.PY
/datastructures/stack.py
1,007
3.578125
4
import sys,os sys.path.append(os.path.join('.')) sys.path.append(os.path.join('..')) from datastructures.linkedlist import LinkedList from datastructures.Node import Node class Stack(LinkedList): """ Typical stack datastructure """ def __init__(self): super().__init__('Empty Stack!') ...
1148386c08ee7b7c9b97aaaa60f2ce775a168eae
N3PDF/madflow
/python_package/madflow/custom_op/transpiler.py
32,089
3.5
4
"""Line by line translation of python syntax into C++ syntax""" import re import madflow.custom_op.aux_functions as op_af import madflow.custom_op.global_constants as op_gc import madflow.custom_op.classes as op_cl # Parse line def parse_line(line, args, scope_variables, scope, inside_comment): """Translate a ...
a68daca09ef7f78200be546c748c67891673a88d
mattjacobs23/deep-NN-from-scratch
/deepNN/loss.py
1,674
3.953125
4
""" A loss function measures how good our predictions are We can use this to adjust the parameters of our network Do MSE here, but if doing a lot of multi-class classification might want to do cross-entropy, add in regularization terms (would have to change the API for that) """ import numpy as np from deepNN.tensor ...