blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
87a49295c340daf760bf3c385215e8ce4bad3700
whz-NJ/PersonalRecommendation
/PersonalRank/util/read.py
1,870
3.515625
4
#-*-coding:utf8-*- """ author:zhiyuan date:20190303 get graph from user data """ import os def get_graph_from_data(input_file): """ Args: input_file:user item rating file Return: a dict: {UserA:{itemb:1, itemc:1}, itemb:{UserA:1}} """ if not os.path.exists(input_file): ret...
4885109079422517a7623add10b890c90ca34839
ncsurobotics/seawolf
/vision/Entities/Utilities/normalize.py
454
3.640625
4
import numpy as np """ turns the frame into a normalized frame input opencv frame, sf the scaling factor for the brightness of pixels output normalized opencv frame """ def norm(frame, sf = 255): Z = np.float32(frame.reshape((-1, 3))) C = np.copy(Z) Z = Z**2 #adding .0000001 to avoid divide by 0 s = np.sqr...
f2d0fd406f6a5b365b3cbd7315edf42563381678
crash-bandic00t/python_dev
/1_fourth/basics_python/lesson4/task3.py
1,288
3.828125
4
""" Доработать функцию get_currency_rate(): теперь она должна возвращать курс и дату, на которую этот курс действует (взять из того же файла ЦБ РФ). Для значения курса используйте тип Decimal (https://docs.python.org/3.8/library/decimal.html) вместо float. Дата должна быть типа datetime.date. """ from requests import ...
d4d5534c309c82cf0c63071fefe383c8dea80644
wasi0013/Python-CodeBase
/ACM-Solution/Prime.py
133
3.5625
4
import sys p=[2] for i in range(3,100001,2): if all(i%x for x in p):p.append(i) try: while 1:print (p[int(input())-1])
2b190499d19f9bda3b4c36b688555de53cea5bb4
pdst-lccs/lccs-python
/Section 7 - Dictionaries/nestedDictionariesV1.py
378
4.1875
4
#PDST Computer Science #Jan 2022 #Nested Dictionaries #Building a nested dictionary class_list = ["Mark", "Anne", "Joe", "Tony", "Neil", "Irene", "Sinéad"] class_dict = { } for item in class_list: class_dict[item]={ } #creating a key in the dictionary using the name from the list print(item) print(cla...
963537dde931c2ad02a3bf93ef5008eac2cacae0
HardProgrammer/pythonRoad
/com/study/while.py
1,354
3.890625
4
''' while 表达式: 当表达式为true的时候继续执行 else: 当没有执行break语句并且while后面表达式不成立时,会执行else语句 break 终止循环操作 ''' # 输出0-100的偶数 even_numbers = 1 while even_numbers <= 100: # 偶数除2取余为0,奇数为1 if even_numbers % 2 == 0: print(even_numbers) even_numbers += 1 # while语句实现0-100相加 num = 1 sum = 0 while n...
340314e2efc4bed25101447eb1365f1fbe3cd0f3
ediboc/EjerciciosPython
/Ejercicios2/x.py
363
3.609375
4
# Ejercicio 10 print "**** Codificado de Frases ****" a = input ("Ingrese palabra: ") c = list(a) m = len(a) d = "" e = "" for j in range(0,m): if c[j] == "a" : d == "4" elif c[j] == "e" : d == "3" elif c[j] == "i" : d == "1" elif c[j] == "o" : d == "0" elif c[j] == "u" : d == "#" ...
01eadd8ed67f2de467d672eb50a3174a4bac2c33
anuroopnag/PythonScripts
/Prime.py
327
3.921875
4
def isPrime(num): if num%1==0 and num%num==0 and num>1: for i in range(2,100): if num%i!=0 and num!=num: return True else: return False else: return False for i in range(1, 20): if isPrime(i + 1): print(i + 1, end...
2fab0181fc9b7f88946b65f30639d738f3472223
atriekak/LeetCode
/solutions/146. LRU Cache.py
2,056
3.765625
4
class LRUCache:    #Approach: Hashmap with doubly linked list    #Time Complexity: O(1) for both, get and put    #Space Complexity: O(capacity) // both data structrues are O(capacity)        def __init__(self, capacity: int):        self.head = Node(-1, -1)        #dummy        self.tail = Node(-1, -1)        #d...
28d563946bd2adfa5e198a260226b480e6779f5c
MiguelP4lacios/holbertonschool-higher_level_programming
/0x0B-python-input_output/12-student.py
600
3.5
4
#!/usr/bin/python3 """Module """ class Student: """Class """ def __init__(self, first_name, last_name, age): """Constructor """ self.first_name = first_name self.last_name = last_name self.age = age def to_json(self, attrs=None): """Method """ ...
ee7e5c62d41e05e153c2a72cd5fd5850972c3af0
Welvis3004/Aprendendo-Python
/DESAFIO 03.py
260
4.03125
4
print ('==== DESAFIO 03 ====') numero1 = input ('Digite o primeiro numero: ') numero2 = input ('Digite o segundo numero: ') soma = int(numero1)+ int(numero2) #FUNÇÃO PARA CONVERTER STRING EM INTEIRO. print('A soma de', numero1,'+',numero2, 'é', soma)
7307791fbb374b51b3147db1476c8f816acc9d66
tsingkk/Python-100-questions
/myexamples/exa014.py
483
4.09375
4
# 将一个整数分解质因数。例如:输入90,打印出90=2*3*3*5。 n = int(input("输入一个整数:")) print(n, '=', end=' ') if n < 0: n /= -1 print('-1 *', end=' ') flag = 1 if n == 0: print('0') flag = 0 while flag: for i in range(2, int(n+1)): if n % i == 0: print('%d' % i, end=' ') flag = 0 ...
d1d0e1fad6bd2de2cd5e84237333af0d176bfc87
LukeCostanza/CIS106-Luke-Costanza
/Assignment 14/Activity 1.py
1,478
3.953125
4
#This program is determining the avergae grade for the user. def read_file(scores): score_arr = [] first = 'y' file = open(scores, "r") for line in file: line = line.strip() if first == 'y': first = 'n' else: scores = get_score(line) score_ar...
0a20f2097eb06953ab1ff5efe14ea80ad0210391
bioidiap/bob.db.base
/bob/db/base/file.py
4,480
3.734375
4
#!/usr/bin/env python # vim: set fileencoding=utf-8 : import os import bob.io.base class File(object): """Abstract class that define basic properties of File objects. Your file instance should have at least the self.id and self.path properties. """ def __init__(self, path, file_id=None, **kwargs): "...
8d7e6c2ccbe73ec0c733ee841c13e730d0b73053
zsmountain/lintcode
/python/two pointers/57_3sum.py
1,690
3.921875
4
''' Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c) The solution set must not contain duplicate triplets. Example For example, giv...
4426abd9925b5bf2353c6c0e64217b3f4b58db5f
sean75p/machine-learning-trial
/matrix_multiplication.py
1,328
4.53125
5
# Program to multiply two matrices using nested loops def matrix_multiplication(X, Y): x_rows = len(X) x_columns = len(X[0]) y_rows = len(Y) y_columns = len(Y[0]) # check to see if the matrices can be multiplied # i.e. x_column must equal y_rows if x_columns != y_rows: ...
34ca79adf64b2da2e3fc7cb19126081f8c7c6483
vikramlance/Python-Programming
/Leetcode/problems/problem1567_maximum_length_of_subarray_with_positive_product.py
816
3.59375
4
""" Maximum subarry with product of all elements is positive nums = [1,-2,-3,4] out = 4 Input: nums = [0,1,-2,-3,-4] 3 Input: nums = [-1,-2,-3,0,1] 2 Input: nums = [-1,2] 1 nums = [1,2,3,5,-6,4,0,10] 4 """ # read items in nums # if item is postive add it to temp arr # if len of max subarry < temp_s...
5267af6c309263f69e2c8b56bda2d0f6f67bfd0a
rlaecio/CursoEmVideo
/100Exercicios/ex015.py
229
3.703125
4
diasAlugados = int(input('Informe o numero de dias alugados: ')) kmRodados = float(input('Informe os Km rodados: ')) valorAPagar = (diasAlugados * 60) + (kmRodados * 0.15) print('O valor a pagar é R${:.2f}'.format(valorAPagar))
eb75850b921220f8c5c3acc9c5d921dd0bff30d8
tontonchin/hulistics_kai1028
/model/zikkou_zissen.py
3,233
3.625
4
"""このプログラムは実行部です""" import numpy as np import random import math from moussaif import fa_dasu, hulistics_1, cal_fij, cal_fiw , dasu_v_1d, dvdt import matplotlib.pyplot as plt import matplotlib.animation as animation import pandas as pd #関数部の関数を全ぶmoussaif.pyからインポートしてから実行する #n = 10 pi = math.pi df1 = pd.read_excel('...
5007bfe60ccf5c712f885ecd29a649b6cb154024
MacHu-GWU/learn_awslambda-project
/example-projects/dice-gamble-project/awslambda.py
2,163
3.59375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import json import random def explain(bowl): """赌骰子秘籍: http://blog.sina.com.cn/s/blog_4c8894390101384t.html baozi: x24 4/17: x50 5/16: x18 6/15: x14 7/14: x12 8/13: x8 9/10/11/12: x6 big/small: x1 ...
af480c57f43594951e8c2c77da59e03a4788e883
nralex/Python
/3-EstruturaDeRepeticao/exercício28.py
806
4.125
4
############################################################################################# # Faça um programa que calcule o valor total investido por um colecionador em sua coleção # # de CDs e o valor médio gasto em cada um deles. O usuário deverá informar a quantidade # # de CDs e o valor para em cada um. ...
c28ca853fc722608835b43526ed4ab4f1e47c674
moniquesenjaya/Assignment-Week-6
/Assignment 3/main.py
565
4.09375
4
def compute_bill(food): total = 0 #Iterate through all items in list for item in food: # Check if stock is more than 0 if stock[item] > 0: # Add price to total and substract 1 from stock total += prices[item] stock[item] = stock[item] - 1 return total ...
471c08563ae52b9b7a0a53b464dc128a9f27b20e
AyushSri19-777/ITT-Lab-Codes
/Sessional2/tst.py
1,017
3.765625
4
import re searchString = "Testing pattern matches" expression1 = re.compile( r"Test" ) expression2 = re.compile( r"^Test" ) expression3 = re.compile( r"Test$" ) expression4 = re.compile( r"\b\w*es\b" ) expression5 = re.compile( r"t[^aeiou]", re.I ) if expression1.search( searchString ): print ('"Test" was found....
401e46a2fff37e78b7e493fb561ee55e3e0f68ef
arsamigullin/problem_solving_python
/leet/binary_search/find_search_and_last_position_in_sorted_array.py
1,974
4
4
# the idea is we keep searching until start == end # to find left most we introduced left parameter. If it is True we keep the hi at mid. That way we find leftmost index # When finding rightmost the left is False. And in case of matching we just increasing leftside boundary (mid + 1) # Need to remember # after the left...
c76ee8849cb4ca9a9d7e52322e728f7c3dd985b9
SavaGeekbrains/Python-1
/Домашняя работа/Урок 2/Задание 2.3.py
785
4.03125
4
number = int(input("Введите номер месяца: ")) if number <= 12 and number >= 1: month_dict = {1: 'Январь', 2: 'Февраль', 3: 'Март', 4: 'Апрель', 5: 'Май', 6: 'Июнь', 7: 'Июль', 8: 'Август', ...
4e9ee14cd1af8f55f1080d971963ff1488b78cc4
meikesara/Heuristieken
/algorithms/constructive.py
4,535
3.96875
4
""" This code contains a depth first search method to find the optimal stability for a protein. It checks all possible ways to fold the protein, except for the mirror images and the rotationally symmetric folds. Meike Kortleve, Nicole Jansen """ import copy import re import time import matplotlib.pyplot as plt from c...
9c4cecc4b45a0c1e09cf4377c6cf39d0330834c6
xanthesoter/Computer-Science
/Vacation Cost Function.py
2,084
4.1875
4
# Vactions Cost # Functions and Parameters example while True: days = int(input("How many days do you plan to stay?: ")) def hotel_cost(): cost = 95 * days if days > 10: cost = cost - 35 return cost def plane_ride_cost(): print("Los Angeles, Washin...
2eac0401235be7a2a85612845828ce3f9c0f3130
sushantsrivastav/crackingcodeInterview
/CountWays.py
814
4.1875
4
#Step: A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. # Implement a method to count how many possible ways the child can run up the stairs. #recursive def count_ways(n): if n < 0 : return 0 elif n == 0 : return 1 else: ...
eb5d0f8f26edf299905cf1b0bb3ae4d8e6756688
lixiang2017/leetcode
/leetcode-cn/2363.0_Merge_Similar_Items.py
582
3.640625
4
''' hash table, using array, no sort 执行用时:40 ms, 在所有 Python3 提交中击败了85.45% 的用户 内存消耗:15.6 MB, 在所有 Python3 提交中击败了42.91% 的用户 通过测试用例:49 / 49 ''' class Solution: def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]: # value -> weight weights = [0] * 1...
511964cc52b1b5cf64de4e2db8201709da15ef2e
romeorizzi/esami-algo-TA
/2019-07-30/tree_transcode_disc/sol/soluzione.py
1,641
3.671875
4
#!/usr/bin/env python3 # -*- coding: latin-1 -*- from __future__ import print_function import sys sys.setrecursionlimit(100000) if sys.version_info < (3, 0): input = raw_input # in python2, raw_input svolge la funzione della primitiva input in python3 """Soluzione di tree_transcode_disc Autore: Romeo Rizzi ...
ac1111feb482c23413b8dae11e7e7abc5f3736e3
cnagadya/bc_16_codelab
/Day_three/minmax.py
304
3.921875
4
""" find_max_min to find the maximun and minimum numbers in the list""" def find_max_min(test_list): #for lists with same min and max if min(test_list) == max(test_list): return [len(test_list)] #lists with different min and max else: return [ min(test_list) , max(test_list)]
e42290323710b40a5a04cc898220ea08073bd4c8
zianke/cmdnote
/cmdnote/command_parser.py
952
3.84375
4
class Parser: """ Parser of commands """ @staticmethod def parse_file(filename): """Parse commands from a file.""" with open(filename, 'r') as f: content = f.read() return Parser.parse_content(content) @staticmethod def parse_content(content): ""...
8862d0ef3f787b92c13e69ec57a423b783aea9ae
ntyagi07/Python
/guessNumber.py
731
3.875
4
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import random number=random.randint(1,25) print("How many games you want to play?") games=int(input()) print("Select number between 1-25") #response=int(input()) n=0 while n < games: print("Take a guess") guess=int(...
7270975079b5dcbc350ee860efa0a7e7e9860de4
aryabartar/learning
/interview/recursion/coin_change.py
936
3.671875
4
def coin_change(n, coins): coins = list(coins) if n == 0: return 0 if len(coins) == 0: return None max_coin = coins.pop(-1) max_coin_numbers = int(n / max_coin) min_value = None for i in range(0, max_coin_numbers + 1): sub_coins = coin_change(n - i * max_coin, li...
738135e0ab959f3ac9c5bec34e14ecaef67ec98f
McHine/net_python
/06_control_structures/task_6_2a.py
1,768
3.5
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Задание 6.2a Сделать копию скрипта задания 6.2. Добавить проверку введенного IP-адреса. Адрес считается корректно заданным, если он: - состоит из 4 чисел (а не букв или других символов) - числа разделенны точкой - каждое число в диапазоне от 0 до 255 Если...
8ee69923ab6fefe3407eb4188d7426ce553b85ae
zhangchenghao0617/Learn
/day 04/课上练习.py
2,190
3.8125
4
# li = [1, 3, 2, "a", 4, "b", 5,"c"] # # # 通过对li列表的切片形成新的列表l1,l1 = [1,3,2] # print(li[:3]) # # 通过对li列表的切片形成新的列表l2,l2 = ["a",4,"b"] # print(li[3:6]) # # 通过对li列表的切片形成新的列表l4,l4 = [3,"a","b"] # print(li[1:6:2]) # # 通过对li列表的切片形成新的列表l6,l6 = ["b","a",3] # print(li[-3::-2]) # li = ['张三','李四','王二','麻子'] # while 1: # name =...
5f2205907bec445cc902b7f5672a76a417d2995b
achoczaj/OCW--MIT-Programming_for_the_Puzzled
/Puzzle_1-You_Will_All_Conform/conform-opt.py
1,899
3.90625
4
# MIT 6.S095 - Programming for the Puzzled - Srini Devadas # Puzzle 1 - You Will All Conform # Input is a vector of F's and B's, in terms of forwards and backwards caps. # Output is a set of commands (printed out) to get either all F's or all B's. # Fewest commands are the goal. caps = ['F', 'F', 'B', 'B', 'B'...
e9eec37dc21476cbeb7079bd6235120ef09636e4
LKolya97/labs
/6.py
199
3.703125
4
def fun(n): if n==0: return 0 elif n==1 or n==2: return 1 else: return (fun(n-1)+fun(n-2)) inp=int(input("Введите число ")) print(fun(inp))
addb9885f9abaaf130f6b6149e29a3b579889c31
jlyon1/python-direct-cache
/main.py
3,536
3.5
4
#this represents the data that would be stored on the actual hard drive for example physical_disk = { 0x11010101: 0xFF00e0FF, 0x10000001: 0xFF00FFFF, # For now all of our data will be exactly one word long 0x10020001: 0xFF0000FF # For now all of our data will be exactly one word long } def print_disk_cont...
a0684bf9f2b7d9f33063f73a697ee4a919597374
m-evtimov96/softUni-python-fundamentals
/1- Basic Syntax, Conditional Statements and Loops/Lab-5.py
351
3.765625
4
num_stars = int(input()) for i in range(1, num_stars+1): print('*' * i) for i in range(num_stars-1, 0, -1): print('*' * i) # for i in range(1, num_stars+1): # for j in range(0, i): # print('*', end='') # print('') # for i in range(num_stars-1, 0, -1): # for j in range(0, i): # pri...
1b13827d346a9d57995d3cda676714524d6d94cd
Shareed2k/sets-implements-in-python
/set_python.py
891
3.671875
4
import sets_in_python as AbstractSet class Set(AbstractSet.AbstractSet): def __init__(self, elems=()): AbstractSet.AbstractSet.__init__(self) self.rep = [] self.insertAll(elems) def contains(self, a): return a in self.rep def insert(self, a): if a not in self.rep: self.rep.append(a) return self...
5f70411c23487784fb047e8d8d0a677a87cbe06b
AdamZhouSE/pythonHomework
/Code/CodeRecords/2621/60693/237238.py
317
3.53125
4
numbers=input().split(',') maxsum=0 left_index=0 right_index=0 for i in range(len(numbers)): for j in range(i,len(numbers)): tmp=0 for k in range(i,j+1): tmp+=int(numbers[k]) if tmp>maxsum: maxsum=tmp left_index=i right_index=k print(maxsum)
61d3a42cf40ce04d5cdfe1f7cc1c97eee319e28b
madhurimukund97/MSIT
/3. CSPP1/m 20/CodeCampMatrixOperations/matrix_operations.py
2,664
3.921875
4
'''mult matrix''' import copy def mult_matrix(m_1, m_2): ''' check if the matrix1 columns = matrix2 rows mult the matrices and return the result matrix print an error message if the matrix shapes are not valid for mult and return None error message should be "Error: Matrix sh...
06075dd6a4e73e34c1aeabca82f1926d1a73b394
SheikArbaz/Algorithms
/Sort/BucketSort.py
639
3.5625
4
from functools import reduce def insertion_sort(arr): n = len(arr) i = 1 for i in range(1, n): j = i-1 key = arr[i] while j>=0 and arr[j]>key: arr[j+1]=arr[j] j-=1 arr[j+1]=key #No need to return: inplace as list is an object # return arr def bucket_sort(A): n = len(A) #Create an array of lists B=...
26ea571aa7cf2542a87ccfa20c4128b9e6784b8b
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/chris_lombardi/Lesson03/strformat_lab.py
1,956
3.609375
4
#UWPCE PY210 #Lesson03, String Formatting Exercise #Task One def format_tuple(tup1): str_formatted = 'file_{:0>3d} : {:>4}{:.2f}, {:.2e}, {:.2e}'.format(tup1[0], "",tup1[1],tup1[2],tup1[3]) print(str_formatted) #Task Two def format_opt2(tup1): print(f'file_{tup1[0]:0>3d} : {tup1[1]:.2f}, {tup1...
4114a201e6465db154b24777f795363bad925678
capsassistant/shellcodes
/faMock/python.py
1,174
3.5625
4
def check_register(input_string): #remove the pass and write your logic here #pass output_string = 'X' if(len(input_string)%4==0): output_string='A' if('KA' or 'ka' in input_string): x=list(input_string) count = 0 for i in r...
8ed450479b219ff44c6d11b28881e832adac2f30
JulietaCaro/Programacion-I
/Trabajo Practico 7/Explicacion PPT/sumar lista.py
259
3.8125
4
# Desarrollar una función para sumar los elementos de una lista def sumarElementos(lista,i=0): if len(lista) == i: return 0 else: return lista[i] + sumarElementos(lista,i+1) lista = [5,9,10,2] print(sumarElementos(lista))
df1d070311cdf2d285d7b4753c80bc6f6f2fb52b
HarshaR99/AI_lab
/iddfs.py
1,160
3.8125
4
from collections import defaultdict class Graph: def __init__(self, vertices): self.V = vertices self.graph = defaultdict(list) def addEdge(self, u, v): self.graph[u].append(v) def DLS(self, src, target, maxDepth): if src == target: return True if m...
2d871a9fb814302f1644ba4c743c956e4b32078f
RiverBuilder/RiverBuilder
/tools/signal_to_riverbuilder.py
16,647
3.546875
4
import pandas as pd import numpy as np import matplotlib import matplotlib.pyplot as plt import tkinter from tkinter import * from tkinter import filedialog import re import os import sys import warnings import math warnings.filterwarnings("ignore") def string_to_list(string): out_list = list(stri...
153e0a47a59f923e10c5f266b11423cf9e34df9c
satoiseki/python_scripts
/renamer.py
2,200
3.796875
4
import os source_dir = "E:/temp_music/" destination_dir = "E:/music/" def simple_renamer(src_dir, dst_dir, name): # example input: "E:/folder/", "E:/another_folder/", "img" for count, filename in enumerate(os.listdir(src_dir)): file_type = os.path.splitext(filename)[1][1:] src = src_dir + file...
785f8e030f92aa0485fbb4e259c2e132b5071b82
mc0505/ct4b_basic
/ss7/minihack1-3/test3.py
237
3.796875
4
month = int(input("Nhập một tháng trong năm: ")) a = [1,3,5,7,8,10,12] if month in a: print("Tháng",month,"có 31 ngày") elif month ==2: print("Tháng",month,"có 28 ngày") else: print("Tháng",month,"có 30 ngày")
1f6c84206c3b8bc86917e09c9fa25b442d1929c7
pablohonney/hidalgos
/src/algorithms/encoding/run_length_encoding.py
804
3.609375
4
""" As for now it works with alphabetic text only. Numbers must be escaped. """ def encode_run_length(plain_text: str) -> str: head = '' count = 0 # version 2: count = '' cipher_text = [] for char in plain_text: if char == head: count += 1 else: cipher_text.ap...
c51f1b93df69f468b65a8db7cd952db637ec60dc
frclasso/turma1_Python_Modulo2_2019
/Cap05_Tkinter/26_place_method.py
458
3.84375
4
from tkinter import * root = Tk() root.title('Place method') l1 = Label(root, text='Physics') l1.place(x=10, y=10) e1 = Entry(root, bd=2) e1.place(x=70, y=10) l2 = Label(root, text='Maths') l2.place(x=10, y=50) e2 = Entry(root, bd=2) e2.place(x=70, y=50) l3 = Label(root, text='Total') l3.place(x=10, y=150) e3 = En...
38f70489c52629723b833a922e4a42dec0e36521
windie-rozureido/Analisis-Numerico
/2-4_Catenaria.py
649
3.890625
4
######################################## # 2-4 La Catenaria # # Este programa calcula la longitud de # # una cuerda atada a dos postes. # # Autora: Ofelia Cepeda Camargo # ######################################## import math def f(lamb): f = lamb*math.cosh(50.0/lamb)-lamb-23.0 ...
2753be3593b24ec7f9b041339d438ff7db2d2eed
lasttillend/CS61A
/exam/exam_prep7.py
4,837
3.9375
4
# OOP Trees and Linked Lists class Tree: def __init__(self, label, branches=[]): for c in branches: assert isinstance(c, Tree) self.label = label self.branches = list(branches) def __repr__(self): if self.branches: branches_str = ', ' + repr(self.branche...
727deacd6ba018553f55cbe57fa4c17d5da2867e
Rafesz/URI_solutions_py
/1165.py
929
3.765625
4
# Na matemática, um Número Primo é aquele que pode ser dividido somente por 1 (um) e por ele mesmo. Por exemplo, o número 7 é primo, pois pode ser dividido apenas pelo número 1 e pelo número 7. # Entrada # A entrada contém vários casos de teste. A primeira linha da entrada contém um inteiro N (1 ≤ N ≤ 100), indican...
b00e161ef91c3cd187f5297f711e2e5a054fd97d
phildavis17/Euler
/problem 6.py
738
3.828125
4
# The sum of the squares of the first ten natural numbers is, # 12 + 22 + ... + 102 = 385 # # The square of the sum of the first ten natural numbers is, # (1 + 2 + ... + 10)2 = 552 = 3025 # # Hence the difference between the sum of the squares of the first ten natural # numbers and the square of the sum is 3025 − 385 =...
56ac8ecf73f64d0ffc76129efe2cef67be4456f7
619496775/yasuospider
/python exercise/01/file_rw.py
218
3.578125
4
# -*- coding:utf-8 -*- with open('text.txt') as f: print(dir(f)) for line in f.readlines(): print(line) with open('text.txt','rb') as f: print(f.read()) s = 'abcdefg' b = bytes(s,'utf8') print(b)
4b3109ae87ba6dcfec8c3d34dea392305ef7abda
reichlj/PythonBsp
/Schulung/solutions/100sol41.py
501
3.65625
4
class Robot: def __init__(self, name="None", build_year=2000): self.name = name self.build_year = build_year @property def name(self): return self.__name @name.setter def name(self, name): self.__name = "Marvin" if name == "Henry" else name ...
cc325b2ba07f6281ba47bfd8498f77d91fe1f09c
vijay-jaisankar/SearchTheWeb
/project1.py
348
3.671875
4
import bs4 import requests #This program takes in an absolute URL from the user, and prints the code of that webpage in 'file.txt' , which the user can review. site=str(input("Enter the ABSOLUTE url: ")) req=requests.get(site) obj=bs4.BeautifulSoup(req.content,'html5lib') file1=open('file.txt','w') file1.write(obj...
72d2e6253311691a2911ace1d179ae4da8e7fb41
castuloramirez/TextFrequencyAnalysis
/TextFrequencyAnalysis.py
5,218
4.03125
4
import math import re import string import sys from collections import Counter import matplotlib.pyplot as plt import pandas # Shows the list of functions that can be run, and the user chooses one of them. def option_menu(): while True: print("---- TEXT FREQUENCY ANALYSIS (EXERCISE 3.1) " + "-" * 200) ...
d5e694e289e9e3426e24f46035f28ce4d2ca3164
defecon/-werken-met-condities
/solicitatie.py.py
1,692
3.953125
4
if float (input ("Hoeveel jaar praktijkervaring heeft u met dieren-dressuur in totaal? :")) <= 4: if float (input ("Hoeveel jaar ervaring heeft u met jongleren? : ")) <= 5: if float (input("hoeveel jaar praktijkervaring heeft u met acrobatiek in totaal? :")) <= 3: print("U voeldoet niet aan onze...
a78e332de7f5db30329356f653424739ffba112d
aggy07/TICTAC
/tictac.py
1,317
3.78125
4
from __future__ import print_function choices = [] for x in range(0,9): choices.append(str(x+1)) playerOneTurn = True winner = False def printBoard(): print('\n ____') print('|' + choices[0] + '|' + choices[1] + '|' + choices[2] +'|') print(' ____') print('|' + choices[3] + '|' + choices[4] + '|' + choices[5] ...
e09dcb771addd30fbedc01012afb7f9fa82b6b31
JuanCHerreraPro/Machine-learning
/Feature engineering/One hot encoding.py
570
3.875
4
# -*- coding: utf-8 -*- """ Some machine learning algorithms cannot handle categorical features, so one-hot encoding is a way to convert these categorical features into numerical features. Let's say that you have a feature labeled "status" that can take one of three values (red, green, or yellow). Because these values ...
6937b4b1fdb4d6c69ecd4bd707407c00adb0785d
baothais/Practice_Python
/handle_file.py
6,733
4.15625
4
# """ # "r" - Read - Default value. Opens a file for reading, error if the file does not exist # # "a" - Append - Opens a file for appending, creates the file if it does not exist # # "w" - Write - Opens a file for writing, creates the file if it does not exist # # "x" - Create - Creates the specified file, returns an ...
6cdafcf647738c1b239d07c1babfcdb4878c27ef
michaelbateman/Rosalind
/tree.py
667
3.515625
4
#Given: A positive integer n (n<=1000) and an adjacency list corresponding to a graph on n nodes that contains no cycles. #Return: The minimum number of edges that can be added to the graph to produce a tree. import numpy as np s = 'rosalind_tree.txt' try: input_file = open(s, "r") print "input file i...
b330ba0f3790f79251466055eedd962f2e7cb5f9
Babarix/poker
/brain.py
558
3.515625
4
#!/usr/bin/python # -*- coding: UTF_8 -*- import random class allIn(): """This is temporarily something which will make a player randomly leave a table.""" def __init__(self, wantToJoinAGame=True, wantToLeaveTheTable=False): self.wantToJoin = wantToJoinAGame self.wantToLeave = wantToLeaveTheT...
6347316b68f2eda0b93bce81f9c2c06327ba5485
moamen-ahmed-93/hackerrank_sol
/python3/np-shape-reshape.py
113
3.53125
4
import numpy arr=numpy.array([int(i) for i in input().split()],dtype=numpy.int) print(numpy.reshape(arr,(3,3)))
c133ecbc39ccdde52f85bcfcc52500c701da9969
aqshmodel/changing_seat
/changing_seat.py
936
3.71875
4
import random def changing_seat(seat,join_member): random.shuffle(join_member) print('---- Aテーブル ----') for i in range(0, 15): seat[i] = join_member[i] print(str(i + 1) + 'の席:' + join_member[i]) if i == 3: print('---- Bテーブル ----') elif i == 8: print(...
23aa3bcb4590d521450e28ff57da0b56bdfeab52
Inish-Bashyal/Group_Project
/Student_Management_System.py
16,634
3.671875
4
from tkinter import * from tkinter import messagebox, ttk from PIL import ImageTk, Image import sqlite3 #creating a window named as root and giving it title and maximum and mimimum size root = Tk() root.title("Student Management System") root.iconbitmap("logo.ico") # root.geometry("1400x800") root.maxsize(width=1400, ...
abd04884c0baf5e0d1153e0fc0665c0b4615df10
jailukanna/Python-Projects-Dojo
/03.Complete Python Developer - Zero to Mastery - AN/02.Python Basics II/34.1 Exercise Repl.py
288
3.578125
4
# Scope - what variables do I have access to? def outer(): x = "local" def inner(): nonlocal x x = "nonlocal" print("inner:", x) inner() print("outer:", x) outer() #1 - start with local #2 - Parent local? #3 - global #4 - built in python functions
3d5c7bff8ade544c3f2371b9adcc6c3853e0269c
st2013hk/pylab
/plab/lab5.py
682
3.921875
4
# def spam(): # eggs = 99 # bacon() # print(eggs) # def bacon(): # ham = 101 # eggs = 0 # spam() # Global variable can be read from local scope # def spam(): # v1=eggs+10 # print(v1) # eggs = 42 # spam() # print(eggs) #same name of global scope and local scope, print local scope variable fi...
fdf22510b717979a573c716d79db6ab5ca6e63fd
V-Plum/ITEA
/homework_8/longest_substring_size.py
349
4.125
4
text = input("Enter text: ") result = 0 substring = "" for sym in text: if sym in substring: cut = substring.index(sym) substring = substring[cut + 1:] + sym else: substring += sym result = max(result, len(substring)) print(f"Longest substring of entered text with unique symbols ...
8a596e3ad233fa1a403d9dff9742cf575faccde4
comorina/Ducat_Assignment
/p98.py
215
3.921875
4
def greaterNumber(x,y): if(x>y): print('{} is greater than {}'.format(x,y)) else: print('{} is greater than {}'.format(y,x)) return None greaterNumber(int(input()),int(input()))
b4feb2dd45a662de909187b4148a759942c5fde7
leandro-alvesc/estudos_python
/guppe/data_e_hora/metodos_data_hora.py
1,593
4
4
""" Métodos de Data e Hora """ import datetime # Com now() podemos especificar um timezone agora = datetime.datetime.now() print(agora) hoje = datetime.datetime.today() print(hoje) # Mudanças ocorrendo à meia noite combine() manutencao = datetime.datetime.combine((datetime.datetime.now() + datetime.timedelta(days=1)...
a4a3654fc8aa719434430b2e4bd8ced2d87be151
JamesXia23/python
/code/obj/对象组合.py
991
3.78125
4
class Fish: def __init__(self, num): self.num = num class Tutle: def __init__(self, num): self.num = num class Pool: def __init__(self, fish_num, tutle_num): self.fish = Fish(fish_num) # 一定要记得加self,不然相当于在函数中定义了一个局部变量,出了函数就无效了 self.tutle = Tutle(tutle_num) def sho...
12c9d42948540a9cbfaa0a8698ee333413f403f0
yannickkiki/stuffs
/tweet-snippets/tip_getattr.py
323
3.578125
4
class Person: def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name person = Person(first_name='Yannick', last_name='KIKI') person.first_name # Yannick person.last_name # KIKI attr_name # could be `first_name` or `last_name` getattr(person, attr_nam...
daf759cbfeee3414dd3fe615d6d390bc41900c8e
geraldo1993/CodeAcademyPython
/Date and Time/Pretty Time.py
750
4.53125
5
'''Nice work! Let's do the same for the hour, minute, and second. from datetime import datetime now = datetime.now() print now.hour print now.minute print now.second In the above example, we just printed the current hour, then the current minute, then the current second. We can again use the variable now to print th...
1fc22468abcb691f69bf0d0a1b8031ec51910f24
edenizk/python_ex
/weird aritmetic.py
464
3.984375
4
def main(): print("its this operation (^) = ",3**2) print("// it divides and down to near int = " , 7//2) x = True y = False # Output: x and y is False print('x and y is',x and y) # Output: x or y is True print('x or y is',x or y) # Output: not x is False print('not x is',not...
5ec85d4c043498d0837e7e5d6b830fce9d1e6935
Michelleoc/myWork
/week08-Plotting/messingWithPieChart.py
236
3.5
4
# messing with pie chart # Author : Michelle O'Connor import numpy as np import matplotlib.pyplot as plt fruit = np.array(["Apples", "Orange", "Bananas"]) numbers = np.array([23,77,500]) plt.pie(numbers, labels = fruit) plt.legend() plt.show()
f05445b0ee222de3a5be88f31e039bd2249a94c7
chenxuhl/Leetcode
/腾讯精选50题/16LRU_Cache/LRUCache.py
2,207
3.796875
4
#146.LRU缓存机制 """ 题目描述: 运用你所掌握的数据结构,设计和实现一个  LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。 获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。 写入数据 put(key, value) - 如果密钥不存在,则写入其数据值。当缓存容量达到上限时, """ #示例: """ LRUCache cache = new LRUCache( 2 /* 缓存容量 */ ); cache.put(1, 1); cache.put(2, 2); cache.get(1); ...
851f13445284472d48a6da267af514959530a276
v-ek/euler-sols
/p1_to_p100/p10_py.py
477
3.5
4
# import numpy as np def primesfrom2to(n): """ Input n>=6, Returns a array of primes, 2 <= p < n """ sieve = np.ones(n/3 + (n%6==2), dtype=np.bool) for i in xrange(1,int(n**0.5)/3+1): if sieve[i]: k=3*i+1|1 sieve[ k*k/3 ::2*k] = False sieve[k*(k-2*(i&1)...
539be65f70820e15b756234da86cbe3cbe2ae704
knuddj1/op_text
/op_text/processing.py
4,216
3.984375
4
import csv from torch import tensor from torch.utils.data import Dataset class DataProcessor: """Processing class to convert text to model input parameters""" def __init__(self, tokenizer, max_seq_len): """ Parameters: - tokenizer : The correct tokenizer for the specific model type. Used to tokenizer input d...
781972cef1276f68933f0c9b9c29b91fcc624624
bregwc/bregwc.github.io
/chatbot.py
1,838
4.0625
4
class personaity(): hiresponce = "" whatsupresponce = "" howareyouresponce = "" otherresponce = "" def processinput(self, responce): if responce == "hi": print(self.hiResponce) elif responce == "whats up?": print(self.whatsupresponcne) elif responce == "how are you?": print(self.howareyouresponce) else: print(self.oth...
1ac3055bdc789c0fda3afea509174e6c9069a69d
taivy/Python_learning_projects
/other/beginner-projects/Menu Calculator.py
601
4.03125
4
menu = """ 1. Chicken Strips - $3.50 2. French Fries - $2.50 3. Hamburger - $4.00 4. Hotdog - $3.50 5. Large Drink - $1.75 6. Medium Drink - $1.50 7. Milk Shake - $2.25 8. Salad - $3.75 9. Small Drink - $1.25""" prices = {'1': 3.50, '2': 2.50, '3': 4.00, '4': 3.50, '5': 1.75, '6': 1.50, '7': 2.25, '8': 3.75...
268ed9df93c9835b08582c93b35f1b95be3d9c1c
taiebchaabini/holbertonschool-higher_level_programming
/0x0B-python-input_output/3-write_file.py
387
4.34375
4
#!/usr/bin/python3 """ function that writes a string to a text file (UTF8) and returns the number of characters written. """ def write_file(filename="", text=""): """ function that writes a string to a text file (UTF8) and returns the number of characters written. """ with open(...
57953714fb993e15e2ddca224567bdcbfe226198
MarizzaM/QA-Architect-Python-Exercise_4
/ex_09.py
465
3.90625
4
def add(x=0, y=0): return x + y def sub(x=0, y=0): return x - y def mul(x=0, y=0): return x * y def div(x=0, y=0): if y != 0: return x / y else: return 'Error: Div by zero' n1 = int(input('Please enter first number: ')) n2 = int(input('Please enter second number: ')) print(f...
f7465444c24adb0f218b2be2f6a878fce8e51f43
arua23/checkio_solutions
/List_1/exercise_1.py
211
3.765625
4
name=input("Enter your name:") age=int(input("Enter your age:")) age_100=2017+(100-age) n=(int(input("Enter numbers of dup:"))) out=name+" You will become 100 years old in:"+str(age_100)+"\n" print(n*out)
07f10f37bd991e4a414928f9d142758f20731b3b
Akilesh2003/Circle-Area-and-Circumference-Calculator
/main.py
290
4.53125
5
print("Hello! Welcome to my free Circle Area and Circumference Calculator!") pi = 3.14 radius = float(input("Please enter the radius of the circle in any unit: ")) area = pi*radius circ = 2*pi*radius print("The Area is {} unit square and the Circumference is {} units".format(area, circ))
42e23105d9c61bc11ee4c2a2347b2ca0d3053d7b
Ryan-Florida/Kattis
/SortOfSorting.py
540
3.546875
4
from sys import stdin def Sort(names): if len(names) == 1: return names for i in range(len(names) - 1): for i in range(len(names) - 1): if names[i][0:2] > names[i + 1][0:2]: names[i], names[i + 1] = names[i + 1], names[i] return names flag = int(stdin.readline())...
f4543e0de2aa91ddc0fff340d0b2e50d6b1a484b
CoderTangYin/LeetCode_Python
/LeetCode/LongestCommonPrefix.py
1,658
3.625
4
from typing import List """ 输入:strs = ["flower","flow","flight"] 输出:"fl" 输入:strs = ["dog","racecar","car"] 输出:"" 解释:输入不存在公共前缀。 """ class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: res = "" for temp in zip(*strs): # ('f', 'f', 'f') # ('l', 'l', 'l') ...
9e192f2a22ca24fc4479a9591c514f03503564c1
SEYEON-PARK/Python_if_else_6
/PythonApplication22.py
212
3.671875
4
a=int(input("정수를 입력하시오. ")) if(a<0): print("음수입니다. ", a, "입니다. ", sep="") elif(a==0): print("0입니다. ") else: print("양수입니다. ", a, "입니다. ", sep="")
cb2fd79170f4776126ec532dc6d8c9c52e8f8c57
learnfunfc/algorithm
/quickSort_ifirst.py
697
3.6875
4
def sort(data,m,n,size): if m<n: k = data[m] i = m + 1 j = n while data[i] < k: if i+1 == size: break i = i + 1 while data[j] > k: j = j - 1 while i<j: data[i], data[j] = d...
7fb74f7f5ebdfdeb75fc256ea56f3dd34764ad16
jguerra7/geeksforgeeks-1
/pairs_with_difference_k.py
722
3.90625
4
""" Pairs with difference K - GeeksForGeeks Problem Link: https://practice.geeksforgeeks.org/problems/pairs-with-difference-k/0 Author: Shyam Kumar Date: 15-09-2019 """ from itertools import combinations def pairs_with_difference(n,k,arr): 'This function uses combinations method to find all th...
d2e0d0449f00dd9aad91c7e2c9512fc1110e03ea
haveGrasses/Algorithm
/SU_IntersectionOfTwoLinkedList.py
4,044
3.640625
4
class Solution(object): """不保证对""" def hasCycle(self, head): """返回的并不是入环节点,而是在环中的一个节点(slow和fast相遇的节点),不排除恰好是入环节点的情况""" slow, fast = head, head while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: return slow...
934ea37af0436dff984c3f7acd50aea972588c06
yopiyama/Tools
/birthday_paradox.py
1,085
4.09375
4
#!/usr/bin/env python # coding:utf-8 """ birthday_paradox.py """ import sys import matplotlib.pyplot as plt import numpy as np def calc(N): """ Calculation probability Parameters ---------- N : int number of people Returns ------- P : float parcentage """ P...
84ee8d80ba0ea24e8cf05eb00686d11ae45ff95d
kahyee/Wi2018-Classroom
/students/rusty_mann/Session08/circle.py
496
3.75
4
import math class Circle(): def __init__(self, radius=4): self.radius = float(radius) @property def area(self): return math.pi * self.radius**2 @property def diameter(self): return 2 * self.radius @diameter.setter def diameter(self, diameter): self.radius ...
b79c1fee363ed5257c1ae357d1a55c7258f4d548
wangscript007/Miniwin
/src/3rdparty/grt/build/python/examples/PreProcessingModulesExamples/double_moving_average_example.py
1,638
3.6875
4
import GRT import sys import numpy as np import math def main(): """GRT DoubleMovingAverageFilter Example This example demonstrates how to create and use the GRT DoubleMovingAverageFilter PreProcessing Module. The DoubleMovingAverageFilter implements a low pass double moving average filter. ...
0ed98bde41b10ecbd59a21e765d108f67a7d91b5
Bharadwaja92/CompetitiveCoding
/LeetCode/5_Longest_Palindromic_Substring.py
1,309
4.125
4
""" Given a string s, return the longest palindromic substring in s. A string is called a palindrome string if the reverse of that string is the same as the original string. Example 1: Input: s = "babad" Output: "bab" Explanation: "aba" is also a valid answer. Example 2: Input: s = "cbbd" Output: "bb" """ class So...
9dd1cfcc88017d7c38124f1e322c1249a1723e0e
lhd0320/AID2003
/official courses/month02/day13/myProcess.py
575
3.578125
4
from multiprocessing import Process class MyProcess(Process): def __init__(self,value): self.value = value super().__init__() # 执行父类init 有了父类属性 def fun1(self): print("步骤1",self.value) def fun2(self): print("步骤2") # 与start结合,最近进程的启动函数 def run(self): if sel...