blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
ff5e3a11d176e39858a44d11e9f2ed0b7e786bdb
emilianolara/Gradiente-Descendiente
/gradient_descent.py
1,995
3.640625
4
from numpy import * import matplotlib.pyplot as plt import pandas as pd # Modificar (df['semana'], df['kwh'] de acuerdo a los headers de su archivo def graph(formula, x_range, df): x = array(x_range) y = eval(formula) plt.plot(x, y) plt.plot(df['semana'], df['kwh'], 'o') plt.show() def compute_error_for_line_gi...
682e49b5594486ecf0ff59e37c31042ed51cac05
PRAVEEN100999/praveen-code-all
/third.py
1,098
3.765625
4
# name = input("enter your name :") # age = int(input("enter your name and age :")) # if (name[0]=='a'or name[0] =='A') and age >= 10: # print("you are eligble..for movie") # else : # # print("not eligble for movie :") # name ="" # if name: # print("a") # else : # print("b") # n = input("enter yo...
8599abed4208174c51b7fea279dfdcbbfd2a48bf
PRAVEEN100999/praveen-code-all
/ds2.py
734
3.890625
4
import numpy as np import matplotlib.pyplot as plt def estiamte_coefficient(x,y): n = np.size(x) mean_x, mean_y = np.mean(x),np.mean(y) SS_xy = np.sum(y*x - n*mean_y*mean_x) SS_xx = np.sum(x*x - n*mean_x*mean_x) b1 = SS_xy/SS_xx b0 = mean_y - b1*mean_x return (b0,b1) def plot_reg...
bf30f21bd3c4ef55d157201b907406d4a9f6ca66
PRAVEEN100999/praveen-code-all
/seven.py
331
3.796875
4
def func(int1,int2): add =int1 +int2 mul =int1*int2 return add,mul print(func(2,3))#return output in the form of tuples add, multi = func(3,4)#diffent out put print(add) print(multi) nums= list(range(1,11)) print(nums) a = str((1,23,4,5,6,5)) print(a) print(type(a)) aa =str([1,4,5,6,7,9]) print(aa) print...
39828b5b1d4857c8ae8e6e16da19ab54463ca068
SayaDuck/jlee10
/12_flask-jinja/app.py
1,113
3.59375
4
# Clyde 'Thluffy' Sinclair # SoftDev -- Rona Ed. # Oct 2020 from flask import Flask, render_template #Q0: What happens if you remove render_template from this line? # It will return this error: “NameError: name 'render_template' is not defined” in the browser and the Flask command line/terminal app = Flask(__name__) ...
978e2b9b55998133ab90b0868126f32367f29d60
samcheck/Tutorials
/ATBSWP/Chap3/collatz.py
348
4.125
4
def collatz(number): if number == 1: return elif number % 2 == 0: print(number // 2) collatz(number // 2) else: print(3 * number + 1) collatz(3 * number + 1) print('Input an interger: ') number = input() try: number = int(number) collatz(number) except ValueError: print('Error: please enter an inter...
cad624fe7301ee8fa4e3ffbcba8b62ade1e5476e
muhammadnajie/fad-crpytography
/classic_cryptography/util.py
979
3.640625
4
import re import os import sys def to_file(filename, msg): try: with open(filename, "w") as f: f.write(msg) print(f"Successfully writing message to {os.path.abspath(filename)}") except: print("Failed to writing to the file.") print("Here is the plaintext")...
0b7a6376ec80a079e0bb1a4177e7bb6fa22dbb65
aviau/INF3005_LAB
/semaine4/insert_input.py
2,626
3.78125
4
#!/usr/bin/python3 import os import sqlite3 def get_connection(): connection = sqlite3.connect('db.sqlite') return connection def read_albums(filepath): albums = [] with open(filepath, "r") as f: for line in f: artist, title, year = line.strip().split("|") albums.a...
5d9519db3e6de1a6d08ef343fd4cbfce459d8234
VinGPan/Machine_Learning_3252_project
/src/s02_prepare_data.py
3,281
3.59375
4
from src.s03_compute_features import compute_features from src.utils import read_yml import pandas as pd import numpy as np import os def make_data(df, config): ''' Depending on the experiment, pre-process the data. There are following 3 choices: 1) Read the data and just return the dataframe 2) Read...
c66e209f641965daf51958dfa172944d66a68fbb
abiraja2004/APL_PythonDeepLearning
/IC5/Problem1.py
488
3.65625
4
import numpy as np import math import matplotlib . pyplot as plt import scipy as sc x=[0,1,2,3,4,5,6,7,8,9] y=[1,3,2,5,7,8,8,9,10,12] yChange = [] meanX = sc.mean(x) meanY = sc.mean(y) print(meanX) print(meanY) t = (meanY/meanX) print('t ',t) for i in x: yChange.append((i*t)+y[0]) print(yChange) print(y) plt.plot(x...
e411475aced374458ce3a826d6370ef6bd9f9817
abiraja2004/APL_PythonDeepLearning
/Lab3/Problem3/Problem3a.py
376
3.515625
4
import nltk nltk.download('wordnet') from nltk.stem import WordNetLemmatizer results = [] with open('textFile') as inputfile: for line in inputfile: results.append(line.strip().split(',')) print(results) sentence = 'cats are fat and going to the mall and eating stuff is awesome' lemmatizer = WordNetLem...
d7ad6abf4b2e3a35772c8e73020dd07e6e00c5e5
abiraja2004/APL_PythonDeepLearning
/IC7/Problem1.py
3,057
3.84375
4
# Extract the following web URL text using BeautifulSoup # https://en.wikipedia.org/wiki/Python_(programming_language) # 2.Save it in input.txt # 3.Applythe following on the text and show output: # Tokenization # Stemming # POS # Lemmatization # Trigram # Named Entity Recognition import nltk import requests import bs4...
f6b8082233895e0a78275d13d2ec29c14bc088cf
Ethan2957/p03.1
/multiple_count.py
822
4.1875
4
""" Problem: The function mult_count takes an integer n. It should count the number of multiples of 5, 7 and 11 between 1 and n (including n). Numbers such as 35 (a multiple of 5 and 7) should only be counted once. e.g. mult_count(20) = 7 (5, 10, 15, 20; 7, 14; 11) Tests: >>> mult_count(20)...
f072e50d9d1e1ff23b24be361133a471422a9119
tms-python/manuals
/patterns/SimpleFactory.py
1,442
3.9375
4
from abc import ABC, abstractmethod # Simple Factory class AbstractDoor(ABC): @abstractmethod def get_width(self): pass @abstractmethod def get_height(self): pass @abstractmethod def create_door(self, width: int, height: int): pass class WoodenDoor(AbstractDoor): ...
44805868e45cb2dbffb1a320ee1feda2bb7a0821
tms-python/manuals
/sms-gates-API/pswd.py
1,082
3.59375
4
import random char_collection = [ 'QWERTYUPASDFGHJKLZXCVBNM', 'qwertyuipasdfghjkzxcvbnm', '123456789', '!#$%', ] def generate_password(char_count): def select_random_char(el): return el[random.randrange(0, len(el))] return ''.join( [ ...
92708ac68a2a67c4a34f5e3770b2a9a92642f18a
brian15co/bokeh
/sphinx/source/docs/examples/line_server_animated.py
1,122
3.5
4
import time from bokeh.plotting import figure, output_server, cursession, show #prepare some data x = [1, 2, 3, 4, 5] y = [6, 7, 2, 4, 5] # output to static HTML file output_server("animated_line") # Plot a `line` renderer setting the color, line thickness, title, and legend value. p = figure(title="One Line") p.lin...
350987375fec0a27f33e0efce6eb7e407035e484
Kirill-Tamogashev/Data-Structures-and-Algorithms
/2. Data Structures/week2_priority_queues_and_disjoint_sets/2_job_queue/job_queue.py
1,102
3.75
4
import heapq class Worker: def __init__(self, id, finish=0): self.id = id self.finish = finish def __lt__(self, other): if self.finish == other.finish: return self.id < other.id return self.finish < other.finish def __gt__(self, other): if self.fi...
52e8dce19b334fb8cf24928d2af19544ccdeed06
johnlaudun/nltk_cli
/clean_np.py
2,071
3.703125
4
#!/usr/bin/env python3 -*- coding: utf-8 -*- """ This script takes an output from: python3 nltk_cli/senna.py --np test.txt > test.np And process the noun phrases to filter out phrases (i) that don't have the last word tagged as NN (ii) has any token that is a stopword (iii) the first and last word in phrase is...
f7f7a5f023f89594db74f69a1a2c3f5f34dfc881
gpallavi9790/PythonPrograms
/StringPrograms/5.SymmetricalString.py
241
4.25
4
#Prgram to check for symmetrical string mystr=input("Enter a string:") n=len(mystr) mid=n//2 firsthalf=mystr[0:mid] secondhalf=mystr[mid:n] if(firsthalf==secondhalf): print("Symmetrical String") else: print("Not a Symmetrical String")
57740b0f61740553b9963170e2dddc57c7b9858b
gpallavi9790/PythonPrograms
/StringPrograms/7.RemoveithCharacterFromString.py
400
4.25
4
#Prgram to remove i'th character from a string mystr="Pallavi Gupta" # Removing char at pos 3 # using replace, removes all occurences newstr = mystr.replace('l', '') print ("The string after removal of i'th character (all occurences): " + newstr) # Removing 1st occurrence of # if we wish to remove it. newstr = myst...
08b09c56959c65547ef2442691bb0793acf87351
gpallavi9790/PythonPrograms
/ControlStatements/2. Eligible for Voting.py
192
4.34375
4
#Program to check whether you are eligible for voting age=input("enter your age:") age=int(age) if(age>=18): print("You can vote") else: print("You can not vote") print("outside if")
05c59e2494495adc812a19cb536f7a98f7b987d2
aquaboom/PythonPrograms
/AdditionOfPositiveNumbersinAlist.py
194
3.984375
4
#Given a list [5,4,3,2,1,-1], compute the addition of all positive numbers in a list list1=[5,4,3,2,1,-1] total=0 for j in list1: if j<=0: break total+= j print(total)
b6a1fb737661d1f005755c21f6a3f7da7861c4f3
YDKDevelop/Past_Dates
/Dates.py
4,690
4.5
4
# # A class to represent calendar dates # class Date: """ A class that stores and manipulates dates that are represented by a day, month, and year. """ # The constructor for the Date class. def __init__(self, new_month, new_day, new_year): """ The constructor for objects of type Dat...
f6dc6108fb255b22fb182aef5f3902e2091c993d
Aadit017/workspace
/python_code/calculator.py
6,157
3.703125
4
from tkinter import * class Calculator: def __init__(self, title): self.title = title self.first_num = None self.current_operation = None self.in_result = False def clear(self): self.entry.delete(0, END) self.first_num = None self.current...
ede4c6f0b5e5e967e165d1b8a85108cde342e5d4
freedom741263313/python
/List.py
695
4.09375
4
# -*- coding: utf-8 -*- l = [1, 2, 3, 4, 5] print(l[1], l[2], l[4], l[-3]) l.append(6) print(l) l.insert(1, 8) print(l) l.pop() print(l) l.pop(1) print(l) l.insert(1, [11, 12]) Len = [] print(l, len(l), len(Len)) tuple = (1, 29, 0, 8) # tuple[0] = 10 # 错误 'tuple' object does not support item assignm...
faf51528984d7ff8593c26d0729ed158cce74993
hes-ron/UFFS_IA
/EXERCICIO_IA/gradient.py
1,508
3.734375
4
#Importing the numpy library import numpy as np #Function sigmoide def sigmoid(x): return 1/(1+np.exp(-x)) #Derivative of the sigmoid function def sigmoid_prime(x): return sigmoid(x) * (1 - sigmoid(x)) #Defaul values learnrate = 0.5 x = np.array([1, 2, 3, 4]) y = np.array(0.5) b = 0.5 # Initial weights ## ...
12585eb0c7b8df1c8374eac0ddb1d1196d8a4b65
JDPowell648/Code
/Data Structures/labs/lab12/lab12/test_dijkstra.py
636
3.828125
4
from graph import Graph from graph_algorithms import dijkstra def buildDigraph(graphFile): g = Graph() gfile = open(graphFile,'r') # add edges from the graph file # NOTE: vertices are added automatically if they don't exist for line in gfile: edgeInfo = line.strip().split() g.ad...
7065f6fbd153879d092272c947473a7bad2f4e48
JDPowell648/Code
/Intro to Computing/maximum.py
540
3.875
4
""" File" Maximum.py Author : CS 1510 Powell Description : Shows which of two scores earned a higher grade """ examOne = input("What was your score on the first exam? ") examTwo = input("What was your score on the second exam? ") scoreOne = int(examOne) scoreTwo = int(examTwo) if scoreOne>scoreTwo: print("Your s...
08b5e2af987f00b8ae01a91dbe22ab47ac9adac4
JDPowell648/Code
/Intro to Computing/countVowels.py
698
3.6875
4
""" Author: Joshua Powell File: countVowels.py Description: """ Text = str(input("Enter a string: ")) output = "" Length = len(Text) numA = 0 numE = 0 numI = 0 numO = 0 numU = 0 for index in range(Length): char = Text[index] if char == "a" or char == "A": numA = numA + 1 elif char == "e" or char =...
a03c2d919c36f3c391876d08342c0a68e95adb7c
JDPowell648/Code
/Data Structures/labs/lab8/timeMergeSort.py
626
3.890625
4
""" File: timeMergeSort.py Completed by: Mark Fienup<PUT YOUR NAME HERE> Description: Times the merge sort algorithm on random data""" import time import random from mergesort import mergeSort def main(): n = int(input("Enter the number of items you would like to sort: ")) myList = [] for index...
62b02e1c160d705291606fcd1f41791a37afbd27
JDPowell648/Code
/Data Structures/labs/lab2/lab2/timeStuff.py
2,911
3.671875
4
# timeStuff.py """Times various algorithms with different big-oh notation""" from time import perf_counter def main(): timingResults = [[],[],[],[],[],[],[]] for n in range(0,51, 10): # Algorithm 0 start = perf_counter() result = 0 for i in range(10000000): result ...
459fe07e46f31237416609caa63d136530a8f94e
JDPowell648/Code
/Intro to Computing/starLine.py
347
4.03125
4
""" Author: Joshua Powell Program: starLine.py Description: Prints a positive number os stars """ Num = int(input("Please enter a positive number: ")) NumPrint = 0 while Num <= 0: Num = int(input("Please enter a positive number: ")) print("Here is your art") while NumPrint < Num: NumPrint = NumPrint + 1 ...
06cf5e12ace0c583aba92eb6a14f08daad7a58a1
JDPowell648/Code
/Data Structures/labs/lab7/timeLinearlSearch.py
583
3.640625
4
# timeLinearSearch.py """Times the iterative sequential search repeatedly""" from time import perf_counter from linearSearch import linearSearch testSize = 10000 # Number of items to search consisting of evenList = list(range(0, 2*testSize, 2)) # even numbers from 0 to 2*(testSize-1) start...
950da52d6efd735fa99e5739dab91426fdffe7d7
JDPowell648/Code
/Intro to Computing/hw07.py
1,593
3.75
4
""" Author: Joshua Powell File: hw07.py Description: """ def findFirstVowel(word): """Finds the first vowel in a word""" vowelstr = "aeuio" newstr = "" char = "" word = word.lower() for loops in range(0,len(word)): char = word[loops] if char in vowelstr: return loops ...
feeba21614c92115d0fadb3ad326d427be74e026
JDPowell648/Code
/Data Structures/labs/lab9/lab9/timeBinarySearchTree.py
1,252
3.734375
4
# timeBinarySearchTree.py """Times the iterative binary search repeatedly""" from time import perf_counter from binary_search_tree import BinarySearchTree import sys import random def shuffle(myList): for fromIndex in range(len(myList)): toIndex = random.randint(0,len(myList)-1) temp = myList[from...
4b0ed5ddb4ebc7cfd6959b81ed3fba5c05d5eb4e
scorchio/pybites
/280/regex_lookahead_lookbehind.py
1,444
3.984375
4
import re def count_n_repetitions(text, n=1): """ Counts how often characters are followed by themselves for n times. text: UTF-8 compliant input text n: How often character should be repeated, defaults to 1 """ matches = re.findall(f'(.)(?=\\1{{{n}}})', text, flags=re.MULTILIN...
1c36065e21069f1a751dba1e40a350ad495821fd
scorchio/pybites
/259/reverse_complement.py
2,244
3.796875
4
import csv # See tests for a more comprehensive complementary table SIMPLE_COMPLEMENTS_STR = """#Reduced table with bases A, G, C, T Base Complementary Base A T T A G C C G """ def get_base_mapping(str_table): str_table_lines = str_table.split('\n') csv_lines = (row.strip() for row in str_...
902b5330f0b3756560eb96aa6cbec2d0937ebb05
vkate174/tasks
/vov12.py
259
3.75
4
import random a=random.uniform (-999,999) if a > 0: print(str(a) + "-" + "Положительное число") elif a<0: print(str(a) + "-" + "Отрицательное число") else: print(str(a) + "-" + "Число 0")
8bc854f0bea52a76252bd429964746c8038d057b
vkate174/tasks
/vov13.py
364
3.84375
4
import math D=10 print("(D) Диаметр поперечного сечения = " + str(D)) A=4 print("(A) Квадратный брус = " + str(A)) d=A * math.sqrt( 5) print("(d) Диагональ бруса = " str(d)) if D>= d: print(" Возможно выпилить") if D<d: print("Невозможно выпилить")
363ea1697760e936775bee8824545f7584b525ce
matthewmajo/Google_Coding_Challange
/google-code-sample/python/src/video_playlist.py
781
4.09375
4
"""A video playlist class.""" class Playlist: """A class used to represent a Playlist.""" def __init__(self): '''The playlist class is initialized''' self._playlist = Playlist self.playlist_name = [] self.in_playlist = [] def get_playlist_name(self): re...
f318db28ba83cbee21939757054ae64a69365185
Jessicammelo/cursoPython
/loop_for.py
1,394
4.0625
4
""" Loop for Loop: estrutura de repetição for: for item in interavel execução do loop """ """ nome = 'Jessica Melo' lista = [1, 3, 5, 7, 9] numero = range(1, 10) #temos que tranformar em uma lista #ex: for letra in nome: #iterando em uma string print(letra) #ex2 for numero in lista: #iterando sobre uma lista...
a8bdf0c4d3abbd4582c4149436a2abed7d48369b
Jessicammelo/cursoPython
/default.py
951
4.15625
4
""" Modulos colection - Default Dict https://docs.python.org/3/library/collections.html#collections.defaultdict # Recap Dicionarios dicionario = {'curso': 'Programação em Python: essencial' print(dicionario) print(dicionario['curso']) print(dicionario['outro']) #???KeyError Default Dict -> Ao criar um dicionario uti...
ac582b05af10382ea245887fae34f853cc48b3fe
Jessicammelo/cursoPython
/tipo_String.py
684
4.375
4
""" Tipo String Sempre que estiver entre aspas simples ou duplas ('4.2','2','jessica') """ """ nome = 'Jessica' print(nome) print(type(nome)) nome = "Gina's bar" print(nome) print(type(nome)) nome = 'jessica' print(nome.upper())#tudo maicusculo print(nome.lower())# tudo minusculo print(nome.split())#transfoma em uma l...
84dbde9af21ff55e79e696e14d53754929cdf550
Jessicammelo/cursoPython
/lambdas.py
1,826
4.90625
5
""" Utilizando Lambdas Conhecidas por expressões Lambdas, ou simplesmente Lambdas, são funções sem nome, ou seja, funções anonimas. #Função em Paython: def funcao(x): return 3 * x + 1 print(funcao(4)) print(funcao(7)) #Expressão Lambda lambda x: #Função em Paython: def funcao(x): return 3 * x + 1 print(fu...
a5a434260106a952466b5ef1eaa825496a053cc5
Yokeshthirumoorthi/Data-Validation
/crash_data_validation/reader.py
10,441
3.53125
4
#!/usr/bin/env python import pandas as pd pd.set_option('display.width', 200) pd.set_option('display.max_columns', 35) pd.set_option('display.max_rows', 200) # nrows : int, default None # nrows is the number of rows of file to read. Its useful for reading pieces of large files df = pd.read_csv('crashdata.csv', nrows=N...
74083c0af8e8d213acee08b39ea1af57488ccd74
johnhjernestam/John_Hjernestam_TE19C
/Laxa Funktioner/uppgift3a.py
120
3.515625
4
import math def avstånd(): avstånd = math.sqrt(5**2 + 2**2) return avstånd s = avstånd() print(f"{s:.3f}")
65c9f4e7710bfc19f1943edc40b799dc0e919d3c
johnhjernestam/John_Hjernestam_TE19C
/Laxa2/ifsats2.py
175
3.71875
4
tal = float(input("Ange ett heltal: ")) if tal%2 == 0: print("Talet är jämnt") if tal%5 == 0: print("Talet är delbart med fem") else: print("Talet är udda")
1e6eed4ebfbedfaa608620fb597b099e74e9bb83
johnhjernestam/John_Hjernestam_TE19C
/Programmeringslaboration/Uppgift 2/duppgift.py
874
3.8125
4
n = 0 # N är en vanlig variabel som används för ett samlingsnamn på nummer/tal burr = float(input("Ange multipel till burr: ")) # Input används för att en användare ska # kunna välja vilken multipel som den vill. birr = float(input("Ange multipel till birr: ")) # En mul...
f83165b3b4b8c2f427e4e032f7ec70ee2b66fe7a
johnhjernestam/John_Hjernestam_TE19C
/Laxa Funktioner/uppgift2,1.py
107
3.71875
4
n = int(input("Mata in ett tal: ")) def talet(n): talet = 2*n + 1 return talet print(talet(n))
d0a98bd3e6f49df1d40088b6c6289595db5431c8
johnhjernestam/John_Hjernestam_TE19C
/introkod_syntax/Räkna med Python/celsius.py
106
3.5625
4
C = float(input("Ange tempraturen i celsius: ")) K = C + 273.15 print(f"{C}Celsius är {K:.0f} Kelvin ")
304746f4a2fdd3835cb837a37de4e86a402079e4
johnhjernestam/John_Hjernestam_TE19C
/Felhantering/annat.py
170
3.65625
4
#while True: #ålder = float(input("Hur gammal är du?")) #asert ålder >= and ålder < 125, "Din ålder ska vara mellan 0 och 124" #break #except
56287e1a11a9ca1f738c47158386c475b405b985
johnhjernestam/John_Hjernestam_TE19C
/Inför prov/ifsatser.py
174
3.9375
4
x = float(input("Skriv ett värde för x: ")) y = float(input("Skriv ett värde för y: ")) if 3*x + 5 == y: print("På linjen!") else: print("Inte på linjen!")
f47f69de9366760f05fda6dd697ce2301ad38e01
johnhjernestam/John_Hjernestam_TE19C
/introkod_syntax/Annat/exclusiveclub.py
453
4.125
4
age = int(input('How old are you? ')) if age < 18: print('You are too young.') if age > 30: print('You are too old.') if age >= 18: answer = input('Have you had anything to drink today or taken something? Yes or no: ') if answer == "no": print('You got to be turned up') else: prin...
f32cffafffab113aeb3cb17cb50ad5d533d8007a
johnhjernestam/John_Hjernestam_TE19C
/Laxa3/inteklaraforsatser.py
421
3.671875
4
#s = 0 #for i in range(1,10,2): #s += i #print(s, end =" ") #for l in range(50,101): #print(150-l, end =" ") #lower = 1 #upper = 100 #print("Prime numbers between", lower, "and", upper, "are:") #for num in range(lower, upper + 1): #if num > 0: #for i in range(2, num): #if (num...
558aa5e7a11a7abf058984398388046c1c1b2fc7
johnhjernestam/John_Hjernestam_TE19C
/Numpy & Matplotlib/codealong.py
226
3.828125
4
import numpy as np array1 = np.array([1,2,3,4,5,6,7,8,9]) print(array1[0]) print(array1[-1]) print(array1[1:4]) # slicing, skivoperatorn lista = [1,2,3,4] print(lista*2) print(array1*2) # varje element multipliceras med 2
84e235162ba717f4df2dcb686888f18dfc81d08e
yellowmarlboro/leetcode-practice
/s_python/056_merge_intervals.py
877
4
4
""" 56. 合并区间 给出一个区间的集合,请合并所有重叠的区间。 示例 1: 输入: intervals = [[1,3],[2,6],[8,10],[15,18]] 输出: [[1,6],[8,10],[15,18]] 解释: 区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6]. 示例 2: 输入: intervals = [[1,4],[4,5]] 输出: [[1,5]] 解释: 区间 [1,4] 和 [4,5] 可被视为重叠区间。 注意:输入类型已于2019年4月15日更改。 请重置默认代码定义以获取新方法签名。 提示: intervals[i][0] <= intervals[i][1] """ f...
6f4bffc558976c6d4b5950a2faf3705a211ce64a
WesleyCastilho/CodeSignalChallenges
/arrays/first_duplicate/first_duplicate.py
220
3.734375
4
class FirstDuplicate: def first_duplicate(self): my_set = set() for element in self: if element in my_set: return element my_set.add(element) return -1
f97b2b20923ea2e2d80c792380c03d38095cb645
isaacto/sufarray
/sufarray/__init__.py
10,261
3.953125
4
"""Sufarray: implementation of suffix array While the performance is reasonable for smaller strings, it is quite slow for long strings (e.g., of 100k in length). Due to the limitations of Python data structures, it is better to find C implementations for such usages (not yet provided here). """ import array import ...
b5b3c2bcb6721b5f9de4b84922b85cf7af44a30e
madsnk/deep-masking
/Stanford Exercises/Exercise 2/cs231n/layers.py
17,028
3.578125
4
import numpy as np def affine_forward(x, w, b): """ Computes the forward pass for an affine (fully-connected) layer. The input x has shape (N, d_1, ..., d_k) where x[i] is the ith input. We multiply this against a weight matrix of shape (D, M) where D = \prod_i d_i Inputs: x - Input data, of shape (N, ...
396d8403fb82b6c4b6f698b5998d0b57f89071fb
felhix/cours-python
/semaine-1/07-boolean.py
2,963
4.1875
4
#! python3 # 07-boolean.py - quelques booléens, opérateurs, et comparateurs # Voici quelques comparateurs print(1 == 1) #=> True, car 1 est égal à 1 print(1 == "1") #=> False, car 1 est un integer, et "1" est un string print("Hello" == "Bonjour") #=> False, car ces 2 strings sont différents print("1" == "...
d74dc6e4b81233d7e3e1d801c0e8be3f5bcc590c
felhix/cours-python
/semaine-1/04-data-types.py
1,208
3.90625
4
#! python3 # 04-data-types.py - montre les trois premiers types de données #Voici quelques integer, ou entier relatifs integer_1 = 1 integer_2 = 0 #un relatif peut être égal à 0 integer_3 = 4 integer_4 = -12 #un relatif peut être négatif integer_5 = 1 + 5 #il est possible d'effectuer des opérations dessus #Il y a...
230e1d2846f4b608c3f541d5d089655ca97f9efe
kmrsimkhada/Python_Basics
/loop/while_with_endingCriteria.py
968
4.25
4
#While-structure with ending criteria ''' The second exercise tries to elaborates on the first task. The idea is to create an iteration where the user is able to define when the loop ends by testing the input which the user gave. Create a program which, for every loop, prompts the user for input, and then prints it...
e1dca0956dc0547a3090e508787df989034b0eaf
kmrsimkhada/Python_Basics
/type_conversion.py
702
4.5
4
#Type Conversions ''' In this exercise the aim is to try out different datatypes. Start by defining two variables, and assign the first variable the float value 10.6411. The second variable gets a string "Stringline!" as a value. Convert the first variable to an integer, and multiply the variable with the string by...
26a5ce912495c032939b4b912868374a6d8f83c7
kmrsimkhada/Python_Basics
/lists/using_the_list.py
2,397
4.84375
5
#Using the list ''' n the second exercise the idea is to create a small grocery shopping list with the list datastructure. In short, create a program that allows the user to (1) add products to the list, (2) remove items and (3) print the list and quit. If the user adds something to the list, the program asks "What...
102f103897fc2ae6d40fbc4e14655dd39f617ddd
DzianisOrpik/Python_Material
/itproger/cicle/list_2.py
213
3.59375
4
l = [] lis = [1, 23, 34, 45, 56, 65, 'Hello Worls', ['Hello MEN']] print (lis) l.append(23) l.append(34) b = [2, 3, 4] l.extend(b) l.insert(2, 222) l.pop() print (l.index(34)) l.count(23) l.sort() print (l)
757433eb5430f06a7c80f3cf09822c73106435cc
DzianisOrpik/Python_Material
/itproger/cicle/Dictionary_module10_python.py
201
3.578125
4
d = dict.fromkeys(['a'], 2) print (d) ivan = {'name': {'last name': 'Orpik', 'first name': 'Denis', 'mid_name': 'Yurevich'}, 'address': {'16 E Old Willow rd'}} print (ivan ['name'] ['last name'])
793b48880dd96e19370323be3ec371426721179d
dylanbud/lambdata-dylanbud
/helper_functions.py
382
3.9375
4
import pandas as pd import numpy as np def null_count(df): '''Counts the number of null values across the entire dataframe''' return df.isnull().sum().sum() def list_2_series(list_2_series, df): '''Takes a list and dataframe then turns the list into a series and adds it to the inputted datafra...
d1dc947b73715083ba2802ff4120e9272b184c25
egarci28/ITSC3155_spring2021_egarci28
/PythonBasics2/pythonBasics2.py
4,738
4.28125
4
# Python Activity # # Fill in the code for the functions below. # The starter code for each function includes a 'return' # which is just a placeholder for your code. Make sure to add what is going to be returned. # Part A. count_threes # Define a function count_threes(n) that takes an int and # returns the number of ...
e456156065f024942234ad9aad7d8c48b4f3c1d6
kim-seungtae/algorithm
/String/leetcode_166.py
1,139
3.546875
4
class Solution: def fractionToDecimal(self, numerator: int, denominator: int) -> str: if numerator == 0: return "0" ans = "" if numerator * denominator < 0: ans += "-" numerator = abs(numerator) denominator = abs(denominator) quotient,...
62dc2654366a4e4eaa6be4510e645ff506ce283c
ranjanghate/DataScience
/Python/functions.py
554
3.8125
4
#basic def greet(name): print("Hello!",name) greet("Ranjan") #two arguments def greet(name , msg ) : print("Hello!",name,",",msg) greet("Ranjan" , "kya kr rha h ?") #default arguments def greet(name , msg="Ohaio"): print("Hello!",name,",",msg) greet("Ranjan","Itadakimasu") greet("Ranjan") #key...
0b03c322547ca62270a2de94c54063d2c0108a72
ranjanghate/DataScience
/Python/conversion.py
373
3.75
4
#implicit conversion int1 = 55 float1=55.55 sum = int1 + float1 print(sum) #explicit conversion float2 = 1.75 int2 = int(float2) print(int2) #string to int string = '555' int3 = int(string) float3=float(string) print(int3,float3) #int/float to string int4=55 float4=55.55 string1=str(int4) string2=str(float4) pr...
f5f92eb2084f154d2a3537edc7d847b0eed79c75
Hazy-Sunshine/json_xml_convert
/json_xml_convert.py
1,119
3.5625
4
#!/usr/bin/env python # -*- encoding:utf-8 -*- import xmltodict import json import sys def pythonConversionXml2Json(pa): """ demo Python conversion between xml and json """ # 1.Xml to Json f = open(pa) xml_str = f.read() reload(sys) sys.setdefaultencoding('utf-8') converted_d...
299fa811b19622f3654f82c2368a6decb2c6210f
lskyo/Python
/OOP/classAndInstence.py
2,718
3.90625
4
import types class Student(object): pass print(Student) print(Student()) class Student(object): def __init__(self, name, score): self.name = name self.score = score def print_score(self): print(self.name, ':', self.score) def get_grade(self): if self.score >= 90: ...
7f5c6f2d50a5e149bd465dc894fb7f90f41a7219
suhanapradhan/IW-Python
/data types/37.py
95
3.65625
4
a = {'a':1, 'b':90, 'c':100} result = 0 for key in a: result= result+ a[key] print(result)
9da42650192b8bd125159ab8c7d8092db57d1d6f
suhanapradhan/IW-Python
/data types/25.py
109
3.5625
4
list = [1, 2, 3, 4] string = 'emp' for i in range(len(list)): list[i] = string + str(list[i]) print(list)
8a49bad35b7b1877abf081adc13ed6b9b63d0de8
suhanapradhan/IW-Python
/functions/6.py
319
4.28125
4
string = input("enter anything consisting of uppercase and lowercase") def count_case(string): x = 0 y = 0 for i in string: if i.isupper(): x += 1 else: y += 1 print('Upper case count: %s' % str(x)) print('Lower case count: %s' % str(y)) count_case(string)
17277f064637629bc2e5f86b572133fc01125381
pjarnhus/SkillTrainer
/tag_finder.py
1,101
3.703125
4
"""Utility functions for searching the tag table.""" import pandas as pd def find_children(start_tag, tag_table): """ Find all leaf nodes below start_tag in the tag_table. Search from the start tag and down through the tag tree, until ending up at children that have no children of their own. Return t...
5de5e40962e64315c754a0e74cee0bba2d804974
ibayun/simple-site
/some_data/authors.py
600
3.65625
4
# nickname, email, password, first_name, last_name import csv def read_file(name_file): with open(f"{name_file}") as file: contain = [line.rstrip().strip(" ") for line in file.readlines()] return contain first_name = read_file("first_name.txt") last_name = read_file("last_name.txt") email = read...
35a98e4bf5b1abcd7d6dd9c6ff64d53d07f8788e
BinyaminCohen/MoreCodeQuestions
/ex2.py
2,795
4.1875
4
def sum_list(items): """returns the sum of items in a list. Assumes the list contains numeric values. An empty list returns 0""" sum = 0 if not items: # this is one way to check if list is empty we have more like if items is None or if items is [] return 0 else: for x in items: ...
992ba82edabd6425e4bc8fe33ee3fede8d0b1a22
Abdelaziz-pixel/Beginner-POO-Python
/Exo3/book.py
259
3.6875
4
""" Exercices 3 """ class Book(): def __init__(self,**parametre): self.title=parametre["title"] self.pages=parametre["pages"] def __str__(self): return "Title: {0}, Pages:\n {1}".format(self.title,self.pages)
a2c141cd2574e015a60f8b5255119e40ed6cb9f6
justinhchae/pandas_project
/do_mods/modify_columns.py
599
3.8125
4
import pandas as pd class ModifyColumns(): def __init__(self): pass def parse_cols(self, df): """ :params df: a data frame :args: replaces col headers with lower case and removes spaces :returns a df with modified columns """ print('------ Parsing column...
02ea340a8364c02bd711f5159968297595f1b6b2
AoifeFahy/twitter-data
/main.py
870
3.640625
4
import requests import json def get_tweets_by_word(word, bearer_token): url = 'https://api.twitter.com/1.1/search/tweets.json' param = {'q': word, 'count': 100, 'result_type': 'recent'} header = {'Authorization': f'Bearer {bearer_token}'} response = requests.get(url, headers=header, params=param) ...
d261e789f04941d36152d02025a65dda90c22ed6
cseu2bw/CS-Build-Week-2
/BackEnd/src/util.py
608
3.734375
4
class Queue: def __init__(self): self.storage = list() def enqueue(self, value): self.storage.append(value) def dequeue(self): if self.len() > 0: return self.storage.pop(0) else: return None def len(self): return len(self.storage) def __len__(self): return self.le...
bd46fd4ce8f4e268c9eb16d84dd1f71f68d04d79
Opportunity-Hack-San-Jose-2017/Team7
/platobot/platobot/workers/pool.py
2,389
3.671875
4
import multiprocessing # Item pushed on the work queue to tell the worker threads to terminate SENTINEL = "QUIT" def is_sentinel(obj): """Predicate to determine whether an item from the queue is the signal to stop""" return type(obj) is str and obj == SENTINEL class PoolWorker(multiprocessing.Process):...
8e61e690c324a798f54c269a953f9ead0c769258
qiuzhuangshandian/haienNote
/huawei/test1.py
392
3.59375
4
import sys if __name__=="__main__": strs = sys.stdin.readline().strip() cs = list(strs) new_cs = [] for c in cs: if ord(c)>=ord('a') and ord(c)<=ord('z'): new_cs.append(c.upper()) elif ord(c)>=ord('A') and ord(c)<=ord('Z'): new_cs.append(c.lower()) ...
31596af21acd4c609ce76fa90d8ca0e8a3d43a4b
stubear66/600X
/FingerExercises/finger2.2.py
248
3.609375
4
L = [ 51, 19, 3] myMax = 0 for x in L : if x % 2 == 1 : print myMax if x > myMax: print "Setting myMax to ", x myMax = x if myMax > 0: print "Largest odd is ", myMax else: print "No odds"
2810c4706cdc694781252f7a6f978e65ff08c002
stubear66/600X
/FingerExercises/finger6.1.1.py
2,830
3.90625
4
def thisRaisesAZeroDivisionError(): x = 1/0 def thisRaisesAValueError(): y = int('Five') def thisDoesNotRaiseAnyErrors(): z = 'just a string' def tryExercise(): print 'A', try: # Line Of Code Is Inserted Here # return print 'B', except ZeroDivisionError as e: p...
45db01a4c78d90ac3dad47d5b13476d38805508c
T3HPYTHONE/2009E
/src/what_is_your_name_version_2.py
119
3.640625
4
a = input("Nhap ten cua ban: ") b = input("Nhap ho cua ban: ") print(f"Hello {a} {b}! You just delved into python.")
7f75954459ed4f9d66b2a700a8daef4bf46f6601
T3HPYTHONE/2009E
/src/prime_number_version_2.py
292
3.796875
4
""" @created: Nguyen Anh Tien @Desc: prime number """ number = int(input("Enter a number: ")) flag = True for index in range(2, number): if number % index == 0: flag = False if flag == True: print(f"{number} la so nguyen to") else: print(f"{number} khong phai la so nguyen to")
973fa4b433370add1476caad1b78ea93a221b1dd
akikob2/School-Programs
/matrix.py
1,146
3.890625
4
# create the two dimensional matrix m # 4 rows, 5 columns, 1 through 20 def sumRows(matrix): #Sums up the rows numRows = len(matrix) numCols = len(matrix[0]) sums = [] for row in range(numRows): rowSum = sum(matrix[row]) sums.append(rowSum) return sums def sum...
296af18543031c0b040f84cc404ef32afa2a8832
PrakharKopergaonkar/LeetCode-July-Challenge
/Week2/Flatten_list.py
1,190
4.0625
4
# Question 10 : Flatten a Multilevel Doubly Linked List """ # Definition for a Node. class Node: def __init__(self, val, prev, next, child): self.val = val self.prev = prev self.next = next self.child = child """ class Solution: def flatten(self, head: 'Node') -> 'Node': ...
e1eec369b52080a3bf5600cc67daa7be146ec48f
PrakharKopergaonkar/LeetCode-July-Challenge
/Week4/Single_Number3.py
468
3.625
4
#Question 3 : Single Number 3 class Solution: def singleNumber(self, nums: List[int]) -> List[int]: x_or = 0 output_list = [0]*2 for i in range(0,len(nums)): x_or = x_or ^ nums[i] bitflag = x_or & ~ ((x_or - 1)) for i in nums: if(i & bitflag ...
9061e3d8ab89555c0d0c336a84e08fbd99e638d5
RahulB98/Practice_Projects
/Tkinter lessons/Random_winner.py
634
3.796875
4
from tkinter import * import random root = Tk() root.title("Random Winner Genertaor") root.iconbitmap("C:/Users/messi/Downloads/favicon.ico") root.geometry("400x400") entries = ['Balbir', 'Sunita', 'Rahul', 'Riya'] def pick(entries): entries = set(entries) entries = list(entries) winner = random.choice(en...
f4027ef86badec7509e5d921d43441d45423cd98
RahulB98/Practice_Projects
/Tkinter lessons/pathplot.py
601
3.796875
4
import numpy as np import matplotlib.pyplot as plt import random n = int(input("Enter the number of steps you wish to generate")) x = np.zeros(n) y = np.zeros(n) for i in range(1,n): val = random.choice(['N', 'S', 'E', 'W']) if val == 'E': x[i] = x[i - 1] + 1 y[i] = y[i - 1] elif val == 'W...
10a994c4da8f4ed7b1cc40c823b0c0c4c3c4092c
RahulB98/Practice_Projects
/Tkinter lessons/dbMANAGE.py
7,539
3.59375
4
from tkinter import * from PIL import ImageTk, Image import sqlite3 root = Tk() root.title("Database") root.iconbitmap("C:/Users/messi/Downloads/favicon.ico") root.geometry("400x400") #Database #create a database or open conn = sqlite3.connect('address_book.db') #create cursor cur = conn.cursor() #create table cur.e...
8dea44863da9360e234c4bdce0c93ecc4a5d07e3
yoshimi-isozaki/Map-knowledge
/Park-knowledge/park_test03.py
4,609
3.71875
4
""" 2021/02/25 15:50 磯嵜佳果 https://www.geocoding.jp/ から経緯度を取得してgooglemapに移動して候補があれば 一番上をクリックしてそのページをクリックする。 csvから得られた『公園名』と照合することで確かさを得る。 """ from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.com...
a9cb243ebc4a52d46e6d214a17e011c293cde3ff
s16323/MyPythonTutorial1
/EnumerateFormatBreak.py
1,464
4.34375
4
fruits = ["apple", "orange", "pear", "banana", "apple"] for i, fruit in enumerate(fruits): print(i, fruit) print("--------------Enumerate---------------") # Enumerate - adds counter to an iterable and returns it # reach 3 fruit and omit the rest using 'enumerate' (iterator) for i, fruit in enumerate(fruits): ...
6e695248df26057643aff8c3dc3d6b0b34c064de
s16323/MyPythonTutorial1
/Functions.py
760
3.65625
4
# funkcje: # def - define # nazwy funkcji nie mogą zaczynać się od liczby, mogą mieć podkreślnik # wyświetl wpisaną liczbę: # def printujTo(liczba): # print("Test:", end = "") # end = "" powoduje, że print() nie łamie linii # print(liczba) # # printujTo(int(input())) # pomnóż: def pomnoz(a, b): return ...
d51b4e8230def2eac49d1505656a5f943d162efc
ricardofelixmont/Udacity-Fundamentos-IA-ML
/zip-function/zip.py
556
4.46875
4
# ZIP FUNCTION # zip é um iterador built-in Python. Passamos iteraveis e ele os une em uma estrutura só nomes = ['Lucas', 'Ewerton', 'Rafael'] idades = [25, 30, 24] nomes_idades = zip(nomes, idades) print(nomes_idades) # Mostra o objeto do tipo zip() #como zip() é um iterador, precisamos iterar sobre ele para mostrar ...
ddd38b71aa661f2c619a9d446adc28bf927e4c89
ricardofelixmont/Udacity-Fundamentos-IA-ML
/lambda-map-filter-reduce/dicionario.py
489
4.09375
4
dicionario = {'Ricardo':25, 'Renata': 24, 'Érika':24, 'Rafael':23, 'Eliane':40} print(dicionario.items()) # items() retorna uma lista de tuplas com chave valor lista_de_compreensao = [chave for chave,valor in dicionario.items() if valor < 40] print(lista_de_compreensao) # Posso usar uma lista de compreensão dentro d...