blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
45338e7d7f344ba0db5682805003fc2fc31bd352
bmoretz/Python-Playground
/src/DoingMathInPython/ch_03/measures_of_center.py
1,310
3.734375
4
from collections import Counter def calculate_mean( numbers ): s = sum( numbers ) N = len( numbers ) # mean mean = s / N return mean def calculate_median( numbers ): numbers = sorted( numbers ) N = len( numbers ) if N % 2 == 0: m1 = numbers[ int( N / 2 ) - 1 ] m2 = numbers[ int( N / 2 ) - 1 ] medi...
6f5afcf047f52551f6d307fb1d8dbf84d9b6b46e
varalakshmisarathi/guvi
/factorial.py
206
4.09375
4
#find factorial of a number def factorial(): #get input from user n=int(input()) factorial=1 for i in range(1,n+1): factorial=factorial*i return factorial res=factorial() print(res)
0def79c313df1e5a8029711fec969f15ad76b2df
DataMechanic/scripts
/fld/Variance.py
302
3.546875
4
import numpy as np import statistics as stc arr = [1,2,3,4,2,3,4,5,4,2,4,5,6,7,8,2,4] print('variance: ' + str(stc.variance(arr))) #### s = 0 for i in arr: s += i avg = s/len(arr) v = 0 for j in arr: v += (j - avg)**2 vrc = v / (len(arr) - 1) print('variance: ' + str(vrc))
5f3fa222ddef62242fb8a8a26595a0ee0a5433cc
lucasolifreitas/ExerciciosPython
/secao4/exerc8.py
139
3.59375
4
temp_kel = float(input('Digite a temperatura em Kelvin: ')) tem_cel = (temp_kel - 273.15) print(f'A temperatura em Celsius é: {tem_cel}')
c72b348130ff2a3cf2108d86edcd04ad3e7e837b
ego6ua/pp1
/10-SoftwareTesting/test_sum_numbers.py
1,259
3.8125
4
import unittest from sum_numbers import sum_even class TestSumEven(unittest.TestCase): def test_sum_even(self): # Testuj sumę liczb naturalnych parzystych # z dowolnego przedziału m,n m = 1 n = 5 result = sum_even(m,n) self.assertEqual(result, 6) def test_sum...
6339c3fea5cbc67e44327ef3ae81ca9881c8dd64
rgdevops123/notes
/python/scripts/sort/srt2_selection_sort.py
1,445
4.28125
4
#!/bin/python3.6 def selection_sort(seq): """ The algorithm divides the input list into two parts: the sublist of items already sorted, which is built up from left to right at the front (left) of the list, and the sublist of items remaining to be sorted that occupy the rest of the list. Initiall...
0fa72765854e8484a251eb78b5739ae602139c37
lecongtuanminh/test_wis
/Bài 3/Bài 3.py
395
3.703125
4
#!/usr/bin/env python # coding: utf-8 # In[4]: import math num = int(input("Nhập số: ")) if num > 1: for i in range(2,(math.floor(math.sqrt(num))+1)): if (num % i) == 0: print(num,"không phải là số nguyên tố") break else: print(num,"là số nguyên tốr") else: print(nu...
0714763146600dcbb22e444432e2506b9dd7b478
sam016/artkoL
/Tasks/Reverse Hash/ReverseHash.py
547
4.15625
4
import math # Reverse hash # Reverts your hash back into a string letters = "acdegilmnoprstuw" def string_from_hash(hash): h = int(hash) result = "" indices = [] while h > 7: ind = (h % 37) indices.append(ind) h = int(h / 37) # int used to convert float values to i...
6eb37e5b503b7673a591218ae38c63a33f2c1a2e
chaitraliv/Assignments
/P17.py
858
3.921875
4
#P17 (*) Split a list into two parts; the length of the first part is given. mylist = ['a', 'b', 'c', 'd', 'e', 'f', 'g','h','i','j','k'] num= int(input("enter number to slice = ")) first,second = [],[] count, length = 0, 0 for item in mylist: #CALCULATE LENGTH OF LIST length +=1 if num <= length: ...
fa0c2e4b2cc6558b624b4bf4b9fd334fbe875bab
floydchenchen/leetcode
/977-squares-of-a-sorted-array.py
774
3.75
4
# 977. Squares of a Sorted Array # Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order. # Example 1: # Input: [-4,-1,0,3,10] # Output: [0,1,9,16,100] # Example 2: # Input: [-7,-3,2,3,11] # Output: [4,9,9,49,121] class So...
42eb9f63d7a8ae4ada691d670f108c5cc51fef5b
MyNameIsBond/exercises_2nd_year
/week_1/advanced_2.py
1,493
4.0625
4
""" A lorry can carry at most {n} kilograms. The name of the materials, the amount of material in kilograms and the material price per kilo are known. Compute a load composition in such a way that the value (price) of the load is maximum. input: N = 10 Copper 7 kg 65 Plastic 15 kg ...
b9182ebf5f9400c1ad144adfebd8775682b4ee85
NazimAliev/public
/python-apps/ab2d.py
1,813
4.125
4
#!/usr/bin/python3 # Copyright (c) by Nazim Aliev # All rights reserved. # nazim.ru@gmail.com """ A simple example of an animated plot """ import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation # генерация цели # координаты x, y в последовательные моменты времени t def xGen(N): ...
b7957c63797d2c66efb41cca5bb4600f3a1ce00d
GhostyPants/calculadoraDeCostos
/main.py
2,628
3.875
4
from clases.Receta import Receta from clases.Ingrediente import Ingrediente from typing import Dict, List import os Recetario: Dict[str, Receta] = {} # precio del articulo / peso del articulo * la cantidad que desea usar def clearConsole(): os.system("cls") def menuPrincipal(): print( """ ====...
badcfaf14a68b32983842030d3774c5fe3e424fa
type812/practice
/subStringinString.py
192
3.65625
4
from re import search def check_substring(str, sub): #using regex if search(sub,str): print('Found') else: print('not found') check_substring('stackabuse','tack')
bb67be5488827396c0c98e55542504121f75fa9a
Liamohainnin/pands-problems
/ineedtiles.py
334
4.0625
4
# This Program caluclates howmany tiles you will need # When tiling a wall or floor in metres squared length = float(input ("Enter Room Length: ")) width = float(input ("Enter Room Width: ")) #length = 4.3 #1width = 2.2 Area = length * width needed = Area * 1.05 print ("You need ", needed ,"Tiles in metres s...
1d3cffc9e1a83119867142f5da49bce6f1ed0fa7
Shivansh2407/hackerrank_python
/Regex_and_Parsing/validating-uid.py
630
3.640625
4
""" https://www.hackerrank.com/challenges/validating-uid Language: Python 3 Sample Input 2 B1CD102354 B1CDEF2354 Sample Output Invalid Valid """ import re check_10chars = lambda s: bool(re.fullmatch(r'[a-zA-Z0-9]{10}', s)) check_2upper = lambda s: bool(re.search(r'[A-Z]\w*[A-Z]', s)) check_3dgt = lambda s: bool(re...
85ab41c1b1e4a7b86634e1374b75bae836fd795c
daniel-reich/ubiquitous-fiesta
/9Kuah39g997SvZmex_6.py
145
3.78125
4
def common_last_vowel(txt): vowels = "aeiouAEIOU" for i in range(len(txt)-1,0,-1): if txt[i] in vowels: return txt[i].lower()
71d061608905754b8991255224b9e29a4bac65a5
stacygo/2021-01_UCD-SCinDAE-EXS
/07_Exploratory-Data-Analysis-in-Python/07_ex_4-05.py
447
3.921875
4
# Exercise 4-05: Plot income and education import pandas as pd import matplotlib.pyplot as plt gss = pd.read_hdf('input/gss.hdf5', 'gss') # Group by educ grouped = gss.groupby('educ') # Compute mean income in each group mean_income_by_educ = grouped['realinc'].mean() # Plot mean income as a scatter plot plt.plot(m...
a2849a572f1262022cbc92e7082eab677a1df1b2
hobsond/codeChallenges
/addTwoNumbers.py
1,242
3.796875
4
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next pList1 = ListNode(3,ListNode(1,ListNode(2))) pList2 = ListNode(6,ListNode(3,ListNode(4))) class Solution: def getValues(self,nlist): current = nlist ...
d8915e028bab365f09e6de68c010014ec5b81351
YiqunPeng/leetcode_pro
/solutions/398_random_pick_index.py
405
3.5625
4
class Solution: def __init__(self, nums: List[int]): """Hash table. Running time: O(n) where n is the length of nums. """ self.index = collections.defaultdict(list) for i, num in enumerate(nums): self.index[num].append(i) def pick(self, target: int) -> int: ...
a5995223f122dcaf81862b52be33e8c9c0bcde51
Lesi-N/Sorting_alg_comparison
/generate_list.py
1,770
4.40625
4
""" Module that generates different types of lists for the experiments: 1. random lists 2. and ascending and a descending list 3. lists with a random amount of repeated elements The last function generates the necessary amount of each of these for a given size """ import random def generate_random(power): """ ...
37fad5ff3dc5f8f879cf1a04ba35fc198f241488
Ahmetyilmazz/Python
/Print calismalari.py
231
3.859375
4
# Calisma Programı.7_Calisma # Programmer : Ahmet YILMAZ counter = 100 miles = 1000.0 name = "John" print (counter) print (miles) print (name) a = input("Bir kelime gir ulen : ") print("Girdiginiz isim : "+a)
c976f03415a65b4c65404fa65956c586861d4997
cg219/learning-python
/blackjack/card.py
548
3.859375
4
class Card: def __init__(self, value=1, suit="hearts"): self.value = value self.suit = suit def __str__(self): cardNumber = "" suit = self.suit.capitalize() if self.value == 1: cardNumber = "Ace" elif self.value == 11: cardNumber = "Jack"...
16d81ec6bf8df989ba168e6ef51fa0df23ce01be
j2k2020/basic_git
/python/sec08/05_local_global_variable.py
1,428
3.515625
4
""" 지역변수: 함수 내부에서 정의된 변수 - 함수 내에서만 사용 가능 - 함수 호출 시 생성되고 함수가 종료되면 소멸(더 이상 사용 불가능) - 함수의 매개변수도 함수 내에서만 사용할 수 있는 지역변수 """ def show(): a = 1 #show() 함수 내에서 정의된 지역변수: 함수 내에서만 사용 가능 print(a) show() # print (a) #함수 외부에서 사용 불가 def show2(b): #매개변수 b도 함수 내에서만 사용가능한 지역변수 b = b +1 print(b) show2(10) # print(b...
2cd08cb1c311c73fc07362678609f44962e016d2
Rifleman354/Python
/Python Crash Course/Chapter 5 Exercises/addedUser.py
306
4.03125
4
Usernames = ['admin'] # This is the user list of the program if Usernames: for Call_Username in Usernames: # A loop that allows new users to be inputted print('Adding ' + Call_Username + '.') # as long as the program runs else: print('We need users!') # If there are no users, this is the output
a0436d037c77fd3285229878db537b7d4f29527c
awenits/CS50-Introduction-to-Computer-Science
/pset6/greedy.py
806
3.890625
4
import cs50 def main(): noofcoins = 0; change = get_valid_change() change = change * 100 change = round(change) while change != 0 : cent = largest_cent(change) noofcoins = noofcoins + (change // cent) change = change % cent print(noofcoins) #returns valid...
01dad37d75c2827db0d02f909e600f318a74b681
JiangLabUCI/TwoCompartment
/staph/utils/roulette.py
1,327
3.96875
4
import numpy as np from typing import List from numba import njit @njit(cache=False) def roulette(prop_array: List[float]) -> int: """Perform roulette selection. For a given array, perform roulette selection and return the selected index. Parameters ---------- prop_array Array of propens...
e0656ca42ec69f732e4efbb1b744ce22c0fc7198
antilectual/CodingPractice
/LeetCode/1302. Deepest Leaves Sum (medium).py
1,580
3.65625
4
# LeetCode problem 1302. Deepest Leaves Sum (medium) # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # Algorithm: Traverses tree to find depth. Re-traverses tree and sums nodes that are at the tree depth....
659190dd5f25bb9c90b08c16d9bca345f24be7f5
ankitgadge15/PythonCodes
/reverse.py
146
3.640625
4
# Sentence Reversal and removing the leading and trailing white spaces in sentence. def rev_sentence(s): return " ".join(reversed(s.split()))
fc16e0540405505a58bf2d3aa7551d8cd67c9560
Hank-Liao-Yu-Chih/document
/OpenCV讀者資源/讀者資源/程式實例/ch25/ch25_11_1.py
147
3.609375
4
# ch25_11_1.py import numpy as np data = np.arange(3) print(f"data = \n {data}") x = np.repeat(data, 3) print(f"After repeat = \n{x}")
dcb1795ed9ec36d72aefc8f3403707fc8598fae5
sundarrajansr/cuddly_journey
/python/sorting/quicksort.py
478
3.65625
4
def quick_sort(nums, lo, hi): if lo < hi: q = partition(nums, lo, hi) quick_sort(nums, lo, q - 1) quick_sort(nums, q + 1, hi) def partition(nums, lo, hi): pivot = nums[hi] i = lo-1 for k in range(lo, hi): if nums[k] < pivot: i += 1 nums[k], nums[...
66ab60ae7d9bcea3339c1df777ea5b29e79b4215
EldanGS/patterns
/src/structural_patterns/facade/facade.py
1,156
3.8125
4
""" intent Facade is a structural design pattern that provides a simplified interface to a library, a framework, or any other complex set of classes. """ class CPU: """Complex system parts""" def __init__(self): pass def freeze(self): pass def jump(self): pass def execu...
3df181dec7adce1dfe3a1c3a3a0485a3ef25e30e
ZdrytchX/QuestionAdminCSP1150
/quizle.py
7,050
3.75
4
# ZdrytchX # Import the required modules. import tkinter import tkinter.messagebox import json import random def inputSomething(prompt):#XXX while True: entry = input(prompt)#multiple entries not allowed for input function? try: stringput = entry.strip().upper() #remove whitespace at ...
3b81b89a7902fa3615b80bbdf82ff57b16deae9a
edche/fheaps
/ds/fibonacci_heap.py
4,505
3.6875
4
from heap import Heap, Node import random import math class FibonacciHeapNode(Node): def __init__(self, value): self.value = value self.rank = 0 self.parent = None self.children = [] self.mark = False class FibonacciHeap(Heap): def __init__(self): self.min = None self.n = 0 self.ro...
e71a21c411c0a8e30f8f1109a5983c113f6372b6
kelliemogg/holbertonschool-higher_level_programming
/0x0B-python-input_output/2-append_write.py
194
3.96875
4
#!/usr/bin/python3 """ module """ def append_write(filename="", text=""): """ appends a string to a text file and returns num of chars written """ characters = 0 return characters
611c07aaa44c9dced59a9af11a68a78572dff077
partho-maple/coding-interview-gym
/algoexpert.io/python/Remove_Kth_Node_From_End.py
498
3.578125
4
# https://www.algoexpert.io/questions/Remove%20Kth%20Node%20From%20End # O(n) time | O(1) space def remove_kth_node_from_end(head, k): counter = 1 first = head second = head while counter <= k: second = second.next counter += 1 if second is None: head.value = head.next.valu...
c6b1af018f17b1f03caee1fc80664b5ae025f547
nayneshrathod/imrjalgoan
/Amol Pc Programs/Rough program.py
152
3.890625
4
n=int(input("How many element you want to read ")) lst=[] for i in range(n): lst.append(input()) print(lst) lst=list(dict.fromkeys(lst)) print(lst)
a4175dd181aca4891b103101aa6fea73145f6272
RiddhiRex/Practice_code
/CodeCommentsRemoval.py
1,260
3.859375
4
sample input: public class HelloWorld { // This program will print "Hello, World" public static void main(String[] args) { System.out.println("Hello/*, World*/"); // A single line comment /* A sample comment spanning multiple lines*/ /*} } Sample Output: public class He...
d6cd426ce3ef7ae5f41684f2ff30a778673f8301
AlexandreLamure/TchoupiTeam
/class_ride.py
1,584
3.65625
4
# -*- coding: utf-8 -*- """ Created on Thu Mar 1 19:12:48 2018 @author: César """ from math import * class Ride: def __init__(self, x0, y0, x1, y1, e, l, index): self.x0_ = x0 self.y0_ = y0 self.x1_ = x1 self.y1_ = y1 self.early = e self.last = l self.inde...
24ae5ce28ebfe4278d477279720cfd4dd0664715
kannanisaboss0/C-97
/Python_Programs/txt/Text.txt/FileOpener.py
212
3.65625
4
file_name=input("File name:") f=open(file_name,'r') count=0 for i in f: try: e=i.split() count=count+len(e) print(e) except: print(error) print(count)
5c2ade89c67536be8d96613ec233c330a4d477c2
ojhaanshu87/data_structures
/String_Archive/lexiographic_order.py
427
4.09375
4
# Source http://www.geeksforgeeks.org/lexicographic-rank-of-a-string/ def factorial(num): if(num<=1): return 1 return (num*factorial(num-1)) def lexiographic_order(string): order=0 to_list=list(string) to_list.sort() for i in range(0,len(string)): for j in range(0,len(to_list)): if string[i]==to_list[j]...
b88ce8fea4707d8edba3162d55967c67ce0143f4
pengweis/shortest_path
/src/heap.py
6,648
4
4
from math import ceil import heapq class Heap: def __init__(self, arr=None): self.heap = [] self.heap_size = 0 if arr is not None: self.heapify(arr) self.heap = arr self.heap_size = len(arr) def heapify(self, arr): """ Convert a given...
fd9b4fd412b376e24fd59329ee47cf658ace4883
keneskhanovm/Web
/week8/3_c.py
123
3.640625
4
import math a = int(input()) b = int(input()) d = math.ceil(math.sqrt(a)) while d**2 <= b: print(d**2) d += 1
67ced69fe026e1b1b2fdb95784f353a87d105584
carloscacua/leetcode-challanges
/Problems/DataStructure/BinrayTree/hasPathSum.py
728
4
4
from treenode import TreeNode # Path Sum # Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all # the values along the path equals the given sum. # iterative solution def hasPathSum(root, sum): """ :type root: TreeNode :rtype: List[int] """ if root is...
2c989eb846bd9586373d090e8aaee9f5f2533343
diazadha/Prak-ALPROG
/Lab 8/5.py
935
3.828125
4
def mergesort(list1): print ("Splitting ", list1) if (len(list1)>1): tengah = int(len(list1)/2) bagiankiri = list1[:tengah] bagiankanan = list1[tengah:] mergesort(bagiankiri) mergesort(bagiankanan) i=0 i2=0 i3=0 while...
ca3e08b5ad0e4d85a7c9758832fe23148b3b383d
momotazmahinkhan/python-challenge
/Solved-Submission/main_final_pybank.py
2,261
3.75
4
import os import csv csvpath = os.path.join('..', 'Resources', 'budget_data.csv') #set variables No_of_month = 0 Total_Profit = 0 Total_Change = 0 last_month_profit = 0 first_month = 0 index = 1 Max = 0 Min = 0 previous_month = 0 #Opens the CSV file with open(csvpath,"r") as budget: csv_reader ...
0d38a31ed787d7dd60d57e2c78bc8c804818bbe1
chinmay-anand/python_spark_tools
/notebooks/streaming/stream_dstream_sparkcontext.py
3,033
3.90625
4
############################################################ ‘’’ Quick Example REF: https://spark.apache.org/docs/latest/streaming-programming-guide.html#a-quick-example We want to count the number of words in text data received from a data server listening on a TCP socket. ‘’’ ######################################...
d54ac170f0485eb57e576d1bb6a1b29b062f0a2e
JASTYN/30dayspyquiz
/exam/hey/NOOFLINES.py
371
3.84375
4
from functools import reduce file = open("PY.txt","r") Counter = 0 Content = file.read() CoList = Content.split("\n") for i in CoList: if i: Counter += 1 print(Counter) def average(num): sum_num = 0 for x in num: sum_num = sum_num + x avg = sum_num / len(num) ret...
5fe47d64d0ce5cae556c33259ed023bfaa177347
aravindbhaskar41/codejam
/clock/plaban_nayak/fuzzy_clock_python.py
3,707
4.03125
4
import time import random def approx(minute,mid): """ returns the string that is to be prefixed to the time and it choosed randomly among the available options""" near = ["nearly ","almost "] exact = ["exactly ","precisely ","now ",""] after = ["after ","about ","around "] if minute...
ed8c925005356fae22b1b5224da17d576356c600
igrapel/Python
/Scraping/numberScrape
486
3.578125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Nov 28 19:01:15 2020 @author: ilan """ #import os import re #for root, dirs, files in os.walk("."): # for filename in files: # print(filename) f = open("text.txt", "r") text = f.read() f.close() print(text) # A sample regular expressio...
042359ee6e20de0d9edd9a157ed4a47f44bbafec
diansheng/directbus-cloud
/calculation/ulti.py
603
3.640625
4
# import numpy as np def find_routes(start_end_points): """ find the acceptable routes based on the start and end points location. both input and output are numpy array :param start_end_points, N by 4 array, each row represents a set of start and end points. in each row, the 4 numbers are start_poi...
ae8db77bda865f8046c42cd8bd9f5b6d2ba63a2a
said-zeid/ITI-COURSE
/pylab/q7.py
253
3.75
4
def myfunc(list1): sumx = 0 for x in list1: sumx = sumx+x return sumx list2 = [1, 2, 3, 4] l = myfunc(list2) print(l) """ list3 = [1, 2, 3] for x in range(0, 3): # list3.append(int(input())) list3[x] = int(input()) """
baf5727872518cd2aa2be842b1044fb0bbd87e2a
connorpheraty/DS-Unit-3-Sprint-2-SQL-and-Databases
/module1-introduction-to-sql/buddymove_holidayiq.py
730
3.71875
4
import sqlite3 import pandas as pd df = pd.read_csv('buddymove_holidayiq.csv') # Convert to SQLite3 conn = sqlite3.connect('buddymove_holidayiq.sqlite3') df.to_sql(name='review', con=conn, if_exists='replace') curs = conn.cursor() # Query Function def query(query): result = curs.execute(query) return result....
31a081bb2aa756975e06915614d49092948f7243
jojonki/atcoder
/abc/abc120d.py
1,514
3.515625
4
from itertools import combinations class UnionFind: def __init__(self, size) -> None: self.parent = [-1] * size self.size = [1] * size def root(self, x: int) -> int: if self.parent[x] == -1: return x else: self.parent[x] = self.root(self.parent[x]) ...
7f53502c72c2f86ad43325de213e4fef1c8f2eb7
Aasthaengg/IBMdataset
/Python_codes/p02265/s161055073.py
497
3.671875
4
# -*- coding:utf-8 -*- import collections n = int(input()) command = [input().split() for i in range(n)] ans = collections.deque() for i in range(n): if command[i][0] == "insert": ans.appendleft(command[i][1]) elif ans == []: continue elif command[i][0] == "delete": try: ...
fdb9b757671b3360f81703ed58113a2b81182ec4
jiangzhengkai/3D-Detection-Code
/lib/core/bbox/region_similarity.py
4,187
3.53125
4
"""Region Similarity Calculators for BoxLists. Region Similarity Calculators compare a pairwise measure of similarity between the boxes in two BoxLists. """ from abc import ABCMeta from abc import abstractmethod from lib.core.bbox import box_np_ops class RegionSimilarityCalculator(object): """Abstract base class fo...
ba6e73c624791e830a77675506040f07944779b2
samueljml/URI-Online-Judge
/Strings/1120/1120.py
254
3.8125
4
while(1): numero, valor = map(str, input().split()) if numero == '0' and valor == '0': break if valor.replace(numero, '') == '': valFinal = 0 else: valFinal = int(valor.replace(numero, '')) print(valFinal)
cec0945352d2b15450cbe8b0409b1d9d8806b92a
ElectricRCAircraftGuy/eRCaGuy_hello_world
/python/socket_udp_send_packed_struct_TODO.py
1,982
3.671875
4
#!/usr/bin/env python3 """ This file is part of eRCaGuy_hello_world: https://github.com/ElectricRCAircraftGuy/eRCaGuy_hello_world 27 Aug. 2022 Practice packing a binary struct and sending it out over an Ethernet UDP socket! - Start by learning how the `struct` modules works in Python, to pack and unpack C-like struc...
1f17c3bc0c968e1488d5a96cbdf792958ed0e7cb
thomas-raynaud/adventofcode
/2018/d1_p2.py
275
3.578125
4
freqs = {0: True} freq = 0 f = open("input_d1", "r") found = False while True: f.seek(0) for l in f: freq += int(l) if freq in freqs: found = True break freqs[freq] = True if found: print freq break
2aea4c59077c7b10c73c44b6888c9fcfd688b5ae
jakehoare/leetcode
/python_1_to_1000/840_Magic_Squares_In_Grid.py
1,940
3.828125
4
_author_ = 'jake' _project_ = 'leetcode' # https://leetcode.com/problems/magic-squares-in-grid/ # A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, # and both diagonals all have the same sum. # Given an grid of integers, how many 3 x 3 "magic square" subgrids are...
bbc1c57dc7ff855ab7c988fa2e0cb3ad45f927ab
thainabsouza/TestepythonCalculadora
/testeCalculadora.py
2,517
4
4
import abc from unittest import TestCase, main class Calculadora (object): def calcular(self, valor1, valor2, operador): operacaoFabrica = OperacaoFabrica() operacao = operacaoFabrica.criar(operador) if(operacao == None): return 0 else: resultado = operacao...
ee0f30dafd9eab9044ddff600cf5ef9f4258c684
v-shchenyatskiy/GB_Python
/8. Lesson_8/les08_2.py
1,004
3.828125
4
# Создайте собственный класс-исключение, обрабатывающий ситуацию деления на нуль. # Проверьте его работу на данных, вводимых пользователем. # При вводе пользователем нуля в качестве делителя # программа должна корректно обработать эту ситуацию и не завершиться с ошибкой. class ZeroDivErr(Exception): def __st...
f980c4ae6a4513ba14c958e0d38b5104ad3f5f6b
GZHOUW/Algorithm
/LeetCode Problems/Tree/Kth Smallest Element in a BST.py
1,238
3.828125
4
''' iven a binary search tree, write a function kthSmallest to find the kth smallest element in it. Note: You may assume k is always valid, 1 ≤ k ≤ BST's total elements. Example 1: Input: root = [3,1,4,null,2], k = 1 3 / \ 1 4 \ 2 Output: 1 Example 2: Input: root = [5,3,6,2,4,null,null,1], k = 3 ...
6846b40cb7cafec2aa66596c85089c70669fa244
sreyaghosh092/JISAssasins
/reverse.py
247
4
4
def reverseWordSentence(Sentence): words=Sentence.split(" ") newWords=[word[::-1] for word in words] newSentence=" ".join(newWords) return newSentence Sentence=input(print(" Enter a sentence ")) print(reverseWordSentence(Sentence))
42dcdb9f3230c6a74ef91fab7289eff8c2d3342b
XMK233/Leetcode-Journey
/code_test-2020/手写堆排序.py
1,863
3.703125
4
## 堆排序有什么功能? 除了排序, 它还可以做诸如, 寻找数组中前/第k大的数字. def heapSort(nums): def bigHeadHeap(nums, i, length): ### 这个函数是仅仅用于调整基本有序的堆. ### 什么是基本有序呢? 比如, (1)大顶堆, (2)堆顶元素挪移. 状态2之后, 新的堆顶那个元素不一定是放在了合适 ### 的位置, 而其他的都放在合适的位置. 这就是所谓基本有序. ### 这个函数要做的, 就是把当前堆顶元素给他调到合适的位置. ### 所以, i就是目前要调的子树所代表的堆的堆顶...
808855e2fce5348c411f85d16307ef2d2e118187
Saurabh323351/PythonPrograms
/number_of_binary_search_tree.py
1,116
4.3125
4
"""Possible Number of Binary Search Tree Program This program is used to generate number of possible binary search tree in given number of test cases Author: Saurabh<singh.saurabh3333@gmail.com> Since: 28 Nov,2018 """ from com.bridgelabz.util.datastructure_util import * from com.bridgelabz.util.utility impo...
c9e01db827687d5077167c1d500642e9c5fe4e4d
ThanhBinhTran/playaround
/csv_lib.py
517
3.625
4
import csv def csv_fwrite(fname, fhead, fdata): if len(fname) == 0: fname = 'out.csv' f = open(fname, 'w', newline='', encoding="utf-8") writer = csv.writer(f, delimiter=",") if len(fhead) != 0: writer.writerow(fhead) for line in fdata: writer.writerow(row) ...
c593035d486de7834812987a0ffddbc5410115bd
linux740305/git-test
/git-test/4-2-1練習白富美.py
786
3.796875
4
#-*- coding:utf-8 -*- EnglishApple = input("請輸入蘋果的英文:") EnglishOne = int(input("請輸入one的數字是:")) EnglishTwo = int(input("請輸入two的數字是:")) EnglishThere = input("請輸入英文數字3的正確答案:") if (EnglishApple=="apple") and (EnglishOne==1) and (EnglishTwo==2) and (EnglishThere=="there"): print("正確答案") elif EnglishApple=="?": print("app...
d1259971da85320de4f9478cf816b892ce7ca125
Shwetasouravtiwari/python-course
/theDouble.py
152
3.671875
4
def doubleChar(doubleit): doubled = [] for letter in doubleit: doubled.append(letter * 2) print("".join(doubled)) doubleChar('the')
f7bf51d910aaf9a7adc502244b3150c1cac0ff2f
murbar/code-challenges
/leetcode/binary-watch.py
1,885
3.90625
4
# https://leetcode.com/problems/binary-watch/ # Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent. # this is basically an array permutation problem # represent bits as minutes # hours 8, 4, 2, 1 minutes, 32, 16 ... # (480, 240...
4638afcfa619c61276682b3ebb2df3cb8a051f56
sunyi1001/leetcode
/jianzhioffer/快速排序.py
948
3.5625
4
# 剑指offer80页 207 class Solution: def fast(self, nums): self.quickSort(nums, 0 ,len(nums)-1) print(nums) def quickSort(self, L, low, high): i = low j = high if i >= j: return key = L[i] while i < j: while i < j and L[j] >= key: # ...
f59c493cdec2563152d05f90962f8effa648f1ac
Hri100v/-
/python/is_prime.py
180
3.796875
4
def is_prime(x): if (x == 1) or (x == 0) or (x < 0): return False; n = 2; while(n <= (x - 1)): if (x % n == 0): return False; n += 1; return True;
ee532228fe090b7fd20a92b15e0b6e7189b6f59e
zhangwei725/PythonBase
/day13/设计模式_单例.py
2,034
3.609375
4
""" 设计模式 优秀的程序员在开发中碰到问题,解决特定问题的一种总结 1 设计原则(后期补充) # 23中设计模式 (淡化) 1>单例模式 2>工厂模式 3>观察者模式 """ """ 什么是单例 作用: 让类在创建对象的时候,在整个系统的生命周期中只有一个实例 # 在开发软件过程中,有些类每个模块都要频繁用到 数据连接(经常回收) (这样的话减少系统创建对象和回收对象负担) 如何创建单例模式 1>使用模块 2> 重新__new__方法 3> 基于装饰器 4> 重写元类 """ """ __new__ 底层创建对象分配内存的方法 在__init__方法之前执行.必须调用有返回值,(调用父类的创建对象) __...
1798d72dd8293d22854a7f465ebd4d75647d413e
Meowsers25/real_Python_Ubuntu
/strings/testy.py
1,300
4.125
4
print("""this is a string that spans multiple lines......""") print('Here is a string across multiple\ lines but printed out on one.') phrase = 'Here is some Py practice' print(len(phrase)) print(phrase[3]) print(phrase[0:5]) # 0 - 5 print(phrase[:5]) # 0 - 5 print(phrase[5:]) # 5 - end print(phrase[:]) ...
f83a7e8bb799be91f7b0e25c279573c3f7d24ced
julianagfarias/python
/quadrado_esfera.py
316
4.03125
4
import math x = float(input("Escolha o valor do lado do quadrado: ")) print("O perimetro de um quadrado de {} é {} ".format(float(x, x * 4))) r = float(input("Escolha o valor do raio de uma esfera: ")) vol = float((4/3) * math.pi * (r ** 3) print("O volume da esfera de raio {} é {}".format(float(r, vol)))
5800fa4cbb7efda4b7b1167d2524c96ab52fc3e4
wellqin/USTC
/DataStructure/链表/翻转.py
3,096
3.734375
4
# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: 翻转 Description : Author : wellqin date: 2019/9/17 Change Activity: 2019/9/17 ------------------------------------------------- """ # -*- coding: utf-8 -*- ''' 链表逆序 ''' class ListNode: def __in...
be65f66aa7bba156d739d633ca793f299e304092
karinamonetti/curso_universidadPython
/ejercicio_clases-laboratorio.py
620
3.78125
4
class Cubo: def __init__ (self,ancho,profundidad,alto): self.ancho=ancho self.alto=alto self.profundidad=profundidad def volumen(self): return self.ancho*self.alto*self.profundidad def tuVolumen(): print("Esta función te devolverá el volúmen de un cubo.") ancho=int(...
394954e763f4eb70234a6796e872fd99a08d79c8
williw3/Hospital
/hospital.py
1,304
3.578125
4
import random def randID(): id = '' for i in range(0,8): id += str(random.randint(0,9)) return id def randBed(max): return random.randint(0,max) class Patient(object): def __init__(self, ident, name, allergies): self.ident = ident self.name = name self.allergies = allergies self.bed = 0 class Hospita...
33b91659e0c6e9e55aee87255ce8acafdece030a
hanihaider1/Stocks
/final_stocks.py
9,137
3.84375
4
import pandas as pd import matplotlib.pyplot as plt class Stocks: ''' Attributes: stocks_ filename: this will have all the data for the stock which we want the data to be presented major_index : This will have the file **(please add info for it i don't know have what will the data have ) Met...
ceb0717311fb7b24f4a1689bc387504dd5e3d1a4
yinruei/ML100Days
/homework/day_01.py
262
3.5
4
import numpy as np # 1. 生成一個等差數列,首數為 0,尾數為 20,公差為 1 的數列。 a = np.arange(0, 21) print(a) # 2. 呈上題,將以上數列取出偶數。 print(a[::2]) # 3. 呈 1 題,將數列取出 3 的倍數。 print(a[3::3])
e1ebc87c29fbf98250dc843a2e0548dd6588e891
Hfixdu2523/NguyenKhoaHaiDuy-C4T8-HW1-2
/session5/BaiTap.py
175
3.953125
4
n = int(input("Please enter year of birth: ")) age = 2018 - n if age > 14: print("You are allowed to watch video") else: print("You are not old enough to watch video")
52affbb554091650cdf2423aa89a8e0a597c8801
angolpow/gbhw
/Python/04/Task1.py
976
3.703125
4
""" 1. Реализовать скрипт, в котором должна быть предусмотрена функция расчета заработной платы сотрудника. В расчете необходимо использовать формулу: (выработка в часах*ставка в час) + премия. Для выполнения расчета для конкретных значений необходимо запускать скрипт с параметрами. """ from sys import argv def salar...
cda424cc0c70ff88fd8df3d8359d1398ae8812d4
Diegoslourenco/CS50x
/pset6/dna/dna.py
2,178
4.03125
4
import csv from sys import argv, exit def main(): if len(argv) != 3: print("type only two arguments in the command line!") exit(1) # Opening csv and txt filetxt = open_text(argv[2]) # Counting the number of columns filecsv = open_csv(argv[1]) numberColumns = len(next(filecsv...
11a1eea4bab3718bf15c4b28854960216ad2791d
yuhaoboris/LearnPythonTheHardWay
/ex_06_strings_and_text.py
1,395
4.09375
4
#coding=utf8 # 习题6:字符串和文本 Strings and Text # format string 格式化字符串 # % 是格式化操作符 # %s 字符串(采用str()的显示) # %r 字符串(采用repr()的显示) # %c 单个字符及ASCII码 # %(name)s 引用字典中的元素,name为字段元素名 # %b 二进制整数 b for binary # %o 八进制整数 o for octonary # %d 十进制整数 d for decimal # %i 十进制整数 # %x 十六进制整数 x for hexadecimal # %e 指数(基底写为e) # %E 指数(基底写为E) # %f...
8ebd5eebc532c0e755d3bd5270933702aab355e7
chrishamblin7/sym_math_nns
/exp1/scripts/symbolic_generation.py
2,492
3.734375
4
'''equation generator ''' import numpy as np import random max_num = 99 decimal = True dec_limit = 3 sym_order = ['?','+','-','*','/','=','(',')','.','0','1','2','3','4','5','6','7','8','9'] sym_num = len(sym_order) def number_generator(max_num=max_num,dec_limit= dec_limit,decimal = decimal): #function returns ...
e9acfb58bcc5cbf60562e4c4209f5a869eb9ecd7
wuxu1019/leetcode_sophia
/medium/tree/test_236_Lowest_Common_Ancestor_of_a_Binary_Tree.py
3,435
3.734375
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p:...
733d2962a3ac5dd2f57823c8509dd47d8eebd030
seun-beta/WeJapa-Data-Science
/Wave 3/CFU_ControlFlow.py
817
4.46875
4
#Question: What type of loop should we use? For Loop #For Loop #You need to write a loop that takes the numbers in a given list named num_list: num_list = [422, 136, 524, 85, 96, 719, 85, 92, 10, 17, 312, 542, 87, 23, 86, 191, 116, 35, 173, 45, 149, 59, 84, 69, 113, 166] #Your code should add up the odd numbers in th...
824a73f363db3350372517b1e4be0f79c92167ae
paulamachadomt/estudos-python-Guanabara
/Python_Guanabara_mundo123/ex026.py
428
4
4
#posição da primeira e última letra A na frase frase = str(input('digite uma frase:')).strip().upper() print('A frase que você digitou tem {} letras.'.format(len(frase))) print("A letra 'A' aparece {} vezes na frase que você digitou.".format(frase.count('A'))) print("A primeira letra 'A' aparece na posição {}.".format(...
58eeb6121715c856bc6893c43ae91f54191f713e
HiPyLiv/HiPyProject
/strings.py
861
4.0625
4
def numerical_to_written_date(date): months = {1: "January", 2: "February", 3: "March", 4: "April", 5: "May", 6: "June", 7: "July", 8: "August", 9: "September", 10: "October", ...
4dcb556a6b7d1107f9ad4634c7f03d4112e0a427
chenlongjiu/python-test
/plus_one.py
567
3.578125
4
''' Given a non-negative number represented as an array of digits, plus one to the number. The digits are stored such that the most significant digit is at the head of the list. ''' class Solution(object): def plusOne(self, digits): if not digits: return [1] carry = 1 for inde...
479f19133ed1193657e2ee969b0ea03abbed9edb
t-ah/adventofcode-2017
/day24/day24.py
1,565
3.546875
4
from collections import defaultdict # add all possible links recursively def add_link(links, last_pin, strength, strengths, length): relev_links = list(links[last_pin]) if len(relev_links) == 0: strengths.append((strength,length)) else: for r_link in relev_links: links[...
fcf4d5f0c45daef0eec4f22b946378d040e58f9e
kacifer/leetcode-python
/problems/problem25.py
2,585
3.9375
4
# https://leetcode.com/problems/reverse-nodes-in-k-group/ # # Given a linked list, reverse the nodes of a linked list k at a time and # return its modified list. # # k is a positive integer and is less than or equal to the length of the # linked list. If the number of nodes is not a multiple of k then left-out # nodes ...
2d1a8b51493cc4347fb9ef8d981e14f34dbe2d98
tonggh220/md_5_nsd_notes
/nsd2009/py02/day03/myclass4.py
1,041
3.6875
4
class Role: def __init__(self, name, weapon, hp=500, mp=300): """被称作构造器方法,实例化时自动调用。 self不是关键字,用任意名称都可以 当创建时例时,用于将属性绑定到实例身上 """ self.name = name self.weapon = weapon self.hp = hp self.mp = mp class Warrior(Role): def __init__(self, name, weapon, qq...
a61792f334120912f668cc03bbc9280a6c8c29b7
nickyfoto/lc
/python/400.nth-digit.py
2,037
3.671875
4
# # @lc app=leetcode id=400 lang=python3 # # [400] Nth Digit # # https://leetcode.com/problems/nth-digit/description/ # # algorithms # Easy (30.22%) # Total Accepted: 47.4K # Total Submissions: 156.4K # Testcase Example: '3' # # Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, # 9, 10, 11...
58b544d96a8a2800489778e001847af500e17454
hvaltchev/UCSC
/python3/code/Lab21_Wrap_Up/raise2.py
276
3.765625
4
#!/usr/bin/env python3 """And, you can re-raise an exception.""" import raise1 def main(): try: number = raise1.GetPositiveNumber("Positive number: ") except ValueError: print("That was wrong!") raise # Raises last exception again main()
31603c0fa420168a57d19670d4e658da90a46fff
l-schuurman/algorithms
/Sieve of Eratosthenes.py
364
3.578125
4
# This is an implementation of the Sieve of Eratosthenes # Determines all prime numbers up to a value n from math import ceil, sqrt n = 1000001 prime = [0] * n def Sieve(): for i in range(2, ceil(sqrt(n))): if (prime[i] == 0): for j in range(i * i, n, i): ...
ccc5ff58a2b5ef8e2add29ca7a58d2996cacfc3b
vivek1395/python-code
/string_start_end.py
523
4.21875
4
s='The sun rises in the east' print(s.startswith('the')) # output is false print(s.startswith('The')) # output is true hence case sensitive print(s.startswith('The sun')) # output is true that means it scan for consecutive words. print(s.startswith('Th')) # output is true means it checks for prefix print(...
a447020ff46c7bd70a1ee23f6ca6668573ed4043
C-CCM-TC1028-111-2113/homework-4-EricCaballeroM
/assignments/06PromedioConDecision/src/exercise.py
286
3.75
4
def main(): #escribe tu código abajo de esta línea #Promedio con Decisión sum=0 div=0 while sum>=0: tot=float(input("ingrese un número: ")) if tot<0: break sum=sum+tot div+=1 prom=sum/div print(prom) pass if __name__=='__main__': main()
1e928dbb46e23beaddecb32151228ce4704896b3
ssamanthamichelle/Sam-Codes-Python
/python02-code.py
1,764
4.40625
4
#Sam Codes """ HEY GUYS, it's me SAM this is the code from Python 02 on my youtube channel... Sam Codes feel free to download and run this! byeeee ;) """ #printing a few lines to make the output look a bit nicer # \n means new line print("\n") print("-------------------------------------") print("Result fr...
c1d7467612378988c35d0aa8f1ce7eb8e599eb4a
klaudiagadek/simple_tasks
/tests/test_simple_tasks.py
1,880
3.5
4
from tasks.simple_tasks import check_if_palindrome, remove_values, move_item, revers_number, reverse_string,\ get_fibonacci, get_dict, zip_strings, get_subsets, prepare_set_int def test_check_if_palindrome(): assert check_if_palindrome([1, 2, 1]) def test_remove_values(): list_a = [1, 2, 3, 4, 5, 6, 7, ...