blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
6c51fb0b5208b05b9152116bff53ffe0944c10d1
hackerAlice/coding-interviews
/程序员面试金典/ 04.03. 特定深度节点链表/特定深度节点链表.py
1,101
4.03125
4
#!/usr/bin/python3 from typing import List # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next =...
bab65fbc526f48956193543b1f392d3f3f80d6d9
hackerAlice/coding-interviews
/力扣/0x98 验证二叉搜索树/验证二叉树1.py
744
3.734375
4
#!/usr/bin/python3 """ 根据二叉树的中序遍历是一个严格递增序列来进行判断 """ # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def isValidBST(self, root: TreeNode) -> bool: result =...
d60ceb85c330376e8ea7c55229ab93d609ea3c9f
hackerAlice/coding-interviews
/程序员面试金典/01.07. 旋转矩阵/旋转矩阵.py
447
3.75
4
#!/usr/bin/python3 from typing import List class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ if not matrix: return n = len(matrix) temp = [[0] * n for _ in range(n)] ...
c91c88f2fa12de7287d6efef6ebc36a92c27691e
tengthan/python_game
/config_reader.py
3,829
3.546875
4
from os import path from defs import * from map import Map class ConfigReader: def __init__(self,filepath): if not filepath: print("Usage: python3 little_battle.py <filepath>") return if not path.isfile(filepath): raise FileNotFoundError(f"Could not find file located at {f...
4c0a4e9063e90b4065f41a898a61b94017dbf83b
KenyonPrater/Pareidolic-Avatar
/Pareidolic-Avatar/turtledrawer.py
2,837
3.625
4
from drawinghandler import * from random import randint, uniform class Turtle: def __init__(self, x=0, y=0, dx=0, dy=0, r=256,g=256,b=256,radius=3): self._x = x self._y = y self._dx = dx self._dy = dy self._r = r self._g = g self._b = b self._radius =...
82a621f0d957be3fbf89f888b6777f860dbffcfc
Jackyzzk/Cracking-the-Coding-Interview-6
/py-程序员面试金典-面试题 10.10. 数字流的秩.py
1,445
3.578125
4
class StreamRank(object): """ 假设你正在读取一串整数。每隔一段时间,你希望能找出数字 x 的秩(小于或等于 x 的值的个数)。 请实现数据结构和算法来支持这些操作,也就是说: 实现 track(int x) 方法,每读入一个数字都会调用该方法; 实现 getRankOfNumber(int x) 方法,返回小于或等于 x 的值的个数。 输入: ["StreamRank", "getRankOfNumber", "track", "getRankOfNumber"] [[], [1], [0], [0]] 输出: [null,0,null,1] 提示:x <= 50000 track 和 getR...
806acc9838320683df7a5cb4a8dc2733ffbbc739
Jackyzzk/Cracking-the-Coding-Interview-6
/py-程序员面试金典-面试题 17.10. 主要元素-摩尔投票.py
1,158
3.6875
4
class Solution(object): """ 数组中占比超过一半的元素称之为主要元素。给定一个整数数组,找到它的主要元素。若没有,返回-1。 输入:[1,2,5,9,5,9,5,5,5] 输出:5 输入:[3,2] 输出:-1 输入:[2,2,1,1,1,2,2] 输出:2 你有办法在时间复杂度为 O(N),空间复杂度为 O(1) 内完成吗? 链接:https://leetcode-cn.com/problems/find-majority-element-lcci """ def majorityElement(self, nums): """ :type nums...
00fb7f299b6864838689415fe93a1d2c46c31074
Jackyzzk/Cracking-the-Coding-Interview-6
/py-程序员面试金典-面试题 17.01. 不用加号的加法.py
763
3.9375
4
class Solution(object): """ 设计一个函数把两个数字相加。不得使用 + 或者其他算术运算符。 输入: a = 1, b = 1 输出: 2 a, b 均可能是负数或 0 结果不会溢出 32 位整数 链接:https://leetcode-cn.com/problems/add-without-plus-lcci """ def add(self, a, b): """ :type a: int :type b: int :rtype: int """ a &= 0xffffffff ...
98fb7c3426510e2057d016aaa664d74223720aac
Jackyzzk/Cracking-the-Coding-Interview-6
/py-程序员面试金典-面试题 02.07. 链表相交.py
3,325
3.796875
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): """ 给定两个(单向)链表,判定它们是否相交并返回交点。请注意相交的定义基于节点的引用, 而不是基于节点的值。换句话说,如果一个链表的第k个节点与另一个链表的第j个节点是同一节点 (引用完全相同),则这两个链表相交。 输入:intersectVal = 8, listA = [4,1,8,4,5], lis...
b2537d794e89a8155da56b69bffd33d667e7de58
ES2Spring2019-ComputinginEngineering/project-one-emma-and-hector
/pendulum project/plotting.py
1,864
3.53125
4
# -*- coding: utf-8 -*- """ Created on Mon Mar 4 16:03:55 2019 plotting!! (to import) @author: Emma Whalen """ import matplotlib.pyplot as plt import numpy as np # function creation: # plotting functions def sim_plot(time, Angle, Velocity, Acceleration): plt.figure(figsize=(4,6)) plt.subplot(...
1e362546fa29f6fa186e4fa43bcc2ac89ec30281
hannyle/Guess_the_number_game
/Guess_the_number_player_pov.py
1,631
3.921875
4
import random, math from math import log, ceil def player_game(): play = 'yes' while play=='yes': print ("Please enter 2 values for range: \n") first_num, second_num=map(int,input().split(',')) if second_num<first_num: print('First number should be less than second numbe...
a2901d88b688ddcf2c72f9433342667fdad41c1e
senordeuce/football-squares
/football-squares.py
2,534
3.6875
4
import random import sys from typing import Iterable, List, Tuple, Union import click from terminaltables import AsciiTable SCORE_VALUES = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] class PlayersAndCountsParamType(click.ParamType): name = "<text,number>" def convert(self, value, param, ctx): try: ...
21bc6ad4d853a9ff74dae17a590a279f2f09a02d
rnjane/pula-yield-index-api
/FlaggedItemsApp/utils.py
552
3.5
4
import numpy as np def find_outliers(values): first_quartile = np.percentile(values, 25, interpolation = 'midpoint') third_quartile = np.percentile(values, 75, interpolation = 'midpoint') inter_quartile_range = third_quartile - first_quartile lower_limit = first_quartile - (1.5 * inter_quartile_ra...
d2af3fdc6bdfa5eba15bbb6bad32280cce1eea2b
VincentBeltman/aoc2020
/day10/main.py
1,692
3.5
4
from Graph import Graph, Vertex def part_1(raw): sortedNumbers = [0] sortedNumbers.extend(sorted(raw)) sortedNumbers.append(sortedNumbers[-1] + 3) nrOfOnes = 0 nrOfThrees = 0 for i in range(0, len(sortedNumbers) - 1): difference = sortedNumbers[i + 1] - sortedNumbers[i] if diff...
cf90be73cbbca43e4ee32f6561d8b9058d372787
fentonmartin/sample-python
/v-class 3 Pre-test.py
965
3.921875
4
x=3 if x == 0: print x-3 elif x == 1 or x == 2: print x else: print x-3*2 ''' x = (1,2,3) print len(x) for y in x: print y, def adder(x, y): return x + y add23 = adder.__get__(23) add42 = adder.__get__(42) print add23(100) class oop: x1='universitas' __x2='gunadarma' x=oop() x.x1 x...
723299fbc43bc9f996ce209e8cf12ae5499af754
amyfang3/Friends
/Friends.py
7,888
4.34375
4
# File: Friends.py # Description: Use linked lists to implement the "friend" functionality of a # Facebook-like application # Student's Name: Amy Fang # Student's UT EID: af27947 # Course Name: CS 313E # Unique Number: 86940 # # Date Created: 07/11/17 # Date Last Modified: 07/16/17 ######## # U...
2a0de4b3c57718b1e8f3e23c7b4fb2fcc8f3f852
ejhb/audit
/2020/01-january/26-class/jeu_carte.py
3,945
3.6875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jan 28 10:11:49 2020 @author: utilisateur """ from random import randrange # On définit la classe Carte qui associe une valeur et une couleur à chaque carte # on définit ainsi l'affichage en forme de tuple (valeur, couleur) class Carte: def __init...
825d1775ba9e01f1d599a2006134134bc3235f8f
ejhb/audit
/2020/02-february/25-pandas/2020-02-25_analyse.py
6,197
3.984375
4
import pandas as pd # Lire le fichier « thanksgiving.csv » avec la librairie pandas et l’assigne à une variable data. # Spécifier dans les paramètre de la fonction permettant de lire le fichier # « encoding=‘latin-1’ » car ce dataset n’est pas encodé normalement. # Utiliser le noms des colonnes contenu dans la 1 ère...
1d31191b8f7a94b60a4d789ce05d3af9ba684114
clementlrms/gradientdescentsimple
/Simple Gradient Descent for xy.py
2,168
3.828125
4
# coding: utf-8 # In[39]: # Defining the f(x1,x2) = x1*x2 function def x1x2Product (X1,X2): return X1*X2 # In[40]: # Testing xyProduct x1x2Product(2,4) # the goal of the following strategies is to improve x1x2 product result by slighlty moving x1 and x2 # In[49]: # Random Local Search - using random nu...
070f0d740c3203c6c8cc2c1ce06020c9516baa47
imvladikon/python-exercises
/itc/solution1.py
724
3.8125
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'getIdealNums' function below. # # The function is expected to return a LONG_INTEGER. # The function accepts following parameters: # 1. LONG_INTEGER low # 2. LONG_INTEGER high # def getIdealNums(low, high): numbers = [] ...
e2eae5a01f049983d04bfd0490e06ca12e345ae0
nishanthgampa/PythonPractice
/Unsorted/guessTheNumber.py
398
3.96875
4
import random number = random.randint(1,20) print("I'm thinking of a number between 1 to 20") for guessTaken in range(1,7): print("Take a Guess") x = int(input()) if x < number: print("You guessed too low") elif x > number: print("You guessed too high") else: break if x == number: print("You guessed it ...
5c31f532ecadf4de74fe5d31f3dd86f8b7201b19
LoftyCloud/py_games
/function_image/func_img01.py
2,079
3.625
4
import tkinter as tk Width, Height = (400, 400) canvas_size = (int(Width * .75), int(Height * .5)) canvas_color = "gray" button_color = "gray" button_count = 3 button_list = [] button_text = ["-", "+", "OK"] button_size = (5, 1) place_list = [ # 画布,标签,输入框,按钮-,按钮+,按钮ok ((Width - canvas_size[0]) / 2, 1...
f047bdc0f653d8ad7ac46d80678c1e5185f3dd2a
sreelakshmi915/python-projects
/turtle graphics/main.py
259
3.65625
4
import turtle colors = ['orange','red','blue','yellow','green'] screen = turtle.Screen() trl = turtle.Turtle() trl.speed(-1) screen.bgcolor('black') for x in range(360): trl.pencolor(colors[x % 5]) trl.width(x/5+1) trl.backward(x) trl.left(25)
79975b6568ada091d6f1ca598f4dd5f9acbb5a5f
DominikaJastrzebska/PyLadies-projects
/Family_BMI.py
1,892
3.859375
4
#Oblicz BMI wszystkich członków rodziny #Stwórz program, który spyta o imię, wagę oraz wzrost każdego z #członków rodziny i wypisze ich BMI. from pprint import pprint as pp family = [] enabled = True while enabled: family_member = {} family_member['name'] = input('Enter your name: ') family_m...
c13cc7a3e5bf961c9c9eb5a097a2248f7e90e4bd
DominikaJastrzebska/PyLadies-projects
/Function_string_list_Voldemort.py
374
3.71875
4
def get_sentence(): sentence = input('Enter freely long sentence: ') sentence_list = sentence.split() return sentence_list def sentence_title(sentence_list): for word in sentence_list: if word.lower() == 'voldemort': print('Sam wiesz kto') else: print(w...
8631ee8907ff7d29fd7b72fe7495d4f735aa6b13
Sajzad/Loan-voice-bot
/prac.py
822
3.703125
4
import pandas as pd columns = ["a", "b"] data =[ { "a":"2", "b":"2" }, { "a":"5", "b":"6" }, ] output_file = "test.csv" def results(data, columns, output_file): if data: print("results are storing ......") try: master_df = pd.read_csv(output_file) except: ...
927aee57f8ab18cd6cfcb6088077a286b6f38a19
renaldyresa/Kattis
/securedoors.py
415
3.625
4
byk = int(input()) data =[] for i in range (byk): kt = input() a,b= kt.split(" ") if a == "entry" : if b not in data : data.append(b) print (b,"entered") else : print (b,"entered (ANOMALY)") elif a == "exit" : if b in data : data.re...
0a5245ce820694ffb0c1fdc92e4693055747b695
renaldyresa/Kattis
/stararrangements.py
187
3.8125
4
ak = int(input()) print(str(ak)+":") for i in range (2,ak): if (ak%(2*i-1)==0)or(ak%(2*i-1)==i): print(str(i)+","+str(i-1)) if (ak%i==0): print(str(i)+","+str(i))
cc9bbe7d7bdb4b3c528b29fc6e80c5412dd0c6d7
renaldyresa/Kattis
/anthonyanddiablo.py
149
3.578125
4
import math a,n = map(float,input().split()) r = n/(math.pi*2) ar = math.pi* r**2 print("Diablo is happy!" if a <= ar else "Need more materials!")
f8cf5c7cc64e94dd9951329795792320ebecbeb8
a1723/python-project-lvl1
/src/base.py
1,078
3.890625
4
import sqlite3 def inserting_into_db(player_name, game_name, true_answers): try: #db connection conn = sqlite3.connect("sqlite_python.db") #object for work with base cursor = conn.cursor() #creating table creating_table_query = ( """CREATE TABLE IF NOT EXISTS...
a510a2d4e00f9520cc477d3a51f7aa062e94ddff
AnDa-creator/Python-games-and-projects
/Exception Handling/Challenge.py
711
4.03125
4
import sys def division(first_num, second_num): return first_num/second_num while True: initial = str(input("Something?? ")) if initial.upper() == "Q": break first_num = input("Enter 1st number: ") second_num = input("ENter 2nd number: ") try: print("The division of {} by {} ...
1d40855cc391f5e119a80d3a6fe9198bf2da2ed0
AnDa-creator/Python-games-and-projects
/IntroToLists/lists.py
532
4.03125
4
# ipAddress = input("Please enter an ip address") # print(ipAddress.count(".")) parrot_list = ["non pinin" , 'no more', 'a stiff', 'bereft of life'] parrot_list.append("A Norwegian Blue") for state in parrot_list: print("This parrot is " + state) even = [2, 4, 6, 8] odd = [1, 3, 5, 7, 9] numbers = even + odd nu...
a68741691a2bb60299ed7924ca616da0a2fdcefd
AnDa-creator/Python-games-and-projects
/Hello world/repfields.py
141
3.75
4
age=24 loss=90 print("My age is {0},{1} years".format(age,loss)) print("""Jan: {2}, Feb: {0}, Mar:{2}""".format(28,30,31)) print() print()
dd175cdf959e2e7b6a6d4201f677ae5d995ac20a
stachenov/PyLeetCode
/problems/wildcard_matching.py
629
3.5
4
class Solution(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ if len(s) < sum(1 for c in p if c != '*'): return False match = [True] for c in p: match.append(match[-1] and c == '*') for ...
b7732b826046e8867bf1c46e69efe4a1473a3505
stachenov/PyLeetCode
/problems/classes.py
1,991
4.03125
4
class ListNode(object): def __init__(self, x): if type(x) is list: self.val = x[0] node = self for n in x[1:]: node.next = ListNode(n) node = node.next node.next = None else: self.val = x self.nex...
26d20493015452cf1e79557360a79ec2f60a1cd1
Balaji-V19/Python
/listfun.py
426
3.796875
4
st=str(input("Enter the list ")) li=list(st.split(",")) print("1.find the count \n 2.append to the particular index") ch=int(input("Enter the option")) if ch==1: n2=str(input("Enter the number to count")) ct=li.count(n2) print("Count of the list %d"%ct) else: n3=int(input("Enter the number to a...
8b8acaf62d695fd1a720e3b1533954caec2ff7bd
Balaji-V19/Python
/Stack.py
515
4
4
class Stack: def __init__(self): self.Stack=[] def Push(self,data): if data not in self.Stack: self.Stack.append(data) return True else: return False def Pop(self): if len(self.Stack)<=0: return ("No element") ...
cafb7bf8c811ed49e976ede497e1cec94b5572e3
Balaji-V19/Python
/dictionarysum.py
228
3.703125
4
"""n={"name":345,"no":123,"add":3456} j=0 for i in n.values(): #print(i) j += int(i) print(j) """ n={"name":"balaji","no":345,"address":"dfg"} j="" for i in n.values(): j += str(i) print(j)
9d0bf9930412084a3d60610af4ad9857190a02ed
Balaji-V19/Python
/vowel.py
354
4.21875
4
st=input("Enter the string") ls=['a','A','e','E','i','I','o','O','u','U'] if st in ls: print("Vowel") else: print("Not Vowel") #Other method :) #if st=='a' or st=='A' or st=='e' or st=='E' or st=='i' or st=='I' or st=='o' or st=='O' or st=='u' or st=='U': # print("Its a vowel") #else...
b9512257c8d552058f859ee24bbfe103018c6602
Balaji-V19/Python
/reverse_list.py
95
3.53125
4
n=list(map(int,input("Enter the list").split(","))) n1=list(set(n)) n1.reverse() print(n1)
869b3416fce34aef78a027c024b75c2037d48eda
LArchCS/Beauty-of-Algorithms
/Other/Q5.py
1,543
3.765625
4
# PS6-Q1 g = {"A":["B", "F", "E"], "B":["C", "F", "G"], "C":["D","G"], "D":["H", "G"], "E":["F"], "F":[], "G":["F", "H"], "H":[]} weights = {"AB": 1, "AE": 4, "AF":8, "BC": 2, "BF": 6, "BG": 6, "CD":1, "CG":2, "DH":4, "DG":1, "EF":5, "GF":1, "GH":1} def dijkstra(g, weights, start): # write your code here ...
0c88bd76cb940f0b4e085fb74085b4761d50d274
KarimnC/Mision_03
/Trapecio.py
639
3.78125
4
#Karimn Daniel Hernández Castorena #Programa que imprima el area y el perimetro de un trapecio. def calcularArea(bmayor, bmenor, alt): area=((bmayor+bmenor)/2) * (alt) print ("Area= %.2f " % area) def calcularPerimetro(bmayor,bmenor,alt): hip= ((((bmenor-bmayor)/2)**2) + (alt**2))**.5 peri= b...
47fd38de4c9be0e343b4776ae6de966f2886def3
pyladies-bcn/python_for_journalists
/meetup_2015_march/01_tutorial_csv_limpiardatos.py
3,215
4.25
4
# -*- coding: utf-8 -*- """ Created on @author: PyLadiesBCN (@PyLadiesBCN) """ """ #1 We check that we have all our files in the directory """ #import os #print os.getcwd() #print os.listdir('.') """ #2 We are going to load the .csv in a dataframe, but first we need to import pandas library """ import pandas as ...
e60abde17f39e8cf438e6be5f5458a61ea8bf1b4
xingbm/python-all-in-one
/elementary-knowledge/string/StringEncodeAndDecodeDemo.py
1,025
3.609375
4
def demo1() : verse = '野渡无人舟自横'; byte = verse.encode('GBK'); print('原字符串:', verse); print('转换后:', byte); # 使用GBK解码 print('使用GBK解码,解码后:', byte.decode('GBK')); byte = verse.encode('UTF-8'); print('转换后:', byte); # 使用UTF-8解码 print('使用UTF-8解码,解码后:', byte.decode('UTF-8')); # utf-8,un...
fa0eadc6073f08ed6891bd69ca911a8b485ee131
GTheja/sentimentanalysis
/twitter_analysis.py
2,562
3.5
4
import string from collections import Counter from nltk.stem import WordNetLemmatizer from nltk.tokenize import word_tokenize #corups is dataset from nltk.corpus import stopwords from nltk.sentiment.vader import SentimentIntensityAnalyzer import matplotlib.pyplot as plt import GetOldTweets3 as got def get_tweets(): ...
4e1c37b945bfa640110433066f4dd9572bd252b6
whitebrandon/spades
/spades_rev/deck.py
962
3.53125
4
from card import Card, Joker class Deck: ranks = [ ("2", 2), ("3", 3), ("4", 4), ("5", 5), ("6", 6), ("7", 7), ("8", 8), ("9", 9), ("10", 10), ("Jack", 11), ("Queen", 12), ("King", 13), ("Ace", 14) ] suits = ["♠ Spades ♠", "♡ Hearts ♡", "♣ C...
27f35b951f651c0416bf004c1cd3447ff233b895
whitebrandon/spades
/card.py
1,219
3.953125
4
class Card: """Card to hold rank, suit and value""" def __init__(self, rank, suit, value): self.rank = rank self.suit = suit self.value = value self.owner = None self.playable = False self.is_trump = True if self.suit == "♠ Spades ♠" else False de...
cfbfaacd53af5c066c40ed40e802aa9891004cda
gagbp/ANN
/Aulas/Git/uma variavel/secante.py
453
3.59375
4
# uma função qualquer def f(x): return x ** 5 - 8 * x - 2 n = 11 x0, x1 = [1, 2] itr = {} itr[0] = x0 itr[1] = x1 a, b = x0, x1 for i in range(n): try: xn = (a * f(b) - b * f(a)) / (f(b) - f(a)) # a - f(a) / ((f(b) - f(a))/ (b - a)) except: raise ValueError(f"Divisão por zero para {a}, {b}...
c6e468b40a074fd7e1775160e9b54a2b79d60866
gagbp/ANN
/Teste2/Q06.py
4,217
3.578125
4
''' Encontre os coeficientes da parabola y=a0+a1x+a2x2 que melhor se aproxima da seguinte lista de 50 pontos [(-2.876, 3.392), (-2.786, 3.636), (-2.766, 3.842), (-2.756, 3.712), (-2.736, 3.708), (-2.726, 3.646), (-2.696, 3.437), (-1.996, 3.474), (-1.466, 3.521), (-1.196, 3.232), (-1.146, 3.352), (-1.066, 3.177), (-0....
6b498906833fdf7294e0c569b77f3c4dd8d7515b
finnbear/squirrel-crawler
/old/main.py
6,662
3.5
4
# +---------+ # | Imports | # +---------+ import sys import lxml from lxml import html from lxml import etree import requests # +-----------+ # | Variables | # +-----------+ # Data file base path and schedule data_file_path = 'data.csv' data_file_schedule = 10 data_file_index = 0 # The first url to process start_ur...
1eebbcfb531bb5c3117f24347b30f81cb1dc389a
SpaceToastCoastToCoast/python-adventure
/config.py
725
3.640625
4
inventory = [] def initgame(): global inventory torches = ["torch", "torch", "torch"] inventory.append(torches) def listinventory(): for item in inventory: print item[0] + " x" + str(len(item)) def useitem(item): found = False for entry in inventory: if item in entry: entry.pop() if l...
b714df7f6ed00fd6c72d005e5e5a52e8550bddec
geipeisong/JingDong
/JD/main.py
611
3.546875
4
# -*- coding:utf-8 -*- #https://list.jd.com/list.html?cat=9987,653,655&page=1&sort=sort_rank_asc&trans=1&JL=6_0_0#J_main #https://list.jd.com/list.html?cat=9987,653,655&page=2&sort=sort_rank_asc&trans=1&JL=6_0_0#J_main #https://list.jd.com/list.html?cat=9987,653,655&page=3&sort=sort_rank_asc&trans=1&JL=6_0_0#J_main fro...
cc2b92eb7768409c245bb7f4ed2d113072d8b92b
Icetalon21/Data-Science
/perceptron.py
1,245
3.515625
4
import sklearn.datasets as skdata from sklearn.linear_model import Perceptron import numpy as np breast_cancer_data = skdata.load_breast_cancer() x = breast_cancer_data.data #feature vector y = breast_cancer_data.target #1's & 0's model = Perceptron(penalty=None, alpha=0.0, tol=1e-3) #trains our perceptron model ...
738d063cd9e5ed931fa6914189dc62c95fe29405
davi-santana/oficial2
/src/book.py
546
3.734375
4
import sqlite3 class Book: def __init__(self): self.connection = sqlite3.connect("database", timeout=1) # self.cursor def book(self, book_id, title, author, publishing_company, publication_year): self.connection.execute("INSERT INTO book VALUES ('{book_id}', '{title}', '{author}', '{p...
d653e28266da07587c328bcb18255832e6ef6658
Rohit-Srivastva/list-in-python
/list in python.py
297
3.765625
4
#list number = [5, 7, 8, 3, 4, 7, 9, 0] number.append(10) print(number) number.reverse() print(number) number.sort() print(number) tp = (1, 3, 5, 6) print(tp) tp = (4) print(tp) tp = (1,) print(tp) #swapping n = 5 m = 9 #temp = n #n = m #m = temp (n ,m) = (m , n) print(n , m)
1a6ac0cd518bf66b02699dc58d3cc9c5acf0d51a
BrauCamacho/Mis_Trabajos_python
/Analisis_Clinicos.py
3,194
3.6875
4
#ver si las persionas tienen diabetes #diabetes glucosa >120 #trigliceridos altos >180 # colesterol alto > 200 def Eliminar(Personas): Buscar = float(input("inserte un INE valido: ")) c = -1 t =0 for i in Personas: if i['INE'] == Buscar: c = t t+=1 if c != -1...
056c767c6b792bf4a4a60daea504a70fd9510215
BrauCamacho/Mis_Trabajos_python
/ejClase.py
781
4.1875
4
#desarrollar un programa en python que permita capturar alumnos (nua, nombre, Calificacion, generar lista de alimnos e imprimir alumno con mayor calificacion) Alumnos = [] iter = 0 while(iter < 1): print("0 .- para capturar alumno") print("1.- para salir") iter = int(input()) if iter == 0: ...
49e9b0eba47468bedaf06c9bbf5e7d8915594c07
BrauCamacho/Mis_Trabajos_python
/practicar.py
1,958
3.765625
4
import os class Persona: def __init__(self): pass class Alumno(Persona): def __init__(self, NUA, Nombre, CURP): self.Nombre = Nombre self.CURP = CURP self.NUA = NUA def __str__(self): return f'NUA: {self.NUA} \nNombre: {self.Nombre},\nCURP: {self.CURP}' ...
a666254d4a8e8ba01dd01f7c79e4e2dff2a29798
RushSh/Python-Learning
/Day13_AbstractClass.py
1,224
4.28125
4
#Task #Given a Book class and a Solution class, write a MyBook class that does the following: #Inherits from Book #Has a parameterized constructor taking these parameters: #string title #string author #int price #Implements the Book class' abstract display() method so it prints these lines: #Title:, a space, and the...
70b0d5fcd7ef8191a2cb3d3556d69c94af4a35e4
RushSh/Python-Learning
/Day7_Arrays.py
400
4.25
4
#Task #Given an array A of N integers, print A's elements in reverse order as a single line of space-separated numbers. #Input Format #The first line contains an integer N, (the size of our array). #The second line contains N space-separated integers describing array A's elements. sizeOfIntArray = int(input()) int...
91a793c72f8a9eb579d4e9865857fd5378b597e7
jisuhan3201/python-algorithm
/data_structures/binary_tree/basic_binary_search.py
1,501
3.890625
4
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def __str__(self): return "Data : {}".format(self.data) def display(tree): if tree is None: return if tree.left is not None: display(tree.left) # print(...
6d6fe17b1ff9cefc5c4c9c2831945ca55c29f0b0
prashanth291989/Python
/Seventh_week_python_assignment/kidprogram.py
1,080
3.9375
4
class Animal: def __init__(self, name): self.name=name if(self.name=="elephant"): self.hints=["I am the largest land-living mammal in the world","I am herbivorous","I am belong to the family Elephantidae"] elif(self.name=="tiger"): self.hints=["I come in black and white or orange and black","I am carnivo...
53b8e1143b0563fa7aca3deb89913187a00d82ca
kaskrex/pythonexercises
/Python Files/20a.py
557
3.625
4
class Person: def __init__(self, name): self.name = name self.quotes = [] def record_quote(self, quote): self.quotes.append(quote) def quote(self): print("%s said: \"%s\"" % (self.name, self.quote)) def all(self): for quote in self.quote...
7927f17b21e9f73b800e4aefb5cf867b7eed1ea7
kaskrex/pythonexercises
/Python Files/maze.py
1,404
3.984375
4
a = input("Choose between 2 doors") if a == str(1): print("Door #1 choosen") elif a == str(2): print("Door #2 choosen") else: print("Wrong door! Choose again!") #if r = 1, restart counter r = 1 while r == 1: a = input("Choose between 2 doors") if a == str(1): ...
4f3e80961a17cc54acc990c832304c1e1c1ae7a6
spikeyball/CB-Challenges
/SimpleAdding.py
226
3.71875
4
def SimpleAdding(num): mynum = 0 for i in range(1, num + 1): mynum += i return mynum # keep this function call here print(SimpleAdding(raw_input()) # could have just done return sum(range(1, num + 1))
db21a0d07f08b7fa4730ffdba794ccbd3eaf8599
ninjasan/P2-TournamentResults
/tournament_my_tests.py
4,273
3.703125
4
#!/usr/bin/env python # # Test cases for tournament.py from tournament import * from random import randint, random from math import log, ceil def clean_tables(): """ Cleans the tables in the database, to start the tests from a clean slate """ # Start from a clean slate deleteMatches()...
01422a173ae2781208fff75ddf0006259902169b
whoji/very-simple-RL
/test/test_game.py
1,502
3.6875
4
import numpy as np import unittest from game import Game class TestGame(unittest.TestCase): """docstring for ClassName""" def setUp(self): self.game = Game() print(self.game.queue_self) print(self.game.queue_enemy) print("Resetting game queue") self.game.queue_self = [0,...
9b0557f1642d3865a41fc86fb951e6d0e3e62603
Brakkar/self-taught-course-registration-system
/src/user_models/form_model.py
984
3.828125
4
class Form: """ Email registration form model. Holds the form data and all operations performed on it. """ def __init__( self, form ): self.form = form def validation_errors( self ): """ Checks if fields from the submitted form are valid.""" error_bag = [] # ...
69b3881fc04f6be541bf97e9aa4c116182d4a45d
banthaherder/machine-learning-coursework
/p1-data-preprocessing/data_preprocessing.py
1,963
3.84375
4
# Data Preprocessing Template # Importing the libraries import numpy as np # A library of mathmetical tools! import matplotlib.pyplot as plt # A library for plotting data! import pandas as pd # A library for importing and managing datasets! # Import a dataset (DON'T FORGET TO SET THE W.D.) dataset = pd.read_csv('Data...
b9bb5ec655e9bc950e557dd0e01305e69b43420b
spicywhale/LearnPythonTheHardWay
/ex7.py
806
3.96875
4
print("Mary had a little lamb.") #prints a line of text and uses the .format command to add more text in print("It's fleece was as {}.".format('snow')) print("And everywhere that mary went.") #prints the period 10 times over print("." * 10) #what'd that do? #it printed the text 10 times #the next twelve lines assign a ...
a4f19689e425d354f4b93e8f05415ade3c18c316
spicywhale/LearnPythonTheHardWay
/ex11.py
452
4.1875
4
print("How old are you?", end = ' ') #sets the value of age to the first input the user puts in age = input() print("How tall are you?", end = ' ') #sets the value of height to the second value that the user put in height = input() print("How much do you weigh?", end = ' ') #sets the value of weight the the third value...
355a113f0dbfcca33f70f5963124adb3a1d0cec0
stshf/Encryption
/classical-cipher/caeser-cipher/dec.py
871
3.859375
4
def Dec(c, n): """ === input === c(string) : cipher text n(itn) : key (1~25) === return === m(string) : plain text """ m = "" for c_ in c: ascii_c_ = ord(c_) if ord('a') <= ascii_c_ <= ord('z'): m += chr((ord(c_) - ord('a') - n) % 26 + ord('a')) ...
c2c6c18869bafd64529d1e164968e84ba33aecaa
stshf/Encryption
/classical-cipher/scytale-cipher/dec.py
520
3.828125
4
def dec(cipher, key): # decryption scytale cipher cipher_list = [c for c in cipher] len_text = len(cipher_list) quotient_key = -(-len_text // key) plain_text = "" for i in range(quotient_key): for j in range(key): plain_text += cipher_list[quotient_key * j + i] return p...
5bfecc0a51a6d49c1d12679d00f5d4453cd29928
foscomerlacci/gse
/popola/popola_utenti/popola_utenti.py
1,455
3.765625
4
import random import string import sys import sqlite3 n_utenti = int(sys.argv[1]) divisione = ["Zuccheri semplici", "Zuccheri composti", "Dolcificanti", "Ricerca&Sviluppo", "Servizi&Logistica", ] ruolo = ['dir', 'seg'] # funzione per generare un'uten...
d2e6600a79851f1224f413c0c8cc9161497d07bf
Tarabyte/pirple-python-assignments
/variables/main.py
1,073
3.890625
4
""" Variables assignment What's your favorite song? Think of all the attributes that you could use to describe that song. """ # Song Title Song = "Yesterday" # Artist Artist = "The Beatles" # Duration DuractionInSeconds = 123 # Minutes and Seconds (DurationMinutes, DuractionSeconds) = divmod(DuractionInSeconds, 60) ...
93455546c7edf317f53a79db83199b1d5e039b34
akhila-madhu/Project1---LMS
/Edyoda project1 - Library Management System/Library Management System/Catalog.py
2,303
3.640625
4
# -*- coding: utf-8 -*- from Book import Book # First Book is file & second is Class class Catalog: different_book_count = 0 books = [] fine = 0 @classmethod # Only available to admin def addBooksList(cls, book): cls.books.append(book) def addFine(days): ...
02bcb9ec6a7a9e19d6a9d7bf5af39f070b1554a2
CarJos/funcionespy
/4.py
681
4.0625
4
'''4. Construir una función que reciba como parámetro un entero y retorne la cantidad de dígitos pares. ''' def cant_digito_par(): entero = int(input("Ingrese un numero entero: ")) cont = 0 ud = 0 if entero < 0: entero *= -1 while entero != 0: ud = entero % 10 if ud % 2 == 0...
49198bcb2d357633e54c6369f7380792327c7518
CarJos/funcionespy
/2.py
561
3.953125
4
'''2. Construir una función que reciba como parámetro un entero y retorne sus dos últimos dígitos. ''' def ultimos_dos_digitos(): entero = int(input("Ingrese un numero entero: ")) if entero < 0: entero *= -1 udd = entero % 100 return udd def main(): try: udd = ultimos_dos_digitos() ...
a43cafb774fa70faa634ca733d5e5babf433181b
rafaelstojoao/pos-unip
/codes/IA/IAUnip/aula2/pertinencias.py
1,099
3.5
4
#regras classes = {'jovem':'acessivel','adulto':'caro','idoso':'muitocaro'} valores = {'acessivel':180,'caro':500,'muitocaro':1200} jovem = [0,15,20,25] def pertinenciaTriangular(x,a,b,c): resultado = max( min((x-a)/(b-a),(c-x)/(c-b)),0 ) return resultado def pertinenciaTrapezoidal(x,a,b,c,d): resulta...
c8c888f76446345fb7ea4e8271fdd4e3f4e42448
svkerr/python_scratch
/integBirthFiles.py
608
3.578125
4
## Reads in birth name files in csv format ## 2011 is the last available year right now ## NOTE(s): ## 1. This script relies on pandas ## 2. Stores pandas dataframe in file called names ## 3. To recover dataframe: names = pd.DataFrame.load('names') import pandas as pd years = range(1880,2012) pieces = [] columns = ['...
0e7adde9c796a23f946c6baf28b2c3663131f2d9
svkerr/python_scratch
/nn_grad.py
1,376
3.796875
4
# Reference: http://karpathy.github.io/neuralnets/-2,3 import numpy as np from numpy import random def forwardMultiplyGate(x,y): return(x * y) x = -2; y = 3 # some input values h = 0.0001 out = forwardMultiplyGate(x,y) # Strategy 2 # Let's compute Numerical Derivatives instead of guessing an x,y pair # Compute th...
cc734e23748d04c3119c2de0943391b5ab5a09c1
msjahid/oop-python
/ListObjectSorting.py
2,988
3.546875
4
class Student: __totalCGPA = 0.0 __totalCredits = 0 def __init__(self, id, name, address): self.__studentId = id self.__studentName = name self.__studentAddress = address def getStudentId(self): return self.__studentId def getStudentName(self): retur...
5eaec2d88747360b369233e71001c39f4723a53c
luzhengcd/Advent-of-Code
/day11/solution.py
2,321
3.765625
4
import string import regex as re import sys import time req1 = {'abc', 'bcd', 'cde', 'def', 'efg', 'fgh', 'pqr', 'qrs', 'rst', 'stu', 'tuv', 'uvw', 'vwx', 'wxy', 'xyz'} req1_pattern = '|'.join(req1) req2_exclude = {'i', 'o', 'l'} valid_letter = [i for i in string.ascii_lowercase if i not in req2_exclude]...
2254575e242619335df44074d78e663f808bdaa0
amandathedev/Python-Fundamentals
/04_conditionals_loops/03_03_for.py
132
4.25
4
''' Using a "for-loop", print out all odd numbers from 1-100. ''' for num in range(1,100): if num % 2 == 1: print(num)
5be4fa18d0a47c05cece78973af1ad941cfbb2b7
amandathedev/Python-Fundamentals
/03_more_datatypes/2_lists/04_09_flatten.py
375
3.875
4
''' Write a script that "flattens" a list. For example: starting_list = [[1, 2, 3, 4], [5, 6], [7, 8, 9]] flattened_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] ''' # https://www.tutorialspoint.com/How-to-join-list-of-lists-in-python starting_list = [[1, 2, 3, 4], [5, 6], [7, 8, 9]] flat_list = [] for i in starting_list: f...
947cd1cf8301a5ff0c2c43b26f5f6fd93b7c5aca
amandathedev/Python-Fundamentals
/03_more_datatypes/1_strings/04_04_most_characters.py
486
4.5
4
''' Write a script that takes three strings from the user and prints the one with the most characters. ''' my_list = [] string_1 = input("Tell me your name: ") my_list.append(string_1) string_2 = input("Tell me your dog's name: ") my_list.append(string_2) string_3 = input("Tell me your street name: ") my_list.append(...
07d9eafc8c62ecb0d8c11b275d7b09d9e5eeb909
amandathedev/Python-Fundamentals
/04_conditionals_loops/03_02_month.py
1,173
4.34375
4
''' Take in a number from the user and print "January", "February", ... "December", or "Other" if the number from the user is 1, 2,... 12, or other respectively. Use a "nested-if" statement. ''' month = input("Please enter a number from 1 to 12: ") month = int(month) if month == 1: print("The first month of the...
ae36161f5f0dea8ac766127aabdf7aedfdf1a3d4
MargoGrinch/Module_Control
/7.py
862
3.640625
4
''' 7. Створіть масив А [1..12] за допомогою генератора випадкових чисел з елементами від -20 до 10 і виведіть його на екран. Замініть всі від’ємні елементи масиву числом 0. Грінченко Маргарита 122 ''' from random import randint import numpy as np while True: A = np.zeros((1,12), dtype = int) i, j...
6d78b1da8f273df2c98295cde84b96717e68c926
MargoGrinch/Module_Control
/5.py
825
3.6875
4
''' 5. Створіть масив А [1..7] за допомогою генератора випадкових чисел і виведіть його на екран. Збільште всі його елементи в 2 рази. Грінченко Маргарита 122 ''' from random import randint import numpy as np while True: A = np.zeros((7,1), dtype = int) i, j, summa = 0, 0, 0 try: for ...
0ba9c552ac286f0afd26e04a58d0c954a1c8a69b
MargoGrinch/Module_Control
/4.py
716
3.71875
4
''' 4. Створіть масив з п'яти прізвищ і виведіть на екран ті з них, які починаються з певної букви, яка вводиться з клавіатури. Грінченко Маргарита 122 ''' import numpy as np while True: A = np.array(['Цеткин', 'Люксембург', 'Санд', 'Стрип', 'Арбатова']) letter = input('letter - ') print(f'{A} ...
e6b5d3d03cd28e2971292697e1aaace035bf918d
MargoGrinch/Module_Control
/55.py
639
3.75
4
''' 55. У будинку, що складається з 30 квартир, переселити мешканців так, щоб мешканці першої квартири переїхали в тридцяту, з тридцятого - в першу, з другої - в 29 і т.д., знайдіть кількість квартир, в яких проживає більше 5 осіб. ''' import numpy as np flats = np.random.randint(0, 10, 30) print(f"Flats: {f...
483ee0e8ae0b3f047c7d7bc6d76a2647fa2d7e4a
MargoGrinch/Module_Control
/31.py
743
3.5
4
''' 31. Обчислити середнє арифметичне значення тих елементів одновимірного масиву, які потрапляють в інтервал від -2 до 10. Грінченко Маргарита 122 ''' import numpy as np while True: i, summa, count = 0, 0, 0 n = int(input('vvedit k-st elementiv v massive = ')) A = np.zeros(n, dtype = int) ...
dc5d0efcb25b1b220215096d644fdc47925f4cc6
MargoGrinch/Module_Control
/51.py
584
3.828125
4
''' 51. Дан одновимірний масив а. Сформувати новий масив, який складається тільки з тих елементів масиву а, які перевищують свій номер на 10. Якщо таких елементів немає, то видати повідомлення. ''' import numpy as np a = np.random.randint(0, 201, 10) a_new = [] for i in range(len(a)): if a[i] > i + 10:...
3df24412026fe5f3fcbbb467a27161cb63b05741
MargoGrinch/Module_Control
/34.py
806
3.84375
4
''' 34. Дано два лінійних масиву однакової розмірності. Скласти третій масив з добутку елементів перших двох масивів, що стоять на місцях з однаковим індексом. Грінченко Маргарита 122 ''' import numpy as np while True: n = int(input('size of matrix = ')) A = np.zeros(n, dtype = int) B = np.zero...
cc5634d5d99931b3e446a6341693abd2db2fc77a
ReticulatedSpline/project_euler
/problem3.py
1,259
4.0625
4
import math """ The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143? """ # classic primality test def is_prime(val): if val < 2: # zero and one are not prime return False if val == 2 or val == 3: # two and three are return True if val % 2 == 0: # rule out ...
8f505d78aaa76bb83e78e2717c367c1af77c61be
aomdahl/N_attenuata_TF_TFBS_pipeline
/Toolkit_scripts/MotifRecognition/errorReporting.py
1,120
3.515625
4
#!/usr/bin/env python #A tool to keep track of unexpected errors import sys errorMap = {} #Store an error for update #@param ToolName is a string #@param Details also a string: tell us about the problem #@param errorType: give us an identifier [RunTime|??] def storeError(toolName, details, errorType): if toolName i...
208ec5d7fc06fd1365578ed6ca4139e2a10f92b5
daineseh/python_code
/file_path/proc_suffixes_file.py
1,611
3.828125
4
#!/usr/bin/env python import os import re import sys SUFFIX_PAT = re.compile(r'_\d\d?$') SUFFIXED_LIST = [] def is_suffixed_file(dir_path, file_name): base_name, ext_name = os.path.splitext(file_name) pos = base_name.rfind('_') if pos == -1: return False match_obj = SUFFIX_PAT.match(base_n...
139fc719a8a0fe6cf23b42f37a8588ae54a0661a
Nandarlynnn/python-exercises
/ex12.py
180
3.90625
4
age=23("How old are you?") height=raw_input("How tall are you?") weight=raw_input("How much do you weight?") print("So , you're %r old,%r tall and %r heavy."%(age, height,weight))
33e66599e407d1b7ca3ec1ee4d5cbb6a7a21fc22
danielzengqx/Python-practise
/CC150 6th/3.4.py
602
4.1875
4
#Using two stack to create a queue #stack -> last in first out #queue -> first in first out #performance improvement -> only reverse the stack when the dequeue happens stack1 = [] stack2 = [] def enqueue(item): global stack1 stack1.append(item) def dequeue(): global stack1, stack2 if len(stack2) == 0: while...
4727047e31e51e95925c96ce2776628a4a68466b
danielzengqx/Python-practise
/CC150 6th/3.2.py
742
3.5625
4
#Stack min list1 = [] class Stack: def __init__(self): global list1 list1 = [0]*10 self.counter = 0 self.min = float("inf") def push(self, item): global list1 #set min if self.min > item: list1[-self.counter-1] = item self.min = item else: list1[-self.counter-1] = self.min #set value li...