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
91a2afde2c12e5dc7637d134a3ce99fb18909942
christina-wei/HackerRank
/30 Days of Code/Day 08 - Dictionaries and Maps.py
513
3.703125
4
# Enter your code here. Read input from STDIN. Print output to STDOUT if __name__ == '__main__': n = int(input()) #read data into phone_book phone_book = {} for i in range(n): item = list(input().rstrip().split()) phone_book[item[0]] = item[1] #query phone book while True: ...
6ea3d3b6a3065168637b3f77458784b6a974ef8d
colekev/dsp
/python/advanced_python_dict.py
1,550
3.765625
4
import csv import re with open('faculty.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') names = [] degrees = [] titles = [] emails = [] lastNames = [] firstNames = [] info = [] # Get degree, titles, emails for row in readCSV: name = row[0] degree = row...
199b1200db2b7d3fa3efc71d1c804689b9955e48
OneFrom/Learning-Git
/Test27.py
1,651
3.609375
4
print('Подсчет повторений элементов списка - от 0 до 5') a = [1,4,0,3,4,2,5,1,0,3,2,4,5,2,0,5,4,1,3,4] # создаем нулевой результирующий список из 5 элементов - по кол-ву count = [0,0,0,0,0,0] #count = [0]*6 for i in a: count[i] +=1 print('Результат') print(count) for i in range(6): print('Элемент ' + str(i) + ' ...
2e3c2b847b3c0f3d91167c191f34ef481b99d563
leelaram-j/pythonLearning
/com/test/package/try_block.py
930
3.765625
4
# try block is useful for runtine errors # print( 10/0) ''' try: a = 10/0 except Exception as e: print(e) ''' try: a = 10/0 except Exception as e: print(e) else: print("value is",a) finally: print("Thats all for today") print(dir(locals()['__builtins__'])) # to print all exception details pr...
6532790fd1d45002068c0ab963f71ba1b989791a
leelaram-j/pythonLearning
/com/test/package/inputtest.py
105
3.984375
4
"""name1, name2, name3 = input("Enter 3 names: ").split(',') print(name1) print(name2) print(name3)"""
bf2443eb20578d0e4b5765abc5bd6d3c46fabdc6
leelaram-j/pythonLearning
/com/test/package/lists.py
1,231
4.125
4
""" List in python written inside [] sequence type, index based starts from 0 mutable """ a = [1, 2, 3, 4, 5] print(a) print(type(a)) print(a[1]) # array slicing print("Slicing") print(a[0:3]) print(a[2:]) print(a[:3]) print("-------------") a = [1, "sample", True, 10.45, [1, 2, 3, 4]] print(a) print(type(a)) prin...
f4b8c5d1fee9053b7b6ae06dbb956742a908f71a
leelaram-j/pythonLearning
/com/test/package/arithmetic_operators.py
104
3.703125
4
a = 123 b = 10 print(a+b) print(a-b) print(a*b) print(a/b) print(a//b) print(a%b) print(a**b)
518f393407a837f8a3e10af8d8494197a33ce491
leelaram-j/pythonLearning
/com/test/package/SampleClass.py
203
3.78125
4
class car(): pass a = 10 print(type(a)) print(type(car)) # in python, class is inside type remember that swift = car() print(isinstance(swift, car)) print(type(swift)) print(isinstance(a, int))
73ea0296bc2092f973fb3709818799e418a9f2f2
apanesar11/python-concepts
/02_functional-programming/05_lambda.py
278
3.765625
4
from functools import reduce lst = [1, 2, 3] doubled_lst = list(map(lambda item: item * 2, lst)) print(lst) print(doubled_lst) odd_lst = list(filter(lambda item: item%2, lst)) print(lst) print(odd_lst) total_sum = reduce(lambda i, j: i+j, lst, 0) print(lst) print(total_sum)
37d5a2fcb0f18f6cf6180bbd664b5dd81d77a83d
Yazuline/juegotortugaspython
/juego.py
1,536
3.953125
4
import turtle import random s= turtle.Screen() s.title("Juego Tortugas") s.bgcolor("#87A8A4") #t= turtle.Turtle() jugador1= turtle.Turtle() jugador2= turtle.Turtle() jugador1.hideturtle() jugador1.shape("turtle") jugador1.color("white","white") jugador1.shapesize(2,2,2) jugador1.pensize(3) jugador1.penup() jugador1...
e06227af5edd3a4da7fbc03ca7bc310c367fe017
Gamez0/LeetCode-Solutions
/Python/496_nextgreaterelement.py
365
3.5
4
class Solution: def check(self, number, nums1, nums2): index = nums2.index(number) for _ in range(index, len(nums2)): if(nums2[_]>number): return nums2[_] return -1 def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: return ...
99ed60af28c839a9f753dc959afb3e05d80b98b9
Gamez0/LeetCode-Solutions
/Python/100.SameTree.py
852
3.921875
4
#Time Complexity: O(n) #Space Complexity: O(n) #Speed: 98.83% #Memory: 13.23% # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isSameTree(self, p: ...
5a55dce71b2428c8541e0d3fde9620c447db084f
Gamez0/LeetCode-Solutions
/Python/994_Rotting_Oranges.py
1,261
3.609375
4
# Time Complexity = O(rows*columns) # Space Complexity = O(rows*columns) class Solution: def orangesRotting(self, grid: List[List[int]]) -> int: n = len(grid) m = len(grid[0]) count = 0 rotten = [] for i in range(n): for j in range(m): if...
0d8e5f9e71338e288044c7e58cd0d1c4816afa5e
Gamez0/LeetCode-Solutions
/Python/621-Task-Scheduler.py
888
3.65625
4
""" Given a characters array tasks, representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle. However, there is a non-negative integer n...
3f27b8b637000cefcfdd3129bb27c05d63391b4f
soorichu/algopy
/Search/SequentialSearchInsert.py
175
3.8125
4
def SequentialSearchInsert(A, n, x): A.append(x)# A[n] = x return A, n+1 if __name__=="__main__": A = [6, 2, 7, 1, 9, 3, 5, 4] print(SequentialSearchInsert(A, len(A), 0))
a796a76fb13855afc5f6805eafb63ac263093811
soorichu/algopy
/Sort/RadixSort.py
850
3.71875
4
#기수 정렬(Radix Sort) #기수 정렬은 입력값을 자릿수 별로 부분적으로 비교하는 정렬 방식으로, #주어진 정렬의 키값을 자릿수별로 나누고, 자릿수별로 계수정렬과 같은 #안정적인 정렬 알고리즘을 반복적으로 적용하여 정렬하는 방법이다. #LSD(Least Sighificant Digit)와 MSD(Most Significant Digit)가 있다. #시간복잡도는 O(n) #안정적인 정렬, 비제자리 정렬 from MergeSort2 import MergeSort def RadixSort(A, n): for i in range(len(str(max(A)))...
ce782a81b3345ee61ed10b452ba5b8840cacde15
soorichu/algopy
/hanoi problen/haoni.py
170
3.875
4
def Hanoi(n, fr, to, ext): if n==1: print(n, fr, "->", to) else: Hanoi(n-1, fr, ext, to) print(n, fr, "->", to) Hanoi(n-1, ext, to, fr) Hanoi(5, "A", "C", "B")
f9a0d2bf34b8fd8ebcbaa58e0d9c1fbadd05711b
soorichu/algopy
/Sort/test.py
111
3.65625
4
A1 = [] for n in range(10): A1.append(2*n-1) print(A1) print(A1[3]) def A2(n): return 2*n-1 print(A2(3))
753e0079d87acbeee9fe057ae50db6fcc2e91bd1
Nduta-jayne27/smartfarm
/mkulimaBora/soil.py
281
3.578125
4
#!/usr/bin/python import RPi.GPIO as GPIO import time #GPIO SETUP channel = 7 GPIO.setmode(GPIO.BOARD) GPIO.setup(channel, GPIO.IN) x=0 while(x<20): if GPIO.input(channel): print( " No Water Detected!") time.sleep(1) else: print ("Water Detected!") time.sleep(1) x=x+1
ba345e195c8874b3e98e031f0c6a0bbf5bdac67e
PROTECO/python_octubre2017
/Tercer Sábado/Códigos_ControlDeFlujo/08ejercicio_extra.py
722
4.09375
4
#-*-Coding:utf-8-*- #Contar palabras '''Este ejericicio no lo logramos a ver, pero la idea es: Dar le un texto al programa y que cuente cuantas palabras de cada tipo le dimos. con la ayuda de un diccionario, cada palabra nueva que veamos la agregaremos como llave y la clave será un varor de uno Si encontramos mas ve...
2ac2708b8abb817835948cc79d235284c3deb0f1
PROTECO/python_octubre2017
/Quinto Sábado/Códigos/Pandas/telescopio.py
495
3.515625
4
import pandas as pd import matplotlib.pyplot as plt data=pd.read_csv('datosTelescopio.csv') """ Si no cargan las cabeceras, se debe hacer manualmente headers=['Distancia','Velocidad de recesión'] data_no_headers= pd.read_csv('datosTelescopio.csv',names=headers) print(data_no_headers.head()) """ #Se muestran los pri...
7060c388eff7b1291ae8b1781107f915a3d172da
vmickus/devito
/devito/ir/clusters/queue.py
2,055
3.84375
4
from itertools import groupby __all__ = ['Queue'] class Queue(object): """ A special queue to process objects in nested IterationSpaces based on a divide-and-conquer algorithm. Notes ----- Subclasses must override :meth:`callback`, which may get executed either before (fdta -- first div...
934f9b2581ab5fa583aaf274d068448b9cc4f0de
sharpchris/coding352
/8.py
2,259
4.375
4
# Codebites URL: https://codechalleng.es/bites/21/ cars = { 'Ford': ['Falcon', 'Focus', 'Festiva', 'Fairlane'], 'Holden': ['Commodore', 'Captiva', 'Barina', 'Trailblazer'], 'Nissan': ['Maxima', 'Pulsar', '350Z', 'Navara'], 'Honda': ['Civic', 'Accord', 'Odyssey', 'Jazz'], 'Jeep': ['Grand Cherokee', '...
cebd6291ec379a182d685fcad1afcfa8a8fe5236
sharpchris/coding352
/talkpython_days/04-06-collections/chris/directors.py
1,264
4.09375
4
from collections import defaultdict, namedtuple, Counter import csv # Name Tuple Movie = namedtuple('Movie','title, rating') # Default Dict directors_with_movies = defaultdict(list) # The Pythonic way of opening a file is to use a context manager ("with") with open("movie_metadata.csv", encoding='utf-8') as f: m...
c9dc054d0eed9d7389749599aeccafdadbd0f4a4
hcarlens/epi-python
/solution_11_1.py
766
3.828125
4
""" Search a sorted array for the first occurrence of k """ import bisect def find_first_occurrence_naive(array, key): """ Naive O(n) solution) """ for index, value in enumerate(array): if value == key: return index def find_first_occurrence_standard_library(array, key): """ Standa...
05e7b9d17cb671ee5f680c0e0db4b3533fff11d3
hcarlens/epi-python
/test_6_1.py
565
3.859375
4
from solution_6_1 import string_to_int, int_to_string def test_string_to_int(): assert string_to_int("1") == 1 assert string_to_int("135462") == 135462 assert string_to_int("0") == 0 assert string_to_int("-1") == -1 assert string_to_int("-20") == -20 assert string_to_int("-0") == 0 assert s...
bd6d47dad3f6770e8621720d6654ab948c03f97a
jjoe0303/cs231n_assignment
/assignment1/cs231n/classifiers/softmax.py
3,862
3.609375
4
from builtins import range import numpy as np from random import shuffle from past.builtins import xrange def softmax_loss_naive(W, X, y, reg): """ Softmax loss function, naive implementation (with loops) Inputs have dimension D, there are C classes, and we operate on minibatches of N examples. I...
915db37e4fd66092f114551ca9023bb601c837ab
AnnHalii/Python_Hillel
/lk_8_hw/1_task.py
145
3.75
4
nums = [61, 228, 9] def biggest_num(list_of_nums): return ''.join(sorted(map(str, list_of_nums), reverse=True)) print(biggest_num(nums))
afc7698858efcd7e99156fcc0799ea3236b57f8f
AnnHalii/Python_Hillel
/lk_2_hw/3_task.py
861
4.0625
4
import sys first_value: str = input('Input first value: ') operation: str = input('Input math operation: ') second_value: str = input('Input second value: ') for value in {first_value, second_value}: if not value.isdigit(): print(f'Value of type {type(value)} {value} is not a digit') sys.exit(0) ...
5b85bb3a3b4644b4895dda470003ceeca33a50c5
AnnHalii/Python_Hillel
/lk_2_hw/2_task.py
351
4.0625
4
password: str = input('Input password:') sign = {'@', '.', '!', '&', '?'} if len(password) <= 8: print(f'Invalid') elif not any(z in sign for z in password): print('Invalid') elif password.isdigit(): print('Invalid') elif password.isalpha(): print('Invalid') elif password.isupper(): print('Invalid...
b37a5af3c95a8fa68976a2948e504d64660e1bc1
Mouhab-dev/cs50-pset-mouhab
/pset6/dna/dna.py
3,540
4.0625
4
''' THIS IS CS50 MOHAB TAHER EL-BANNA FROM: EGYPT ''' from sys import argv, exit import csv def main(): # check for correct no. of command line arguments if len(argv) != 3: print("Some command line arguments are missing: dna.py CSV file, TXT file") exit(1) STRs = [] ...
f65e852f760696d1229198bffdc5cf1ca6aff645
dragonlee8/leetcode
/244 Shortest Word Distance II.py
856
3.890625
4
import sys def worddist(str1, str2, mapping): if not str1 or not str2 or not mapping or str1 not in mapping or str2 not in mapping: return -1 l1 = mapping[str1] l2 = mapping[str2] idx1 = idx2 = 0 ret = sys.maxint while idx1 < len(l1) and idx2 < len(l2): ret = min(r...
c8dde30269fa09082a7ab4e42145052ebfe445c8
AbdulSaif/Image-Classifier
/train.py
3,288
3.859375
4
# This function is used to train a model in classifying a set of data using a # pre-defined parameters of CNN arch, learning rate, epochs and size of hidden # layer def train_model(train_datasets, trainloader, validloader, model, epochs, learning_rate, device, save_dir): ''' This function is used to train a mo...
099b839ba1efeed610f3c22d792d6e69c8e1a618
juanse962/analisis-numerico
/machine/binary_to_integer.py
870
3.5625
4
def binary_to_integer(number_binary): aux1 = 0 aux2 = 0 if '.' in number_binary: integer,decimal = number_binary.split('.') integer = integer[::-1] decimal = decimal[::-1] long_integer = len(integer) -1 long_decimal = (len(decimal) * -1)-1 for i in rang...
43d150cc0a2fe5eb292f813a61d30f73d6f596ba
juanse962/analisis-numerico
/metodos/incremental_search.py
840
3.9375
4
from sympy import * import math x = symbols('x') function = log(x**2+1) +x*cos(6*x+3)-3*x-10 x0= input("Write the initial value: ") delta = input("interval length (delta): ") niter = input("number of iterations: ") x0 = float(x0) delta = float(delta) niter = int(niter) fx0 = function.subs(x, x0) i...
65eddd56439704cc3c2dbda2d61fbb0385679d08
gitotk/python
/09.py
82
3.703125
4
data = [1,2,3,4,5] print(data) ndata = [n*2 for n in data if n!=3] print(ndata)
4275fd6a4ed2817fc5760d1c29d6f76390ddb806
gitotk/python
/43.py
340
3.984375
4
file = input("ファイル名:") try: f = open(file,"r") except FileNotFoundError: print("ファイルをオープンできませんでした") else: lines = f.readlines() print("-------") for line in lines: print(line, end="") f.close() finally: print("-------") print("処理を終了")
ed2c79ed003627360d67824f5450105dc72255a2
WeKeyPedia/toolkit-python
/wekeypedia/metrics/lsm.py
5,673
3.515625
4
# -*- coding: utf-8 -*- from __future__ import division from collections import defaultdict import numpy as np import nltk def compare(text1, text2): """ Compare two texts using the Linguistic Style Matching (LSM) [1]_ method .. math:: LSM_{preps} = 1 - \\frac{|preps_1 - preps_2|}{preps_1 + preps_2 + 0...
67fde28b0c772eff458cf326520c573a944ebd0e
asivapra/Hivery
/paranuara.py
9,059
3.875
4
""" Paranuara Challenge Created by: Dr. Arapaut V. Sivaprasad on 17 May, 2020 Last modified on: 18 May, 2020 Your API must provides these end points: - Given a company, the API needs to return all their employees. Provide the appropriate solution if the company does not have any employees. - Given 2 people, provide ...
037920de71306887635d46953eb21890f00d9593
yeri96/AlgoritmicaBasica_2018
/Mayor_Menor/mayor_menor.py
1,617
4.4375
4
# coding: utf-8 numero1 = input("Introduce el primer número: ") numero2 = input("Introduce el segundo número: ") numero3 = input("Introduce el tercer número: ") if numero1 == numero2 and numero1 == numero3: print "Ha escrito 3 veces el mismo número" else: if numero1 == numero2 and numero1 != numero3: p...
a017de5cb43b53b1f7c796ab015b91a68f09efdf
abhishekratnam/Datastructuresandalgorithmsinpython
/DataStructures and Algorithms/Recursion/Reverse.py
445
4.1875
4
def reverse(S, start, stop): """Reverse elements in emplicit slice S[start:stop].""" if start < stop - 1: S[start], S[stop-1] = S[stop - 1], S[start] reverse(S, start+1, stop - 1) def reverse_iterative(S): """Reverse elements in S using tail recursion""" start,stop = 0,len...
dcf4eae00150258a156a6bbfe39b736cc779bd92
jeyaprakash1/pattern_programs
/testpattern.py
147
3.5
4
# 1 # 2 3 # 4 5 6 # 7 8 9 10 # 1112131415 i=1 for row in range(1,6): for col in range(row): print(i,end="") i=i+1 print()
69e53ffc102c625353d4172f5001e3f6e6fad682
gaozuxin/tkinter_demo
/tkinter/checkbutton.py
998
3.609375
4
# !/usr/bin/python # -*- coding: UTF-8 -*- import tkinter as tk # 导入 tkinter 库 window = tk.Tk() # 创建窗口对象的背景色 window.title("my window") window.geometry("800x200+200+100") # 设置窗口大小 并初始化桌面位置 window.resizable(width = True,height = True) # 宽不可变 高可变 默认True l = tk.Label(window,bg="yellow",width=20,text="empty") l.pack...
1c0c67c4759c8d5764b6440f81508577fca2093f
ertugrulsmz/machinelearning
/Machine_Learning/basics/Preprocessing.py
1,112
3.53125
4
import numpy_ex as np import pandas as pd dataset = pd.read_csv("csvfiles/data.csv") X = dataset.iloc[:,:-1].values y = dataset.iloc[:,3].values from sklearn.impute import SimpleImputer imp = SimpleImputer(missing_values=np.nan, strategy='mean') X[:,1:3] = imp.fit_transform(X[:,1:3]) # Encoding categorical data # E...
ec59dde65e26830a8cc8c1ede1a305c4ccd17088
mycaule/leetcode
/python/exo242.py
335
3.515625
4
# Leecode 242 # pylint: disable-all from collections import Counter def is_anagram(s, t): c = Counter(s) print(c) for x in t: c[x] -= 1 print(c) return all([x == 0 for x in c.values()]) s = "anagram" t = "nagaram" print(is_anagram(s, t)) # True s = "rat" t = "car" print(is_anagram(s...
576e4f5c490a0be063255b9a6e480044cbc62ab8
mycaule/leetcode
/python/exo005.py
1,073
3.78125
4
# Leetcode 005 # pylint: disable-all def longest_substring(s): """ O(N^2) in time O(N) in space """ print(s) palindromes1 = [] palindromes2 = [] for i in range(len(s)): palindromes1.append("") palindromes2.append(s[i]) # i-delta < i < i+1+delta in odd symmetry ...
459f01153bfe2033437124ae407b7c661616f653
lihaineng/little-projects
/card/2名片管理系统-文件版.py
4,679
3.671875
4
""" pass:用来测试,跳过不想执行的代码块 """ # 导包 import sys import os # 定义全局变量 info_list = [] userName = "admin" passWord = "123456" # 定义函数 def loadInfo(): global info_list if os.path.exists("info_list.text"): f = open("info_list.text", "r", encoding="utf-8") data = f.read() info_list = eval(data) ...
e03f40711cfe8a26b38de0c63faaee30e1b0e336
pragatishendye/python-practicecode
/FahrenheitToCelsius.py
338
4.40625
4
""" This program prompts the user for a temperature in Fahrenheit and returns the Celsius equivalent of it. Created by Pragathi Shendye """ tempInFahrenheit = float(input('Enter a temperature in Fahrenheit:')) tempInCelsius = (tempInFahrenheit - 32) * (5 / 9) print('{} Fahrenheit = {:.2f} Celsius'.format(tempI...
f6ebe68c4b89409a1eb999256a34fb5e7bbf8ae4
franksoong/python-graph-algos
/code/adjacencySet/graph.py
816
3.6875
4
import abc import numpy as np class Graph(abc.ABC): def __init__(self, num_vertices, directed=False): self.num_vertices = num_vertices self.directed = directed @abc.abstractmethod def add_edge(self, v1, v2, weight): # v1 and v2 are vertices pass @abc.abstractmethod ...
23a9baab1b0308bde129e6d01894f56ea79e3c64
iresbaylor/codeDuplicationParser
/engine/utils/printing.py
921
4.1875
4
"""Module containing methods for pretty-printing node trees.""" def print_node_list(node_list): """ Print a list of TreeNodes for debugging. Arguments: node_list (list[TreeNode]): a list of tree nodes """ for node in node_list: if node.parent_index is None: print_node...
7258e67f6c162282fd19a7d7caf1f2e93724e68b
iresbaylor/codeDuplicationParser
/engine/algorithms/iodine/anti_unification.py
2,108
3.796875
4
from ...nodes.pattern import PatternNode def anti_unify(list1, list2, index1, index2, worktable, num_holes=0): """ Create a tree of PatternNodes from two lists. Arguments: list1 {list of TreeNodes} -- first tree to be compared list2 {list of TreeNodes} -- second tree to be compared ...
0eea7b063e2d2b2f4141b23d886bb55783965170
upputuriyamini/yamini
/62.py
123
3.75
4
a=raw_input() for c in a: if c>='2': print ('no') break; else: print ('yes')
f29ca346f0977a08234ceeb742e13ff1ec31fb11
upputuriyamini/yamini
/al.py
211
4.15625
4
al=int(input()) if al == 0: exit(); else: if((al>='a' and al>='z') or (al>='A' and al>='Z')): print(al, "is an alphabet.") else: print(al,"is not an alphabet")
835ea8d4027416729350e476abaf5a3b2ced033f
saipooja123/python-jenkins-git-demo
/func.py
323
3.59375
4
# -*- coding: utf-8 -*- """ Created on Mon Jan 25 15:37:57 2021 @author: RajagiriSaiPooja """ # def num1(x): # def num2(y): # return x+y # return num2 # print(num1(2)(3)) import re data=[5,10,15,25] y=list(map(lambda x:x*4,data)) print(y) name="helloworld" pattern=r"o" print(re.split(pattern,name...
7f207c723ac165c0df65952c1456b7fc7558eaed
Mr0o/simple-fireworks-simulator
/vectors.py
2,427
4.09375
4
# This is my own Vector library that I created for the fun of it # Plenty of vector libraries already exist that are more robust and have lots more features # In here you will find a Vector class with methods for performing basic vector math # All vector math is 2-Dimensional meaning that all Vectors have just an ...
00bf0676a2aae047572d5ff72f16a16d51a4dc3b
ghostlyman/Python_Practice
/Happy_Number.py
439
3.59375
4
def add(num): return sum[int(x) for x in str(num)] # ret = 0 # for i in str(num): # ret += (int(i)) ** 2 # return ret def happy_number(num): results = {num} ret = num while ret >= 10: ret = add(ret) if ret in results: return False results.add(ret)...
187e44d855188c404d5e2c07439bcd7225e55193
christophermoverton/astropywork
/redshiftcosmtut.py
5,395
3.984375
4
# Each redshift corresponds to an age of the universe, so if you’re plotting some quantity # against redshift, it’s often useful show the universe age too. The relationship between # the two changes depending the type of cosmology you assume, which is where astropy.cosmology # comes in. In this tutorial we’ll sho...
19dba090b02333b50c4e26769a80b11f757d5491
christophermoverton/astropywork
/editfitsheadertut.py
3,017
3.671875
4
# This tutorial describes how to read in and edit a FITS header, and then write it back out to disk. # For this example we’re going to change the OBJECT keyword. from astropy.io import fits # astropy.io.fits provides a lot of flexibility for reading FITS files and headers, but most of the time # the convenience fun...
eca5ed8cc790022797ef1e6d685928220e266b77
WeiHao97/macrobase-diff
/mbdiff/pretty_print.py
819
3.609375
4
"""Present explanations in a more approachable way.""" from typing import List, Dict from tabulate import tabulate from pandas import DataFrame def present_explanations(explanations: List) -> str: pres_df = [] for score, explanation in explanations: row = {"score": score} row = {**row, **expla...
d3f09d44fc3c548b26fe0076aeb0daf498752244
paolopoli1980/project-euler
/euler53.py
411
3.640625
4
# -*- coding: utf-8 -*- """ Created on Sat Sep 17 14:26:59 2016 @author: paolo """ import math def binomial(i,j): x=math.factorial(i) y=math.factorial(j) z=math.factorial(i-j) return x/(y*z) lista=[] c=0 n=101 l=1000000 for i in range(n): print "*" for j in ran...
b6dc11066be6f7b3d5f1dfdf9b502e5b111901b6
mmatheusvidal/Python
/POO/Playlist.py
1,598
3.765625
4
class Programa: def __init__(self, nome, ano): self._nome = nome.title() self.ano = ano self._likes = 0 @property def likes(self): return self._likes @property def nome(self): return self._nome @nome.setter def nome(self, novo_nome): self._...
08cadff37914621d569f83b46f89a00625691cad
MartinPSE/Python
/AlgoPrac/AnotherPractice/Max_Min/max_min.py
516
3.578125
4
# 1~100 사이 숫자 중 랜덤으로 10개 뽑아서 리스트 만들기 import random numbers = [] for i in range(1, 10): number = random.randint(1, 101) numbers.append(number) print(numbers) # 랜덤리스트 내의 숫자 중 최대값, 최소값 구하기 import sys min = sys.maxsize max = -sys.maxsize for i in range(len(numbers)): if numbers[i] > max: max = number...
568e949167eb9fd767c818001ac7af3fed8bccdc
MartinPSE/Python
/AlgoPrac/1_Week_Stack_Queue/Stack.py
756
3.71875
4
''' < Stack > LIFO - Last In First Out 1. Push --> LIST 맨위에 추가 2. Pick --> '엿보다' 맨 마지막 데이터 보자 3. Pop ---> 맨 마지막 데이터 빼자 ''' class Stack(list): push = list.append def peek(self): return self[-1] # peek # pop 은 미리 있어. s = Stack() s.push(1) s.push(5) s.push(10) print(s) print("popp...
ba2e13e9d2c92fe13aea871dd89439d56087f940
florinhegedus/Python
/monotonic.py
162
3.796875
4
def isMonotonic(A): return (all(A[i] < A[i+1] for i in range(len(A)-1)) or all(A[i] > A[i+1] for i in range(len(A)-1))) A = [6,5,4,3,2,1] print(isMonotonic(A))
6f61a39c441c1d656942a1a1a9dd43b1f59d2612
kexinshine/leetcode
/24.两两交换链表中的节点.py
613
3.5
4
# # @lc app=leetcode.cn id=24 lang=python3 # # [24] 两两交换链表中的节点 # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def swapPairs(self, head: ListNode) -> ListNode: temp=head...
dc77588f9da4173f6df953417b219f762619b6a4
kexinshine/leetcode
/126.单词接龙-ii.py
3,848
3.703125
4
# # @lc app=leetcode.cn id=126 lang=python3 # # [126] 单词接龙 II # # @lc code=start class Solution: def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: if endWord not in wordList: return [] # 定义了从头向后访问的集合,从尾向前访问的集合 # 将wordlist转成了set,方便做减法运算。定义了默认首次访问方向为...
b771fa575efa5b8dd4a8b9c3238acc7eda6f9fea
kexinshine/leetcode
/111.二叉树的最小深度.py
803
3.5625
4
# # @lc app=leetcode.cn id=111 lang=python3 # # [111] 二叉树的最小深度 # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def minDepth(self, root: ...
0757ef6bfd9032fd5990485fcc846342cddcc8a6
amarish-kumar/Practice
/coursera/coursera_data_structures_and_algorithms/course_1_algorithmic_toolbox/Week_4/majority_element/majority_element_naive.py
1,538
4
4
#python3 ''' A naive implementation of the majority element problem. Here, two nested loops will be used to compare an element with the rest of the elemnents. An array will be maintained that will show the number of times each element occurs in the input. If an element is present such that it'...
433453e34c036cf7b04079f06debd27ba3c31e69
amarish-kumar/Practice
/coursera/coursera_data_structures_and_algorithms/course_1_algorithmic_toolbox/Week_4/binarysearch/binary_search.py
2,180
4.15625
4
#python3 '''Implementation of the binary search algoritm. Input will contain two lines. First line will have an integer n followed by n integers in increasing order. Second line will have an integer n again followed by n integers. For each of the integers in the second line, you have to perform bi...
57b89746ed658682ea3ef303f59ef27f2857c128
penn-z/study_requests
/scrapetest.py
744
3.5
4
#!/bin/bash/evn python3 # -*- coding: utf-8 -*- from urllib.request import urlopen from urllib.error import HTTPError from bs4 import BeautifulSoup # html = urlopen("http://pythonscraping.com/pages/page1.html") # print(html.read()) # bsObj = BeautifulSoup(html.read(), 'lxml') # print(bsObj.html.body.h1) try: html ...
be88a717aba6b4cec969dc24c57f08cbb1da90e1
MrVeshij/Megafon
/task_1.py
2,370
3.71875
4
# 1. Сделать рандом строку, и найти значение в списке, которое встречается чаще всего, # строку можно сделать таким образом: a = [int(random()*5) for i in range(15)] # Импортируем модуль рандом import random # Создаем список наполняя его рандомными значениями в диапазоне от 0 до 14 a = [int(random.random()*5) for i i...
a58e51493d43ad0df89b3836366ef7b729223d57
jnoriega3/lesson-code
/ch6/printTableFunctions.py
2,680
4.59375
5
# this is the printTable function # parameter: tableData is a list of lists, each containing a word # we are guaranteed that each list is the same length of words # this function will print our table right-justified def printTable( tableData ): #in order to be able to right-justify each word, we'll...
72218d09cd2c9a05bae3d9a2f22eccba436a554d
jnoriega3/lesson-code
/ch4/1-list-print.py
638
4.46875
4
#this defines a function with one parameter, 'theList' def printList( theList ): # this for loop iterates through each item in the list, except the last item for i in range( len(theList)-1 ): #can you remember what this line does? #this will add a comma after each list item print( str(theList[i]...
db8cc0d6b26b66a57b5db9b2478bedb0b463e5a6
burakdemir1/BUS232-Spring-2021-Homeworks
/hw7.py
407
4.21875
4
names = ("Ross","Rachel","Chandler","Monica","Joey","Phoebe") friends_list = set() for name in names: names_ = input(f'{name}, enter the names of the friends you invited: ') name_list = names_.split() for name in name_list: friends_list.add(name) print('This is final list of people invite...
f75894a940d83c20c8eefa246e98e663ab325628
ImDahmash/Test_QA
/LoadData.py
734
3.5
4
import nltk from nltk.corpus import stopwords sentence = "" stop_words = set(stopwords.words("english")) stop_words.update(['.', ',', '"', "'", '?', '!', ':', ';', '(', ')', '[', ']', '{', '}','#']) file = open('Paragraph.txt', 'r') for lin in file: sentence += lin print("{ " + sentence + " }") # D...
18290bee33c550d52f7b3133320f40f1f43296ff
edersonlucas/Calculadora_IMC_Python
/calculadoraIMC.py
2,272
4.15625
4
''' Calculadora IMC Autor: Ederson Lucas ''' #Entrada do Nome nome = input('Qual seu nome? ') # Laço ano while True: idade = input('Qual sua idade? ') if idade.isdigit() == False or int(idade) <= 0: print('Digite uma idade valida!') continue else: idade = int(idade) if i...
827236b908ff014cfd4ce750e61836a7c700fd7d
htpeter/advent-of-code-2020
/8.py
3,323
3.65625
4
print("day 8") class BootLoaderSimulation: """ Usage: example_instruction_set = '''nop +0 acc +1 jmp +4 acc +3 jmp -3 acc -99 acc +1 jmp -4 acc +6 ''' loader = BootLoaderSimulation(example_instruction_set) loader.r...
167f4a17143c1a85e9c73a60c8ce351c60e0aaf6
josemrsantos/pylytics
/pylytics/library/schedule.py
1,240
3.9375
4
from datetime import time, timedelta from pytz import UTC class Schedule(object): """ Used for scheduling when facts will update. The assumption here is that facts will update at least once a day. """ def __init__(self, starts=time(hour=0), ends=time(hour=23, minute=59), repea...
642bd9d9add4a1f08851557f778766b2240422fd
prathmeshgat/TriesDS
/Classes/Node.py
1,676
3.625
4
__author__ = 'Prathmesh' class Node: def __init__(self): self.word = None # dict of nodes self.nodes = dict() def get_all(self): #Get all of the words in the trie x = [] #loop through each and every node in tree for key, node in self.nodes.items() : ...
9004ce43cdf2077a80f5b3f2a8a541862a010077
KvitkaAzaleya/wwcode_mit_spring2017
/problemSet1.py
1,322
3.6875
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 25 13:11:48 2017 @author: Oksana Borovyk """ year_salary = float (input ("Input your year salary - ")) total_coast = float (input ("Input total coast your dream house - ")) k = float (input ("Input parth of salary in % - ")) count_month = 0 month_salary = year_salary / ...
5b3e97472430c99ef525447a29989b67e9b6bbfd
marauderlabs/codingbat
/python/Warmup-1/front3.py
153
3.8125
4
# https://codingbat.com/prob/p147920 def front3(str): front = "" if len(str) <= 3: front = str else: front = str[:3] return front*3
7608d9b267fb4184ab12428a0b0c399a5b80e110
graevskiy/mit_6.0001
/PSet1/ps1c.py
1,466
3.84375
4
#! python3 import sys if len(sys.argv) != 2: sys.exit('parameters to provide annual_salary') try: annual_salary = int(sys.argv[1]) except: sys.exit('one of your parameters is of incorrect types') # need to find portion_saved semi_annual_raise = 0.07 portion_down_payment = 0.25 current_savings = 0 r = ...
b421639598ef97abedac09ee17f2fb65fbb22169
skoolofcode/SKoolOfCode
/TrailBlazers/LiveClass/Files_Writing.py
1,263
4.0625
4
#Writing to a file. def read_print_file(name): f = open(name,"r") for line in f: print(line) f.close() #The "w" option print("=== START Write to a file ==\n") #Let's write 10 lines to a file f = open("data/newFile.txt","w") # Note : "w" f.write("My name is Sam!") f.close() print("writing to file ...
e0c8f24b3fd76f748f8aff3e31c04ec314ab6bba
skoolofcode/SKoolOfCode
/TrailBlazers/LiveClass/IntroToObjects_List.py
741
4.53125
5
#Lists - An unordered sequence of items groceryList = ['Greens', 'Fruits', 'Milk'] print("My Grocery list is ", groceryList) #You can iterate over lists. What's Iterate? #Iterate means go one by one element traverssing the full list #We may need to iterate the list to take some action on the given item #e.g. what is ...
19a636342dcb726c0a3c1ac89dab78319e4ca0c7
skoolofcode/SKoolOfCode
/TrailBlazers/LiveClass/Files_Reading.py
1,152
4.28125
4
#Opening a file using the required permissions f = open("data/drSeuss_green_eggs_n_ham.txt","r") #Reading a file using readline() function print("== Using for loop to read and print a file line by line ==") #Default print parameters for line in f: print(line) #Extra new lines after the every line. Why? #Specify...
01dc63ff29161279ab8cb689d375895180efc241
skoolofcode/SKoolOfCode
/The Geeks/modules/IntroToModule.py
780
4.15625
4
#introduction to Modules #Let's create a module hello that has 2 function helloWorld() and helloRedmond() #Diffirent ways of importing the module #1. Import module as is with its name. Note the usage <module>.<function> import hello hello.helloIssaquah() hello.helloRedmond() hello.helloSeattle() hello.helloBangal...
fac14e0cfee5d22b65ca14fce29909c03c5a4f83
skoolofcode/SKoolOfCode
/TrailBlazers/LiveClass/Class_3_2_Live.py
820
4.15625
4
#Print a decimal number as binary #"{0:b}".format(number) j = 45 print("The number j in decimal is ",j) print("{0:b}".format(j)) #Use ord() to get Ascii codes for a given character storeACharacter = 'a' print("I am printing a character ", storeACharacter) print("The ASCII code for a is ", ord(storeACharacter)) #Lets ...
83e14b2a1a0b7d360c9ef3b979b5ac1c6fff630f
skoolofcode/SKoolOfCode
/CodeNinjas/SimplifiedHangMan.py
1,441
4.46875
4
#Simplified Hangman #Present a word with only first 3 characters. Rest everything is masked #The user would be asked to guess the word. He/She wins if the word is correctly guessed. #A user get a total of 3 tires. At every try a new character is shown. #Let's have a global word list. worldList = ["batman","jumpsui...
dbf8ea3834665ffc7df5953b5974455849501e16
skoolofcode/SKoolOfCode
/The Geeks/list_methods.py
1,042
4.59375
5
# This file we'll be talking about Lists. #Create a list print("\n *** printing the list ***") groceryList = ['Milk', 'Oranges', "Cookies", "Bread"] print(groceryList) #Append to the list. This also means add a item to the list print("\n*** Add pumpkin to the list") groceryList.append("pumpkin") print(groceryList) #...
de3d28e5137225d304e65e4285058079374dfad8
skoolofcode/SKoolOfCode
/TrailBlazers/Ishita/Practice/Phonebook.py
716
3.875
4
d=input("Would you want to add a phone number to the phonebook or find?") if d == "Add": while True: file = open('phonebook.txt', 'a') print("Enter X for stopping(This stops only in the name.)") a=input("Name?") if a == "X": break b=input("Phone number?") c=input("Additional info?") file.write("...
ac998b57fae60f1088db024c902ec8a9994b00d3
skoolofcode/SKoolOfCode
/TrailBlazers/maanya/practice/caniguessyourage.py
1,024
4.125
4
def thecoolmathgame (): print("Hello. I am going to guess your age today! I promise I will not cheat :)") startnum = int(input("Pick a number from 1-10:")) print("Now I will multiply your chosen number by 2.") age = startnum * 2 print ("Now I will add 5 to the new number.") age = age + 5 print("Now I will multip...
7d19167efcc920003408f714e908efa4539eac29
skoolofcode/SKoolOfCode
/TrailBlazers/Ishita/Project/MathQuizBotV02.py
14,712
4.15625
4
# Ideas and to dos: # Work on test # Make the inputs cleaner #Frame it like a game def awake(): a = input("Ready to go on?") def howtoadd(number): global b b = input("What is your friend's name?") print("--------------------How to add----------------------------------------") if "1" == number:...
8298f0182e62a5037bef05117a1a1a240af893bc
wayxin/text
/Pycharm/untitled/新建文件夹/回文字符串.py
293
3.828125
4
#! /usr/bin/python # -*- coding:utf-8 -*- # s = input('请输入一组字符串,以逗号隔开:') # b = s.split(',') # b.reverse() # a = b.copy() # a = ','.join(a) # print(a) # if a == s: # print('您输入的字符串是回文') # else: # print('您输入的字符串不是回文')
7692af19c369e14f0643e2a83afe44b8fe2fb86f
wayxin/text
/Pycharm/untitled/新建文件夹/判断三角形.py
436
3.828125
4
#! /usr/bin/python # -*- coding:utf-8 -*- # a=int(input('>>')) # b=int(input('>>')) # c=int(input('>>')) # if c>a and c>b and a+b>c and a+c>b and b+c>a: # if a**2+b**2==c**2: # print('直角') # if a**2+b**2>c**2: # print('锐角') # if a**2+b**2<c**2: # print('钝角') #...
f41fe217244ec54d8bae5761b56edb25975b36d4
ShinCheung/LeetCode
/16.最接近的三数之和.py
937
3.53125
4
# 给定一个包括 n 个整数的数组 nums 和 一个目标值 target。 # 找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。 # 例如,给定数组 nums = [-1,2,1,-4], 和 target = 1. # 与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2). class Solution: def threeSumClosest(self, nums, target): """ :type nums: List[int] :type target: int ...
26ae6dfa365523125328e36cfd06d2c2096e708e
ShinCheung/LeetCode
/28.实现strStr().py
768
3.78125
4
# 实现 strStr() 函数。 # 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。 # 如果不存在,则返回 -1。 # 示例 1: # 输入: haystack = "hello", needle = "ll" # 输出: 2 # 示例 2: # 输入: haystack = "aaaaa", needle = "bba" # 输出: -1 class Solution: def strStr(self, haystack, needle): """ :type haystack: ...
babdf4adc081f0e09c31b1f83a24336f303c06fb
ShinCheung/LeetCode
/78.子集.py
1,112
3.96875
4
# 给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集 # 说明:解集不能包含重复的子集 # 示例: # 输入: nums = [1,2,3] # 输出: # [ # [3], # [1], # [2], # [1,2,3], # [1,3], # [2,3], # [1,2], # [] # ] # 迭代思想 # 数组中只有一个数字时,返回空集合和数字本身,再新加一个数字时,将原先的所有子集加上新的数字, # 就是包含新数字的子集,保留之前不包含新数字的子集。这两个子集直接相加就是新的所有子集。 # 一样地当数组长度不断增加,不断往原来子集上迭代新的集合即可。 class Solut...
5d9e36503e7b88ff0712cfdfdf16893f2b59ede2
philipdongfei/Think-python-2nd
/Chapter07/Ex7_1.py
631
3.703125
4
from square_roots import * import math def mysqrt(a): return square_roots(5, a) def test_square_root(): space = ' ' print('a',space*4,'mysqrt(a)',space*6,'math.sqrt(a)',space*3,'diff') print('-',space*4,'-'*9,space*6,'-'*12,space*3,'-'*4) for a in range(1, 10, 1): print(a, end = ' '*4) ...
012951eee9b3fc4373320070f51f5982e6bd3a34
philipdongfei/Think-python-2nd
/Chapter12/Ex12_2.py
1,030
3.796875
4
def signature(s): t = list(s) t.sort() t = ''.join(t) return t def all_anagrams(filename): d = {} for line in open(filename): word = line.strip().lower() t = signature(word) print(t) if t not in d: d[t] = [word] else: d[t].appen...
ff8d828475eb4c1146530b87e1a417198015b518
philipdongfei/Think-python-2nd
/Chapter12/Ex12_1.py
591
3.71875
4
def most_frequest(s): hist = make_histogram(s) t = [] for x, freq in hist.items(): t.append((freq, x)) t.sort(reverse=True) res = [] for freq, x in t: res.append(x) return res def make_histogram(s): hist = {} #t = s.split(" ") t = s for x in t: hi...