blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
0c11d36e4d4a820eef2d875824f6a6bbfbf1613b
maples1993/LeetCode
/q112.py
1,011
3.890625
4
""" Date: 2018/8/19 """ class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def hasPathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: bool """ if not root: ...
7193f12a74129089b07e16f3892e1039f820fa40
maples1993/LeetCode
/q371.py
414
3.53125
4
""" Date: 2018/9/20 """ class Solution: def getSum(self, a, b): """ :type a: int :type b: int :rtype: int """ # a denotes sum, b denotes carry while b: a, b = a ^ b, (a & b) << 1 a &= 0xFFFFFFFF b &= 0xFFFFFFFF ...
678c79cbcc7105095ade6707bf26ba47689099b7
maples1993/LeetCode
/q125.py
922
3.796875
4
""" Date: 2018/8/21 """ class Solution: def is_valid(self, c): return ord('a') <= ord(c) <= ord('z') \ or ord('0') <= ord(c) <= ord('9') def isPalindrome(self, s): """ :type s: str :rtype: bool """ if len(s) <= 1: return True ...
c9dfcdbaf8b562f6c49c077a234c1155208fee8b
hybrid-kg/clep
/src/clep/sample_scoring/z_score.py
2,421
3.5
4
# -*- coding: utf-8 -*- """Carry out Z-Score based single sample DE analysis.""" from typing import List import numpy as np import pandas as pd def do_z_score( data: pd.DataFrame, design: pd.DataFrame, control: str = 'Control', threshold: float = 2.0, ) -> pd.DataFrame: """Carry...
5335970e03ebdd0e707e4cf381c88caeb9e36600
DenisPerez/Python-Games
/pong.py
2,982
3.609375
4
import turtle import os window = turtle.Screen() window.title("Pong by DA") window.bgcolor("black") window.setup(width=800, height=600) window.tracer(0) # Score score_a = 0 score_b = 0 #Paddle A paddle_a = turtle.Turtle() paddle_a.speed(0) #animation speed paddle_a.shape("square") paddle_a.color("white") paddle_a.sh...
228cb253905d601074949f814d4423e2d4d671f8
karasatishkumar/python-practice
/day5/mathlib.py
241
3.5625
4
def square(num): res = num ** 2 print("SQUARE = ", res) def greet(): print("Good Morning!!") def add(a, b): ans = a + b print("SUM = ", ans) def express(a, b, c): ans = a * b + b / c print("EXPRESS = ", ans)
0bb55155259788920504e791bb431f1fca7b4ebe
zendox/python-lesson
/y.py
371
4.0625
4
#create a dict, add datas like , roll no ,name ,marks,along with gender, # now i want to print all the names and marks whose gender is male ,how would you do that ? d = {'rollno':[1,2,3,4], 'name':['ram','sita','hari','rama'],'gender':['male','female','male','female']} tmp=[] for i in range(len(d['name'])): if d['g...
3dc2103547cb83b09df429259b3152365a924dd4
zendox/python-lesson
/msthematical expression.py
137
3.796875
4
a = (input("enter the value of x")) b = (input("enter the value of y")) c = str((a**3), + (3*a**2*b), + (3*a*b**2), + (y**3)) print (c)
838821e64bac30c0a0e106cb364dcc72bc4106a2
zendox/python-lesson
/multiplication of 5.py
273
4.0625
4
# 1,2,3,4,5,6,]=[sunday,monday,tuesday,wednesday,thursday,friday] days = ["SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY"] number = int(input("number")) print(days[number - 1]) if number == 0 or number == 6: print("Holiday") print([0])
962a83a9399f9f808f21d98e6dc17dbe4b88565f
jichenmv/tutorials
/PyMLTutorial/regression.py
2,874
4.03125
4
import numpy as np from sklearn import preprocessing, model_selection, metrics from sklearn.linear_model import LinearRegression import pickle import util def train_linear_regression(data_frame, feature_list, label_list): """ Train simple linear regression models using the features in feature list against the...
63bcca7240f1f8464135732d795e80b3e95ddd1f
RichardLitt/euler
/007.py
565
4.125
4
# What is the 10001st prime? # Import library to read from terminal import sys # Find if a number is prime def is_prime(num): if (num == 2): return True for x in range(2, num/2+1): if (num % x == 0): return False else: return True # List all primes in order def list_pri...
b2643d19da4f16ffad76d0ade0d0062b4b1be942
nagavenkateshgavini/coding-problems-set
/arrays/1_Find_the_maximum_difference_between_two_elements_such_that_larger_element_appears_after_the_smaller_element.py
713
3.59375
4
''' Input: 2 7 2 3 10 6 4 8 1 6 7 9 5 6 3 2 Output: 8 2 ''' def find_maxdiff(arr): arr = [int(ele) for ele in arr if ele] max_diff = 0 min_ele = arr[0] for curr_ele in arr[1:]: if curr_ele < min_ele: min_ele = curr_ele curr_diff = curr_ele - min_ele if curr_diff < 0...
eceb3d9da046b3ac1792d0a3ef03df8aa3cf6bfa
telenz/dnn_significance_loss
/utils/draw_linear_activation.py
1,300
3.640625
4
#import section from matplotlib import pylab import pylab as plt import numpy as np #sigmoid = lambda x: 1 / (1 + np.exp(-x)) def f_three_range(s_1, s_2, s_3, x_1, x_2, y_pred): # Calculate scaling factor to bring output between 0 and 1 a = s_1*x_1 + s_2*(x_2-x_1) + s_3*(1-x_2) sf = 1./a f_1 = np.max...
71462cc30d62954a5e28d108ba8ad06cf996213f
gridl/voicebook
/chapter_3_featurization/numpy_commands.py
1,144
3.90625
4
''' numpy_commands.py Quick overview of some basic numpy commands. Although this was done in the IDLE3 window, I have commented out those sections so you can follow along. ''' import numpy as np # convert a list into an array g=[5,2,61,1] type(g) g=np.array(g) type(g) # index an array g[0] # serialize array data...
4155b9115c6bf574e37a2179b215745ac45527a2
gridl/voicebook
/chapter_9_security/encrypt_file.py
2,060
3.796875
4
''' encrypt_file.py Take in a file and encrypt it. From following this pycrypto tutorial: https://eli.thegreenplace.net/2010/06/25/aes-encryption-of-files-in-python-with-pycrypto ''' import hashlib, pickle import os, random, struct from Crypto.Cipher import AES import generate_password as gp from os import urandom d...
50f88a17445a1916ff88896eb73ce982a63cf455
gridl/voicebook
/chapter_1_fundamentals/speak_custom.py
4,304
3.78125
4
''' Speak_custom.py This script customizes a voice to your needs and outputs the default voice to a defaults.json file. Then you can use the voice into the future by calling the speak_text_custom(text, voiceid, rate) function. Pyttx3 has great documentation. You should check it out here: https://github.com/nateshm...
ee6cbd077ccfc99082710b7d42a4b0c5056ac691
gridl/voicebook
/chapter_6_visualization/text_stream.py
1,968
3.578125
4
''' text_stream.py Transcribe an audio file every 1 second and then propagate it on the screen. Do this in an asyncronous manner, as transcription can take some time. ''' #################################################### ## IMPORT STATEMENTS ## ########################################...
7981f6a7dad24aae4280e3a553f29f307245b954
Romario27/Intro-Taller-de-Programacion
/Introduccion/Codigos/POO/python/FiguraInicial.py
607
3.609375
4
class Fig: def __init__(self,x,y): self.__x = x #el doble "__" lo que quiere decir es q lo hace privado self.__y = y def getX(self): return self.__x def setX(self,x): if x>=0 and x<=1023: self.__x = x else: print ("E...
46c07849820933fa670c082b98084f921ee864df
Romario27/Intro-Taller-de-Programacion
/Introduccion/Examenes/rramirez-parcial 3/rramirez-parcial 3.py
1,289
3.734375
4
class Operaciones: def __init__(self): pass def contar (self): num=int(input("ingrese el numero:")) cont=0 while num!=0: cont+=1 num=num//10 print("Tiene",cont,"digitos") def ordenar(self,lista): ind1=0 ind2=1 ...
065f70d80dd0166698ff51ca69493f13daafcf82
Romario27/Intro-Taller-de-Programacion
/Introduccion/Codigos/Recursividad de pila/Operaciones numeros/11) 4-4-2018 lambda.py
2,350
3.53125
4
def revise(num): if isinstance(num, int): entre0y4= lambda digito: digito <=4 entre5y9= lambda digito: digito >=5 return revise_aux(num,entre0y4),revise_aux(num,entre5y9) else: return "Error" def revise_aux(num,condicion): if num==0: return 0 elif cond...
e8c887c7e729008133c95ab66ade453c7dd4be02
Romario27/Intro-Taller-de-Programacion
/Introduccion/Codigos/Recursividad de pila/Listas/7) 14-03-18 listas.py
2,424
4
4
#--------------------------tarea de intro---------------------------------- def suma(lista): if isinstance(lista,list): return suma_aux(lista) else: return "Error. debe ingresar una lista" def suma_aux(lista): if lista==[]: return 0 else: return lista[0]+suma_...
2c91f734d48c6d0ab620b6b5a9715dc4f5e4ddb7
smoke-hux/pyhton-codes
/2Dlistmatrixes.py
1,044
4.46875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jan 28 05:54:12 2020 @author: root """ matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] print(matrix[1]) matrix[0][1] = 20 print(matrix[0][1]) #we can use nested loops to iterate over every item in the list...
3e00ca2c95674548fb70ca8d7de7a934a660f286
ViniciusLoures/BCC701
/[P-02]/p02q03.py
284
4
4
l = float(input('Forneça o comprimerto do fio: ')) p = float(input('Forneça a força peso: ')) m = float(input('Forneça a massa: ')) g = p / m t = 2 * 3.14 * ((l / g)**0.5) print('A aceleração da gravidade é {:.3f}'.format(g)) print('O período do pêndulo é {:.3f}'.format(t))
4d1f17b48ad9d60432702e4f440b5b42e8182796
ViniciusLoures/BCC701
/[P-04]/p04q04.py
1,223
4.125
4
# Vinicius Alves Loures França 20.1.1039 years = int(input('Anos de experiência: ')) language = int(input('Linguagens de programação: ')) projects = int(input('Projetos: ')) diff_years = 3 - years diff_language = 3 - language diff_projects = 5 - projects diff_years_senior = 10 - years diff_language_senior = 5 - languag...
f9b2debb3736dfa6d2db8682bd661f11d024baf6
ViniciusLoures/BCC701
/[P-10-2]/p102q01.py
1,431
3.609375
4
# Vinicius Alves Loures França 20.1.1039 def preencherVetor(valores, tipo): vetor = [] valores = valores.split(',') for i in range(len(valores)): if tipo == 'int': valor = int(valores[i].strip()) elif tipo == 'float': valor = float(valores[i].strip()) else: ...
dbba20d66854917ca45c494dad846c2bbdff8d4d
ViniciusLoures/BCC701
/[P-09]/p09q04.py
286
3.765625
4
# Vinicius Alves Loures França 20.1.1039 def calculaF(x, y): r = (x ** 2) + (2 * x * y) + y return r def calculaG(x, y): r = (y ** 2) + (2 * x * y) + x return r a = int(input('a: ')) b = int(input('b: ')) p = int(input('p: ')) print(f'Intervalo definido: [ {a}, {b} ], com passo {p}.')
a3ea070237cce16317864837efa7fa2e36f975be
adrbcsk0/intermediate-python-course
/dice_roller.py
478
4.03125
4
def main(): import random dice_rolls=int(input('How many rolls? ')) dice_sum=0 dice_size=int(input('How big is your dice? ')) for i in range (0, dice_rolls): roll=random.randint(1,dice_size) dice_sum+=roll if roll==1: print(f'Siiiiick! Its a {roll}') elif roll==dice_size: print(...
7f44a3ce1ebc5dc682fb9a71a62413640101ed46
mdev-qn95/python-code40
/challenge-counter-app.py
642
4.15625
4
# Basic Data Types Challenge 1: Letter Counter App print("Welcome to the Letter Counter App") # Get user input name = input("\nWhat's your name: ").title().strip() print("Hello, " + name + "!") print("I'll count the number of times that a specific letter occurs in a message.") message = input("\nPlease enter a messa...
2687cd134e20e44c8510645a2cd1054af555da36
daviidluna/PythonOperators
/operatirs.py
859
3.71875
4
print(78+90) print(78-90) num_w_comm = '{:,}'.format(89898*9898909) print(num_w_comm) other_ = '{:,}'.format(203482309+238423482343) print(other_) division = '{:,}'.format(8100000000/9) print(division) x = 6 x *= 9 print(x) x = 78 y = 87 print(x == y) x = 9 y = 980980980 print(x != y) x = 67 print (x > 5 and x > 54) ...
e5162cfd848d2079cd0a2783413cdce62c365e39
rajkamalthanikachalam/PythonLearningMaterial
/com/dev/pythonSessions/07Functions.py
2,940
4.5625
5
# Function: a piece of code to execute a repeated functions # Recursion: A function calling itself # Arguments : *arg is used to pass a single arguments # Key words : **args is used to pass a multiple arguments in key & value format # Lambda functions : Anonymous functions or function without name # Function def fun...
6b29494683b19238977e6a1e01ff9292b64b50ee
rajkamalthanikachalam/PythonLearningMaterial
/com/dev/pythonSessions/02Strings.py
3,178
4.78125
5
# String declarations # types of calling, using the string operators # String declaration str1 = "Hello world in double quotes" # is preferred str2 = 'Hello world in single quotes' # single quotes can also used print(str1) print(str2) print(str1[0]) # to identify the character at first position print(str1[27]) ...
3c83bcb69b992b68845482fbe0cf930bb0faaf22
Japan199/PYTHON-PRACTICAL
/practical2_1.py
257
4.21875
4
number=int(input("enter the number:")) if(number%2==0): if(number%4==0): print("number is a multiple of 2 and 4") else: print("number is multiple of only 2") else: print("number is odd")
df188cbc10627bf268777d3c54b076fd12b3d552
Japan199/PYTHON-PRACTICAL
/practical6_1.py
151
3.734375
4
def fibbo(n): prev=0 next=1 for _ in range(0,n): print(prev) prev,next=next,(prev+next) return 0 fibbo(10)
20770527e59381ca8af97e826a68d167fe0b8032
Shinyobject123/Cowabunga
/Problems/02_lists.py
2,117
4
4
# LISTS (25pts) # Show work on all problems. Manually finding the answer doesn't count # PROBLEM 1 (Using List Comprehensions - 8pts) # Use list comprehensions to do the following: # a) Make a list of numbers from 1 to 100 # b) Make a list of even numbers from 20 to 40 # c) Make a list of squares from 1 to 100 (1 ** ...
1c2a0602f5b8e3ec8dc95dd73f55dad5b0f43ba8
spartypkp/IntroMLProjects
/Code 6 Decision Trees.py
11,282
3.84375
4
#!/usr/bin/env python # coding: utf-8 # # Decision Trees # # Decision Trees are versatile ML algorithms that can perform both classification (predicting classes) and regression (predicting values) tasks. They are very powerful algorithms, capable of fitting complex datasets. DTs are the building blocks of Random For...
98d91f20f106a8787e87e6e18bfb0388bb96a24e
Douglass-Jeffrey/Assignment-0-2B-Python
/Triangle_calculator.py
499
4.25
4
#!/usr/bin/env python3 # Created by: Douglass Jeffrey # Created on: Oct 2019 # This program calculates area of triangles def main(): # this function calculates the area of the triangles # input num1 = int(input("Input the base length of the triangle: ")) num2 = int(input("Input the height of the tri...
719849729d766d9e77393ff65e07461a47916891
npucino/hylite
/hylite/analyse/sam.py
2,249
3.578125
4
""" Functions for calculating spectral angles and doing spectral angle mapping. """ import numpy as np def spectral_angles(reference, spectra): """ Calculate the angle between each spectra and each reference. *Arguments*: - reference = a numpy array of reference spectra. - spectra = a numpy arr...
4f7e0349b8dcba405d3b60b69a05009d6df21c86
npucino/hylite
/hylite/analyse/indices.py
4,332
3.671875
4
import numpy as np def band_ratio(data, num, den): """ Calculate a band ratio to map broad absorbion features (e.g. iron). *Arguments*: - data = HyData instance to calculate a band ratio for. - num = the numerator of the band ratio. Integers are treated as indices, floats as wavelengths. ...
6c3847de682d13d754de806f5018d6587be51871
crys1992/Python-Turtle-Visualizations
/fractal.py
618
3.734375
4
from turtle import * def hilbert2(step, rule, angle, depth): if depth > 0: a = lambda: hilbert2(step, "a", angle, depth - 1) b = lambda: hilbert2(step, "b", angle, depth - 1) left = lambda: left(angle) right = lambda: right(angle) forward = lambda: forward(step) if rule == "a": ...
c38e41e1b0dc47877c9017c7ef8ce3839562b710
tonyraubenheimer/CrackingTheCodingInterview
/ChapterTwo.py
12,574
3.953125
4
import math class LinkedList: header = None def __init__(self): pass def printLinkedList(self): runner = self.header while(runner is not None): print(runner.value) runner = runner.next def appendToList(self, value): new =...
43a955339f7b9ce3a97a573bb4135636684f50f2
Nikita-Negi/MTA
/stock_prediction.py
2,462
3.9375
4
#importing necessary libraries import pandas as pd #used to create dataframes import numpy as np #used for mathematical functions and arrays import quandl #used to load the stock data import matplotlib.pyplot as plt #used for plotting purposes from sklearn.line...
9dc610df933ef0d10919da0fd9f20617d5354bcf
tomcatcn/common_tools
/data_struct/bitree.py
1,797
3.765625
4
""" 二叉树类 提供操作二叉树方法 思路分析: 1. 使用链式存储, Node表达一个节点(值,左链接,右链接) 2. 分析遍历过程 """ #二叉树节点 from data_struct.queue import LQueue class Node: def __init__(self,val,left=None,right=None): self._val = val self._left = left self._right = right class Bitree: #传入树根 def __init__(self,root): ...
73b8058f76913080f172dd81ab7b76b1889faa11
ibrahimuslu/udacity-p2
/problem_2.py
2,115
4.15625
4
import math def rotated_array_search(input_list, number): """ Find the index by searching in a rotated sorted array Args: input_list(array), number(int): Input array to search and the target Returns: int: Index or -1 """ def findPivot(input_list,start,end): if start == end...
2e04365b3fb8fd503c779e3f3c93852f6229b189
ThunderShiviah/numerical-integration
/montecarlo_int.py
1,489
3.828125
4
# Numerical Integration using Monte Carlo method # FB - 201006137 import math import random import numpy as np from numpy import * import scipy as sp from scipy import integrate from scipy.integrate import simps # define any function here! def f(x): f = 1 + math.sin(x) + 0.3*math.cos(9*x) return f # define a...
3b73266ec3b6c7fd26a4e5fe3e290b3c4bc68631
Onlee97/Object-Detection-and-Avoidance-with-Intel-Realsense
/python/audio.py
711
3.53125
4
def list_devices(): """List all available microphone devices.""" try: import pyaudio except ImportError: print("You have to install extra 'sound' in order to use this shell script") return 99 pa = pyaudio.PyAudio() for i in range(pa.get_device_count()): dev = pa.get_...
4038c107fcee3138086e2808cbc9fbac875ebd5d
mdinamulirshad/Snake-Game
/main.py
4,689
3.625
4
import sys, random import pygame from pygame.locals import * def run_game(): #initialize the game and create the window. pygame.init() #Screen Settings screen_width = 600 screen_height = 500 screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_ca...
4cc4599ea6aafa191cb27c080077ef27504a1a0b
juhidesai/x9115baymax
/project/test_maincode_real.py
221
3.5
4
def check_em(a, b): c = a + b if c % 2 == 0.25: print("------------------") print("1.25") print("target achieved") print("------------------") else: print("Odd")
e87b7479bacfa110dda49e148a0842c670af5826
MEKAon/Python
/if2.py
170
3.84375
4
a = input() b = int(a) if b >= 90: print('A') elif b >= 80: print('B') elif b >= 70: print('C') elif b >= 60: print('D') else: print('F')
701ba769551b398d4181e5d18713c11c9da37611
dodoph/udacity-homework
/Lesson12/NumbersInList2.py
985
4.0625
4
# Numbers in lists by SeanMc from forums # define a procedure that takes in a string of numbers from 1-9 and # outputs a list with the following parameters: # Every number in the string should be inserted into the list. # If a number x in the string is less than or equal # to the preceding number y, the number x shoul...
d7c9f6ca43c28f8c62fb24980dc1fc2714522366
anudeike/Recreational-Code-Generator
/example-files/PlotGraphExample/json-parsing.py
5,610
3.65625
4
import json path = r"C:\Users\Ikechukwu Anude\Documents\recreational-code-generator\example-files\PlotGraphExample\example.json" """ // this is the correct notation for json { "program": { "PlotGraph": { "name": "Quadratic", "start": 0, "stop": 100, "samples": 100, "expression": "x^2", "title": "Q...
9c32bdc16d600dd759dab7593342f94451a0ca9c
john-montgomery2003/bridging
/constant/constants.py
2,053
3.875
4
#This could be controlled with __name__ but I found this to be a slightly more elegant approach #As it allows the GUI to be used from terminal as well as an IDE #DB URI (if using DB) dbURI = "postgres://zvulcvbmreajwj:fc82588eee9a53d2f2a98d9697ad7711dbc89642a4b681352840a9f41e02ead8@ec2-54-247-78-30.eu-west-1.comput...
a4de98dbe81f04066afd6f2c2fb5be95a714b517
varunbarole/learning_python
/vskills.in_practice_python-mock-test.py
4,404
4.0625
4
#list1 = [1,2,3,4,5] #new_list = list1.insert(2,5) #print (list1) ######################## #def func(a,b=4,c=12): # print(a,b,c) #func(2,7) #func(20,c = 13) #func(c = 50,a = 10) ######################## #range11= range(2) #print (range11) ######################## #def power(x, y=2): # r = 1 # ...
8895f049cca3c9196226a0770d161387e76824cd
CoachFoster/CreativeCodingProject_GeometricArt
/main.py
4,541
3.953125
4
### Turtle Graphics ### make a geometric pattern import time import random import turtle scrn = turtle.Screen() ct = turtle.Turtle() ct.hideturtle() ct.speed(0) ### Step 1: Make a hexagon for i in range(6): ct.forward(100) ct.left(60) time.sleep(1) ### Step 2: Repeat the hexagon for n in range(36): # complet...
5f9814c813358382c866de1298e734dcd18bc11c
ccollum-lang/Address-Book
/AddressBook.py
2,506
3.78125
4
firstNames = [] lastNames = [] numbers = [] emails = [] address = [] socialMedia = [] pet = [] inputFile = open("contactList.txt", "r") contacts = inputFile.readlines() inputFile.close() for i in range(len(contacts)): pieces = contacts[i].split(";") firstNames.append(pieces[0].strip()) lastNames.a...
6af55266a95dd4c5b84d50752fcccbbbc16fe3c8
jpark314/UCLA_courses
/CS35L/assignment 3/randline_python_with_comments.py
3,233
3.578125
4
#!/usr/bin/python ### this is the very first line, use the python interperter followed by this path in bin directory """ Output lines selected randomly from a file Copyright 2005, 2007 Paul Eggert. Copyright 2010 Darrell Benjamin Carbajal. This program is free software: you can redistribute it and/or modify...
7ed335fe4f22036846863201d0a3729c144ebe7c
dshaaax/python
/robotics assignment 1/task 1.py
1,239
4.0625
4
import random choice=[1,2,3,4,5,6] over=int(input("\nEnter the number of overs=")) over_1=over no_of_overs_1=1 your_run=0 ball=1 comp_ball=random.randint(0,over) comp_score=comp_ball *36 print(f"computer has scored runs= {comp_score}.") print(f"Your target runs= {comp_score +1}") print("over=",no_of_overs_1)...
afddecbb0e2499503277275c97b953df14af41b0
beni55/PuzHub
/rosalind/python/DNA/DNA.py
1,112
4
4
#!/usr/bin/python # DNA.py # http://rosalind.info/problems/dna/ """ Given a string of length at most 1000 that contains the characters A, C, G, and T, this script will count the number of each, and print the number of each respectively on a single line separated by spaces. The given string will actually be read from...
c9ca634d5a511662e9b75a6ec2aa937260b47265
anandvipul/DataStructure
/pymap/chainmap.py
770
3.515625
4
import collections dict1 = {'day1': 'Mon', 'day2': 'Tue'} dict2 = {'day3': 'Wed', 'day1': 'Thu'} res = collections.ChainMap(dict1, dict2) res1 = collections.ChainMap(dict2, dict1) # Creating a single dictionary print('Map1 \n') print(res.maps, '\n') print('Map2 \n') print(res1.maps, '\n') print('Keys = {}'.format(li...
a412f09c1e6c2b796a5b4de120fcca97a5293959
avasilistov/OOP
/demonstr_adapter.py
2,111
3.9375
4
import re from abc import ABC, abstractmethod text = ''' Design Patterns: Elements of Reusable Object-Oriented Software is a software engineering book describing software design patterns. The book's authors are Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides with a foreword by Grady Booch. The book is divi...
e30af57d76479a89497d3135aa2ca50b432ca091
ryanchao2012/frappuccino
/adventofcode/2017/day16_permutation_promenade.py
4,257
3.84375
4
""" --- Day 16: Permutation Promenade --- You come upon a very unusual sight; a group of programs here appear to be dancing. There are sixteen programs in total, named a through p. They start by standing in a line: a stands in position 0, b stands in position 1, and so on until p, which stands in position 15. The pro...
72e1b44d735cca5c460078fd3a8da80d9864b696
ryanchao2012/frappuccino
/adventofcode/2017/day04_high_entropy_passphrases.py
2,027
3.9375
4
""" --- Day 4: High-Entropy Passphrases --- A new system policy has been put in place that requires all accounts to use a passphrase instead of simply a password. A passphrase consists of a series of words (lowercase letters) separated by spaces. To ensure security, a valid passphrase must contain no duplicate words. ...
8d51cea9b4008e2acd7775c706848c79ba06191e
QianDong/DSAL
/Binary_tree_traversal/Binary_tree_traversal.py
2,228
4.0625
4
class Node(object): def __init__(self,value,left_child = None, right_child = None): self.value = value self.left_child = left_child self.right_child = right_child class Tree(object): def __init__(self): self.root = None # default root is None def add_root(self,valu...
1c82565b84b0f2c287183f6c62abadaa1ee64ae9
edponce/FACET
/facet/matcher/similarity/base.py
963
3.703125
4
from typing import Any, Iterable from abc import ABC, abstractmethod __all__ = ['BaseSimilarity'] class BaseSimilarity(ABC): """Interface for similarity measures.""" @abstractmethod def min_features(self, length: int, alpha: float) -> int: """Minimum number of features for searching similar str...
6bfce074c8e7584294d982eef133aa9fa7d07a0b
Elite2017/17B01A0231
/problem25.py
247
3.890625
4
#What is the index of the first term in the Fibonacci sequence to contain 1000 digits? def thousandfib(a,b): result = 2 while(len(str(b)) < 1000): a , b = b , a + b result = result + 1 return result print(thousandfib(1,1))
1499c04062f7012e75c55598a050376181caed2a
Elite2017/17B01A0231
/problem56.py
370
3.890625
4
#considering natural numbers of the form a^b, where a,b < 100 what is the maximum digital sum? def power_sum(a,b): sum = 0 n = pow(a,b) while(n > 0): r = n % 10 n = n / 10 sum = sum + r return sum max = 0 for i in range(1,100): for j in range(1,100): sum = power_sum(i,j) ...
7b5787dcd9590e489cc46a1692bbab8295c5a7dc
DonaldJennings/Sodoku-Solver
/solver2.py
1,378
3.828125
4
# -*- coding: utf-8 -*- """ Created on Thu Feb 13 18:46:31 2020 @author: Donald """ import numpy as np def possible(y,x,n): global grid #Checks the Row for i in range(0,9): if grid[y][i] == n: return False #Checks the Column for i in range(0,9): ...
a14e1029ab2fb8d0f27c116beb7409acfece536f
mariotinelli/UENP
/Inteligencia_Artificial/trabalho_inteligencia_artificial/dijkstra_search.py
2,260
3.5
4
class Dijkstra: def __init__(self, grafo, start, goalNode): self.visitados = [] self.listaAdj = [] self.custos = {} self.caminho = {} self.grafo = grafo self.start = start self.goalNode = goalNode def iniciarBusca(self): self.dijkstra...
bcfd6f06a20c44a826f5845c34545e6fa9916ee8
jasonmyers/discount_calculator
/discount_calculator_tests.py
1,712
3.53125
4
import unittest from discount_calculator import DiscountCalculator class DiscountCalculatorTests(unittest.TestCase): def test_ten_percent_discount(self): discount_calculator = DiscountCalculator() result = discount_calculator.calculate(100,10,'percent') self.assertEqual(10.0, result) ...
100067c7eb55e5a99aa20c720fb936ed35b97e3d
JoeCP17/algorithm-week2
/02_get_node_linked_list.py
1,265
4.03125
4
# Q. 링크드 리스트에서 index번째 원소를 반환하시오. class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self, value): self.head = Node(value) def append(self, value): cur = self.head while cur.next is not None: ...
f563eecd82b937683213aff5c386f83a692daa95
ffismine/leetcode_github
/普通分类/tag分类_栈/94_二叉树的中序遍历.py
798
3.515625
4
from typing import List from tag_tree import TreeNode class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: WHITE, GRAY = 0, 1 res = [] stack = [(WHITE, root)] while stack: color, node = stack.pop() if node is None: continue i...
da8b9b29c0a56c35c4ebf7b687608f3c7a61e751
ffismine/leetcode_github
/剑指offer/剑指 Offer 12. 矩阵中的路径.py
1,146
3.875
4
# -*- coding: utf-8 -*- # Time   : 2020/8/10 12:54 # Author : Zhang Xie """ 请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。 路径可以从矩阵中的任意一格开始,每一步可以在矩阵中向左、右、上、下移动一格。 如果一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子。 例如,在下面的3×4的矩阵中包含一条字符串“bfce”的路径(路径中的字母用加粗标出)。 [["a","b","c","e"], ["s","f","c","s"], ["a","d","e","e"]] 但矩阵中不包含字符串“abfb”的路径,因为字符串的第一...
a808dc3429962041389b32542919276460361257
ffismine/leetcode_github
/普通分类/tag分类_栈/42_接雨水.py
2,903
3.78125
4
# -*- coding:utf-8 -*- # Author : Zhang Xie # Date : 2020/3/5 16:33 """ 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。 示例: 输入: [0,1,0,2,1,0,1,3,2,1,2,1] 输出: 6 """ import inspect ''' 出于加解法考虑,这题貌似动态规划比较好。 出于简单考虑,可以分列求,暴力解法,见Solution 但是出于栈专题考虑,还是在Solution1里面使用栈解。 ''' # -------------------------------------------...
aeeb3c7c5b8cbe15fdd5afe7dad434ba9cbcd229
ffismine/leetcode_github
/剑指offer/tag分类_剑指offer_队列/面试题59_滑动窗口的最大值(推荐).py
1,703
3.6875
4
""" 给定一个数组 nums 和滑动窗口的大小 k,请找出所有滑动窗口里的最大值。 示例: 输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3 输出: [3,3,5,5,6,7] 解释: 滑动窗口的位置 最大值 --------------- ----- [1 3 -1] -3 5 3 6 7 3 1 [3 -1 -3] 5 3 6 7 3 1 3 [-1 -3 5] 3 6 7 5 1 3 -1 [-3 5 3] 6 7 5 1 3 ...
5f0d951b996bff2894e3a9d1ecb4a58e15a2280f
ffismine/leetcode_github
/剑指offer/tag分类_剑指offer_位运算/面试题15. 二进制中1的个数.py
990
3.546875
4
# -*- coding:utf-8 -*- # Author : Zhang Xie # Date : 2020/4/10 15:27 """ 请实现一个函数,输入一个整数,输出该数二进制表示中 1 的个数。 例如,把 9 表示成二进制是 1001,有 2 位是 1。 因此,如果输入 9,则该函数输出 2。 示例 1:输入:00000000000000000000000000001011 输出:3 解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。 示例 2:输入:00000000000000000000000010000000 输出:1 解释:输入的二进制...
894bc08ece7968512d1214ea6853199951b49de5
ffismine/leetcode_github
/普通分类/tag分类_链表/2_两数相加.py
1,657
4.125
4
""" 2. 两数相加 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。 示例: 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807 """ # 思考: # 需要注意几个点:1,位数不相等 2,进位 3,最后还要进位 # Definition for singly-linked list. # class ListNode: # ...
40a2f62f6d1bb410e3e85b9c4a4253130bf980e8
ffismine/leetcode_github
/普通分类/tag分类_链表/21_合并两个有序链表.py
3,275
3.84375
4
# -*- coding:utf-8 -*- # Author : Zhang Xie # Date : 2020/3/15 3:51 """ 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。  示例: 输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4 """ ''' 思考:这题还是挺简单的,比较之前链表元素大小,小的插入新链表,并且当前链表后移 第二种解法递归,递归需要考虑两个因素: 递归函数必须要有终止条件,否则会出错; 递归函数先不断调用自身,直到遇到终止条件后进行回溯,最终返回答案。 因此本题递归函数的终止条件就是有一个链表空了,那么可以直接返...
17c913ab775c26cdd3160217b0f8afbc703d8b4f
ffismine/leetcode_github
/普通分类/tag分类_链表/160_相交链表.py
2,697
3.640625
4
# -*- coding:utf-8 -*- # Author : Zhang Xie # Date : 2020/3/12 1:45 """ 编写一个程序,找到两个单链表相交的起始节点。 输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3 输出:Reference of the node with value = 8 输入解释:相交节点的值为 8 (注意,如果两个列表相交则不能为 0)。 从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。 在 A 中,相交...
c69b703cb6369360146c71691eb6ca77037d1766
ffismine/leetcode_github
/普通分类/tag分类_堆/215_数组中的第K个最大元素.py
1,425
3.625
4
# -*- coding:utf-8 -*- # Author : Zhang Xie # Date : 2020/3/9 18:32 """ 在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。 示例 1: 输入: [3,2,1,5,6,4] 和 k = 2 输出: 5 示例 2: 输入: [3,2,3,1,2,4,5,5,6] 和 k = 4 输出: 4 说明:你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。 """ ''' 思考: 创建一个k长度的最小堆。然后先放进去k个,然后大于于堆顶就替换 ''' from heapq impo...
3f375e24a0eddaef1a024c41fadde2c6d78bfcb4
260/192-Composite_number
/192_Composite_number.py
152
3.5
4
#!/usr/bin/python3 # This problem is http://yukicoder.me/problems/391 first_line = input() number = int(first_line) print(int(number / 2) * 2)
60965d5bac4a8727e7e2065bad8d32c7a2dbc7cb
Adityaaj17/SE-Experiment
/add.py
177
4.03125
4
a = int(input("Enter first number:")) b = int(input("Enter second number:")) def add(a, b): return a+b c = add(a, b) print ("The addition of two numbers is:", c)
e27b719ca9e6e6d6067a7e6ad7ae8fa066c99594
Xuefann/LearnPython
/0006.py
1,026
3.65625
4
# -*- coding: utf-8 -*- """ 你有一个目录,放了你一个月的日记,都是 txt,为了避免分词的问题,假设内容都是英文,请统计出你认为每篇日 记最重要的词。 """ import os import re def findWord(DirPath): if not os.path.isdir(DirPath): return fileList = os.listdir(DirPath) reObj = re.compile('\b?(\w+)\b?') for file in fileList: filePath = os.path.join(DirPa...
0ebfeec1f322e2af0df67918616742997c8d77d6
leventegal/10.E
/oraifeladat.py
884
3.5625
4
inputList = [] inputList += [int(input("Kerek egy szamot: "))] inputList += [int(input("Kerek meg egy szamot: "))] inputList += [int(input("Kerek meg egy szamot: "))] print("A legnagyobb beolvasott szam: "+str(max(inputList))) inputList = [] inputList += [int(input("Kerek egy szamot: "))] inputList += [int...
159be50ec4bf04798b2adeda9b79b0e68beb21f2
luik-2210/my_captain
/data_structures.py
824
4.03125
4
#assigning elements to different lists a=[int(x) for x in input().split()] print("How many nos. you want to add = ") n=int(input()) for i in range(n): print("no. which you want to add = ") f=input() a.append(f) print(a) #accessing elements from a tuple tu=("c","c++","python","java","ruby","PHP")...
edb368b4f2000cdffb8438bfa9c831547eb10736
KFreund91/python-challenge
/pybank_main.py
1,716
3.703125
4
import os import csv budget_csv = os.path.join("..",'python-challenge', 'budget_data.csv') months = [] revenue = [] revenue_change = [] monthly_change = [] with open(budget_csv, 'r',newline = '') as csvfile: csvreader = csv.reader(csvfile, delimiter=",") next(csvreader) for row in csvreader: mont...
b2b27d69caeab17bc3150e1afe9c1e1de3ac5d9e
aniketchanana/python-exercise-files
/programmes/listMethods.py
922
4.46875
4
# methods are particular to a given class # append insert & extend first_list = [1,2,3,4,5] # first_list.append([1,2,3]) # print(first_list) # [1, 2, 3, 4, 5, [1, 2, 3]] simply pushes it inside the list # no matter what is that <<append takes in only one arguement>> # first_list.extend([1,2,3,4]) # print(first_l...
7b1dc9a8946dc49e8510f56a454e490d4dbe0fb4
aniketchanana/python-exercise-files
/programmes/list.py
596
3.859375
4
# list are same as arrays in python # tasks = [1,2,3,4] # print(len(tasks)) # r = range(1,10) # li = list(r) # print(li) friends = ["a","b","c","d"] colors = ["red","orange","yellow"] # print(colors[-1]) # print("red" in colors) # # print(friends[0]) # if "red" in colors : # print("red is there inside") nu...
5fbbfd843c662a09a20b1e5bad1861a2a82f53fa
aniketchanana/python-exercise-files
/programmes/bouncer.py
270
4.125
4
age = input("How old are you") if age : age = int(age) if age >= 18 and age < 21 : print("Need a wrist band") elif age>=21 : print("you can enter and drink") else : print("too little to enter") else : print("Input is empty")
3432ca0662fd2ed64b1234e8ca7523cf2fa48abd
aniketchanana/python-exercise-files
/programmes/tuple_and_sets.py
503
3.921875
4
# alphabets = ('a','b','c','d','a') # print(alphabet) # for alphabet in reversed(alphabets) : # print(alphabet) # i = len(alphabets) - 1 # while i >= 0 : # print(alphabets[i]) # i -= 1 # print(alphabets.count("a")) # print(alphabets.index("a")) # s = set(alphabets) # print(s) # s.add("z") # print(s) ...
d3dfc731a62bcb7b8d1a35807286cdde242f7057
lil-val/she-codes
/src/Ex14/check_box.py
1,854
3.9375
4
from tkinter import * class Application(Frame): def __init__(self, master): """initialize the Frame""" Frame.__init__(self, master) self.grid() self.create_widgets() def create_widgets(self): """create widgets for movie type choice""" Label(self, text="Choose ...
2fb5c6ea2c083c7c56f868652b5490dbfcfcff5c
lil-val/she-codes
/src/Ex13/Ex13_Frame.py
615
3.703125
4
from tkinter import * root = Tk() # creating an application (window) top_frame = Frame(root) top_frame.pack() bottom_frame = Frame(root) bottom_frame.pack(side=BOTTOM) bottom1 = Button(top_frame, text='Bottom 1', fg='red') bottom2 = Button(top_frame, text='Bottom 2', fg='blue') bottom3 = Button(top_frame, text='Bot...
a63cf238ddb170dc2b3bf8c928c311e249bf471e
lil-val/she-codes
/src/Ex5/Ex5_2.py
345
3.8125
4
def same_first_last(strings): #sum the number of strings that len >= 2 and first and last letters are equal result = 0 for i in strings: if len(i) >= 2 and i[0] == i[-1]: result += 1 return result print(same_first_last(['aba', 'xyz', 'aa', 'x', 'bbb'])) print(same_first_last(['x', ...
97f14ca684caaa17158f8e7018fcf919bcdb0e0d
lil-val/she-codes
/src/Ex2/Ex2_2.py
441
4.0625
4
from datetime import datetime now = datetime.now() current_year = now.year def name_age(): first_name = input("What is your first name?") last_name = input("What is your last name?") year_of_birth = input("what is your year of birth?") initials = first_name[0].upper() + last_name[0].upper() age = c...
966a567b7a47c88751896717ae03a0836e7a0529
lil-val/she-codes
/src/Ex14/radio_buttons.py
1,498
3.859375
4
from tkinter import * class Application(Frame): def __init__(self, master): """initialize the Frame""" Frame.__init__(self, master) self.grid() self.create_widgets() def create_widgets(self): """create widgets for movie type choices""" Label(self, text="Choose...
62954e8eae6c6404b10ec2ccd0336a15f0f2c427
Azefalo/Curso-Algoritmos_e_Logica_de_programacao
/Sessão 06 - Exercício 03.py
125
3.90625
4
p = 0 i = 0 n = int(input("Informe um número ")) if n % 2 == 0: p = n else: i = n print(p, end=" ") print(i)
3862e06a4303f9f995275e6de13d3a104334dc84
Azefalo/Curso-Algoritmos_e_Logica_de_programacao
/Sessão 06 - Exercício 09.py
466
3.953125
4
poluicao = float(input("Informe o índice de poluição: ")) if poluicao >= 0.3 and poluicao < 0.4: print("Atenção: Indústrias do grupo 01 deve suspender atividades") elif poluicao >= 0.4 and poluicao < 0.5: print("Atenção: Indústrias do grupo 01 e indústrias do grupo 02 devem suspender atividades") elif polu...
dfaa73fd6fea79271b5ac3359e8685d670a03dd1
aparnasj-sj/StartUpfundingDataset
/prg1.py
914
3.6875
4
''' Check the trend of investments over the years. To check the trend, find - Total number of fundings done in each year. Plot a line graph between year and number of fundings. Take year on x-axis and number of fundings on y-axis. Print year-wise total number of fundings also. Print years in ascending order. ''' import...
c5238645150f5c023aee2f6515a53c30ceb7cd48
Sumittripathi07/Find_SquareCube
/mapfunc.py
376
3.984375
4
while(True): work = input("s Square and c for cube---->") if work=="s": number = int(input("Enter a number---->")) square = number*number print(square) continue if work=="c": number = int(input("Enter a number---->")) cube = number*nu...
575598e3cf96955904e85b9fc727d6cee28bd19b
PsycheShaman/PythonAssignments
/Python Assignments/Q3.py
542
3.90625
4
# -*- coding: utf-8 -*- """ Created on Mon Mar 23 08:35:27 2015 @author: gerhard """ inputThing = raw_input('please enter a word to see whether it is a palindrome: ') list1 = [] for let in inputThing: list1.append(inputThing) length = len(list1) i = 0 j = length-1 k = 0 if length%2 == 0: print 'it\'s not a...
4116a9dab8d3501204cfd87afa23d07dc990b44c
phipps980316/TCP-simulator
/14729831_server.py
20,738
3.625
4
from socket import socket # import for the TCP Socket object from json import dumps, loads # import for turning the packet object into a json string from random import randint # import to generate random number encrypting a packet from sys import getsizeof # import to get the size of a packet object in bytes ...
323d6a7fec566957e2cf4b0ab225c0f57ed09843
jordanaron22/Weighted-Voting-Comps-Winter-Spring-2018
/4Search.py
4,499
3.9375
4
def main(): #These lists will have the final answers in them winning_combos = [] winning_combos_power =[] def summary(): print("The possible winning combinations are:") print(winning_combos) print("") print("There are ", len(winning_combos_power), " different ...