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
46ac665bde6f80fb3089104071703ce37ecb9e1a
DmitryIvanov10/MetodyNumeryczneI
/Tasks/Lista7/task3.py
540
3.875
4
# Lesson7, Task3 # import ln from math import log # import exponent from math import e # import function from own module from numerical_methods import newton # initial data u = 2510 M0 = 2.8 * 10**6 m = 13.3 * 10**3 g = 9.81 vs = 335 # define function def v(_t): return u*log(M0/(M0-m*_t), e) - g*_t - vs # ca...
964b2972c692bc9686b6e0579da2096d6d56d419
EverSaidGr/PythonCourse
/iva.py
247
3.734375
4
# precio de producto # Muestre valor del IVA print ('Calcular el IVA') precio=float(input ('Da el precio del producto: ')) iva=precio*0.16 total=precio+iva print('El iva del producto es: ',iva) print('El precio del producto con IVA es: ', total)
20bb85458ea5b8e92bcb89a406314491416635f7
keepexploring/streamz3
/streamz3/scheduler.py
2,335
4.0625
4
import datetime import pdb class Scheduler(object): """A function for creating an object to collect the schedule for running the analysis at regular intervals example of use: SS=Scheduler() SS.every().hour.at('0:0:0') # in the at command you put in 'hour:minute:second' when you want the command to repe...
a3f15d3d658b95be458f98d2d7f8131f5286be87
topliceanu/learn
/python/algo/test/test_splay_tree.py
1,719
3.65625
4
# -*- coding: utf-8 -*- import unittest from src.splay_tree import SplayTree, PARENT, LEFT, RIGHT, KEY class SplayTreeTest(unittest.TestCase): def test_insert_splays_node_to_the_root(self): st = SplayTree() for i in range(30): st.insert(i) self.assertEqual(st.root[KEY], 29, ...
fc09f18fbc354e6251ddbdfbc0bfc4441db4be42
liao2014/Python20190618
/day09/mythread6_event.py
917
3.578125
4
# Author:UserA # 线程之event示例——红绿灯 import time import threading event = threading.Event() def lighter(): count = 0 event.set() while True: if count > 5 and count <= 10: # 改成红灯 event.clear() # 把标志位清空了 print('\033[41;1m red light on \033[0m') elif count > 10: ...
ff8b6a8a5cad6c09a9b8c45970307fe902f6fe60
nandiniananthan/Python
/Data Structures/Array/HR left and right rotation of an array.py
408
3.65625
4
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ n = 5 d = 2 a = [1, 2, 3, 4, 5] OP = [4,5,1,2,3] ################# right rotation ############## for i in range(d): a.insert(0, a.pop(n-1)) print(a) ################# left rotati...
058e824be38cfaff820ddb938892cfc13052a4b2
KaraKala1427/python_labs
/task 4/98.py
1,169
3.890625
4
def hex2int(hexa): H = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'] h = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'] decimal = 0 while True: for i in hexa: if (i in h) or (i in H): continue else: ...
69e86833fbc788c25e2b47814a4a90ac31446050
balwinder34/hangman
/STPchallenges/chapter 4/chal5.py
358
4.28125
4
a= input("type a string:") a= str(a) try: def f(a): return float(a) print(f(a)) """ This function is nestled in a try/except clause to correct the input of the user who puts a string of letters, instead of a number to be floated """ except ValueError: print("Wait, sh...
584f20e1e33578fab1ad3043e2402cbb053706ab
ricardogando/sfof
/sfof/python/functions/comp.py
1,314
3.546875
4
########################### # COMPUTATIONAL FUNCTIONS # ########################### import numpy as np def find_bin(value, min_value, bin_size): """ Fine corresponding bin of a given value. """ return np.floor(round((value - min_value) / bin_size, 8)).astype('int') def num_bins(min_value, max_value, ...
d1a49e78e17d56f3ebe9f72f8dc4af828469baac
hypersimple/Fbt
/DSL/src/writers/BatchedWriter.py
1,570
3.765625
4
#!/usr/bin/env python """ A writer that buffers output and tries to 'batch' multiple chars into a single integer write to reduce instructions. """ class BatchedWriter(object): def __init__(self, inner): self.inner = inner self.batch = [] def write_comment(self, text): self.inner.write...
d6c188b9489db5200dbaf257a265201a9ddb463e
martinteh/Imperial_Mechanical_Engineering
/ME1/Session 1/Session 1 Task A.py
975
3.640625
4
import numpy as np #task A '''A = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] B = [20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30] B[5] = A[2] + A[3] print(B) Product = B[4] * 2 print(Product) X = A[len(A) - 1] print(X) Y = A[0] A[0] = X A[len(A)-1] = Y print(A) i = 3 j = 5 J = A[j] A[j] = B...
8f591958c0090bb518c93c1d3d94abd80a065402
shadiaf/Google-Books-Dataset
/one_gram_plotter.py
1,235
3.90625
4
import matplotlib.pyplot as plt import one_gram_reader import numpy as np import string #This function will aid in returning a plot of the relative frequency of certain words over a span of specific years def plot_words(words, year_range, word_file_path, totals_file_path): total = one_gram_reader.read_total_count...
2c009e773baf2bb8cc8d959ac44f6842cc2030c2
jemtca/CodingBat
/Python/Logic-1/less_by10.py
323
3.90625
4
# given three ints, a b c, return true if one of them is 10 or more less than one of the others def less_by10(a, b, c): bool = False if abs(a - b) >= 10 or abs(a - c) >= 10 or abs(b - c) >= 10: bool = True return bool print(less_by10(1, 7, 11)) print(less_by10(1, 7, 10)) print(less_by10(11, 1, 7...
bc82bbe392e3b28f076d88265f85a7560be215f3
chfumero/operationsonfractions
/operationsonfractions/mixed_number.py
4,097
3.84375
4
import re import math from fractions import Fraction def simplify_fraction(fraction): if type(fraction) is not Fraction: return fraction if fraction.denominator == 1: return fraction.numerator if abs(fraction.numerator) > fraction.denominator: return MixedNumber(whole=int(abs(fra...
1238ce8f38ee61d899afa1623fcc263ba47717cf
Yamievw/class95
/python/read_data.py
5,332
3.640625
4
# This file reads in the data and fills two lists: one with # students and one with courses. This data can be readily used # by importing this module. import csv import math # for ceil. class Course(): def __init__(self, name, components, registrants): self.name = name # a dictionary w...
2f3b9fe7dfe70944571339938ede21d857aa2d59
BeatrizYokota/python-exercises
/ex042.py
484
4
4
a = float(input('Digite a medida da primeira reta: ')) b = float(input('Digite a medida da segunda reta: ')) c = float(input('Digite a medida da terceira reta: ')) if a < b + c and b < a + c and c < a + b: print('É possível fazer um triângulo') if a == b == c: print("Triângulo equilátero!") elif a !...
b418f24ad68d219899877520b698cafc75a9597f
Akhilnazim/Problems
/leetcode/leap_year.py
641
4.28125
4
def leapYear(y): if (y%400 == 0) or ((y%4 == 0) and (y%100 != 0)) : print("it is a leap year") else: print("not a leap year") leapYear(2004) # Python program to check if year is a leap year or not year = 2016 # To get year (integer input) from the user # year = int(input("Enter a year: ...
9605b57e0ebc75ade536a62b59bd8778da930346
snehangsude/Tic_Tac_Toe
/grid.py
4,317
4.21875
4
import random class Grid: def __init__(self): """Initilaizes the Grid of the Tic-Tac-Toe""" self.lines = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]] self.create_grid(None, None) self.comp_list = [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)] ...
2cd15d1d96704f9cd047c0dc50998480c4fc6897
31p7410/leetCode
/4.寻找两个正序数组的中位数.py
2,799
4.0625
4
""" # 寻找两个正序数组的中位数 给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。 示例 1: 输入:nums1 = [1,3], nums2 = [2] 输出:2.00000 解释:合并数组 = [1,2,3] ,中位数 2 示例 2: 输入:nums1 = [1,2], nums2 = [3,4] 输出:2.50000 解释:合并数组 = [1,2,3,4] ,中位数 (2 + 3) / 2 = 2.5 链接:https://leetcode-cn.com/problems/median-of-two-sorted-arrays/ """ ...
add8d8d681d7aac0ac1785ea07c3be24c11d6547
reetamdutta1/TCS-Ninja-Coding-Qstns-Solutions-only-Python-
/Codes/generate_ticket.py
868
3.953125
4
def generate_ticket(airline,source,destination,no_of_passengers): ticket_number_list=[] i= 0 if no_of_passengers < 5: while no_of_passengers != 0: ticket_number_list.append(airline + ":" + source[:3] + ":" + destination[:3] + ":" + str(101+i)) i=i+1 no_of_p...
d105acb40fca0a8c97d4beb3d0424a658ad1ae1b
QingqiLei/LearnPython
/PythonFundamentals/functionalprogramming/returnFunction.py
1,248
3.828125
4
def lazy_sum(* args): # args is a tuple, tuple is not def sum(): ax = 0 print(type(args)) for n in args: ax = ax + n return ax return sum f = lazy_sum(1,2,3,4,5) f f() # call f function ''' sum() is the inner function of lazy_sum(), and inner function sum() can use th...
75ea890a5609a3dbfef9d991b5a7f6577cd706ce
Nike-one/FirstGit
/longestWord.py
218
3.796875
4
import re txt = "Hey there Nikhil this side" l = [] x = re.split(" ",txt) for i in x: l.insert(0,i) longString = max(l,key = len) print("Longest String: ",longString) print("Length of Longest String",len(longString))
3fb1e02d969e2154385c5690f868c788289cd227
rwxrr/Python
/enuzunstring.py
452
3.78125
4
# -*- coding: utf-8 -*- """ Fonksiyona parametre olarak verilen stringin içerisindeki en uzun kelimeyi bulan program """ metin=raw_input("Cümleyi giriniz") def en_uzun_kelime(metin): kelimeler=metin.split() kelime_length=[] for i in kelimeler: kelime_length.append((len(i),i)) ...
3bc11fabe8e643d754302e86761ab7a8c1bfa4bc
HemantDeshmukh96/Credit-Card-Verification-Toolkit-Program
/Credit Card Verification .py
770
3.703125
4
num=int(input("Enter 8 digit Credit Card Number :")) n1=num//10000000 n11=num%10000000 n2=n11//1000000 n21=n11%1000000 n3=n21//100000 n31=n21%100000 n4=n31//10000 n41=n31%10000 n5=n41//1000 n51=n41%1000 n6=n51//100 n61=n51%100 n7=n61//10 n8=n61%10 a=n8+n6+n4+n2 n12=n1*2 n32=n3*2 n52=n5*2 n72=n7*2 if...
d7d5c671c98cf5e2959a7da2c1a186cf83de7745
dfhampshire/RInChI
/rinchi_add.py
1,522
3.5
4
#!/usr/bin/env python3 """ RInChI Addition Script ---------------------- This script adds together flat files of RInChIs separated by newlines. Modifications: - C.H.G. Allen 2012 - D.F. Hampshire 2016 Rewritten to use argparse module and Python3 """ import argparse from rinchi_tools import tools, utils ...
615990804edd93a0d5c1a7891b7152c3f4c89226
azure1016/MyLeetcodePython
/JavaImpl/EPI/Strings/efficient_String.py
1,006
4.34375
4
''' String is immutable, so: 1. adding elements to the front of string n times, time complexity: O(n^2) 2. adding elements to the end of string n times, time complexity? 3. replacing elements by index in string n times, time complexity? 4. Note that some implementation ... 5. example: converting integers to strings H...
388d12f64a99ad24c21cf9ae7a215afce4d28db3
IvannikovG/Python-cheatsheet
/ooptutorials/OOPTutorial4.py
1,528
3.8125
4
# OOP Tutorial 4 class Employee: raise_amount = 1.04 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay def fullname(self): return f'{self.first} {self.last}' def email(self): return f'{self.first}.{self.last}@mail.com' ...
33d2a7cfb4f3291a42ac64db26dc92676b3d0792
gloria-ho/algorithms
/python/prime1001.py
477
3.671875
4
# https://projecteuler.net/problem=7 # By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. # What is the 10 001st prime number? def find_prime(arr, targ): num = arr[-1] while len(arr) < targ: num += 1 prime = True for x in arr: if num % x == 0: ...
28c8d66d3f048c74d0532154715af6728bcc3bb5
Hakkim-s/python-tutorials
/exception.py
608
4.0625
4
'''try: num1 = 5 num2 = 0 print(num1/num2) except ZeroDivisionError: print("zero division error") finally: print("this code will excecute whatever happens") ''' try: print("Hello") print(1 / 0) except ZeroDivisionError: print("Divided by zero") final...
0bb020bc080249c2676cbf9275afe4c5a7cdf503
ajorve/pdxcodeguild
/lists/list_practice.py
2,211
4.5
4
""" Given an input list, return it in reverse. >>> backwards([56, 57, 58, 59, 60]) [60, 59, 58, 57, 56] Find the max number in a given list. Then, change every element in the list containing the first number of the maximum to the maximum number. >>> maximus([56, 57, 58, 59, 60]) [60, 57, 58, 59, 60] >>> maximus([56...
3e8f914419e7b13886320e8503dc5bb09b46403a
danielazieba/frontiernews
/python-src/stanford_news_to_json.py
1,049
3.5625
4
#functions relating to taking parsed website data and converting it to JSON #used as reference for this file: https://stackabuse.com/reading-and-writing-json-to-a-file-in-python/ import json from stanford_scrape import * from bs4 import BeautifulSoup def stanford_to_json(articles): resulting_json = {} resulti...
618d1e84930afe68fb048b1c345b45a1ef9a1cb8
SimmonsChen/LeetCode
/双指针/75. 颜色分类.py
1,331
4.4375
4
""" 给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。 此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。 注意: 不能使用代码库中的排序函数来解决这道题。 示例: 输入: [2,0,2,1,1,0] 输出: [0,0,1,1,2,2] """ class Solution(object): # 思路:双指针 # i和j分别从头尾遍历,i收集0,j收集2。 def sortColors(self, nums): """ :type nums: List[int] ...
c0ebf10b8c0cb4af11608cafcdb85dbff4abdf90
mourakf/Python-FDS-Dataquest
/Python - Practice Problems/finding_the_pair.py
625
3.96875
4
""" Find two distinct numbers in values whose sum is equal to 100. Assign one of them to value1 and the other one to value2. If there are several solutions, any one will be marked as correct. Optional step to check your answer: Print the value of value1 and value2. """ values = [72, 50, 48, 50, 7, 66, 62...
d74621bcc0b2e6ac549162f1d600f5a20183a73f
NikeSmitt/TowerDefense
/menu/menu.py
2,413
3.515625
4
import os import pygame from menu.menuImages import menu_images class Button: def __init__(self, x, y, img, name): self.name = name self.img = img self.x = x self.y = y self.width = img.get_width() self.height = img.get_height() pygame.font.init() s...
ceda1155a14ef7908b56a6a26ab9ae2c20d46eee
soarflighting/LeetCode_Notes
/twoPointer/hasCycle_141.py
994
3.828125
4
# 141.环形链表(Easy) # 给定一个链表,判断链表中是否有环。 # 为了表示给定链表中的环, # 我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 # 如果 pos 是 -1,则在该链表中没有环。 class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): # 使用双指针,一个指针每次移动一个节点, # 一个指针每次移动两个节点,如果存在环,那么这两个指针一定会相遇。 ...
616716ba2e6e68d1df18093da2e9c8f933e09f29
sinsomi/Coding-Test
/쿠팡코테준비/탐욕알고리즘(그리디).py
503
3.78125
4
activity = [[1,1,3], [2,2,5], [3,4,7], [4,1,8], [5,5,9], [6,8,10], [7,9,11], [8,11,14], [9,13,16]] def activitySelection(act): result = [] sortedAct = sorted(act, key=lambda x: x[2]) print(sortedAct) last = 0 for i in sortedAct: if last < i[1]: result.append(i) las...
768ae5f7f49fc7aa4c0db188f10adaee325a892b
dmgrogers/Exercises
/Py_ModernPythonBootcampUdemyNotes/14dictionaries.py
4,186
4.5
4
# Dictionaries: # dict, assignment, [], get, values, keys, items, # in, copy, is, clear, fromkeys, pop, popitem, update d = {'key1': 1, 'key2': 2} dl = {'key3': [1, 2], 'key4': [3, 4]} dd = {'dict1': {'key5': 1, 'key6': 2}, 'dict2': {'key7': 3, 'key8':4 }} # Note that the order of keys in a dictionary is not set as i...
c1ae914fb290d426036dadb1d22c8941b82118c0
unssfit/python-programming-work-
/removeExclamationMark.py
266
4.0625
4
string = '?how?much you cost??for this? hel? no dud?' def remove_exclamation_mark(string): st = list(string) for i in range(len(st)): if st[i] == '?': st[i] = '' return ''.join(st) res = remove_exclamation_mark(string) print(res)
ff39b5e200c61ce57e8e139f022b854d3dcbd938
mcfee-618/FluentPy
/03/test_dict.py
345
3.859375
4
#coding:utf-8 """ @author: mcfee @description:字典推导 @file: test_dict.py @time: 2020/6/24 上午11:05 """ import collections list1=[1,2,3,4,5] print({str(item):"" for item in list1}) # 字典推导表达式 class MyDict(dict): def __missing__(self, key): return 22 a= MyDict() print(a[22]) #找不到调用__missing__方法
177205d1ee4a7a1dd72219e9407b7d52a3bd932a
epangar/python-w3.exercises
/Python_basics/11-20/14.py
271
4.125
4
""" 14. Write a Python program to calculate number of days between two dates. Sample dates : (2014, 7, 2), (2014, 7, 11) Expected output : 9 days """ from datetime import date first = date(2014, 7, 2) last = date(2014, 7, 11) answer = first - last print (answer.days)
33bebc94d74829650c8fb9807f623961f29a1d5f
GerardoArayaCeciliano/TallerVisionArtificial
/Practica6/funciones.py
1,998
3.578125
4
import cv2 import numpy as np #Este programa permitira dubijar objetos sobre una ventana de openCV #Construir una imagen en blanco de tamaño definido # imagen = 255 * np.ones((400,600,3), dtype=np.uint8) # #parametros de line(Superficie, codenadaIni, coordenaFin,color, grosor) # cv2.line(imagen,(0,0),(600,4...
5a5ce28865e1b7ae2c8dee2e15cfb726e106aac9
YJL33/LeetCode
/current_session/python/426.py
2,983
4.03125
4
""" 426 Convert a Binary Search Tree to a sorted Circular Doubly-Linked List in place. Think of the left and right pointers as synonymous to the predecessor and successor pointers in a doubly-linked list. For a circular doubly linked list, the predecessor of the first element is the last element, and the successor of...
6056730fe7967fa47824ecb1ea7cb92e954915c0
Laeh03/Election_Analysis
/Resources/Loops.py
161
4.0625
4
x = 0 while x <= 5: print(x) x = x + 1 numbers = [0, 1, 2, 3, 4] for num in numbers: print(num) for num in range(5): print(num)
1d9cd11e40158844110422191bc89fd4772e3396
khanirfan196/pythonprograms
/Programs_on_Strings/string_count.py
284
3.796875
4
# Program to demonstrate count() function on strings # Author : Irfan Khan Mohammed str = "Always be Motivated and keep up the good work" print(str) print("Count func: counting occurrence of 'o'") print(str.count('o')) print() print("Count func: counting blank spaces:") print(str.count(' '))
b002effc4fe3ae3ec8dff16be8be1953a826aabb
gstamatelat/find-duplicates
/find-duplicates.py
2,921
3.578125
4
#!/usr/bin/env python3 import sys, os, filecmp, argparse # Arguments parser = argparse.ArgumentParser(description='Find duplicate files using their MD5 hashes.') parser.add_argument('directories', metavar='DIR', type=str, nargs='+', help='directories to search recursively') parser.add_argument('-d'...
7cc5d5e62eeb937aec4906a4f91e1e1987c60809
Harishkumar18/data_structures
/leetcode_preparation/maximal_rectangle.py
876
3.828125
4
""" Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area. Example: Input: [ ["1","0","1","0","0"], ["1","0","1","1","1"], ["1","1","1","1","1"], ["1","0","0","1","0"] ] """ def maximalrectangle(matrix): if not matrix or not matrix[0]: ...
f0910a4833d1f819f7851c744105e54eb1fa82b3
PavliukKonstantin/learn-python
/learn_python/hexlet/dictionary/lessons/count_all.py
1,077
4.15625
4
# Цель упражнения — функция count_all. Эта функция должна принимать на # вход iterable источник и возвращать словарь, # ключами которого являются элементы источника, а значения отражают # количество повторов элемента в коллекции-источнике. # Вот пара примеров, демонстрирующих то, как функция должна работать: # def cou...
51ebb5a612b3be307a17935bb9221d00ab9f4ccb
Aubergines/BasePython
/com/cn/main/structure/Queue.py
995
3.953125
4
# coding=utf-8 # 队列的实现 class Queue(): def __init__(qu,size): qu.queue=[]; qu.size=size; qu.head=-1; qu.tail=-1; def Empty(qu): if qu.head==qu.tail: return True else: return False def Full(qu): if qu.tail-qu.head+1==qu.size: ...
13cdec0d0b06afbcedb2283f51260a551978b743
masasin/advent_of_code_2015
/day_10.py
1,805
4.1875
4
""" http://adventofcode.com/day/10 --- Day 10: Elves Look, Elves Say --- Today, the Elves are playing a game called look-and-say. They take turns making sequences by reading aloud the previous sequence and using that reading as the next sequence. For example, 211 is read as "one two, two ones", which becomes 1221 (1 ...
8dc61900c6b46419df2dffbdc54842bd677c0df5
eselyavka/python
/leetcode/solution_1051.py
590
3.953125
4
#!/usr/bin/env python import unittest class Solution(object): def heightChecker(self, heights): """ :type heights: List[int] :rtype: int """ sorted_height, res = sorted(heights), 0 for i in range(len(sorted_height)): if sorted_height[i] != heights[i]: ...
a73e23e7c79bf6476ea38e6ef2f753e92c15c986
cgilbert-rep/wiki_extract
/modules/utils.py
341
3.734375
4
import os def build_folder(folder): ''' Build a folder if it doesn't exist param folder: folder to build type output_folder: string return: None rtype: None ''' if not(os.path.isdir(folder)) and (folder != ""): print("%s does not exist, making it..." % folder) os.mkdi...
3e4975cffd44b1080cee5773fd30ab1d9f3acdf8
cealvar/Practice
/Review/Stack.py
2,960
3.9375
4
from Node import Node class StackArray: def __init__(self): self.stack = [] self.size = 0 def push(self, item): self.stack.append(item) self.size += 1 def pop(self): if self.size: item = self.stack[self.size-1] self.stack = self.stack...
e48e28692e8377194201173847a1c4da458a1890
sandesh23/employee
/EmployeeInfo.py
1,350
3.59375
4
class Emp: def __init__(self,id,nm,address,salary): self.empId = id self.empName = nm self.empAddress = address self.empSalary = salary def __repr__(self): return str(self) def __str__(self): return 'EmpId :{} , EmpName : {}, EmpSalary: {} ,EmpAdd...
f4614b12d1a0a632eef8ef276642dc87e2fada75
AlexWombat/Labb3
/engelska_meddelande.py
710
3.75
4
from bintreeFile import Bintree svenska = Bintree() with open("word3.txt", "r", encoding = "utf-8") as svenskfil: for rad in svenskfil: ordet = rad.strip() if ordet in svenska: print(ordet, end=" ") else: svenska.put(ordet) print("\n") engelska = Bintree() with open...
dbd60147dadad4544105b602620a7fc46e0aad52
fvoulgari/avl_tree
/avltree.py
6,018
3.75
4
import random import datetime class Node(): def __init__(self, key,card,payment,day,counter): self.key = key # node's key self.left = None # node's left child self.right = None # node's right child self.height = 0 # node's height = 1 + max(-1, -1) self.day=[day]...
4019fc8167fad25f6cea5730f1b9345882c34663
meryemozdogan/Bby162
/uygulama04.py
1,053
3.6875
4
kadinismi = input("Bir kadın adı giriniz...:") erkekismi = input("Bir erkek adı giriniz...:") mısra = int(input("Mısra sayısı giriniz...Maksimum 9 mısra yazdırılabilir..")) import random sarki = [erkekismi + " bugün bende bir hal var " , kadinismi + " ürkek ürkek bakar" , "Yağmur iri iri düşer toprağa " ,...
b02285bb81ed48e5947fccdef9f3301513b429e0
mironmiron3/SoftUni-Python-Advanced
/Comprehensions/Number-Classification.py
611
3.703125
4
list_of_numbers = [int(num) for num in input().split(", ")] positives = [] negatives = [] odds = [] evens = [] [positives.append(el) if el >= 0 else negatives.append(el) for el in list_of_numbers] [evens.append(el) if el % 2 == 0 else odds.append(el) for el in list_of_numbers] positives = [str(item) for item in ...
7ddbab0c7f4942cfa4997d6742dd2a3c5702fd53
siri-palreddy/CS550-FallTerm
/CS-HW/HW10-15-17:MineSweeperProject.py
2,341
3.984375
4
import sys import random import math def getRow(cellNumber): rowNumber = math.ceil(cellNumber/totalColumns) return rowNumber def getColumn(cellNumber): columnNumber = cellNumber%totalColumns if columnNumber == 0: columnNumber = totalColumns return columnNumber try: totalRows = int(input('How many rows would...
a3789258951581cb4b08197622b5db7412164b89
DannyVanpoucke/Amadeus
/subroutines/maths/GridModule.py
1,497
3.625
4
# -*- coding: utf-8 -*- """ Created on Mon Nov 19 09:15:17 2019 Function designed to generate small 1D grids. @author: Dr. Dr. Danny E. P. Vanpoucke @web : https://dannyvanpoucke.be """ def Grid1D(Min: float=0.0, Max: float=1.0, NGrid: int=5, GridType: str=None ): """ Creates a arry containing a grid. ...
40f0e0af9431a3314530c1148e3ba95e2e06384f
aruquense/FSI
/clase1.py
65
3.609375
4
l=[1,2,3,4,5] print(l) l2=[(e**2,e**3) for e in l[::2]] print(l2)
f9e4b76a84970953a805d40263a4cdc0df805b6c
Jiawei-Wang/LeetCode-Study
/475. Heaters.py
1,499
3.984375
4
""" 1. For each house, find its position between those heaters (thus we need the heaters array to be sorted). 2. Calculate the distances between this house and left heater and right heater, get a MIN value of those two values. Corner cases are there is no left or right heater. 3. Get MAX value among distances in ste...
a87b6a201622306e7537fe575b5b9804c94d7545
bobtodd/edscripts
/StatsFns.py
1,759
3.953125
4
#!/usr/bin/env python3.1 # StatsFns.py # A pared-down module containing some functions commonly used # to get statistics. from math import sqrt def corr(x, y): """Find the correlation between two lists of data.""" assert len(x) == len(y), "lists must have equal length" xSum = sum(x) ySum = s...
89f6ae1f798afc68c2cb3280019654a7f56cc26e
vxela/altera-batch5-
/Struktur Data/Problem 3/4-polindromeRecursive.py
426
3.515625
4
def polindromeRecursive(sentenc) : if len(sentenc) < 2 : return True else : if sentenc[0] == sentenc[-1] : return polindromeRecursive(sentenc[1:len(sentenc)-1]) else : return False print(polindromeRecursive('katak')) print(polindromeRecursive('blanket')) print(po...
511c629134fb4fc5dc3ea8c3b95a590225497c12
KPW10452025/PythonCodeRecipes
/p186_try_except_else_finally02.py
1,961
3.59375
4
# try except else finally 實務 # 在實務上開發時,不論是資料庫的連線或是檔案處理 # 最後運算完成都要把資源釋放,否則資源將耗盡或無法開啟檔案 # 在一般情況下,我們都會把釋放資源的程式碼放在運算的最後,如下範例: names = ["swift", "python", "java", "flask", "django"] try: file = open("p182_Error.py") seq = names.index("seiftUI") # 開啟檔案後,會在這裡出現錯誤,程式會跳到 except seq += 1 except: print("You got ...
ff1a1a7ca0897316da3aab1d1f4dc679bf58ae95
Peter-John88/ConquerPython
/022returnFunc.py
1,514
3.828125
4
# -*- coding:utf-8 -*- # ## 函数作为返回值 def calc_sum(*args): # 定义一个可变参数的求和函数 ax = 0 for n in args: ax = ax+ n return ax print calc_sum(1,2,3,4,5) def lazy_sum(*args): #可以不返回求和的结果,而是返回求和的函数! def calc_sum(): ax=0 for n in args: ax=ax+n return ax retur...
c6d73449284c22704f49cd316d5df461b035761a
looyea/PythonStudy
/NumPy/jianshu/Demo03.py
1,150
3.640625
4
# _*_ coding:utf-8 _*_ import numpy as np # Test 1 # 一维矩阵 a = np.arange(3, 15) print(a) # 输出矩阵的第三个元素 print(a[2]) # Test 1 result # [ 3 4 5 6 7 8 9 10 11 12 13 14] # 5 # Test 2 # 二维矩阵 a = np.arange(3, 15).reshape(3, 4) print(a) # 输出矩阵的第二行 print(a[1]) # 输出矩阵的第一个元素 print(a[0][0]) # 输出矩阵某个位置上的元素 print(a[2][1]) pri...
498bce1d2b1cd2c62325858642a4c84371dbe261
RubenIbarrondo/GAscripts
/Exercises/MaxInteger.py
5,383
3.90625
4
## ## Title: Maximize the integer ## Author: Rubén Ibarrondo ## Description: ## Maximizes the integer ## representation in binary ## string. import numpy as np import matplotlib.pyplot as plt import plotTools def crossover(c1, c2, i): '''Returnes the crossovers at i of chromosomes c1 and c2.''' if ...
120b9ee6f2567ebe96669dab80896e389123881f
ArturM94/Challenges
/hackerrank/30_days_of_code/06_lets_review.py
585
4.09375
4
# Task # # Given a string, S, of length N, that is indexed from 0 to N - 1, # print its even-indexed and odd-indexed characters as 2 space-separated strings # on a single line (see the Sample below for more detail). # # Note: 0 is considered to be an even index. # Number of test cases for t in range(int(input())): ...
e25b9c7b4b99a68ca4bd25be3649a0b0927ec6bd
YuriZalukovskiy/homework
/first.py
752
3.96875
4
def insertionSort(arr): for i in range(1, len(arr)): x = arr[i] j = i while j > 0 and arr[j - 1] > x: arr[j] = arr[j - 1] j -= 1 arr[j] = x return arr def selectionSort(arr): for i in range(len(arr) - 5): minIndex = i for j...
27c5e6f67543ee9e22255925104c4b51cfd9081e
EmersonDantas/SI-UFPB-IP-P1
/Python Brasil - Exercícios/Strings/PB-11-Jogo da forca- STR.py
1,010
3.828125
4
import random palavras = ['agua','chocolate','bacon','python','linux','UFPB','hidratado'] palavra = str.upper(palavras[random.randint(0,len(palavras)-1)]) tracos = [] usados = [] erros = 6 acertos = 0 for i in range(len(palavra)): tracos.append('_') def visual(): for a in range(len(tracos)): print(tra...
cd72b1a03ed9e57ca515de247b22224b36e788ce
ssahaje/Demo_Ci_Cd_Pipeline_project
/list_methods.py
1,238
4.15625
4
sample_list = [2,7,9,7,5,3,3] list_item_coumt = sample_list.count(7) print(list_item_coumt) copy_sample_list = sample_list.copy() print(copy_sample_list) print(sample_list.pop(0)) print(f'After popping up: {sample_list}') sample_list.sort() print(f'Sorted list: {sample_list}') sample_list.reverse() print(f'Descending ...
e186b84d4c80c2e7d632ee8bce3d0ddbaa56589e
pernici/sympy
/sympy/geometry/polygon.py
36,175
3.671875
4
from sympy.core import Basic, S, C, sympify, oo, pi from sympy.simplify import simplify from sympy.geometry.exceptions import GeometryError from entity import GeometryEntity from point import Point from ellipse import Circle from line import Line, Segment, Ray class Polygon(GeometryEntity): """A two-dimensional p...
1b3120e07d809147dd0b1a856adb2fa665cf9ec1
shekharkrishna/ds-algo-udi-20
/Data Structures/Trees/1. Creating Binary Tree/trees_3_reexploed_values.py
2,317
4.5
4
# Add functions that assign a left child or right child class Node(object): def __init__(self, value=None, left = None, right = None): self.value = value self.left = left self.right = right def get_value(self): return self.value def set_value(self, value): self....
7029f3661a93199c102baa5c1c4eeb9693ac4e01
shafayatnabi/BA_EN_NUM_OCR
/Hand.py
2,171
3.515625
4
def array_left_rotation(a, n, k): temp=a[0:k] temp1=a[k:n] temp1.extend(temp) return temp1 n, k = map(int, raw_input().strip().split(' ')) a = map(int, raw_input().strip().split(' ')) answer = array_left_rotation(a, n, k); print ' '.join(map(str, answer)) def check_binary_search_tree_(root): if r...
7243dc79ae1d10332730c9b250a4ec50fabfb27d
Jburns22/CCLocalChat
/chatserver.py
5,468
3.65625
4
import socket from _thread import * import chatserver import os # This program receives incoming messages from all clients and interprets # what it should do with a given message, be it broadcasting it to everyone else, # sending a given message to an individual recipient, removing the sender from the chatroom, or # s...
0671e16c50764273cee48a6a9cb21ed0372bd1a6
sachin3496/PythonCode
/batch10_dec_2018/mypkg/mod1.py
328
3.765625
4
"""mod1 module consits two function add(a,b) --> print result a+b pat(n) --> will print normal pattern of n lines """ def add(a,b): """add(a,b) --> print a+b""" print(f"Result = {a} + {b} = {a+b} ") def pat(n): for var in range(10): print("*"*var) if __name__ == "__main__" : add(4,5) ...
9d538c3144654744a59186d5f05a24ea5527a044
Rhysj125/tensorflow
/src/deep-neural-net.py
4,010
3.734375
4
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # Get data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) ## Help functions to create weights and bais variables, convolution and pooling layers # Using RELU activation function. Must be initialised to a small positive ...
da99534e998b1d74be8e507c2fa58d3a48b74aff
vxda7/end-to-end
/Problem/zigzag.py
282
3.78125
4
numbers = int(input()) real=[] for number in range(numbers): get = int(input()) result=0 for i in range(1,get+1): if i%2: result+=i else: result-=i real.append(result) cnt=1 for i in real: print(f'#{cnt} {i}') cnt+=1
d8a113b7508ff47765a9f0d56723d2c29f0d564e
usagainsttheworld/Principles_of_Computing
/principle_of_computing1_courseNotes.py
17,910
4.03125
4
#######Quiz One###### #Q5 Which of the following expressions returns the last character in the non-empty string my_string? mystring = 'abc' print mystring[len(mystring)-1] #Q7 Consider the following snippet of Python code. What is the value of val2[1] after executing this code? val1 = [1, 2, 3] val2 = val1[1:] val1[2...
0906b070a69d53e66a3470455fba9132792a100d
kimha1030/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/100-matrix_mul.py
1,829
4.28125
4
#!/usr/bin/python3 """Module to find the product o f two matrix """ def matrix_mul(m_a, m_b): """Function to find the product of two matrix """ msg1 = "m_a should contain only integers or floats" msg2 = "m_b should contain only integers or floats" msg3 = "each row of m_a must be of the same size" ...
0c81137d9a81ced94d7b9d7ed52c33a6ccd93b70
Shirinzha/-
/factorialAndFuzzbuzz.py
551
3.984375
4
for x in range (1,101): if x % 3 == 0 and x % 5 == 0: print('fuzzbuzz') elif x % 3 == 0: print('fuzz') elif x % 5 == 0: print('buzz') else: print(x) # 1 * 2 * 3 *4 * 5 n = int(input("Введите число")) factorial = 1 for x in range(1, n + 1): fac...
4f1defd48e2734ea66c72e26f0554a765bead7ad
padamcs36/Introduction_to_Python_By_Daniel
/Chapter 9 GUI's Programming Using TKinter/ScrollBar.py
447
3.765625
4
from tkinter import * class ScrollBar: def __init__(self): tk = Tk() tk.title("Scroll Bar") frame1 = Frame(tk) frame1.pack() scrollBr = Scrollbar(frame1) scrollBr.pack(side=RIGHT, fill=Y) text = Text(frame1, width=40, height=10, wrap=WORD, yscroll...
7ad6724f77281ad77e9dac7c1bbaf07becc6b509
thewinterKnight/Python
/dsa/miscellaneous/rearrange_array_alternately.py
1,731
3.96875
4
import queue def Partition(arr, start_indx, end_indx): initial_pivot_indx = end_indx pivot = arr[initial_pivot_indx] partition_indx = start_indx for i in range(start_indx, end_indx): if arr[i] < pivot: Swap(arr, i, partition_indx) partition_indx += 1 Swap(arr, partition_indx, initial_pivot_indx) retur...
0039b42d43ff497a518a7be5be155d70e74cd8e6
Willianan/Interview_Book
/剑指offer/51_构建乘积数组.py
925
3.875
4
# -*- coding:utf-8 -*- """ @Author:Charles Van @E-mail: williananjhon@hotmail.com @Time:2019-08-28 20:40 @Project:InterView_Book @Filename:51_构建乘积数组.py @description: 题目描述 给定一个数组A[0,1,...,n-1],请构建一个数组B[0,1,...,n-1], 其中B中的元素B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1]。 不能使用除法。 """ class Solution: def multiply(self, ...
66ce0b02b7deba4d4dd1c4d2b131b5ec681ed424
sravanrekandar/akademize-pylearn
/w01D02/07.py
259
4.09375
4
"""07. REadability in string formation """ """String Concatenation.""" name = "Sravan" location = "Bengaluru" print(name + " lives in " + location) age = 80 # print(name + " is an " + str(age) + " year oldman.") print(f"{name} is an {age} year oldman.")
cfbd585d723627bec4ae84feb102ad5811821e45
CharmingCheol/python-algorithm
/백준/그래프/1976(여행 가자-Union Find).py
891
3.8125
4
import sys def getParent(x): if cities[x] == x: return x cities[x] = getParent(cities[x]) return cities[x] def unionParent(a, b): a = getParent(a) b = getParent(b) if a < b: cities[b] = a else: cities[a] = b def findParent(a, b): a = getParent(a) b = getParent(b...
98e1572726615c69acdd7617ccbf7020061c6346
brett-ford/calendar
/leap.py
717
4.34375
4
#Determines if a year is a leap year. Leap year = true, common year = False. #if (year is not exactly divisible by 4) then (it is a common year) #else if (year is not exactly divisible by 100) then (it is a leap year) #else if (year is not exactly divisible by 400) then (it is a common year) #else (it is a leap year) d...
0271bd9ada84f26c3ad0a2f52fa85f1020989778
tchapman1140/Python_box
/Python_box.py
418
4.25
4
#displaying a box. Input the size of box #variables length = int() width = int() stars = str() #ask user for length and width length = int(input("Enter the length: ")) width = int(input("Enter the width: ")) stars = "*" + ((width - 2) * " ") + "*" #loop to draw the box for counter in range (0, length): if cou...
b6f872cae4051ac9f0cecb1da3b5999728750968
cfsoft-net/deepl-translate
/tests/test_sentence_split.py
430
3.5
4
from deepl.api import split_into_sentences def test_split_into_sentences(): text = "This is a text. This text has words. The end? The end! I'm not sure... who knows." expected_sentences = [ "This is a text.", "This text has words.", "The end?", "The end!", "I'm not sure...
f9b93808e878fa734ed0356be11579d44cbecb74
rishiraja76/Data-Science
/Data Analysis/Purchases/main.py
1,605
3.875
4
#importing package import pandas as pd #reading the file ecom=pd.read_csv("Ecommerce Purchases") #printing the first 5 entries from the file print(ecom.head()) #printing the information about the file print(ecom.info(())) #printing the average of the purchase price column print(ecom["Purchase Price"]....
f0410c7886b64673c02ad83fa1425a746c77cb8c
jesoleil/PythonExamples
/sayi_tahmin_oyunu.py
824
3.71875
4
import time import random print("Sayı Tahmin Oyununa Hoş Geldiniz..\n 1 ile 40 arasında bir sayı tuttuk, 7 tahmin hakkınız var..") rastgele_sayi=random.randint(1,40) tahmin_hakki=7 while True: tahmin=int(input("Tahmininiz: ")) if(tahmin<rastgele_sayi): print("Bekleniyor..") time.sle...
c4c73fab3c9bc59985da5ca5762d65e4e3001b8a
benbendaisy/CommunicationCodes
/python_module/examples/416_Partition_Equal_Subset_Sum.py
1,713
4.03125
4
from functools import lru_cache from typing import List class Solution: """ Given a non-empty array nums containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal. Example 1: Input: nums = [1,5,11,5] ...
1ee5845c2bd394dde6754c923cd1c8c646ae6a96
eliomardev/Python
/# Calcula Volume da Esfera.py
289
3.828125
4
# Calcula Volume da Esfera import math print("\n******** Calcula Volume da Esfera *******") #irá imprimir na tela a mensagem de boas vindas n1=float(input('Qual o raio da esfera? ')) ve=(4 * math.pi*(n1**3)/3) print('O raio da esfera e {} e o Volume da Esfera é {}'. format(n1, ve))
d4a7240b69add9bb8345e3945a9c661c7e5de34d
santileortiz/cutility
/scripts.py
1,722
3.578125
4
class file_scanner: def __init__(self, string): self.string = string self.pos = 0 self.len = len(self.string) self.is_eof = False def advance_char(self): if self.pos < self.len: self.pos += 1 if self.pos == self.len: self.is_eof = True ...
a7e35cf87f3c5b2e4832a7eef4c3d8ffee482908
alexey-ernest/algorithms
/sortings.py
2,924
4.53125
5
""" sortings.py: standard sorting algorithms (python 2.7). """ def sort_selection(items): """Sorts an array in place using Selection Sort algorithm. Uses ~n**2/2 compares and n (linear!) exchanges to sort collection of length n. Args: items: array to sort. """ if not items: retur...
18c748ecd481ffb673eaf402eda8516cb7ea2de8
Courtesy-Xs/LeetCodePy
/Q48.py
2,250
3.75
4
from typing import List """ "@ClassName:作于9.18生病 "@Description:TODO """ class Solution: def rotate(self, matrix: List[List[int]]) -> None: #solution1: 作于生病,累死了 # """ # Do not return anything, modify matrix in-place instead. # """ # n = len(matrix) # if n...
9dd6b7517c42deca56166e7da41dd486b63c62ff
mandmyay1/ard-public
/Quiz1/ProblemSet5/ps5.py
11,972
3.96875
4
# 6.00.2x Problem Set 5 # Graph optimization # Finding shortest paths through MIT buildings # import string # This imports everything from `graph.py` as if it was defined in this file! from graph import * # # Problem 2: Building up the Campus Map # # Before you write any code, write a couple of sentences here # des...
950e32640a2829981aa05476a506b9999d660074
Jestefano/ApproximatingRoots
/programa - bachillerato/fractionFinal.py
1,986
3.703125
4
## Clase fraccion: class fraction(): def __init__(self,numerator,denominator=1): assert str(type(numerator))=="<class 'int'>", 'Numerator is not integer' assert str(type(denominator))=="<class 'int'>", 'Denominator is not integer' assert denominator!=0, 'Denominator is zero' se...
03b207e033fbec0a2a381fee61ff160d5ca86b09
skeltonjakob/Python-projects
/PythonGame/exceptions.py
318
4.125
4
name = input("Enter your Name: ") age = input("Please enter your age: ") try: print("Hello {}! You were born in {}".format(name, 2020 - int(age))) except ValueError: print('Unable to calcute the year you were born' \ +'"{}" is not a number'.format(age))
d2076c88d25ca55c55c1f069a3e6ee5e780506f7
khalifardy/tantangan-python
/listmanipulasi.py
803
3.953125
4
#Pertanyaan : buatlah sebuah program dengan input sebuah string dengan spasi menghasilkan output yang berurutan #dan tak ada kata yang sama, contoh siapa yang tahu tentang siapa aku akan menghasilkan output : aku siapa tahu tentang yang #cara 1 : x = input("masukan kalimat: ") z = x.split() string = "" hasil = list(...