blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
5b8ee7e99275ef107ca49e86bfeb27e06bf20066
nptit/python-snippets
/Strings.py
2,641
3.96875
4
def isUniqueChars(s): '''check a string has all unique characters, O(n)''' return len(set(s)) == len(s) def isUniqueChars(s): '''check a string has all unique characters, no additional data structure allowed, O(n^2)''' for i, c in enumerate(s): if c in s[:i] or c in c in s[i+1:]: r...
cc5d62e7c954ab19aa8caa9cf9ac4a77151d8f12
nptit/python-snippets
/qsort-count2.py
1,855
3.625
4
__author__ = 'qxu' import math def partition1(arr): # partition using first element of arr p = arr[0] i = 1 for j in range(i, len(arr)): if arr[j] < p: arr[i], arr[j] = arr[j], arr[i] i += 1 arr[0], arr[i-1] = arr[i-1], arr[0] return arr[0:i-1], arr[i-1], arr...
e729ac20db0b0797fb5a2d98a344cd8f4477aeeb
nptit/python-snippets
/getSublist.py
786
4
4
def getSublists(l, n): '''This function returns a list of all possible sublists in L of length n without skipping elements in L. The sublists in the returned list should be ordered in the way they appear in L, with those sublists starting from a smaller index being at the front of the list.''' nlen = len(l) ...
7cbfe796eac3b984de310a201547b220325b4d40
nptit/python-snippets
/checkio/bird-language.py
756
4
4
VOWELS = "aeiouy" def wordconv(w): 'translate a word' i, result = 0, [] while i < len(w): c = w[i] result.append(c) if c in VOWELS: i += 3 else: i += 2 return ''.join(result) def translate(phrase): 'translate a phrase' return ' '.join([w...
d841217d8a1cc2bea328237e88c499f6f6e0b8d6
nptit/python-snippets
/DFS-assignment4.py
2,935
3.90625
4
__author__ = 'qxu' ''' The file contains the edges of a directed graph. Vertices are labeled as positive integers from 1 to 875714. Every row indicates an edge, the vertex label in first column is the tail and the vertex label in second column is the head (recall the graph is directed, and the edges are directed from ...
56bd848878824ec82484bb6493f2f5c6b3eeaa43
nptit/python-snippets
/backtracking-sodoku-nQueen.py
3,698
3.734375
4
'''sodoku solver using backtracking''' def nextEmptyCell(board): for i in range(9): for j in range(9): if board[i][j] == 0: return (i, j) return (-1, -1) def row_nums(board, row): '''return values in row''' return [e for e in board[row] if e != 0] def col_nums(boa...
9873c9b3ab3e313962c33ff294e6f02cb2bc4dfe
nptit/python-snippets
/checkio/black-holes.py
3,220
3.953125
4
__author__ = 'qxu' from math import sqrt, acos, pi def dist(c1, c2): return sqrt((c1[0] - c2[0])**2 + (c1[1] - c2[1])**2) def area(r): 'area of a circle with radius r' return pi * r**2 def area_intersect(c1, c2): 'calculate intersection area between two circles --given as (x, y, r) tuples' 'ret...
60ff1e24b53bc33a9c5ccc09e9887d16b317fbfb
nptit/python-snippets
/checkio/word_reverse.py
863
3.765625
4
'reverse words in string' import re def reverse_words(sentence): words = re.findall(r'\w+', sentence) puncs = re.findall(r'\W+', sentence) return ''.join([a+b if a.isdigit() else a[::-1]+b for (a, b) in zip(words, puncs)]) #s = 'I have 36 books, 40 pens2.' #print reverse_words(s) def reverse_words(se...
545c65b2b0628f1d3c23d51fa97a13094b8893c9
nptit/python-snippets
/checkio/path.py
829
3.53125
4
from collections import defaultdict def checkio(edges): # convert it in a graph represented by a dict net = defaultdict(set) for pair in edges.split(','): p1, p2 = list(pair) net[p1].add(p2) net[p2].add(p1) # DFS search stack = ['1'] visited = list() while stack: ...
38ec3c60f8006cbd5222953e7986fbfb6409fb43
nptit/python-snippets
/merge2-stack.py
1,541
3.734375
4
def merge(l1, l2): stack1 = l1[:] stack2 = l2[:] res = [] while stack1 and stack2: if stack1[0] <= stack2[0]: res.append(stack1.pop(0)) else: res.append(stack2.pop(0)) return res+stack1+stack2 def merge(l1, l2): stack1 = l1[:] stack2 = l2[:] res ...
9de75a22fe840ef19ed4dc63a83ea17fca9c4777
tugraz-sww/intensity_duration_frequency_analysis
/idf_analysis/little_helpers.py
2,570
3.515625
4
__author__ = "Markus Pichler" __credits__ = ["Markus Pichler"] __maintainer__ = "Markus Pichler" __email__ = "markus.pichler@tugraz.at" __version__ = "0.1" __license__ = "MIT" import pandas as pd def delta2min(time_delta): """ convert timedelta to float in minutes Args: time_delta (pandas.Timede...
a894a4571badd13fd12b979a44b4618883974ce2
SemmiDev/Python-Basic
/petanikode/TitikKoma.py
211
3.578125
4
print("hello"); print("hello2"); print("hello4") # disini titik koma berfungsi sebagai separator atau pemisah # bukan mengahiri # contoh lain x = 10 y = 12 z = 13 if x < y < z : print(x); print(y); print(z)
a6d79200f13596d0322d0cfed54df3e8bca00263
SemmiDev/Python-Basic
/petanikode/files/XMLParsingWithDOMAPI/App.py
1,054
3.734375
4
from xml.dom import minidom def main(): # parse untuk load file xml -> memory # dan lakukan parsing doc = minidom.parse("file.xml") # cetak isi doc dg tag pertamanya print(doc.nodeName) print(doc.firstChild.tagName) nama = doc.getElementsByTagName("nama")[0].firstChild.data alamat = ...
1b9805936f0fe2dd95d47b60ebb95f4f1685b551
SemmiDev/Python-Basic
/petanikode/files/FileReaderAndWriter/training/Main2.py
474
3.796875
4
print("Selamat datang di Program Biodata") print("=================================") # buka file untuk dibaca dan ditulis file_bio = open("biodata.txt", "r+") teks = file_bio.read() # cetak isi file print(teks) # Ambil input dari user nama = input("Nama: ") umur = input("Umur: ") alamat = input("Alamat: ") # form...
91f9a79aceba700da010ccc95f115bce9021740e
SemmiDev/Python-Basic
/CodeWithSiza/StringReverse.py
235
3.984375
4
def reverse(s): str = "" for i in s: str = i + str return str def reverse2(s): if len(s) == 0: return s else: return reverse2(s[1:]) + s[0] s = "hello" print(s[::-1]) # print(reversed(s))
6792b2606eb998461415f7b314be9cfd9c987359
SemmiDev/Python-Basic
/petanikode/List.py
1,038
4.0625
4
warna = ["merah","kuning",123,True,43.2] print(warna) print(warna[1]) # latihan my_friends = ["adit","dandi","gusnur","rauf","ayatullah"] # show index 3 print("isi my friend yg ke-3 : {}".format(my_friends[3])) # show all print("jumlah teman : {}".format(len(my_friends))) for friend in my_friends: print(friend) #...
e23a40edb2fb69e3a9a03f104fde2d29c5c338c1
SemmiDev/Python-Basic
/TipsAndTrickPemrogramanPython/TableTranslasi-33.py
582
3.53125
4
input = 'aku tidak suka kamu' source = 'au' destination = 'ii' translation_table = str.maketrans(source,destination) output = input.translate(translation_table) print(output) # input = 'kota padang' # source = 'aieo' # destination = '4130' # tabel_translasi = str.maketrans(source,destination) # outp...
259cad5dfdc66058693748e300231c0611c23a0c
SemmiDev/Python-Basic
/TipsAndTrickPemrogramanPython/SlicingListAndString-13.py
215
3.5
4
listku = [1,2,3,4,5,6,7,8,9,10] listmu = [] lista = listku[2:5] # inclusive exclusive lista = listku[2:] # awal sampai ahir lista = listku[:5] # awal sampai ahir print(lista) kata = "im love cila" print(kata[7:])
a64567432397427b24d8903ef090a1af9806651d
SemmiDev/Python-Basic
/TipsAndTrickPemrogramanPython/Lambda-9.py
163
3.6875
4
myList = [1,2,3,4,5] myList2 = [2,3,4,5,6] yourList = list(map(lambda x: x * 2, myList)) yourList = list(map(lambda x,y : x * y, myList, myList2)) print(yourList)
13718fe611b8921b1d102687106278b02aa75de1
MrNocTV/ThugLifeCreator
/Converter.py
855
3.609375
4
import PIL.Image as Image import sys import os def gif_to_png(gif_img): try: img = Image.open(gif_img) except IOError: print("Failed to read", gif_img) sys.exit(1) try: # start converting # actually, this must be placed inside a while loop # since gi...
a29e93459befa766b84729a6704d6503b61eda17
ydj515/record-study
/Web_Crawling_Python3/BeautifulSoup4/22_requests_refactoring_ex.py
712
3.578125
4
#crawling하는 코드 import requests from bs4 import BeautifulSoup # url을 넣어서 bs bs_obj를 return하는 function def get_bs_obj(url): result = requests.get(url) bs_obj = BeautifulSoup(result.content, "html.parser") return bs_obj # company_code를 받아서 price를 return하는 function def get_price(company_code): u...
82d9e57233b9cce0c833b42274c321a55e4fe7af
ydj515/record-study
/Web_Crawling_Python3/BeautifulSoup4/13_naver_menu.py
894
3.578125
4
import urllib.request import bs4 def main(): url = "https://www.naver.com" html = urllib.request.urlopen(url) # url에 해당하는 html이 bsObj에 들어감 bsObj = bs4.BeautifulSoup(html, "html.parser") # <ul class="an_l">의 ul 태그만 뽑는다 ul = bsObj.find("ul",{"class":"an_l"}) # 위의 찾은 ul 태그에서 li태그를 다 찾아 list...
7ec6aacd69262b19315d57518746f829e2ed68a3
AltairCGS/Pensamiento-Algoritmico
/Estudio.py
3,656
3.6875
4
""" num_integrantes = 0 cont_M = 0 cont_F = 0 cont_personas = 0 cont_menores = 0 menor_armas = 9999999999999999999999999 for i in range(1,5): num_in = int(input(f"\nIngrese el numero de integrantes concentrados en la zona {i}: ")) can_M = int(input(f"Ingrese la cantidad de hombres en la zona {i}: ")) can_F ...
3cfc76b8673e9f25775b5ea00b24a49ea6ad1ae9
bjmiao/Word-Segment
/ss/initialize.py
964
3.5
4
import re def token_sentence(text): '''return a list, each element is a sentence''' text=re.sub(r'([,。?!:;])',r'|\1|',text) text=re.sub(r'[  \t\n]+','|',text) if '||' in text: text=text.replace('||','|') sentence_list=text.split('|') if ('\n' in sentence_list):sentence_list.remove...
c9a78cebadab459596ffda6a0062e4206441496f
sgw1374/mywork
/APCS/p1.py
396
3.53125
4
# coding: utf-8 m = input() n = m.split() o=[] for i in n: k=f'{int(i):0>5}' o.append(k) o.sort() p=[] for j in o: k=int(j) p.append(k) print(p[0],p[1],p[2]) if int(p[0]) + int(p[1]) < int(p[2]): print("No") elif int(p[0])**2 + int(p[1])**2 < int(p[2])**2: print("Obtuse") elif int(p[0])**2 ...
3dec823dfdf9dac29a2ac74eb480f47ed0c5584e
ebmoh18/exercises
/chapter-4/ex-4-1.py
1,050
4.375
4
# Programming Exercise 4-1 # # Program to total the values of five integers. # This program the user for an integer five times, # and totals them up, # then displays the total entered on the screen. # Initialize variables for bugs collected and total bugs. # be sure to initialize them as integers # Get th...
5f231313ee7dccedd7706dd7c3989636da987b3b
LitoleNINJA/Maze-Solver
/aStar.py
3,662
3.796875
4
from heapq import * import pygame from maze import maze # Function to calculate Heuristic def heuristic(i, j, l, r): return abs(i - l)**2 + abs(j - r)**2 # Function to solve the maze def solveAStar(maze, i, j, l, r, solution): height = maze.height width = maze.width # If we've reached the end, we're ...
4db97ffb3f6f908c53b7fddfd25e72436cbb2a83
mercyden21/CS6843_Computer_Networking
/mail.py
1,801
3.625
4
from socket import * msg = "\r\n I love computer networks!" endmsg = "\r\n.\r\n" # Choose a mail server and call it mailserver mailserver = "localhost" mailport = 25 # Create socket called clientSocket and establish a TCP connection with mailserver clientSocket = socket(AF_INET, SOCK_STREAM) clientSocket.connect((mai...
79633825534d3995d3c07d192a772d3489b09205
jakobcodes/Algorithms-And-Data-Structures-AGH-Course
/templatki/dijkstry.py
647
3.859375
4
from queue import PriorityQueue from math import inf def dijkstry(G,s): def relax(u,v): if d[v] > d[u] + G[u][v]: d[v] = d[u] + G[u][v] parent[v] = u Q = PriorityQueue() d = [inf for _ in range(len(G))] parent = [-1 for _ in range(len(G))] visited = [False for _ in ...
8608f443e05a56019f8796538b6f8eb90f139b22
kevinalx/PythonEjercicios
/punto4.py
748
3.828125
4
#Un alumno desea saber cual será su calificación final en la materia de Algoritmos. Dicha #calificación se compone de los siguientes porcentajes: #55% del promedio de sus tres calificaciones parciales. #30% de la calificación del examen final. #15% de la calificación de un trabajo final. cal1=float(input("Digite su pr...
2ad92e0c0e87014521a1858e13f1561dcc3de40b
kevinalx/PythonEjercicios
/punto3.py
286
3.65625
4
#Una tienda ofrece un descuento del 15% sobre el total de la compra y un cliente desea #saber cuanto deberá pagar finalmente por su compra. compra=float(input("Digite el valor de la compra: ")) desc=compra*0.15 pago_total=compra-desc print(f"Su total a pagar es de: ${pago_total}")
afcf660cb7a288cc80d8cef391152f510aafdbc1
zhong-jl/gitdemo
/merge_sort.py
1,217
3.796875
4
#merge sort(A) #以下函数完成子表的划分 def splitsort(seq): #如果子表长度为1,则直接返回该表 if len(seq)<=1: return seq #否则,取表正中位置,记为mid mid=int(len(seq)/2) #分别对左右半表进行划分 print('mid=',mid) print('left=',seq[:mid]) print('right=',seq[mid:]) left=splitsort(seq[:mid]) right=splitsort(seq[mid:]) ...
e1a967d019386bb070477042fa5b2eb1dd07d352
aarti1207/Project
/WeatherForecast-WebDriver.py
504
3.703125
4
# -*- coding: utf-8 -*- """ Created on Wed Jun 10 18:48:27 2020 @author: Aarti """ from selenium import webdriver driver = webdriver.Chrome(executable_path=r'C:/Users/Aarti/PythonProject/chromedriver_win32/chromedriver.exe') city =str(input("Enter the name of the city you want the weather forcast for :...
e6e212fbd82cc4ddd86d9cf76f3f47a355a00605
Bhavana-G/GitLearningRepo
/example/hello.py
2,103
3.921875
4
import tkinter from tkinter import messagebox from tkinter import END from random import randint #GUESSING GAME: low = 0 high = 20 rand = randint(low, high) print(rand) def check(guess): if guess < rand: tkinter.Label(tk, text=f"{guess} is too low").pack() elif guess > rand: tkinter.Label(tk, ...
6eb74e3a864a185af448baafb7bf62b1a16ed262
zjijz/cse474-compiler
/archive/proj4/lexer.py
3,684
3.9375
4
import re import sys class LexerError(Exception): """ Exception to be thrown when the lexer encounters a bad token. """ def __init__(self, msg): self.msg = msg def __str__(self): return str(self.msg) class Token: """ A class for storing token information. The variable...
a743209b94934c903ff7f4c382e843f4b06cfff7
yuki-9/Python-Data-Mining
/chapter7/chapter7/test/data/preprocesseddata.xls
680
3.671875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @File : c7.py # @Author: ZhuNian # @Date : 2020/6/28 20:05 """ 1.题目: 买卖股票的最佳时机含手续费 2.解题思路: 方法:动态规划 """ class Solution: def maxProfit(self, prices, fee): cash = 0 # 不持有股票的收益 hold = -prices[0] # 持有股票的收益 for i in range(1...
e2ff1b5f10a359aee28d3afc630794e22829b69b
Yamini-R-99/Task
/rock_paper_scissor.py
456
3.828125
4
n1=input("Enter rock/scissor/paper:::") n2=input("Enter rock/scissor/paper:::") if(n1=="scissor"and n2=="paper"): print("Player 1 wins....") if(n1=="scissor" and n2=="rock"): print("playe 2 wins....") elif(n1=="paper"and n2=="scissor"): print("Player 2 wins...") elif(n1=="rock"and n2=="paper"): print("Player 2 ...
d83de1a28871dcb27206948bc30a298138c6b5b5
Mahmoud-AbdElHalim/MachineLearningNanodegree
/30- XGBoost/XGBoost.py
1,777
3.6875
4
# Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Churn_Modelling.csv') X = dataset.iloc[:, 3:13].values y = dataset.iloc[:, 13].values # Encoding categorical data from Labels into continious 0 1: from sklearn.pr...
134c0e08b860d027969fb9d9f8351348f35d56ef
bradleecrockett/PasswordComplexityChecker
/PasswordComplexityChecker.py
583
3.5
4
# Name: # Date: # Period: ''' Your task is to create a program that tests to determine whether a password is complex or not. A password is considered complex if it is **at least 8 characters long** and meets at least 3 of the next 5 requirements. 1) Contains a lowercase character 2) Contains an uppercase character 3...
41625be8280b6755291455a03f6c09b106766b3d
dkorzhevin/code
/Python/Coursera/Crash Course on Python/infinite_loop.py
363
4.15625
4
def smallest_prime_factor(x): """Returns the smallest prime number that is a divisor of x""" # Start checking with 2, then move up one by one n = 2 while n <= x: if x % n == 0: return n n += 1 # This fixed infinite loop here print(smallest_prime_factor(12)) # should be 2 pri...
026007e81b6f445e1cbd83aab9e5a332ce52cb92
dkorzhevin/code
/Python/Coursera/Using Python to Interact with the Operating System/generate_report_from_csv.py
416
3.53125
4
#!/usr/bin/env python3 import csv def read_employees(csv_file_location): csv.register_dialect('empDialect', skipinitialspace=True, strict=True) employee_file = csv.DictReader(open(csv_file_location), dialect = 'empDialect') employee_list = [] for data in employee_file: employee_list.append(data) return emp...
f1de71d85b7126e508071df6ca4d719e69cfbc3f
dkorzhevin/code
/Python/Coursera/Crash Course on Python/rectangle_area_refactor.py
326
3.90625
4
# Refactor function to calculate the area of a rectangle # Before refactor: #def f1(x, y): # z = x*y # the area is base*height # print("The area is " + str(z)) # After refactor: def rectangle_area(base, height): area = base * height # the area is base * height print("The area is " + str(area)) rectangle_area...
e15d119e743a06c9a881a8c76984743de8864238
cat-in-the-box/jennifer-lee
/7_calculator_finished.py
1,420
4.25
4
def run_calculator(): run_program = input("Which function would you like to run (pick A,B,C)? Your options are: \nA. add_numbers \nB. subtract_numbers \nC. average_numbers \nYou can also input 'Quit' if you don't want to play: ") if run_program == "A": print ("Okay, let's get started with add_numbers!")...
faa2c7f7d0d45c1bbaf26f2e39f3a59a0ce7b109
Elkip/BlackJack
/blackjack.py
3,169
3.890625
4
from collections import namedtuple from random import shuffle Card = namedtuple('Card', ('Suit', 'Rank')) class Deck: def __init__(self): self.cards = [] self.construct_deck() def construct_deck(self) -> None: # Define ranks and Suits ranks = [_ for _ in range(2, 11)] + ['Ja...
0ca6c2d4a77736e66d174378ed7ac846e8b5dab6
mattsuri/unit5
/fwordDemo.py
182
4.09375
4
#Matthew Suriawinata #4/23/18 #fwordDemo.py - print out words with f words = input("Type in some wordsL ").split(" ") for item in words: if "f" in item or "F" in item: print(item)
431e713577cca394ba9b501a1b1a8fe16baedd72
mattsuri/unit5
/dictionaryDemo.py
220
3.859375
4
#Matthew Suriawinata #4/25/18 #dictionaryDemo.py - more list practice words = ["computer", "mortify", "dog", "firetruck", "yes", "python", "cat"] words.sort() num = int(input("What number owrd to you want?")) print(words[num-1])
ed2bcb21892b29b1f2ccd0b63217f2d57cca3a3b
estelora/python
/madLibs.py
146
3.5625
4
noun = input("Enter noun") verb = input("Enter verb") color = input("Enter color") print("One day, the " + noun + " and saw a " + color + "sky.")
ab6ec020a0cf1c8c6a0caddf472f668c668640f2
NicolasLagaillardie/Python
/Pascal.py
419
3.65625
4
#Affichage du triangle de Pascal #Python 2.7 rang='a' while type(rang)!=int or rang<0: print 'Jusqu\' quel n voulez-vous afficher le triangle de Pascal' rang=input() print '' tableau=[[1]] for i in range(0,rang): tmp=[] curseur=tableau[i] for k in range(0,len(curseur)-1): tmp=tmp+[curseur[k]+curseur[k+1]] t...
b09e70dcd15f468e83f8e2ed7c2950297ccdfa8b
NicolasLagaillardie/Python
/divisionEucli.py
187
3.625
4
p=input('p ?') n=input('n ?') q=0 while p*(q+1)<=n: q=q+1 print 'Le quotient de la division de ',n,' par ',p,' est : ',q print 'Le reste de la division de ',n,' par ',p,' est : ',n-p*(q)
0196206869132d43e9abf8bd62e05696b47dbe5d
NicolasLagaillardie/Python
/Recuit simulé/Recuit.py
2,378
3.65625
4
#-*-coding:utf8;-*- #qpy:2 #qpy:console from random import randint from copy import deepcopy from math import sqrt from math import exp from random import random from matplotlib import pyplot as plt import numpy as np def distance(v1, v2) : return sqrt((v1[0]-v2[0])**2+(v1[1]-v2[1])**2) def longueur(listeV) : ...
aec8d9e0967c2746512bd72e339ea849fcef87af
NicolasLagaillardie/Python
/arbre_test.py
242
3.5
4
def arbre(graphe): import connexe if connexe(graphe)=='Faux': return 'Faux' else: arrete=0 for i in range(0,len(graphe)): arrete=arrete+len(graphe[i]) if arrete-len(graphe)==len(graphe): return 'Faux' else: return 'Vrai'
2b00138e3fad98da5f2d27b5e5a2d3188ed71ed7
NicolasLagaillardie/Python
/sans_repet.py
457
3.578125
4
def sans_repet(a=3): #Si l'utilisateur ne rentre pas un tableau if type(a)==float or type(a)==int: a=int(a) from random import randrange t=[] for i in range(a): t.extend([randrange(11)]) else: t=a a=len(t) #Tri tableau for j in range(1,a): cle=t[j] i=j-1 while i>=0 and t[i]>cle: ...
cc41c6aca8beab89472a310e46dd9432ae7c75c8
NicolasLagaillardie/Python
/palindrome.py
291
3.890625
4
def palindrome(n=3): if type(n)==float or type(n)==int: n=int(n) from random import randrange t=[] for i in range(n): t.extend([randrange(11)]) else: t=n n=len(t) k=int(len(n)/2) for i in range(0,k-1): if n[i]!=n[len(n)-1-i]: return False return True
625755b4b278e7825aadcabbf908bc722dc94db5
NicolasLagaillardie/Python
/nombreParfait.py
650
3.890625
4
# -*- coding: utf-8 -*- """ Created on Mon Sep 30 21:46:31 2013 @author: Nicolas """ from math import sqrt n=-1 while type(n)!=int or n<=0: # Un entier n strictent positif n=input('n ? ') s=0 for i in range(1,int(sqrt(n))): # Cherhcer jusqu'à la racine carrée réduit if (n%i)==0: # les calculs s...
68dd823dd261061a4b7fcae6bb23040f3e0afe84
NicolasLagaillardie/Python
/hearth.py
298
3.578125
4
# -*- coding: utf-8 -*- """ Created on Thu Dec 05 09:33:35 2013 @author: Nicolas """ import matplotlib.pyplot as plt import numpy as np x=np.linspace(-5,5,100) plt.plot(x,np.sin(x)) # on utilise la fonction sinus de Numpy plt.ylabel('fonction sinus') plt.xlabel("l'axe des abcisses") plt.show()
0c20d24850833221f661d68ed4a3720343dc8dfa
NicolasLagaillardie/Python
/Fusion.py
395
3.703125
4
# La fonction ''fusion'' prend en argument deux listes triées par ordre croissant liste1 et liste2 # Elle renvoie la liste obtenue en fusionnant liste1 et liste2 de manière à ce qu'elle soit triée def fusion(liste1,liste2): if liste1==[]: return liste2 elif liste2==[]: return liste1 else...
6a196dc59ae3d40035d2907fa80ac44b40e78c18
tobyqin/py_quiz
/factorial.py
338
4
4
""" 实现正整数阶乘函数。 5! = 5 * 4 * 3 * 2 * 1 = 120 """ def factorial(n): if not isinstance(n, int): return None if n < 0: raise ValueError('n should be non-negative integer!') if n == 0: return 1 else: return n * factorial(n - 1) print(factorial(5)) print(factorial(20))
c25ca94ff2301a069071bbf446b0ed0ad07a2543
rolandoibl/Ejemplogit
/practice09.py
2,978
3.71875
4
mne#!/usr/bin/env python # # AUTONOMOUS MOBILE ROBOTS - UNAM, FI, 2021-1 # PRACTICE 9 - COLOR SEGMENTATION # # Instructions: # Complete the code to estimate the position of an object # given a colored point cloud using color segmentation. # import numpy as np import cv2 import ros_numpy import rospy from sensor_msgs....
166d4212f65a00022f35229002f31eec3ab856bd
gemihaha/python3_practice_mbs_tft
/ETC/codes/2-4.py
109
3.703125
4
number = 0 while number < 10: print('10보다 작습니다.') number += 1 else: print('종료')
7ee4ad5c4fc73573830f87db751ecdb00d67774c
gemihaha/python3_practice_mbs_tft
/ETC/codes/2-8.py
95
3.703125
4
for x in range(2,10): for y in range(1,10): print(x*y, end=' ') print('')
494a11062cd728b2bcd417b75e59ec22de997e30
gemihaha/python3_practice_mbs_tft
/ETC/practice1/1-9.py
184
3.859375
4
salary = {'David':30000, 'John':50000, 'Andrew':45000, 'Rita':70000, 'Michale':10000} for a in salary.keys(): if salary[a] >= 50000: print(a + '\'s salary is', salary[a])
258366d87b36efdd2b5fe6f4b0d49c9e41e8e96f
appinfin/comparison-of-numbers
/test.py
3,540
3.703125
4
from tkinter import * import math def get_sums(number_string): shift = math.ceil(len(number_string) / 2.) # число символов до середины (левая половина в приоритете) left_sum = sum(map(int, number_string[:shift])) # суммируем от первого символа до "середины" right_sum = sum(map(int, number_string[...
6a575eb77df6c16efc4068dc10e0d043c4049352
CadenLambert/MachineLearning
/Perceptron.py
2,984
3.734375
4
import numpy as np from matplotlib.colors import ListedColormap import matplotlib.pyplot as plt class Perceptron(object): def __init__(self, rate = 0.01, niter = 10): self.rate = rate self.niter = niter def fit(self, X, y): """Fit training data X : Training vectors, X.shape : [...
d0d392790fe46b91307ec29f1340200d28b8576d
CadenLambert/MachineLearning
/Drivers/ThresholdDriver.py
569
3.71875
4
import numpy as np import Threshold as th test = np.array([1,2,3,4,5,6,7,8,9,10]) thresholdClass = th.Thresholds(test) print(thresholdClass.allLabelings()) goodInput = False while goodInput is False: choice = int(input("Enter function choice: ")) if choice >= 0 and choice < len(test): goodInput ...
4be51e482b387fb09d44fde5876594636a2628ff
angelsumalini/degree
/perfect number.py
194
3.84375
4
n=int(input("enter a number")) s=0 i=1 while i<n: if n%i==0: s+=i i+=1 if s==n: print(n,"is a perfect number") else: print(n,"is not a perfect number")
a7aa5f1e15192bad4da20763f6182f34ae1711c1
HMurkute/PythonPanda
/LearnPanda2.py
590
4.3125
4
import pandas as pd # We first see the operation by which we can perform merging of two dataframes. df1 = pd.DataFrame({'HPI':[80, 90, 70, 60],'Int_Rate':[2, 1, 2, 3],'Ind_Gdp':[50, 45, 65, 23]}, index = [2001, 2002, 2003, 2004]) df2 = pd.DataFrame({'HPI':[80, 90, 70, 60],'Int_Rate':[2, 1, 2,...
e764cc68f6dc55e5215fdac06842a50b5a37d9ed
shashiprajj/Turtle-Library-Python
/turtle_race.py
2,871
3.859375
4
import turtle import time from turtle import Turtle from random import randint import random # window setup window = turtle.Screen() window.title("Turtle Race") turtle.bgcolor("forestgreen") turtle.color("White") turtle.speed(0) turtle.penup() turtle.setpos(-140, 200) turtle.write("TURTLE RACE", font = "...
898109fa4a513e1a43fd33da3b7430e348e09ccb
butigard/Notes
/My Fractal.py
758
3.96875
4
import turtle import random import math my_turtle = turtle.Turtle() my_turtle.showturtle() my_turtle.shape("turtle") my_turtle.speed(0) my_screen = turtle.Screen() my_screen.bgcolor('white') my_turtle.width(1) my_turtle.fillcolor("grey") colors = ["pink", "purple", "blue", "yellow", "green", "orange", "red"] #-------...
0f81ae04f6197f5d8def41621b6027f6f200ceac
oliveira-marcio/challenge-customer-invitation
/utils.py
3,135
3.921875
4
# coding: utf-8 from math import radians, sin, cos, asin, sqrt import json def calculate_distance(p1, p2): ''' This method uses Haversine formula to calculate smallest distance between 2 points on Earth surface. https://en.wikipedia.org/wiki/Haversine_formula hav = sin(delta_lat/2)...
7335a0187b451dbc38b3ebf61903729a39939214
genEM3/genEM3
/playground/AK/tutorials/exampleScript.py
984
3.6875
4
import argparse import logging parser = argparse.ArgumentParser() # two integers parser.add_argument("num1", help="the first number", type=int) parser.add_argument("num2", help="the second number", type=int) # a string, limited to a list of options parser.add_argument("op", help="the desired arithmetic operation", cho...
3dd1e2453d320ba6505ebae98cc23dad1c99628c
n-st/ipgrep.py
/ipgrep.py
1,377
3.671875
4
#!/usr/bin/env python3 import fileinput import ipaddress import unicodedata EXCLUDED_PUNCTUATION_CHARS = ['.', ':'] def is_delimiter(char): if char in EXCLUDED_PUNCTUATION_CHARS: return False cat = unicodedata.category(char) # Space_Separator or *_Punctuation or *_Control return cat == 'Zs'...
8ad395b0211843f15c82e2e7b9f8a0cd9c23e7c8
HidekiHrk/ed_poo
/third_week/2.py
2,053
3.859375
4
class Queue: def __init__(self): self.__items = [] @property def size(self): return len(self.__items) def push(self, item): self.__items.append(item) def pull(self): return self.__items.pop(0) def iter_all(self): while self.size > 0: yield ...
061117680d6cb704a9fda53231ad9bc08519e141
AstroSnout/py-threaded-chat
/threaded_tcp_chat_server.py
2,453
3.734375
4
from socket import * from threading import * class ClientHandler(Thread): def __init__(self, cl_sock, cl_address, cl_username): self.sock = cl_sock self.address = cl_address self.username = cl_username # Append thread to all clients clients.append(self) ...
895fbdbea9273d2fe5959c9c62f540a0e0bf118d
ksquarekumar/MITx-6.00.1x-2016-Sep
/Ch1/Ex1 MIT.py
231
3.96875
4
s= raw_input('Enter String',) # s already defined def vowelcount(s): n=0 for i in s: if (i == 'a' or i == 'e' or i == 'o' or i=='i' or i =='u'): n+=1 return n print vowelcount(s)
a85be533273a550d3a487b295a370af4c2d9233a
kcc112/Python-Lab-1
/pi_wal.py
286
3.71875
4
def calculate_pi(n): approximation = 1 for i in range(1, n + 1): output_text = 'Iteracja nr: {} | przybliżenie {}' approximation *= (4 * i ** 2) / (4 * i ** 2 - 1) pi = approximation * 2 print(output_text.format(i, pi)) n = 10 calculate_pi(n)
523299eb120e2f65ce3ea5b2d5796db5d491147e
turtlecoder207/Python-Practice
/mul2.py
98
3.765625
4
result = 0 for n in range(1,1000): if n%3 ==0 or n%5==0: result += n print(result)
4d988ac3f55f6bb83e9325f7c42226bb5cdcac30
Abhishek1998-cpu/DSA-Sheet-450-Questions
/1.py
813
3.71875
4
class Solution: def merge(self, arr1, arr2, n, m): self.arr1 = arr1 self.arr2 = arr2 self.n = n self.m = m int(n) int(m) for i in range(0, len(arr2)): arr1.append(arr2[i]) arr1.sort() # arr1 = arr1[0: n-1] # arr2 = arr2[n-1:...
d064e5ce20ee46ad33c1e115317de37c6900c318
Abhishek1998-cpu/DSA-Sheet-450-Questions
/Arr_Rev.py
178
3.9375
4
# Reverse the list or Array def revlist(l): M = l[::-1] return M # l = [1,2,3,4,5,6,7,8,9,10] # print(revlist(l)) L = ['abc', 'xyz', 'def'] print(L) print(revlist(L))
ec540834bcfc1059d417aca942d2e7805aa54af7
amnghd/A_Review_on_Pyspark
/NLP using Pyspark/notebooks/codes/scalable_wc.py
1,594
3.515625
4
# finding pyspark import findspark findspark.init() # adding pyspark to sys.path # importing require modules from pyspark import SparkConf, SparkContext # importing regex to perform tokenization import re # setting up spark environment conf = SparkConf().setMaster('local[4]').setAppName('WordCounter') sc = SparkConte...
6cd83b8aa26cd460e50cb4931dc2114fd8690070
kelknightly/scifibot
/sentences/base_sentence.py
272
3.5
4
# parent class # common functionality that every sentence will need class base_sentence(object): sentence_name = "" def __init__(self, sentence_name): self.sentence_name = sentence_name def get_name(self): return self.sentence_name
f572b4cbad5aa68016fddd2c1249dbb20c6ffcc6
prlombaard/excelpasswordscanner
/gogetit.py
882
3.578125
4
# gogetit.py # Given a filename that point to a excelfile on disk. Try to get the password for the Excel file. # Use either a wordlist or generate a sequence of letters / numbers from zipfile import ZipFile def scan_zip_passwords(filename='evil.zip', wordlist='dictionary.txt', verbose=False): with ZipFile(filena...
2d0f02b1c57433319f35d5c9fb5d19affd6931bb
tejasvicsr1/Rock-Paper-Scissors
/R_P_S.py
3,078
4.21875
4
# importing libraries import os from random import choice # to clear screen every time this program rounds os.system('cls') # pre defining the list of option and their superiority rps = ('Rock', 'Paper', 'Scissors') rps_dict = { 'Rock' : {'Superior':'Scissors', 'Inferior':'Paper'}, 'Paper' : {'Superior':'Rock...
57a2095737124385c63c129885b8428ce65e2a25
IAlwaysBeCoding/TicTacToe
/tictactoe/hash/__init__.py
4,921
4.125
4
""" Making hashes from hashable objects === To make a **_tic-tac-toe_** game it was necessary to create every **move**, **cell**, **board**, **game position** as a `hash`. In a sense, it would be very useful to be able to _reproduce_ these _basic_ **things** : * `Cell` : A place where a player could place a mark. * `...
713270330f3a8f60a64e00117180f8ebb3c2e8f4
ferodia/Tic-Tac-Toe
/test_board.py
1,972
3.71875
4
from unittest import TestCase from board import Board class TestBoard(TestCase): def test_mark_cell(self): board = Board() n = 3 self.assertFalse(board.is_full()) board.mark_cell(1, 1, "X") board.mark_cell(1, 0, "O") def test_invalid_mark_cell(self): board = B...
5ddc7cdd060671666f562f28f62615be95c9cc7a
anxiousmodernman/quadratic
/quadratic.py
2,283
3.875
4
## Quadratic Eq. Solver ## TODO: FIX THE ERRORZ ## TODO: After finishing, we can make the script accomodate complex roots. For extra credit. from math import * class QuadEq: """A class that defines a quadratic equation to find the real roots of quadratic function.""" values = [] def quadraticSolver(se...
e155c75e3fc808b326ffd2bc071f41e1f06a3f86
yadavp53/IOT-Based-Traffic-Violation-Control-System
/Tracker/test.py
940
3.546875
4
import tkinter as tk from tkinter import ttk root = tk.Tk() root.title("gui") root.geometry('400x200') tab=ttk.Notebook(root) page1=ttk.Frame(tab) tab.add(page1,text="home") tab.pack() name_Label=ttk.Label(page1,text="name") name_Label.grid(row=0,column=0,sticky=tk.W) city_Label=ttk.Label(page1,text="c...
654243ed2cfe7b88707dc1d6f7f9ac3cbb57459f
sdetcoding/Python_Basics
/basic/datatype/list.py
893
4.09375
4
# List and Tuple ls = [1, 2, 8, 5, 7, 7, 0, 8, 9, 5, 6, 5, 5, 0] # printing list print(ls) # remove ls.remove(2) del ls[-1] # append in list ls.append(3) ls[4] = 21 # removing duplicate from list ls = list(dict.fromkeys(ls)) print("remove dup", ls) # count the frequency of word print(ls) print(ls.count(5)) print(l...
5d5eb3b23658102c24fc9b44474af017fe25b71a
sdetcoding/Python_Basics
/basic/filehandling/readingfile.py
721
4.09375
4
# opening a file by providing path and giving only read privilege f = open("D:\\pythonproject\\basic\\data\\read.txt", "r") # reading the file print(f.read()) # closing file f.close() # opening a file by providing path and giving only appened privilege f = open("D:\\pythonproject\\basic\\data\\read.txt", "a") f.write(...
2b06d86ce1d1009252123f3e1ec2223544cd6e71
nhaney/PigLatinTranslator
/atinlay
1,705
3.75
4
#! /usr/bin/python import re #regex used for my function to split up the line import sys import os from igpay import igpay def stringToList(string): '''removes spaces and then seperates characters and symbols in a list of lists''' #first split by spaces newStrings = string.split() #then we will further split thi...
c2c4914edd4954c295e4e65e064d4fe0a8acfed9
devpruthvi/ds_algo
/uncategorized/largest_rect_in_histogram.py
828
3.515625
4
import random heights = [random.randint(1, 10) for i in range(10)] # heights = [8, 9, 7, 3, 5, 2, 2, 7, 10, 3] def getMaxRectInHistogram(heights): s = [] maxRect = 0 for i,h in enumerate(heights): if len(s) == 0 or h >= heights[s[-1]]: s.append(i) i += 1 else: ...
40b7851333cface821db0307b276810297c205e8
kamuc2012/Session_1_to_5
/Session5/ProblemStatement2.py
851
4.3125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Implement a Python program to generate all sentences where subject is in ["Americans","Indians"] and verb is in ["Play", "watch"] and the object is in ["Baseball","cricket"]. Hint: Subject,Verb and Object should be declared in the program as shown below. subjects=["A...
ec6fa8b0e583123151060a40e4e403ad569cf699
kamuc2012/Session_1_to_5
/Session5/ProblemStatement1.py
301
3.9375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Write a function to compute 5/0 and use try/except to catch the exceptions. """ def division(val, by): try: print("{} / {} = {}".format(val, by, val/by)) except ZeroDivisionError as ex: print("Exception:", ex) division(5, 0)
c1ecf246fe8fad674454bea05869044c36916ea7
Yang19960405/Mathematica
/urllib练习/urlparseLX.py
1,281
3.578125
4
#使用urlparse()进行URL解析 from urllib.parse import urlparse, urlunparse, parse_qsl result=urlparse('https://www.baidu.com/index.html;user?id=5#comment') #返回类型包含六个部分 print(type(result),result) #urlparse()组合成URL date=['http','www.baidu.com','index.html','user','s=4','comment'] print(urlunparse(date)) #urlsplit()返回的远足类型 可以...
1f11ad28f32dda332b872f21973703f69d961db2
kaouthardjezzar/Data_Boot_Camp
/Unit 1/Exceptions_Homework.py
242
3.75
4
a = 12 s = "Hello" try : print ("inside try") print (a + s) print ("printed using original data types") except TypeError : print ("inside except") print (str(a) + s) print ("printed using type-casted data types")
449023a6854cfff34c5d9d32ea168f472fa7d841
gendo7985/Coding-Practice
/Programmers/level_2/jadencase.py
231
3.546875
4
# JadenCase 문자열 만들기 def solution(s): answer = "" tmp = " " for i in s: if tmp == " ": answer += i.upper() else: answer += i.lower() tmp = i return answer
05bd7815f973acc5cf4c9fa20bb8e0ef4577c1ad
gendo7985/Coding-Practice
/Programmers/level_2/target_number.py
228
3.671875
4
# 타겟 넘버 def solution(numbers, target): if len(numbers) == 0: return int(0 == target) arr = numbers[1:] number = numbers[0] return solution(arr, target + number) + solution(arr, target - number)
4cf05c39580279d32a8c7ee6b0242e63f2d52345
gendo7985/Coding-Practice
/Programmers/level_1/take_two_and_sum.py
516
3.53125
4
# 두 개 뽑아서 더하기 def solution(numbers): answer = [] N = len(numbers) for i in range(N): for j in range(i + 1, N): s = numbers[i] + numbers[j] if s not in answer: answer.append(s) answer.sort() return answer if __name__ == "__main__": numbers = [2,...
37257f96246c2800e699ba97a6693c5113b20d4b
gendo7985/Coding-Practice
/Programmers/level_2/parentheses_rotation.py
400
3.734375
4
# 괄호 회전하기 def parentheses(s): while s.find("()") + s.find("[]") + s.find("{}") > -3: s = s.replace("()", "") s = s.replace("[]", "") s = s.replace("{}", "") return len(s) == 0 def solution(s): if len(s) % 2 == 1: return 0 answer = 0 for i in range(len(s)): ...
1eb15df0b877052b6731e1764843491f22e5c9e0
toskpl/Portfolio
/Projects/Disaster-Response-Classification/project/ml/data.py
644
3.609375
4
from sklearn.model_selection import train_test_split def prepare_datasets(df, test_ratio=0.2): """Slices dataframe into inputs and target columns. Columns are sliced and shuffled again via train_test_split function of scikit-learn. Function returns train and test inputs as well as train and test targets slice...
98e7c2baede2765ba383524f1f4f83348121283b
toskpl/Portfolio
/Projects/Disaster-Response-Classification/project/ml/metric.py
1,716
3.6875
4
import pandas as pd from sklearn.metrics import f1_score, precision_score, recall_score def _metric_per_class(Y_expected, Y_pred, metric): """Function returns a list of scores for each class for given metric. Parameters: ----------- Y_expected: numpy.ndarray Numpy array containing expected pr...