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
dd0edfecff7fa3a748aae167c0578d29a886f1cc
h-zhao1997/continuous-rl
/code/memory/sumtree.py
2,250
3.703125
4
"""Implementation of sumtree for finite distribution sampling.""" import numpy as np from typing import Optional, Tuple class SumTree: """Implement a sum tree data structure. A sum tree is a complete tree where the value of each node is the sum of the values of its children. """ def __init__(self,...
223f559ee5d478ed95f261acc3a7e647ed8d13d4
zestyping/stubs
/stubs/matchers.py
4,900
4.46875
4
"""A concise way to express patterns of values to match for tests. This module exports a special object named `_`, which is an instance of a Matcher and can be used to make more Matchers, and the `match` function, which checks a value against a matcher. `_` on its own matches anything: match(3, _) # True You c...
aae55ebdc8ac2746e22e0f8342cffea4ef67446d
TanmoyX/CodeStore-Cracking_The_Coding_Interview
/Chap1/1.7 - RotateMatrix/rc-sol.py
907
3.796875
4
def transpose(arr, R, C): for i in range(R): for j in range(i, C): t = arr[i][j] arr[i][j] = arr[j][i] arr[j][i] = t def reverseColumns(arr, C): for i in range(C): j = 0 k = C - 1 while j < k: t = arr[j][i] arr[j][i] = ...
ac96cf0e2ab8e77a576743b00c938e0d259aa089
TanmoyX/CodeStore-Cracking_The_Coding_Interview
/Chap2/2.1 - RemoveDuplicates/n2-sol.py
936
4.125
4
class Node: def __init__(self, val): self.data = val self.next = None def printLL(node): while node != None: print(node.data) node = node.next def insertNode(node, val): if node == None: return None while node.next != None: node = node.next node.next...
0b83573dccb411dd49fd33b67e93ff83b0a08f73
mani5112/Simple-Elearning-Pages
/hr/login.py
1,567
3.515625
4
# -*- coding: utf-8 -*- """ Created on Mon Dec 7 20:32:03 2020 @author: mani """ import tkinter as tk import mysql.connector from tkinter import * import PIL from tkinter.messagebox import showinfo,showerror def submitact(): user = Username.get() passw = password.get() print(f"...
dcc1cf9a1a3e14da5f1e39d9f11447d0354b39d9
Visorgood/CodeBasics
/Python/MergeSort.py
966
4.1875
4
def mergesort(array): if len(array) == 1: return array else: middle = len(array) / 2 half1 = mergesort(array[:middle]) half2 = mergesort(array[middle:]) mergedarray = merge(half1, half2) return mergedarray def merge(half1, half2): mergedarray = [] lenhal...
7f23279b2536a3a094603265e11303abedec2a73
amit2014/spoj-10
/GCD2.py
224
3.71875
4
#### # For python3 #### def gcd( a , b ): if b == 0: return a else: return gcd ( b , a % b ) t = int(input()) while t != 0: s = input() a , b = ( int(x) for x in s.split() ) c = gcd(a,b) print(c) t = t - 1
eef6803ad685c5fced72ee8353b1371a35d37ab7
dsarratt/sudoku
/test_sudoku.py
7,759
3.5625
4
"""Test cases for sudoku""" import unittest import sudoku TESTGRID = """ 24 8 147 91 73 2 16 75 2 145 8 43 71 8 72 13 183 4 67 """ class CanonicaliseTest(unittest.TestCase): def test_canonicalise(self): grid = [[1, 2, 3, set((4,5)), set((4,5)), set((6,7,8)), set((6,7,...
6caa02f1b5c4d8c9bbdd8bd1ca84fe80c1ae7ea7
GummyWorld/chaos-games-equations
/SierpinskisTriangle.py
2,588
3.734375
4
import pygame import random import tkinter as tk from tkinter import * import os WHITE = (255, 255, 255) BLUE = ( 0, 0, 255) GREEN = ( 0, 255, 0) RED = (255, 0, 0) YELLOW = (255, 255, 231) GREY = (89, 101, 109) TEXTCOLOR = ( 0, 0, 0) (width, height) = (500, 500...
3c7ae1a237ec3de979773165c1c2b9136ce6ddd0
Mariag39/Aprendizaje-Automatico
/Practica0.py
2,445
3.59375
4
import numpy as np from matplotlib import pyplot as plt from scipy import integrate as integrate import random as rnd import time # Integración con vectores def integrate_vector(fun,a,b,num_puntos=10000): # Capturamos el tiempo inicial tic = time.process_time() # Creamos el espacio x = np.li...
7f8be46a01d986de37906424a7c6e7e186ca30c3
Shivani3012/PythonPrograms
/conditional ass/ques33.py
484
4.375
4
#Write a Python program to convert month name to a number of days. print("Enter the list of the month names:") lname=[] for i in range(0,12): b=input() lname.append(b) #print(lname) m=input("Enter the month name:") ind=lname.index(m) #print(ind) if ind==0 or ind==2 or ind==4 or ind==6 or ind==7 or ind==9 or ind...
21d89fe0a3fbf5d59124847acd307845da9205ce
Shivani3012/PythonPrograms
/guessing a number.py
876
4.15625
4
print(" Welcome to the Guessing a Number Game ") print("You have to guess a number if the number matches the random number") print("you win the game else you will only get three chances") name=input("Enter the user name") import random for i in range (1,4): print("Chance",i) r=random.randint(10,50)...
53ca55ed41ad6b133f43f1951a52320980eed50d
Shivani3012/PythonPrograms
/conditional ass/ques6.py
419
4.15625
4
#Write a Python program to count the number of even and odd numbers from a series of numbers. a=int(input("Enter the number of elements in the list")) print("Enter the list") l=[] countev=0 countodd=0 for i in range(a): b=int(input()) l.append(b) for i in range(a): if l[i]%2==0: countev+=1 else:...
c430d14f36c86413bef67fa27a49f5e79ce059d1
Shivani3012/PythonPrograms
/seclar_sma.py
309
3.859375
4
a=int(input("Enter the number of elements in the list")) print("Enter the list") l=[] for i in range(a): b=int(input()) l.append(b) print(l) l.sort() print(l) las=a-1 seclar=las-1 sesma=1 print("Second smallest number in the list is",l[sesma]) print("Second largest number in the list is",l[seclar])
52a686724c000189abcae44a27fc2e0eda9f4b70
Shivani3012/PythonPrograms
/conditional ass/ques35.py
212
4.40625
4
#Write a Python program to check a string represent an integer or not. s=input("Enter the string") a=s.isdigit() #print(a) if a==True: print("This is an integer.") else: print("This is not an integer.")
8ecc89851cf7d8a9c796cd631b4bd3fc037c5b80
rafaellehmkuhl/vec
/vec/__init__.py
21,325
3.59375
4
#!/usr/bin/env python3 # # vec # Copyright 2019-2020 by Larry Hastings # # A collection of classes for vectors and rects # designed to be convenient for use in video games. # # Features: # * Vectors are immutable. # * Vectors support both cartesian and polar coordinates, # and lazily calculate them as needed. #...
9f6e0b487e0d18a3aa77ca4753248148710e3fab
bend-is/pystudy
/basics/lesson_3/task_5.py
1,578
4.0625
4
""" Программа запрашивает у пользователя строку чисел, разделенных пробелом. При нажатии Enter должна выводиться сумма чисел. Пользователь может продолжить ввод чисел, разделенных пробелом и снова нажать Enter. Сумма вновь введенных чисел будет добавляться к уже подсчитанной сумме. Но если вместо числа вводится специал...
bd87a4ee20fdf0e51fad300f66b818f95a5d76dc
bend-is/pystudy
/basics/lesson_5/task_3.py
879
4.21875
4
""" Создать текстовый файл (не программно), построчно записать фамилии сотрудников и величину их окладов. Определить, кто из сотрудников имеет оклад менее 20 тыс., вывести фамилии этих сотрудников. Выполнить подсчет средней величины дохода сотрудников. """ MIN_SALARY = 20000 with open('task_3.txt') as f: total_sa...
86c212bb843d178fc0744f9d0b0db790f8d8ba47
bend-is/pystudy
/basics/lesson_3/task_4.py
1,183
4.21875
4
""" Программа принимает действительное положительное число x и целое отрицательное число y. Необходимо выполнить возведение числа x в степень y. Задание необходимо реализовать в виде функции my_func(x, y). При решении задания необходимо обойтись без встроенной функции возведения числа в степень. """ from typing import ...
d4d969a12d5c53bb762b58523e6c680b0cd4dd47
bend-is/pystudy
/basics/lesson_8/task_2.py
990
3.890625
4
""" Создайте собственный класс-исключение, обрабатывающий ситуацию деления на нуль. Проверьте его работу на данных, вводимых пользователем. При вводе пользователем нуля в качестве делителя программа должна корректно обработать эту ситуацию и не завершиться с ошибкой. """ class MyZeroDivision(Exception): def __ini...
16c02f1a57a85d4e45879e71444e013a6092c395
bend-is/pystudy
/basics/lesson_1/task_5.py
1,388
4.15625
4
""" Запросите у пользователя значения выручки и издержек фирмы. Определите, с каким финансовым результатом работает фирма (прибыль — выручка больше издержек, или убыток — издержки больше выручки). Выведите соответствующее сообщение. Если фирма отработала с прибылью, вычислите рентабельность выручки (соотношение прибыли...
2f52dd30b21783612269acd3c994084f9ca88d5d
kav137/cs373
/Search/dynamicProgramming.py
2,009
3.765625
4
# ---------- # User Instructions: # # Create a function compute_value which returns # a grid of values. The value of a cell is the minimum # number of moves required to get from the cell to the goal. # # If a cell is a wall or it is impossible to reach the goal from a cell, # assign that cell a value of 99. # ---------...
465a8ddfb5d1d6a2855af9dd3dff2363fbf3676a
KingEnoch/Python-Projects
/gibberishGame.py
4,278
4.21875
4
####################################################################################### # Program Description: Program that converts a word input by a user into gibberish and displays the gibberish word. # Author: Thamsanqa Sibanda & Enoch Oppong # Date: 07/10/2019 # Compiler: PyCharm Python 3.x ##################...
b800cc996771714a056e466026e51f1a575e4758
jmais/Database-Assignment-5
/test.py
362
3.546875
4
import sqlite3 con = sqlite3.connect('flowers2019.db') cur = con.cursor() t = ('California flannelbush',) rows = cur.execute("SELECT * from SIGHTINGS Where SIGHTINGS.NAME =? ORDER BY SIGHTINGS.sighted DESC LIMIT 10",t) for row in rows: print('name ' + str(row[0])+ 'person ' + str(row[1]) + 'location ' + str(row[2]...
102507d21bb4f7467b16902047c1155cafa86807
dipanjanmantri/python-projects
/letter_guessing.py
713
3.96875
4
#create a list of fruits #guess a random fruit from the list #draw spaces #take guesses #draw guessed letters and strikes #print out win/lose import random fruit_list=[] while(True): value=input("Yes or no :") if value=='n': break else: fruit=input("enter fruits :") fruit_list.append(fruit) pick_...
81a34f1c18765039365bf4ac937ec1bb21def9c0
atanumaiti16/pythonprogramming
/Q1.py
239
3.828125
4
import re ip=input("enter the sentence") ip2=re.sub("[^\w]", " ", ip).split() print(ip2) ip3=list() print(type(ip3)) for i in ip2: if i not in ip3: ip3.append(i) ip3.sort() print(ip3) #ip_list=[str(n) for n in ip.split()]
3041880f9948f191028112a011e381c506ce9a0b
maasilva/python_exercises
/python_introdution/web_scraping.py
815
3.53125
4
## Scrping the ConsumerReport products list using BeautifulSoup ## importing bs4, requests modules import bs4 import requests ## initializing url url = "https://www.consumerreports.org/cro/a-to-z-index/products/index.htm" ## getting the reponse from the page using get method of requests module page = requests.get(ur...
962e915e6a483ebffda3b6ad797ebb85e8a837ab
maasilva/python_exercises
/Postgresql database/question3.py
1,452
3.5
4
import psycopg2 def get_connection(): connection = psycopg2.connect(user="postgres", password="yourpassword", host="127.0.0.1", port="5432", database="python_db") return conne...
1926084e0309cda976cd685cb51934000c96a437
boulund/adventofcode
/2021/Day_04_Giant_Squid/04.py
2,306
3.59375
4
#!/usr/bin/env python """AdventOfCode Day 4: Giant Squid""" __author__ = "Fredrik Boulund" __date__ = "2021-12-04" from sys import argv, exit from itertools import repeat import argparse import pandas as pd def parse_args(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("problem_...
306e186c7db1219a79cfa10e9afdfe5c3da990c5
4XMili/QRcodder
/QRcodder.py
350
3.5
4
# Import QRCode from pyqrcode import pyqrcode from pyqrcode import QRCode selectURL = input("pleas enter the url: ") # String which represent the QR code s = selectURL # Generate QR code url = pyqrcode.create(s) url.svg("QRcodder.svg", scale = 8) print("Your URL is https://"+selectURL); print("Pleas chec...
6b8cd8deff9dd62c195b9b49b5548ea226899de2
sudnya/misc
/my_daa_examples/heapStuff.py
7,628
3.703125
4
############################################################################### # # \file heapStuff.py # \author Sudnya Padalikar <mailsudnya@gmail.com> # \date Saturday Aug 27, 2016 # \brief heap sort using min and max heap # ############################################################################### impo...
9b2fd564b15cdc072fa2a7993bfb34eb159c3d9a
sudnya/misc
/my_daa_examples/uber-1.py
2,574
3.640625
4
## This is the text editor interface. ## Anything you type or change here will be seen by the other person in real time. # Integer: number of courses (3) (0, 1, 2) # List of tuples: ((0, 1), (1, 2)) # 2 prerequisites: (1 must be taken before 0), (2 muts be taken before 1) # 2-->1-->0 # Boolean: whether it is pos...
398c85c38f5f596001a596eb4ccdd579c4aa50e3
Keda87/kulik
/learn-python/divide_and_conquer.py
1,424
3.9375
4
def max_and_min_bad(lst): """Find minimum and maximum value within list with O(n). :arg: list :return: (min, max) """ minim = lst[0] maxim = lst[0] for i in lst: if i < minim: minim = i if i > maxim: maxim = i return (minim, maxim) def m...
7af8b74cebc424c530f370af17574429bbf45ec8
sh-chae/algorithm_study
/dynamic_fibonacci_recursive.py
224
3.65625
4
# memoization # top down 방식 d = [0] * 100 def fibo(x): if x == 1 or x == 2: return 1 if d[x] != 0: return d[x] d[x] = fibo(x-1) + fibo(x-2) return d[x] print(fibo(99)) print(d[:20])
4112f792af4b4e1cd696891ebaa81dcd6868a4c1
KaanSerin/python_side_projects
/rock_paper_scissors_game.py
2,879
4.28125
4
import random def welcomeMessage(): print("Welcome to my very basic rock, paper, scissors game!") print('You can play as long as you want.') print('Whenever you want to quit, just enter -1 and the game will end immediately.') #Implementing the rules of rock paper scissors with if-else blocks d...
d1a4c915fcf438f2d419a603593a5c4f4b1ae42b
brown4224/weather_data
/weather.py
8,610
3.609375
4
# Sean McGlincy import math import numpy as np import pandas as pd from scipy import spatial from datetime import datetime import sys import warnings if not sys.warnoptions: warnings.simplefilter("ignore") def reformat_data(weather_data): ''' Seperates the Date and Time. Time is added a a new column in the ...
5f47437f138f8d1bc7c0da304d9f8e8a0c5694de
ronnyen/Data-Analysis-Course
/python/naive_bayes_pandas.py
1,937
3.546875
4
import pandas as pd import numpy as np import math df = pd.read_csv("pima-indians-diabetes.data3.csv", header=None) # # f(x) = (1/s(2m)^0.5)*e # # e = e^((x-m)^2/(2s^2)) def calculateProbability(x, mean, stdev): exponent = math.exp(-(math.pow(x-mean, 2)/(2*math.pow(stdev, 2)))) return (1 / (math.sqr...
792a41cb4cb177cc3c4a9aaedab7abb15afdf72d
HorizonRL/Morse-Code-Interpeter
/src/Interpreter.py
763
3.515625
4
import os import MorseFactory actions = { "QUIT": 'Q', "FROM_MORSE": 'E', "TO_MORSE": 'M' } action_str = "\n\nTo quit press: " + actions["QUIT"] + \ ", To translate from english to morse press: " + actions["TO_MORSE"] + \ ", To interpret morse to english press: " + actions["FROM...
28eef0cf86c7051ddee043c3af4e08229118eb27
hnytun/advent-of-code
/december-1/puzzle_1_1.py
642
3.78125
4
""" December 1st. """ def frequencyList(inputFile): inputFile = inputFile frequencyList = list() startingFrequency = 0 while(True): for line in open(inputFile,"r"): if list(line)[0] == "+": number = line.split("+")[1:][0] startingFrequency += int(num...
d43a964b2eddddbfd01ad71ee356b7711f7945fd
s-ajensen/2017-18-Semester
/knockKnock/blackbelt.py
1,857
4.21875
4
# Samuel Jensen, Knock Knock Joke Blackbelt, 9/28/2017 # Checks user input, gets frustrated when user doesn't go with the joke, unnecessary recursion # Get user's name name = input("Hi what's your name?") # Ask user if they want to hear a joke hearJoke = input("Nice to meet you " + name + ", would you like to hear a ...
f0711f4ce91967b5e49e7e9f6068813af7402860
dhirensr/Ctci-problems-python
/leetocde/isIsomorphic.py
317
3.515625
4
def isIsomorphic(s,t): _map = {} for i,j in zip(s,t): if i in _map: if j != _map[i]: return False else: if j not in _map.values(): _map[i] = j else: return False return True print(isIsomorphic('a','a'))
e17ab9cc96faaf76e543e5edfd32f79e78c24ea4
dhirensr/Ctci-problems-python
/leetocde/canJump.py
658
3.8125
4
vals=[] def helper(nums,index): value=False if index >= len(nums): value= True elif nums[index] >= len(nums): value= True elif index== len(nums)-1: value = True else: for i in range(1,nums[index]+1): value = helper(nums,index+i) vals.append(value) ...
80528b10f540dfb5bb2ddcb9293338a0ee2b1b6f
dhirensr/Ctci-problems-python
/arrays/array_inversion.py
250
3.59375
4
def inversion_count(array): count=0 for idx,i in enumerate(array): for j in range(idx,len(array)): if(array[idx] > array[j] and idx < j): count=count+1 return count print(inversion_count([2,4,1,3,5]))
4c033a94f3c6f73bb1e28545c98fa0a37debd5b8
dhirensr/Ctci-problems-python
/leetocde/increasingBST.py
624
3.734375
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None vals= [] def traverse(root): if root: vals.append(root.val) if root.left: traverse(root.left) if root.right: traverse(root.right) def increasingBST(root): """ ...
5185e56d396ec1620b22855e7f04172eafd6382d
dhirensr/Ctci-problems-python
/leetocde/freqalphabets.py
367
3.546875
4
def freqAlphabets(s): output="" i=0 while (i < len(s)): if(len(s)-i > 2 and s[i+2]=='#'): output+=chr(96+int(s[i:i+2])) i+=3 else: output+=chr(96+int(s[i])) i+=1 #print(output) return output print(freqAlphabets('12345678910#11#12...
1b72d87c71a45ad7d6ed17eff557fcfe963b49fb
dhirensr/Ctci-problems-python
/linked_lists/remove_duplicates.py
1,499
3.828125
4
class Node: def __init__(self,data): self.next=None self.val=data def __str__(self): return "Node" + str(self.val) class LinkedList: def __init__(self): self.head=None def traverse(self): data=[] temp=self.head while(temp): data.appen...
053681a62b7dc36d1d13221bbd1d4486969f3bff
dhirensr/Ctci-problems-python
/stacks_queues/paranthesis_checker.py
388
3.875
4
left_brackets=['{','(','['] right_to_left={'}':'{',']': '[',')':'('} def paranthesis_checker(input_str): stack=[] for char in input_str: if char in left_brackets: stack.append(char) elif not stack or stack.pop() != right_to_left[char]: return False if stack: ...
4ab825c144255d10591f9e5b63c8b96629c0cb81
dhirensr/Ctci-problems-python
/leetocde/reverse.py
383
3.59375
4
def reverse(x): """ https://leetcode.com/problems/reverse-integer/ """ if(x >= 0): reverse = "".join(str(x)[::-1]) output = int(reverse) else: reverse = "".join(str(x)[1::][::-1]) output = -1*int(reverse) if(output< -1*2**31 or output > (2**31-1)): return...
5040778574b0546706beaf79cf98bb5d4ba3257e
dhirensr/Ctci-problems-python
/leetocde/findElementsBST.py
974
3.796875
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class FindElements: def __init__(self, root): """ https://leetcode.com/problems/find-elements-in-a-contaminated-binary-tree/ """ if root.val == None: retur...
c6e8f77a621141961a56c0f830c9a3db661449ae
dhirensr/Ctci-problems-python
/codeforces/dominant_piranha.py
470
3.8125
4
def dominant_piranha(piranhas): index = -1 max_element = max(piranhas) for i in range(len(piranhas)): if piranhas[i]==max_element: if (i>0 and piranhas[i-1]< max_element) or (i<len(piranhas)-1 and piranhas[i+1]<max_element): index = i+1 break return in...
eda3e5a05d052744153e65c16f271ac69b22f6a2
dhirensr/Ctci-problems-python
/leetocde/lcs.py
656
3.53125
4
def longestCommonSubsequence(text1,text2): val_matrix= [[0]* len(text2) for j in range(len(text1))] for i in range(len(text1)): if text2[0] in text1[:i+1]: val_matrix[i][0] =1 for i in range(len(text2)): if text1[0] in text2[:i+1]: val_matrix[0][i] =1 for i in r...
43f660547090af9ccf72568f7f8f7c92764cf66d
B2BDA/Machine-Learning-Projects-1
/Human Activity Detection with Machine Learning.py
23,113
3.578125
4
import pandas as pd import matplotlib.pyplot as plt import seaborn as sb import numpy as np train=pd.read_csv("train.csv") test=pd.read_csv("test.csv") from sklearn.utils import shuffle #to remove the sequence complete randomness test=shuffle(test) train=shuffle(train) #sample=train.head() #to observe t...
aa3028d077084ebf949703609ab97bfe3e9ae009
matiaschaud/Web-Scrapping
/Carrefour/En mejora/import sqlite3.py
1,237
3.703125
4
import sqlite3 from sqlite3 import Error def sql_connection(): try: con = sqlite3.connect("ws.db") #con = sqlite3.connect(':memory:') return con except Error: print(Error) def sql_table(con): cursorObj = con.cursor() cursorObj.execute(""" CREATE TABL...
a687cd697817450e0763666619d140e9422fa0cd
CSCATT/OOPy200_FINALEXM
/directory200/dataVersion769.py
6,809
3.96875
4
# Лабораторная работа № 1.2 # Слушатель (ФИО): TILLOEV TILLO ABDULLOEVICH class Date: DAY_OF_MONTH = ((31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31), # usual year (31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)) # intercalary year def __init__ (self, *args): """ Example: d1 = Date(2010, 11, 15) # ...
9e024031172a25af706fe203a223da46ef5a59cd
raj13aug/python_experiment
/string.py
228
3.84375
4
# Strings (the str type) "couples".find('es') ''' This for three quotestion ''' print ("Hai") print ('raj') print ("Nat" + "araj") print ('raj' * 4) LOWER = 'RAJ' print (LOWER.lower()) print ("Hai\\") print ("He\nello")
c5226adae6184e9123045337cbca10e9d476e5fd
noeljungin/noeljungin_work
/python/test/test2.py
482
3.546875
4
#python 동일한 값 필터링 하기 import collections #collections.Counter() #컨테이너에 동일한 값이 몇개나 들어있는지 확인이 가능하다 a = [1, 1, 2, 3, 4, 5, 6, 7, 7] b = [1, 2, 3, 4, 5, 6, 7] #a 에서 b에 들어있는 중복값을 한번씩만 제거해주어야 한다 c = collections.Counter(a) - collections.Counter(b) print(c) #Counter({1: 1, 7: 1}) #dict 형태로 출력되기 때문에 필요한 키값만 출력해준다 print(c.k...
e1c03ac65f66a81d252f1cefe05e896d6be85394
lionsarmor/Python-Programs
/Web scrappers/good.py
1,954
3.84375
4
### This is an example of how to have very clean code. ### That not only works well, but is efficient. ### Each function has 1 and only 1 job, and it does it well. ## Here are the libraries we will be using import requests import json ## The job of the main function is to give direction, or instructions ## To manage ...
036bb4b0829ecb67613eb303f7b37105a0bb3b58
markm541374/blender
/src/utils.py
965
3.5
4
from typing import Tuple, Union, List import numpy as np class Float3D(): def __init__(self, value): self._value=np.array(value) if not self._value.shape == (3,): raise ValueError("must be 3vector") @property def x(self): return self._value[0] @property def y(s...
4328c4132e5cd6c3b3bc4da09496cb4a797f137b
daltdoerfer/Python_Templates-1
/01_Tutorials/Udemy Kurs Machine Learning/35_KLASSIFIKATION_KNN_Implementation_NEU.py
3,998
3.578125
4
''' ### K-Nearest Neighbor Algorithmus: #### Parameter: dataset = (X, Y) mit X := Features und Y := Classes K := Hyperparameter für die nächsten k Nachbarn sample := Neuer Datenpunkt zum Klassifizieren #### Pseudo-Code: kNN (dataset, K, sample): - Bestimme von jedem Punkt $p \in dataset$ die Distanz, mit der geg. ...
31f40f164cacbc5cc4842fdcf3bde1bb90a3542f
daltdoerfer/Python_Templates-1
/00_Templates/01_Basics/08_Listen_Comprehension_Vetors_2_Matrix.py
516
3.5
4
# Hier wird beschrieben wie man Vektoren entweder Zeilenweise oder Spaltenweise hinzufügt # https://stackoverflow.com/questions/20978757/how-to-append-a-vector-to-a-matrix-in-python import numpy as np # Hinzufügen eines Vektors in X Richtung -> x0 Richtung aka Spalten m = np.zeros((10, 4)) v = np.ones((10, 1)) c = np...
171a9d63a5952504fe32746b1e2681a8f92368e3
daltdoerfer/Python_Templates-1
/01_Tutorials/Udemy Kurs Ehical Hacking/09_Praxis_MITM_mit_HTTP-Proxy/95_Exkurs_Klasse_erstellen_2.py
817
3.765625
4
# Die Folgende Möglichkeit ermöglicht die Klasse noch kompakter zu schreiben als in Kapitel 93 class Hacker: # Konvention -> Klasse wird Groß geschrieben def __init__(self, firstname, lastname): self.firstname = firstname self.lastname = lastname def get_name(self): print(self.firstnam...
66746b81072bd4d48c8c6006fa785f1bfcff29ad
daltdoerfer/Python_Templates-1
/01_Tutorials/Udemy Kurs Machine Learning/118_Eigen_k-means_Clustering.py
4,477
3.625
4
# Unsupervised Learning k-means Clustering # https://www.udemy.com/course/machine-learning-grundlagen-mit-python-inkl-ai-einfuhrung/learn/lecture/11566166#overview # https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html # Wichtigste Parameter: # n_clusters -> wieviele Centroids bzw. Cluster wir ...
f7b353f903f773892c834561b89e06b732cb61ca
x223/cs11-student-work-ibrahim-kamagate
/april11guidedpractice.py
861
4.25
4
# what does this function return ? This prints the x*2 which is 7*2 def print_only(x): y = x * 2 print y # how is this one different ? This does the same thing as the print function but you dont see it def return_only(x): y = x * 2 return y # let's try to use our 2 functions print "running print_only ..."...
c3da7e650f04b7b00b8ef68d1e232142e4faa2a9
x223/cs11-student-work-ibrahim-kamagate
/scope.py
1,054
3.734375
4
# a = [1, 2, 4] # b = a #it had set b equal to a # input: a list of ints # output: an int # def update_list(a_list):#it replaced the thrid index in the list with yo # b = a_list[4] # b = 100 # my_list = [1, 2, 3, 4, 5] # update_list(my_list) # print my_list # var_1 = "kittens" # var_2 = "cookies" # # input: a...
333a4bf4a5771259bf47092dab1b7e4e9358d6e6
gbsnaker/myleetcode
/058-length-of-last-word/length-of-last-word.py
732
3.828125
4
# -*- coding:utf-8 -*- # Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. # # If the last word does not exist, return 0. # # Note: A word is defined as a character sequence consists of non-space characters only. # # Example: # # ...
90e995d7a410da9d546f1c3a2f687c9e12c74995
prasanth-vinnakota/python-gvp
/generator-fibonacci.py
358
4.125
4
def fibonacci(n): a = 0 b = 1 for i in range(n): yield a a, b = b, a + b size = None try: size = int(input("Enter size of fibonacci series: ")) if size == 0: raise ValueError except ValueError: print("input must be a number and greater than 0") exit(0) for j in f...
3586d5cb6f2fe057190a8175e4dbb4891abe7531
ColemanJohnston/Code2040_API_Challenge
/step5.py
888
3.5
4
#Author: Coleman Johnston #Date: 26 October 2016 #Description: Code2040 API challenge step 5. import requests import json import ast import datetime from datetime import timedelta def main(): token = # Put API Token here url = "http://challenge.code2040.org/api/" payload = {'token' : token} r = req...
96ca5e5b3e19d3d6642988c90e158eff436f4f94
Tanvi-Phaltane/DE-Project1
/class_rank.py
1,155
3.625
4
class Rank(object): def __init__(self): #self._freq_dict[num]=0 self._rank_num=-1 #self._rank_dict[num]=-1 #print ("constructor is called") def freq(self,num,freq_dict): freq_dict2={} if num not in freq_dict: freq_dict2[num]=1 else: freq_dict2[num]+=1 return freq_dict2 ...
857390b0a1b08f16b3f54d393ddd9c510ca92491
DaMexicanJustice/frantic_midnight
/Hand-in 3/prog_Human_Development.py
509
3.59375
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt #Which country has the highest HDI and which has the lowest? #country 1, HDI 2. HDIs = pd.read_csv("HDI.csv") dd = HDIs.as_matrix() countries = np.unique(dd[:,1]) HDI = np.unique(dd[:,2]) country = np.array([np.sum(dd[(dd[:,1] == count)][:,2])...
7a7fff0168a8f3669dabb9aace3fb11594b15983
ieee-saocarlos/exercicios-ia
/Raul Cotrim Ferreira/Lista 2/Exercicio 4.py
641
3.8125
4
def comprimento(): if (len(string1) == len(string2)): print 'As strings tem o mesmo tamanho' else: print 'As strings nao tem o mesmo tamanho' def conteudo(): if (string1 == string2): print 'As strings sao iguais em conteudo' else: print 'As strings sao diferentes em cont...
2c88bda5fe158b01b3b3e9d50d9b5ccd56023441
ieee-saocarlos/exercicios-ia
/Vitorstraggiotti/Lista 3/ex_4_lista3_vitor.py
807
3.78125
4
print 'JOGADOR 1\n\n Escolha o numero referente a jogada:\n\n [1]- PEDRA\n [2]- PAPEL\n [3]- TESOURA' jogada_1 = int(raw_input()) print 'JOGADOR 2\n\n Escolha o numero referente a jogada:\n\n [1]- PEDRA\n [2]- PAPEL\n [3]- TESOURA' jogada_2 = int(raw_input()) if(jogada_1 == jogada_2): print '\n\n EMPATE...
3c86b4be1943399afdee8e86a7e9d160b51ba1d2
ieee-saocarlos/exercicios-ia
/Vitorstraggiotti/Lista 3/ex_1_lista3_vitor.py
298
4.125
4
print "Este programa ira mostrar se uma palavra e um palindromo" palavra = input("digite uma palavra entre aspas: ") palavra_invertida = palavra[::-1] if(palavra_invertida == palavra): print "\n\nA palavra digitada e um palindromo" else: print "\n\nA palavra digitada nao e um palindromo"
4fb6bbe864c3e36063bdec05057a048df3afc7b0
ieee-saocarlos/exercicios-ia
/Vitorstraggiotti/Lista 3/ex_2_lista3_vitor.py
665
3.640625
4
print "Entre com duas listas de numeros e sera feita a intersecao" lista_1 = input("Primeira lista: ") lista_2 = input("Segunda lista: ") lista_intersec = [] comprimento_1 = len(lista_1) comprimento_2 = len(lista_2) for i in range(0, comprimento_1, 1): for j in range(0, comprimento_2, 1): if(lista_1[i...
bf792f86d519eb5187ad57d63bd3867a655bab52
ieee-saocarlos/exercicios-ia
/Raul Cotrim Ferreira/Lista 4/Exercicio 7.py
631
3.828125
4
from random import * set1 = set() set2 = set() set3 = set() for i in range(randint(1,20)): set1.add(randint(1,100)) for i in range(randint(1,20)): set2.add(randint(1,100)) print set1 print set2 set3 = set1 | set2 print set3 set3 = set1 & set2 print set3 set3 = set1 ^ set2 print set3 max = 0 min = 10...
4f088c9d41d906b4cb872db481d8aee41cd1bb84
ieee-saocarlos/exercicios-ia
/Raul Cotrim Ferreira/Lista 3/Exercicio 5.py
269
3.890625
4
tamanho = input("Digite o numero inteiro que determinara o tamanho da tabela a ser criada (Ex. numero = N => N x N):") linha_espaco = '' linha_traco = '' for i in range(tamanho): print (' ---' * tamanho) print ('| ' * (tamanho + 1)) print (' ---' * tamanho)
75c4210141a6628b5a88d6aad212b1a6cd588561
ieee-saocarlos/exercicios-ia
/Seiti/Lista3/ex3.2_Seiti.py
189
3.546875
4
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] comum = [] i=0 for i in range (0,13): if b[i] in a: comum.append(b[i]) print (comum) exit()
286c1c2b0ffa3bdac7c31f90cac23014c7d12e2b
JeremiahDjianto/csc111-finalproject
/ui.py
8,473
3.59375
4
from __future__ import annotations import tkinter as tk from typing import Optional BG_COLOUR = 'gray10' WINDOW_WIDTH = 900 WINDOW_HEIGHT = 600 class Page: """ an abstract class representing a single page in the application""" _frame: tk.Tk _user_interface: UserInterface def __init__(sel...
145ebe3aca1fdbbd62e2c30698a78f83317fa286
manthakrishnavasavi/datascience-assignment
/may21/circle.py
466
3.578125
4
import matplotlib.pyplot as plt circle1 = plt.Circle((0, 0), 0.2, color='r') circle2 = plt.Circle((0.5, 0.5), 0.2, color='blue') circle3 = plt.Circle((1, 1), 0.2, color='g', clip_on=False) fig, ax = plt.subplots() # note we must use plt.subplots, not plt.subplot # (or if you have an existing figure) # fig = p...
d73f8c1e37595064dbd132af21a40490e5898d4c
chenjinhui520/actual-17-homework
/10/zhangyongwei/user/class_animal.py
338
3.578125
4
#!coding: utf8 class Animal(object): def __init__(self,name,age,sex,type='牧羊犬'): self.name = name self.age = age self.sex = sex self.type = type def getName(self): return '名字是:%s' % self.name def getType(self): return '犬种是:%s' % self.type
7e214722ee79550fda93ef09ee9631e481974224
chenjinhui520/actual-17-homework
/02/jibaoman/Palindrome_judgment.py
314
4.0625
4
#!/usr/bin/env python #-*- coding:utf-8 -*- number_input = raw_input('pls input number:') num_list = [] # # print len(number_input) for i in number_input: num_list.append(i) if num_list == num_list[::-1]: print "%s是回文数"%number_input else: print '%s不是回文数'%number_input
4c3dae6a6022df1f5596daeec2cf34a5d1aa9b95
chenjinhui520/actual-17-homework
/02/zhengzhijiang/input_sort.py
790
3.53125
4
#!/usr/bin/env python # -*- coding: UTF-8 -*- # input count = 0 input_list = [] print 'pls input 10 nums!!!\n' while count < 10: input_str = raw_input('pls input ur num:') if True == input_str.isdigit(): input_list.append(input_str) count += 1 else: print 'ur input is not correct,...
c8c2d4092b9b22b62cc497fd921c794146b6310f
chenjinhui520/actual-17-homework
/01/yanggongwang/课外练习/求数组交集.py
1,239
3.640625
4
# -*- coding: utf-8 -*- # 作者:杨公旺 # 日志:2017-11-30 # 功能:求两个数组去重后的交集 arr1 = [1,2,3,4,212,13,14,3,2,12,13,14,3,21,2,2,2,45,22] arr2 = [1,2,3,4,212,12,13,100,14,3,21,200,45,22] # 去重 # 方法2: # 思路:使用count()统计元素的数量,大于1的元素进行弹出 # 实现:需要循环检测,直到所有元素的计数都是1为止。 for i in arr1: while True: if arr1.count(i)>1:...
bb23ba4c196bec020e4fdb117c754c5e48ed76c5
chenjinhui520/actual-17-homework
/01/yanggongwang/课堂练习/6.2.1_判断字典中是否包含指定元素.py
882
3.796875
4
#!/usr/bin/python # -*- coding:utf-8 -*- # 作者:杨公旺 # 日期:2017-11-28 # 功能:判断字典中是否包含指定元素 #设置字典内容 my_dict = {'age': 26, 'name': 'nick', 'title': 'devops'} input_string = raw_input("请输入您要查找的内容:") # 方法1 使用in判断指定元素是否存在于字典中 if input_string in my_dict: print "方法1输出:您查找的内容%s在字典中!"%(input_string) else: print "方法1输出:您查找...
f2049fbd68d615a2912199884b8d6419238dc7e9
chenjinhui520/actual-17-homework
/01/yanggongwang/99.py
564
3.671875
4
#coding=utf-8 # 作者:杨公旺 # 时间:2017-11-27 # 版本:V1.2 # V1.1变更内容:1、输出结果增加空格;2、调整输出结果值i、j的位置顺序。 # V1.2变更内容:1、对输出进行判断,通过增加空格的方式使输出结果对齐。 for i in range(1,10): for j in range(1,i+1): number=i*j if(i==3 and j==3): print " %s * %s = %s "%(j,i,number), elif(i==4 and j==3): print " %s * %s = %s ...
6755622173d3633254c165de1bb7708eed282424
chenjinhui520/actual-17-homework
/02/lihaifeng/quchongpaixu.py
1,590
3.828125
4
first_num = raw_input("please input first number:") second_num = raw_input("please input second number:") third_num = raw_input("please input third number:") fouth_num = raw_input("please input fouth number:") fifth_num = raw_input("please input fifth number:") sixth_num = raw_input("please input sixth number:") sevent...
7afdba3abe62a8821fed263a4511ef945d973269
Conor-Coakley/Project-2021
/Conor's_Project/main.py
8,153
3.9375
4
def choice_one(): races_file = open("Races.txt", "r") num = 0 results_list = [] for line in races_file: num = num + 1 line = line.strip() #to get rid of \n print("Please Choose " + str(num) + "." + " " + line) results_list.append(line) ...
4f9c93397bb808e54cc1670e2d879994b8b49293
zachmolony/programmingChallenges
/vigenereCypher.py
1,705
4.0625
4
import string alpha = string.ascii_uppercase # note: i created this function to generate a tabula recta, but i realised this was not necessary with the main method i used, however i left this in as i like the approach i used to solve this problem def tabulaRecta(): import string alpha = list(string.ascii_uppe...
4f475f852a3639e0f30e4934f54e9a23fa619780
rhinshaw253/class-work
/Exercise_7_2.py
113
3.671875
4
fname = input("Enter your file name: ") fhand = open(fname) for line in fhand: total count print( total/count)
110bce19773c8585daf1339848fecc80ca62c14f
rhinshaw253/class-work
/Exercise_2_5.py
147
3.890625
4
cel_temp = input("Enter a temperature in celsius: ") fahr_temp = 9.0/5.0 * float(cel_temp) + 32 print("Converted to fahrenheit: " + str(fahr_temp))
2ea23456925e8912693a676e37cedaeb931809f4
rhinshaw253/class-work
/Exercise_9_1.py
178
3.703125
4
dict = {} fname = "words.txt" fhand = open(fname) for word in fhand: if word not in dict.keys(): pair = word.rstrip() dict[pair] = pair print(dict)
10ec59054ff3b938918fa32ff788f1f7e23821fb
Isotope77/MIPS
/Lab 11 - Controls - Mouse.py
1,091
3.515625
4
import pygame # Colors BLACK = ( 0, 0, 0) WHITE = (255,255,255) pygame.init() # Set Width and Height of Screen [Width, Height] size = (700, 500) screen = pygame.display.set_mode(size) pygame.display.set_caption("Controls Tests") # ----------------FUNCTIONS------------------ def drawsquare(x_coord,y_coord): ...
e9eea0d01e357b5e936f26e8b114d7657ba56b5f
luiz-ricardo-dev/Python
/aula2.py
796
4.15625
4
#Operadores Aritiméticos a = int(input('Entre com o primeiro valor: ')) b = int(input('Entre com o segundo valor: ')) soma = a + b subtracao = a - b multiplicacao = a * b divisao = a / b resto = a % b resultado =('Soma: {soma} ' '\nSubtração: {subtracao} ' '\nMultiplicação: {multiplicacao} ' '\nDivisã...
566a550a2f2fcc21dad004db48254d7f69c60b53
TechVentureBuilder/plost
/streamlit_app.py
10,499
3.515625
4
import streamlit as st import numpy as np import pandas as pd import plost st.set_page_config(page_title='Plost', page_icon=':tomato:') """ # 🍅 Plost A deceptively simple plotting library for [Streamlit](https://github.com/streamlit/streamlit). _“Because you've been writing plots wrong all this time”_ Below you'l...
72ae6ee2ab744d71bd2077ee8cad94daa12dff35
DattaprasadKopele/Assignment_02
/General/02_decorater.py
333
4.09375
4
''' What are decorater? write a decorator to display function name and print start and end''' ''' A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. Decorators are usually called before the definition of a function you want to d...
55cc8cfb44213187372940e601c79b8844c3d8f3
DattaprasadKopele/Assignment_02
/Imp program/duplicate_no_in_list.py
707
3.984375
4
" count number which appears more than once in list " ## method1 using counter() function from collection module # from collections import Counter # # l = [1, 2, 3, 4,1, 2, 1, 3, 5, 6, 7, 8, 8, 8, 8, 9, 10] # # d = Counter(l) # # print(d) # # new_list = list([item for item in d if d[item]>1]) # print(new_list) ## ...
7d5e2118495c1d39cfdaeb2e782b6977db959fbb
jawad-unmarshal/TrialRepo
/BST-Trial.py
3,971
3.984375
4
from os import system class BinTree: NumNodes = 0 def __init__(self,val): self.left = None self.right = None self.data = val BinTree.NumNodes += 1 print("{0} was added to the tree.\nIt Currently has {1} nodes".format(val,BinTree.NumNodes)) def InsNode(self,val): ...
4a4dcd504ae1d087b88b47fd435f572a17f6ae62
colincron/python_algorithms
/search.py
2,358
3.65625
4
from sums import timer # from time import time # def time_it(func): # start= time() # func(*args, **kwargs) # end=time() # print("Run time: %s" % end-start) def seq_search(array, element): position = 0 found = False while position < len(array) and not found: print("SeqS Array posit...
ca3a8779a9154fbd17ccd891beb6c1e4373f02fe
abraidotti/kali-extra-tools
/new-script.py
1,431
3.609375
4
#!/bin/python3 import sys # bring in system functions and parameters from datetime import datetime as dt # bring in just one and give it an alias print(sys.version) print(dt.now()) my_name = "Buddy Boo" print(my_name[0]) # print first char of str print(my_name[-1]) # last sentence = "This is a sentence." print(se...
7d3b4b49a7386af1faa0a4c2129225f5a4c722f1
jing1988a/python_fb
/900plus/NextGreaterElementII503.py
1,023
3.828125
4
# Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greate...
73eda4193862c1eb0def80cb258bafa3a4536a03
jing1988a/python_fb
/amazon/amazon_oa/kSubStringWithKdifferentChar.py
1,584
3.796875
4
# Given a string S and an integer K. # Calculate the number of substrings of length K and containing K different characters # # Example # String: "abcabc" # K: 3 # # Answer: 3 # substrings: ["abc", "bca", "cab"] # String: "abacab" # K: 3 # # Answer: 2 # substrings: ["bac", "cab"] import collections class Solution: ...