blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
60adfc350c8822bee32b05fe2703c096473a0fb7
pranjalparmar/Learn-Python
/learn/prime.py
199
4.0625
4
a = int(input("Enter the number you want to check for = ")) for i in range(2,a/2): if a % i == 0: print("Is not a prime number") break else: print("is a prime number")
82bcaf23f95b7c45146b96daac15652a6ac7dd87
pranjalparmar/Learn-Python
/HackerEarth Solutions/Doctor's Secret.py
145
3.5625
4
a,b = input().split() if int(a) <= 23 and int(b)<=1000 and int(b) > 500: print("Take Medicine") else: print("Don't take Medicine")
9ec0c34cb6bb41abd5a9e2c5e6ec33168820f98f
pranjalparmar/Learn-Python
/learn/araynupy.py
474
3.625
4
from numpy import * # arr = array([1,2,3,4,5,6]) # # #Using of linspace() # # arr1 = linspace(1,15,20) # #range goes from 1 to 15 aand divides it into 20 parts # # arr2 = logspace(1,15,16) # # arr3 = arange(1,15,2) # # print(arr3) arr1 = array([ [1,5,3], [5,6,3], ...
7d46e0aa7f46ab84ca2cf97a92c75e8445f55c84
rahulbarate/rahul_barate_bluepineapple_assignment
/wordfrequency.py
180
3.875
4
wordList = input("Enter something : ").split(" ") freq = {} for word in wordList: if word in freq.keys(): freq[word] += 1 else: freq[word] = 1 print(freq)
cab2a41acab19a785b68e9b39b5b3fa4f93eacdb
noverzero/python_sandbox
/python_sandbox_starter/tuples_sets.py
1,126
4.34375
4
# A Tuple is a collection which is ordered and unchangeable. Allows duplicate members. #create a tuple literal fruits = ('apples', 'oranges', 'grapes') #create a tuple using a contsructor fruits2 = tuple(('apples', 'oranges', 'grapes')) print('fruits: ', fruits, 'fruits2: ', fruits2) #tuple with only 1 value needs ...
db9b815aa1118dc1da38996ead6dd6f47b4fddf0
ismailkol/python
/Python/PYTHON BASIC CODE/Lesson_2.py
367
4.125
4
print('Ismail Kol') print("Ismail Kol") ilk="Ismail" son="Kol" """stringlerde sadece toplama ve carpma edılır burda carpma ıkı strıng carpması olmaz sadece tek bır strıngın ınt bır sayı ıle carpabılırız float bır sayı ıle carpmamız hatayan sebeb olacaktır""" print(ilk + son) print(ilk *3) print(ilk+ilk+ilk) print(s...
e83dcb167ca899f162703334160a1a1ced8c3e93
Aingty/CECS-328-Data-Algorithms
/Binary-Search-Tree/BTSNodeClass.py
1,026
4.15625
4
class Node(object): """ Custom Node class to be use with Binary Search Tree class. """ def __init__(self,value): """ Constructer for Node class with initial value of *value*. """ self.value = value self.leftChild = null self.rightChild = null def set...
12f2fa20c30442a2652642191e758ebccee4cd7e
mintchatzis/Algorithms_from_scratch
/Data_Structures_in_Python/Linked_List/node.py
3,421
4.09375
4
class Node(): '''Class representing a Node of a LinkedList''' def __init__(self,data = None, next = None): self.data = data self.next = next def __str__(self): return str(self.data) def __eq__(self,other): if type(self) != type(other): return Fal...
c89d7b14c0f75776d9b63f9a4b0a83ac79483fad
mintchatzis/Algorithms_from_scratch
/notes.py
152
4.09375
4
import re my_str = "We are taking the hobbits to Isengard" regex = r'[a-z]' matches = re.findall(regex,my_str) for match in matches: print(match)
6477ad280490002ef82424d778c87feb9bfa8842
yashmallik/hr-solutions
/math/hand shake.py
626
3.5625
4
At the annual meeting of Board of Directors of Acme Inc. If everyone attending shakes hands exactly one time with every other attendee, how many handshakes are there? Function Description Complete the handshakes function in the editor below. handshakes has the following parameter: int n: the number of attendees ...
b835a0a9882db087a0bf4b9949629a780a89b287
AVBelyy/LisiyNos
/29.10-03.11.2012/Intellect/Day1/fiblong.py
316
3.5
4
import math sqrt5 = math.sqrt(5) F1 = lambda n: int(round((((1+sqrt5)/2)**n-((1-sqrt5)/2)**n)/sqrt5)) def F2(n): F = [0]*(n+2) F[0] = 0 F[1] = 1 for x in xrange(2,n+1): F[x] = F[x-1]+F[x-2] return F[n] n = int(open("fiblong.in").readline()) open("fiblong.out", "w").write(str(F2(n)))
ae88374d03501a4e4e5e3c8995cf5889730a9476
psykidellic/sandbox
/airavat/albumSimilarities.py
1,029
3.59375
4
#-*-coding: utf-8 -*- ''' Given a dataset of albums and genres, how can we compute the similarity between pairs of movies? ''' from mrjob.job import MRJob from itertools import combinations class AlbumsSimilarities(MRJob): # OUTPUT_PROTOCOL = SemicolonValueProtocol def steps(self): return [ ...
672c17b3745bc238980c264355e24485a700f62e
harsh-vish14/python-codes
/college start/patterns/pattern_8.py
611
3.515625
4
def create(n): counter = 0 for i in range(1,n+4): if(i%2 == 0): continue print(' '*(n+4-i),end="") nextLoop = list(range(i)) for j in nextLoop: if(j == i-1 or j == 0): print(' *',end="") else: centerElement = nex...
76e90ed34418ed0ffde15d9dc6eda0cbacc0133f
harsh-vish14/python-codes
/college start/patterns/pattern_9.py
511
3.90625
4
def Fibonacci(n): if n < 0: print("Incorrect input") elif n == 0: return 0 elif n == 1 or n == 2: return 1 else: return Fibonacci(n - 1) + Fibonacci(n - 2) def create(n): counter = 0 for i in range(1, n + 1): print('\t' * (n + 1 - i), end="") for...
d8990467fd79cf98d6259a7049fa35829e1d2456
ogol254/M-1
/if.py
109
3.5
4
#if else statement distance = 121 if (distance == 100) : print("The jouney was long") :
56a3f94aa8404fb858229c36826fd5f14225de05
angelgris1789/UTN_nivel_avanzado_trabajofinal_tkinter
/observer.py
718
3.515625
4
class Tema: # gestion de observadores observadores = [] def agregar(self, obj): self.observadores.append(obj) def quitar(self, obj): pass def notificar(self, codigo, accion): print("hola desde notificar") for observador in self.observadores: if accion == "...
8c437584150db8b5ebaa2cff69ae94c62333ccb9
mayank6/leetcode
/middlelinklist.py
1,083
3.96875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def middleNode(self, head): """ :type head: ListNode :rtype: ListNode """ current,last=head,head.next ...
7ae8b9e81472939cd1c4cb3360e1880516d328c8
taeyoung02/argorithm
/strassen/strassen_multi.py
107
3.578125
4
def main(): num1 = int(input()) num2 = int(input()) sum = num1 + num2 print(sum) main()
4ea3f2fb223af1984bd281d0defccfcc14164845
zarkle/desktop-database
/multi_widget_gui.py
793
3.6875
4
from tkinter import * def convert(): kg = int(entry_val.get()) gram = kg * 1000 pound = kg * 2.20462 ounce = kg * 35.274 # t1.delete("1.0", END) -- in solution code but not necessary t1.insert(END, gram) # t2.delete("1.0", END) t2.insert(END, pound) # t3.delete("1.0", END) t3.insert(END, ounce) ...
2b34f06f9ddc3a1e703eac5ece70735a2b026c11
Quickmotions/Encryption-Program
/EncryptModule.py
1,695
4.15625
4
def generate_key(file_name): from cryptography.fernet import Fernet key = Fernet.generate_key() with open(file_name, "wb") as key_file: key_file.write(key) return key def encrypt_message(data, key): from cryptography.fernet import Fernet f = Fernet(key) encrypted_message = f.encryp...
ece02cea01d727537b27a57f8aa384f947b57d52
Alich13/Mithocondrial-assembly
/minimusCicleFinder_v4.5.py
5,541
3.765625
4
#!/usr/bin/env python #-*- coding: UTF-8 -*- from __future__ import division import sys import subprocess import os import argparse def fasta2dict(file): """ This fuction screens a fasta file and stock the information within a dictionary """ #--Variables fasta = {} seq = "" #-- We scre...
926a6ba3f48ec8391797f3f62f3821aba15a66aa
dbravender/python-constraint
/examples/sudoku/sudoku.py
2,133
3.671875
4
# # Sudoku puzzle solver by by Luigi Poderico (www.poderico.it). # from constraint import * problem = Problem() # Define the variables: 9 rows of 9 variables rangin in 1...9 for i in range(1, 10) : problem.addVariables(range(i*10+1, i*10+10), range(1, 10)) # Each row has different values for i in range(1, 10) : ...
c32d38106ff5531057480850fdd0f67442b1d68e
durenmc/Study
/Test/Day6/Day6-Practice.py
629
3.796875
4
#!/usr/bin/env python # -*- coding:utf-8 -*- class Restaurant(): def __init__(self,name,type): self.name = name self.type = type def describe_restaurant(self): print("name:"+self.name+","+"type:"+self.type) def open_restaurant(self): print("open") class IceCreamStand(Resta...
fa87b9520da8d4360ec6b57fd40b2128fee9c953
durenmc/Study
/Test/Day7/pi_string.py
635
4.03125
4
#!/usr/bin/env python # -*- coding:utf-8 -*- #使用文件的内容 filename = 'pi_digits.txt' with open(filename) as file_object: lines = file_object.readlines() pi_string = '' for line in lines: pi_string += line.strip()#删除空格 print(pi_string) print(len(pi_string)) #大型文件 filename = 'pi_million_digits.txt' with open(fil...
989c327bf69e0e4c870aea3f874b6d9c06483847
liada1993/mat1
/equations.py
1,615
4.125
4
def exponent(x:float): if x<0: y=1 x=x*-1 else: y=0 counter=1 stage_1=1 stage_2=1 sum=0 while True: stage_1=stage_1*x stage_2=stage_2*counter stage_3=stage_1/stage_2 sum=sum+stage_3 counter=counter+1 if stage_3...
bdd427f1157fa39d2550ed060fa886a3b948a239
Stx666Michael/alien_invasion
/bullet.py
2,223
3.5625
4
import pygame from pygame.sprite import Sprite class Bullet(Sprite): def __init__(self,ai_settings,screen,ship): super().__init__() self.screen = screen self.ai_settings = ai_settings self.image = pygame.image.load('images/love1.png') self.rect = self.image...
57a680cd897ba5f4015322651f790574f32ddad6
ArturoMarquez48/Mision-03
/rendimiento.py
1,713
3.8125
4
#Autor: Arturo Márquez Olivar. A01376086 #Calcula el rendimiento de un auto. #Esta función calcula el rendimiento en km/lt. def calcularRendimientoKm(kilometrosRecorridos, gasolinaUsada): rendimientoKm= kilometrosRecorridos / gasolinaUsada return rendimientoKm #Esta función calcula el rendimiento en mi/ga...
c251e4d2bfe2c6d6a1e66b1809180b55ee95ea9a
Daransoto/holbertonschool-interview
/0x00-lockboxes/0-lockboxes.py
599
3.5625
4
#!/usr/bin/python3 """ This module contains the function canUnlockAll. """ def canUnlockAll(boxes): """ Function that checks if all boxes can be unlocked. """ boxes_amount = len(boxes) if boxes_amount <= 1: return True locked = set([box for box in range(1, boxes_amount)]) current_k...
2971f3035329abf35a4d03af05bc272c161f25f6
qumino2/nltk_exercises
/chapter2/chapter2_10_howmanywordstypes_accountfor_a_third_of_diy.py
556
3.515625
4
import nltk from nltk.book import* from __future__ import division def percentage(word, text): return 100*([word for word in text ].count(word))/len(text) fdist4 = nltk.FreqDist([word.lower() for word in text4 if word.isalpha()]) vocabulary4_tuples = fdist4.items() vocabulary4_tuples = sorted(vocabulary4_tuples, key...
e579c8e31f607e241b049bbfd79f85a0c6f7c5f7
yizhiyan1992/Graph
/BFS.py
1,334
4.03125
4
import queue #use Breadth First Search to find the shortest path for unweighted graph # Basic idea: use queue to store each node, pop one element each time, and detect if connected nodes are visited already or not # If not visit, push element, assign the distance +1 # Do it until the queue is empty #Run time a...
59b793944285bd9bf6a7e4c73045f16ee4a8466b
chepkoy/python_basics
/python_datatypes/deletion.py
113
3.578125
4
# Deleting list members in a list deleted_item = [0,1,2,3,4,5,6,7,8,9] del deleted_item[7] print(deleted_item)
19033fb2f637c727e83bc329a0eeac1bcd578203
chepkoy/python_basics
/spliting_joining.py
444
4.1875
4
# Strings are iterable string = list('hello') print(string) # Splits by default breaks on white space split = "Hello there students" print(split.split()) # Spliting on something colors = "Red:Blue:Green" print(colors.split(':')) # Changing lists into strings drinks = ['milk', 'soda','coffee'] print(', '.join(dri...
e4aa49f7f85d38c77300ae1eedb745a497a736e0
pelumy/Python-Journey
/tuples.py
96
3.953125
4
tuple1 = ('a','b', 'c', 'd') tuple2 = ('e', 'f') tuple1+=tuple2 print(tuple1) print(tuple1[1:5])
4f924e6418b4eab53cb39916616932238f4b56d0
mj3428/spark4practice
/RDD_cal.py
1,504
3.5625
4
# 1 from pyspark import SparkConf, SparkContext # conf = SparkConf().setMaster("local").setAppName("My App") sc = SparkContext() nums = sc.parallelize([1, 2, 3, 4]) squared = nums.map(lambda x:x * x).collect() for num in squared: print("%i" %(num)) # 返回的是序列的迭代器 输出的RDD并不是迭代器,而是一个包含各个迭代器可访问的所有元素的RDD # 2 from pyspa...
c857b85960c2364d98cba74835160e44c90ef1da
debortoli/NWXP
/src/level0.py
3,848
3.59375
4
import pygame from pygame.locals import * import pdb import Tkinter as tk from level1 import damLevel,initLevel1,powerProduced def tutorialSequence(board,disp,root): #on the first iteration, add all of the messages if(len(board.updateQueue)<1 and board.progress==0.): m1="Welcome to the Grid Simulator Game!"+'\n'+\...
1c2ddc67adfffea27b13bd3c9dc7ee35950586e1
fishy-rishy/fishy.space
/furry_gen.py
5,118
4
4
#!/usr/bin/python """ this is a fursona generator! have fun! """ import random first_name = raw_input("What is your first name?") last_name = raw_input("What is your last name?") fave_colour = raw_input("What is your favourite colour?") jack_hand = raw_input("What hand do you masturbate with?") gender = random.randran...
5b764b11ec6d2fd32bcd7a7697a65fc7c0646b19
jason-lean/CS-2620-Assignment-4
/proxy.py
2,580
3.53125
4
# Networking & Security for Informatics - Assignment 4 # Programmer: Jason Lin # Import socket library from socket import * import time ''' Helping Functions ''' def HTTP_GET(host, port): # Declare socket clientSocket = socket(AF_INET, SOCK_STREAM) clientSocket.settimeout(1.0) # Connect ...
49e2ff60bf76bab73f213545fa3f9e5dc4356ca4
prathamSharma25/PythonPractice
/SineCosine.py
280
3.515625
4
import numpy as np import matplotlib.pyplot as plt x=np.linspace(-360,360,45)*np.pi/180 plt.subplot() sin_=plt.plot(x, np.sin(x),label="Sine Curve") cos_=plt.plot(x,np.cos(x),label="Cos Curve") #_tan=plt.plot(x,np.tan(x),label="Tan Curve") plt.legend(['sin','cos']) plt.show()
3aedfad612e0f8530fbe03f65c182cef8d003c2b
klapmo/python-udemy
/user.py
202
3.671875
4
class User: def __init__(self, name, age): self.name = name self.age = age def speak(self): return f"Hey I'm {self.name}" user1 = User("david",32) print(user1.speak())
87ac6d7a29158ce3ec1e4e4bfb303a7d56221b62
Zhuoshi-Liu/course-content
/tutorials/W3D3_NetworkCausality/solutions/W3D3_Tutorial1_Solution_1ab9b01c.py
2,178
3.5625
4
def get_perturbed_connectivity_single_neuron(perturbed_X, perturb_freq, selected_neuron): """ Computes the connectivity matrix for the selected neuron using differences in means. Args: perturbed_X (np.ndarray): the perturbed dynamical system matrix of shape (n_neurons, timesteps) perturb_fr...
8c7ec44b7b8c7df4125dd620b3f8b6f55fc7fa81
Zhuoshi-Liu/course-content
/tutorials/W1D5_DimensionalityReduction/solutions/W1D5_Tutorial1_Solution_c9ca4afa.py
522
4.15625
4
def define_orthonormal_basis(u): """ Calculates an orthonormal basis given an arbitrary vector u. Args: u (numpy array of floats): arbitrary 2-dimensional vector used for new basis Returns: (numpy array of floats) : new orthonormal basis columns correspond to b...
925ddfc10b0a84e5a1aed3cfcbf42c4e61e49bd5
cpe202spring2019/lab1-ZMDominik
/lab1.py
1,574
4.125
4
def max_list_iter(int_list): # must use iteration not recursion """finds the max of a list of numbers and returns the value (not the index) If int_list is empty, returns None. If list is None, raises ValueError""" if int_list is None: raise ValueError elif len(int_list) == 0: return No...
97452695e5a3b84ebed88a3e62c2fc93ad08d238
CERN/TIGRE
/Python/tigre/utilities/visualization/plot_angles.py
6,203
3.671875
4
""" Visualization of ordered subset of angles # This file is part of the TIGRE Toolbox # Copyright (c) 2015, University of Bath and # CERN-European Organization for Nuclear Research # All rights reserved. # License: Open Source under BSD. # ...
1789a3de980f1431c34972d1100d05df00ad660f
Rishabhbisen/Python-Code
/08_if_else.py
1,206
4.03125
4
a = 13 if a == 2: print('yes') # if first condition is true other case will not be run elif a < 12: print('no this is wrong value') elif a > 3: print(' a is greter than 3') else: print('no') age = int(input(' Enter your age\n')) if a > 18: print(' yes ! you can vote ') else: print(' no ! you...
20b1d2938f90b9d783b6540cdbb36e9e4ad486b9
Rishabhbisen/Python-Code
/10_function.py
712
3.765625
4
def my_func(): print(" hello from a function") my_func() def fun(fname): print(fname+"refrance") p = fun("email ") print(p) fun("goal ") fun("linux ") def myfun(fname, lname): print(fname + lname) myfun("Rishabh ", " Bisen") myfun("Is a ", " good boy") def name(*kid): print(" youngest kid i...
292492a2392b0523b7ea5bd7d9f4b0bf27722755
Rishabhbisen/Python-Code
/11_file.py
1,153
4.1875
4
# f = open('sample.txt', 'r') f = open('sample.txt') # by default r ( reading mode) data = f.read() # data = f.read(5) # first fir character read only print(data) f.close() # other method to read the function f = open('sample.txt', 'r') data = f.readline() # read first line print(data) data = f.readline() # read ...
a030a88be9ab63223713c3119cbb9cb4fdba9184
jnvalino/knightsequences
/src/knightsequences.py
2,843
3.90625
4
#!/usr/bin/python import sys def is_vowel( keychar ): if keychar in 'AEIOU': return 1 else: return 0 # static keypad assigned as a dictionary of dictionaries keypad = {1: {1:'A', 2:'B', 3:'C', 4:'D', 5:'E'}, 2: {1:'F', 2:'G', 3:'H', 4:'I', 5:'J'}, 3: {1:'K', 2:'L', 3:'M', 4:'N',...
a236e1548c003a725fadfb7952f12e7bc4f6a6a5
richard-salaschavez/Python-Programs
/SalasChavezRichardA2.py
4,821
4.125
4
"""RichardSalasChavezA2Q1 COMP 1012 SECTION A01 INSTRUCTOR Terry Andres ASSIGNMENT: A2 Question 1 AUTHOR Richard Salas Chavez VERSION February 3, 2015 PURPOSE: to find the square root of your student number with Python in as many ways as you can. """ # imports import math, cmath, numpy, time #s_ = 7654321 #student...
950d2fc186554243534d734e09876f6988b4d376
haileyhansard/CS2-Notes-and-Algorithm-Problems-Week-5
/Day_2_Beej_Notes.py
1,749
3.921875
4
""" DAY 2 NOTES - Lecutre with Beej 9/29 GET(key): get the index for the key search the linked list at that index for the key if found, return the value else return None PUT(key): get the index for the key search the linked list at that index for the key if the key is found, overwrite th...
e108c30c7659724080ad33912a36a79945a32d5a
haileyhansard/CS2-Notes-and-Algorithm-Problems-Week-5
/Day_1_Artems_Lecture_Notes.py
2,730
4.5
4
''' HASH TABLES - First two days: build your own hash table from scratch - Second two days: applications of hash tables DAY 1 NOTES: HASH FUNCTIONS: - Any string input ---> returns/outputs a Specific Number (within some range) - This function is deterministic, meaning, the same input will always return the same out...
955d2da4afbd5d69b1cc1e7f4d2766b5cf05aabc
lamfo-unb/consensus_project
/data_reuters/merge_data.py
3,832
3.765625
4
""" merges fundamentus and reuters data the final dataframe is saved in data/consolidate/ """ import pandas as pd import pickle as pk from glob import glob def clean_zero_columns(df): # removes zero columns of a dataframe df = df.loc[:, (df != 0).any(axis=0)] return df def fix_duplicates(df,ticker,fol...
4546767ea00cab69cb3c76809371313511c4bd94
meadsteve/lagom
/lagom/util/functional.py
1,195
3.6875
4
"""Code to help understand functions """ import inspect from typing import Callable, TypeVar, Generic, Iterator def arity(func: Callable) -> int: """Returns the arity(number of args) Given a callable this function returns the number of arguments it expects >>> arity(lambda: 5) 0 >>> arity(lambda x...
bce65facff9169389a19bfe5dfe3018279ad6d7e
sairatabassum/SQlite3_with_Python3
/SQLite3 with Python 3.py
1,876
3.9375
4
import sqlite3 con = sqlite3.connect('student.db') c = con.cursor() #---Create Table--- def create_table(): c.execute("""CREATE TABLE IF NOT EXISTS students( first text, last text, id integer )""") def data_entry(): c.execute("INSERT INTO ...
4056036efed36ec2083e53c9d9cbd720e16db650
reyfico/curso_python
/video_16_radio.py
233
4.03125
4
### ejecicio del circulo import math radio = float(input("Ingresar el radio: ")) area = math.pi * radio**2 circunferencia = 2 * math.pi * radio print(f"El area es {area:.2f}") print (f"La circunferencia es {circunferencia:.2f}")
a953d296feb901c3af4c8146b89d4195799220cd
Gyczero/Leetcode_practice
/Python/二叉树/二叉树路径/leetcode_257_所有路径.py
911
3.828125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/10/24 5:46 下午 # @Author : Frankie # @File : leetcode_257_所有路径.py from typing import List # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class ...
c8947a6d18fd57262a8537571fd8b67d26fc3f2a
Gyczero/Leetcode_practice
/Python/数组/Easy/leetcode_219.py
840
3.578125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/9/10 9:30 PM # @Author : taicheng.guo # @Site : # @File : leetcode_219.py # @Software: PyCharm from typing import List class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: """ 注意点: 1、时间...
3f1bbae61d7ab7bf72b20f9bf661ed7f9ce3e396
Gyczero/Leetcode_practice
/搜索 - 二分查找/leetcode_74_二分矩阵.py
3,094
3.734375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/10/17 7:59 下午 # @Author : Frankie # @File : leetcode_74_二分矩阵.py from typing import List class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: """ 高效算法 -> 矩阵中是否存在一个目标值 o(m*n)以下 1、从左 -> 右升序,二...
8b56dbed2410f0c355f7487f8e54ab0d8ceb9983
Gyczero/Leetcode_practice
/Python/数组/Easy/leetcode_118.py
890
3.765625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019-09-05 21:30 # @Author : Frenkie # @Site : # @File : leetcode_118.py # @Software: PyCharm from typing import List class Solution: def generate(self, numRows: int) -> List[List[int]]: """ 第一个和最后一个都为1 x[i][j] = x[i-1][j-1...
c09b5b0acd2548bf0d666cba49a592a77d18d3cd
Gyczero/Leetcode_practice
/Python/数组/Easy/leetcode_35.py
679
3.84375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019-09-03 22:04 # @Author : Frenkie # @Site : # @File : leetcode_35.py # @Software: PyCharm from typing import List class Solution: def searchInsert(self, nums: List[int], target: int) -> int: """ 注意点:【极端条件判断】如果target是最小/最大怎么办 | ...
f8b34357d6b4a14548bc8bb4c5e40daa479b633a
Gyczero/Leetcode_practice
/Python/二叉树/二叉树to链表/leetcode_114_二叉树to链表.py
934
3.875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/10/25 11:42 上午 # @Author : Frankie # @File : leetcode_114_二叉树to链表.py from typing import List # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None cla...
45071fcce95690da6fc8fa4023119d893fd37db0
Gyczero/Leetcode_practice
/Python/数组/Easy/leetcode_119.py
818
3.703125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019-09-05 21:49 # @Author : Frenkie # @Site : # @File : leetcode_119.py # @Software: PyCharm from typing import List class Solution: def getRow(self, rowIndex: int) -> List[int]: """ 优化算法 => 空间复杂度O(k),只保存上一次的结果 :param rowI...
195d6f062b91dec6e9ba0a1427b5c253a3bf30fa
Gyczero/Leetcode_practice
/Python/数组/Easy/leetcode_26.py
1,255
3.625
4
# -*- coding: utf-8 -*- # @Time : 2019-08-18 12:03 # @Author : Frenkie # @File : leetcode_1.py from typing import List class Solution: def removeDuplicates(self, nums: List[int]) -> int: """ 注意点:空间O(1) 且 必须原地修改输入数组 => append, insert, remove first value, pop index, nums[0] = 1 ...
47fdac6bb1a774a994983f45710cc191c872361c
Gyczero/Leetcode_practice
/Python/链表/Easy/leetcode_203.py
917
3.859375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019-09-14 12:47 # @Author : Frenkie # @Site : # @File : leetcode_203.py # @Software: PyCharm # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object):...
5f46e9fc1ca5e314454fc232b63949b3b99a35ef
BFangs/data_structures_fun
/balance_parens.py
339
3.953125
4
from stacks import Stack def balance(equation): """check if parentheses are balanced""" parens = Stack() for char in equation: if char == "(": parens.push("(") elif char == ")": if parens.is_empty(): return False parens.pop() return...
7a333b5188fbbe55667ffd067dd8ab3ba5f0efec
BFangs/data_structures_fun
/queues.py
439
3.78125
4
from linked_lists import LinkedList class Queue(object): def __init__(self): self.queue = LinkedList() def enqueue(self, data): self.add(data) def dequeue(self): return self.del_at_index(0) def is_empty(self): if self.queue: return True return Fal...
906e57c0b07791f2c61733236df372650cc4c313
Amanjot25/Bucles-while
/nveces_01.py
112
3.921875
4
# coding-utf 8 num=int(input("Introduce un numero")) i=0 while (i<num): i=i+1 print(input("Dime un numero"))
2320db0e5492b1e61641a6a1c24656cbc6389f9e
Amanjot25/Bucles-while
/mayorK07.py
486
3.828125
4
# coding:utf -8 a= int(input("Escribe un numero: ")) b= int(input("Escribe un numero mayor que " + str(a) + ": ")) while a >= b: b=input(str(b) + "No es mayor que " + str(a) + "Inténtalo de nuevo:") c=float(input("Escribe un numero entre" + str(a) + " y " + str(b) + ": ")) count=0 while a <= c <= b: count += 1 ...
4b20645775a83b3793d57b17b02134abdf9bc9d0
ksvulchev/task_week1
/taks18.py
158
4.03125
4
#!/usr/bin/python def is_increasing(seq): for i in range(1,len(seq)): if seq[i] < seq[i-1]: return False return True print(is_increasing([5,6,-10]))
7e05bbc4714140d47b353a1b7474a58fee71e60c
xionCode/shiyanlou
/challenge3_3 端口扫描/scan.py
1,167
3.515625
4
from socket import socket import sys, re def get_argv(): argv_list = sys.argv[1:] try: host_index = argv_list.index('--host') host_temp = argv_list[host_index + 1] port_index = argv_list.index('--port') port_temp = argv_list[port_index + 1] if re.match('^(\d{1,3}\.){3}\...
5a06a443165509bfe50a9b9903673f2b8acf992f
finfou/viclearning
/pyscripts/pythoncookbook3/2.1_split/split.py
604
3.609375
4
#!/usr/bin/env python line = 'asdf fjdk; afed, fjek,asdf, foo' line1 = 'asdf fjdk afed fjek asdf foo' import re def split1(): print(line1.split(' ')) split1() def split2(): print(re.split(r'[;,\s]\s*',line)) split2() def split3(): print(re.split(r'(;|,|\s)\s*', line)) split3() def split4(): print(re.split(r...
0f9bc763724685dbb5455bbd2831f0bf7d6a92d9
jianbinzhong/LearningPythonTest
/TestCode/FrequentlyFunction.py
652
3.890625
4
#add def add(num1,num2): if isinstance(num1,(int,float)) and isinstance(num2,(int,float)): print 'you have input two int or float number:' elif isinstance(num1,(str)) and isinstance(num2,(str)): print 'you have input two strings:' else: print 'input error,please try again' return...
a3e0f08adc4a7b48df9d8bf992989763aea5310e
emord/projects
/python/numbers/prime_factor.py
641
4.4375
4
#!/usr/bin/python """ Have the user enter a number and find all Prime Factors (if there are any) and display them. """ def prime_factors_of(num): """ Returns list of prime factors of num """ result = [ ] cur_prime = 2 while num > 1: if num % cur_prime == 0: result.append(cu...
f5da95b3f800c41e7e708dd4ebb9fcdd9832a098
emord/projects
/python/numbers/factorial.py
908
4.25
4
#!/usr/bin/python """ The Factorial of a positive integer, n, is defined as the product of the sequence n, n-1, n-2, ...1 and the factorial of zero, 0, is defined as being 1. Solve this using both loops and recursion. """ def factorial_iteration(num): """ Returns num! through iteration """ res = 1 ...
5ac2fc9e0fdcaba2ba419a483c3545639f2576c5
emord/projects
/python/classic_algorithms/collatz_conjecture.py
692
4.5
4
#!/usr/bin/python """ Start with a number *n > 1*. Find the number of steps it takes to reach one using the following process: If *n* is even, divide it by 2. If *n* is odd, multiply it by 3 and add 1. """ def collatz_steps(num): """ Returns number of steps in Collatz conjecture for num """ steps = 0...
cc195659dcc560e6493ebebe1b94cb683263e0de
johnseremba/Andela-Lab-Excercises
/data_type.py
495
3.5625
4
def data_type(param): if type(param) == str: return len(param) elif param is None: return "no value" elif type(param) == bool: return param elif type(param) == int: if param == 100: return "equal to 100" elif param < 100: return "less than ...
6d0b58ef5d87069d7aba33a189ecd31edf6a8c43
kashyapmishra/mycode
/ease the array.py
1,269
3.890625
4
Given an array of integers of size N. Assume ‘0’ as invalid number and all other as valid number. Write a program that modifies the array in such a way that if next number is valid number and is same as current number, double the current number value and replace the next number with 0. After the modification, rearrange...
924324db0dd6267fc9975d7c803a7a424bdfe0a3
coding-with-fun/My-Python-Codes
/web-scraping/web-scrap.py
3,462
3.984375
4
""" This is the code for web scrapping from a website named Box Office Mojo. https://www.boxofficemojo.com I've used Pandas module, requests module and requests_html module. -> requests module help to access the website and get the data as a plain text. -> requests_html module helps to extract HTML elements from the ...
57c7c375db5996200d3f55c0a4ed455a0c471c2b
Laura7089/practicalProjects
/week2/funcVersions/question2.py
388
4.0625
4
print("How many hours did you work?") hours = float(input(">")) print("How much do you get paid (per hour)?") salary = float(input(">")) print("You're owed " + str(hours * salary) + " pounds in ordinary wages.") if hours > 40: print("You've worked overtime!") overtime = hours - 40 print("You're owed " + st...
090ce7648356e12d23f23b7b3528c2bb8a884a91
Laura7089/practicalProjects
/week7/level1.py
1,048
3.640625
4
def saveListToFile(sentences, filename): outputFile = open(filename, "w") for string in sentences: outputFile.write(string) outputFile.close() def saveToLog(entry, logfile): output = open(logfile, "a") outputFile.write(entry) outputFile.close() def upperCasePrint(fileName): with ...
aacd351e621c7842847bed7dfc96c6c39ada1725
Laura7089/practicalProjects
/week2/question3.py
446
4.09375
4
print("What was the speed limit?") limit = int(input(">")) print("How fast were you going?") speed = int(input(">")) if speed > limit: print("You were speeding!") if speed > 90: print("You were also over 90 so you owe extra!") fine = 300 + 5 * (speed - limit) else: fine = 100 + 5 * ...
0f0449618c015707aa434b5a56dea0f229e61734
jm3635/project1
/webserver/server.py
17,154
3.578125
4
#!/usr/bin/env python2.7 """ Columbia W4111 Intro to databases Example webserver To run locally python server.py Go to http://localhost:8111 in your browser A debugger such as "pdb" may be helpful for debugging. Read about it online. """ import os from operator import itemgetter from sqlalchemy import * from...
5612d233e5d188b2ce7c8c7fc028f1c8608caab5
YUZI22/Testphueyusef
/huetest.py
2,078
3.875
4
from phue import Bridge # https://github.com/studioimaginaire/phue # in and for meaning: https://www.quora.com/In-Python-what-does-for-return-and-in-mean # https://stackoverflow.com/questions/19845924/python-how-to-generate-list-of-variables-with-new-number-at-end # the hub 192.168.1.107 b = Bridge('192.168.1....
f17dbbf55c285055affe91cf841ee141da2465bc
RandallCastroValenciano/prueba
/largo_string.py
279
3.703125
4
""" Dada una lista de strings, devolver una lista con el largo de cada string: """ lista_strings = ["sfas","sd","sfg","yth","lkl"] lista_largo_de_cada_string = [] for string in lista_strings: lista_largo_de_cada_string.append(len(string)) print(lista_largo_de_cada_string)
7dc016ce2c09ce050dafc0bfceadda7be0f8c669
RandallCastroValenciano/prueba
/BJJ_1.py
511
3.875
4
tecnicas = [] input_usuario = "" input_usuario = input("¿Qué técnicas deseas dominar? (Escribe FIN para salir): ") while input_usuario != "FIN": tecnicas.append(input_usuario) input_usuario = input("¿Qué técnicas deseas dominar? (Escribe FIN para salir): ") largo_lista = len(tecnicas) indice_actual...
85e78ceda10e389c09e454658961597f93800e84
tgandor/meats
/toys/frequency.py
686
3.515625
4
#!/usr/bin/env python import time def go(): print("Keep pressing <Enter> or enter something to quit.") last_hit = time.time() line = "" lagavg = 0 while line == "": line = input() hit = time.time() delay = hit - last_hit lagavg = (4 * lagavg + delay) / 5 ...
e8cf38dbba98384b9d3881edbfa261331125fc49
tgandor/meats
/lang_lawyer/python/new_arguments.py
482
3.59375
4
class Foo(object): def __new__(cls, *args, **kwargs): print("Creating Instance", args, kwargs) # instance = super(Foo, cls).__new__(cls, *args, **kwargs) # gives: # TypeError: object.__new__() takes exactly one argument (the type to instantiate) instance = super(Foo, cls).__n...
38d2b84a21b8d7c03d33a586f01616164fcf0503
tgandor/meats
/network/ip_to_hex.py
462
3.625
4
#!/usr/bin/env python import sys import re x = sys.argv[1] if re.fullmatch(r"\d{1,3}(\.\d{1,3}){3}", x): ip = [int(d) for d in x.split(".")] elif re.fullmatch(r"(IP-)?[0-9a-f]{8}", x, re.IGNORECASE): if x.lower().startswith("ip-"): x = x[3:] ip = [int(x[i : i + 2], 16) for i in range(0, 8, 2)] el...
2ad105b58688904f6c5313151b827cd18c8861e2
tgandor/meats
/lang_lawyer/python/ordered_dict_equality.py
502
4.125
4
d1 = {'a': 1, 'b': 2} d2 = {'b': 2, 'a': 1} assert d1 == d2 print(d1 == d2) a = [1, 2, 3, 1, 2, 3] b = [3, 2, 1, 3, 2, 1] ad = [{'a': x} for x in a] bd = [{'a': x} for x in b] # https://stackoverflow.com/questions/7828867/how-to-efficiently-compare-two-unordered-lists-not-sets-in-python # assert sorted(ad) == sor...
31add6c979a17e5ee797a78c2b7dd2924c2bae29
tgandor/meats
/lang_lawyer/python/generator_return.py
307
4.03125
4
#!/usr/bin/env python3 # https://stackoverflow.com/a/16780113/1338797 def f(): return 1 yield 2 def g(): x = yield from f() print('yielded from f():', x) # g is still a generator so we need to iterate to run it: for _ in g(): print('g() yielded something:', _) # this won't print!
132b41d4293809b25f36df1dca2c770c0bf594ee
tgandor/meats
/lang_lawyer/pandas/utils.py
763
3.84375
4
def sanitize_column_names(df, inplace=True): "Replace all non-identifier characters in column names with _." def sanit(name): import re name = name.lower() name = re.sub('\W', '_', name) name = re.sub('__+', '_', name) name = re.sub('(?<=.)_$', '', name) # positive lookb...
a76eb11318232ddc2db60e5fa4c6b7bc24fe7327
skc3779/python-analysis-demos
/chapter0212.py
466
3.703125
4
#!/usr/bin/env python3 import pandas as pd import sys #pandas를 활용 #열의 헤더를 사용하여 특정 열을 선택하는 방법 input_file = sys.argv[1] output_file = sys.argv[2] data_frame = pd.read_csv(input_file) data_frame_column_by_name = data_frame.loc[:, ['Invoice Number', 'Purchase Date']] data_frame_column_by_name.to_csv(output_file, index=F...
53a1c010a510d737d1ef1586fe75be1966a83eeb
randerson04/SentenceGenerator
/generator.py
1,346
4.03125
4
''' program: generator.py author: ry 10/05/2020 pages 150-153 app generates and displays sentences using simple grammar and vocab. words are chosen at random. ''' #import statement for the random module import random #global vars and cosnts #vocab: words in 4 diff parts of speech articles = ('A', 'THE'...
9ccd71c983653976421c2051f1306ff845f2e441
R-Hurl/Breakout
/circleRectIntersect.py
2,143
4.09375
4
from graphics import Circle, Rectangle, Point def circleRectIntersect(circle,rectangle): ### Python algorithm for intersection of a circle and rectangle created as ### a hybrid of several postings show on the following webpage at StackOverflow ### http://stackoverflow.com/questions/401847/circle-rectangle-...
da144476dfe9bc690bfbb0f98a86eaba83d32f54
tekelia-powe/afs-210
/Week5/Searching and Sorting/searchandsort.py
379
3.96875
4
def binary_search(list, term): #finding length of list list_size = len(list) #loop through list and returns True if term equals number in list otherwise returns false for i in range(list_size): if term == list[i]: return True return False my_list= [0,1,3,8,14,18,19,34,52] print...
2659afa40148369f08e6e48b622adcc2d851bbcb
poshangqiucao/python-test
/test.py
427
3.96875
4
character_name = "chenggang" #string character_age = 67.587567466 #number isMale = True #boolean is_male = False print("There once was a man named " +character_name+",") print("he was "+character_age+" years old.") character_name = "Tom" print("He really liked the name "+character_name+",") print("but didn't like ...
8d7f90574766ea11cbdedf60e72845f4b149d1b7
EduFelix/Exercicios-Python
/ex007.py
226
3.921875
4
n1 = float(input('Digite a primeira nota?')) n2 = float(input('Digite a segunda nota?')) media = (n1 + n2)/ 2 print("Primeira nota do aluno {}, \n Segunda nota do aluno {}\n Média das notas do aluno {}".format(n1, n2, media))
ed166bc7da2e198c746431fe403ba2a3038f8d49
EduFelix/Exercicios-Python
/ex015.py
293
3.65625
4
km = float(input('Quantos kilomentros percorridos?')) dias = float(input('Por quantos dias o carro foi alugado?')) vTotal = (60*dias)+ (0.15*km) print('O preço a pagar pelo o aluguel do carro durante {} dias' 'pecorrendo {} kilomentros. Corresponde a Reais {}'.format(dias, km, vTotal))
ad86c80dfcf0fa7c7ccc6129817d86a8aeb9a869
EduFelix/Exercicios-Python
/ex023.py
268
3.75
4
nun = int(input('Digite um numero que possua até quatro digitos?')) u = nun // 1 % 10 d = nun // 10 % 10 c = nun // 100 % 10 m = nun // 1000 % 10 print('Unidades {}'.format(u)) print('Dezenas {}'.format(d)) print('Centenas {}'.format(c)) print('Milhar {}'.format(m))
09016204d58e2ac15e3fa422ecc7043a5c7644f1
weiguxp/pythoncode
/ProblemSets/Draw Box.py
922
3.84375
4
def add_space(num_spaces, target_string): repeart_unit = ' ' target_string = repeart_unit*num_spaces return target_string def right_align(target_string): spaces_needed = 70 - len(target_string) target_string = add_space(spaces_needed, target_string) + target_string print target_string def print_multiple(print_...
cafe104a6f008344701c53fb6ceab909b490c991
weiguxp/pythoncode
/ProblemSets/CompoundInterest.py
692
3.734375
4
def calcInterest(Balance, AnnRate, MinPay): minMonthPay = round(Balance * MinPay,2) paidPrinciple = round(minMonthPay - (Balance * (AnnRate/12)),2) Balance = round(Balance - paidPrinciple,2) print ('minMonthPay', minMonthPay) print ("paidPrinciple", paidPrinciple) print ("Balance", Balance) ...