blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
130cf717ee5f3b2dfdb24a4131ae09b04fd9ae02
DarrenZheng/python3_base
/fifthday/raise_except.py
470
3.828125
4
class ShortException(Exception): def __init__(self, length, atleast): Exception.__init__(self) self.length=length self.atleast=atleast def __str__(self): return "是什么" try: s = input("enter something:") if len(s) < 3: raise ShortException(len(s), 3) except EOFEr...
a77ec46f2cf8c1b7982bf2df970e11e581699731
xchmiao/Leetcode
/Data Structure/Implement Trie.py
1,471
4.0625
4
""" https://leetcode.com/problems/implement-trie-prefix-tree/ """ class TrieNode: def __init__(self): self.children = {} # mapping char to TrieNode, i.e. char: TrieNode() self.is_word = False class Trie: def __init__(self): """ Initialize your data structure here. ...
fc2007a6da1d388c3099b69518e3728d24ae6ca4
eronekogin/leetcode
/2020/robot_bounded_in_circle.py
1,129
3.96875
4
""" https://leetcode.com/problems/robot-bounded-in-circle/ """ class Solution: def isRobotBounded(self, instructions: str) -> bool: """ After one round of all the instructions: 1. If the robot goes back to the original point, it will still be at the original point after...
9f76b757395a2b062f7fcf2072a3f314752af614
SaloniGandhi/leetcode
/876. Middle of the Linked List.py
778
3.828125
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def middleNode(self, head: ListNode) -> ListNode: count=1 if not head: return #compute the len of ll temp=head wh...
147f17d7d8e28d7c2009b8b395f3212140ff4a24
meghanathmacha/Ad-Safe
/contentanalyzer/build/lib.linux-x86_64-2.6/contentanalyzer.py
22,490
3.5625
4
""" Adsafe About the Program : The program has two mode Basic(Gives the result as True or False for a particular class) and Advanced(Gives a rating of 1 to 5 (5 being very bad) How do i use it ? : You can send 3 arguments (<url name>,<html of the url>,<list of the links on the url>) to any of the functions (Basic or...
36a351dac11e166e8618ac602a3e7494029a1e90
ckidckidckid/leetcode
/LeetCodeSolutions/775.global-and-local-inversions.python3.py
2,859
3.625
4
# # [790] Global and Local Inversions # # https://leetcode.com/problems/global-and-local-inversions/description/ # # algorithms # Medium (33.05%) # Total Accepted: 5.8K # Total Submissions: 17.6K # Testcase Example: '[0]' # # We have some permutation A of [0, 1, ..., N - 1], where N is the length of # A. # # The nu...
7af9fce1d6e929f46ac252eee91ed59a53cf63fe
ArunkumarRamanan/CLRS-1
/ProgrammingInterviewQuestions/34_HeapMax.py
6,098
3.875
4
# -*- coding: utf-8 -*- """ Created on Sun Oct 02 21:24:40 2016 @author: Rahul Patni """ # heap sort import random class HeapMin(): def __init__(self): self.array = [None] * 30 self.start = 0 self.end = 0 def insert(self, val): self.array[self.end] = val self...
dd38832fca9b24df5e41102af6cc2417e8cf93fe
jordanvtskier12/Picture
/picture.py
1,860
3.96875
4
""" picture.py Author: Jordan Gottlieb Credit: None Assignment: Picture Use the ggame library to "paint" a graphical picture of something (e.g. a house, a face or landscape). Use at least: 1. Three different Color objects. 2. Ten different Sprite objects. 3. One (or more) RectangleAsset objects. 4. One (or more) Cir...
9cc0e4dac8a70502d3e0e707e62f93a86c96600e
crisrm96/Python-ejercicios1
/while.py
89
3.890625
4
count = 0 while count <=3: print ("I love learning Python!") count = count + 1
cc2b401fd164dbf299a922f2533fbdf510f3796f
RenaldoDaVinci/SwitchNE
/Switch/TestFolders/testnormal.py
966
3.6875
4
import numpy as np Output = np.random.rand(8,8) F = 0 #Tolerance. if set 0.5, it considers any output that has more than 50% of the highest current as "non-distinguishable" threshold = 0.5 #Criteria 1 TransOutput = np.transpose(Output) for a in range(len(Output)): count = 0 tempout = TransOutput[a] maxi = m...
16db71161221cd94621a8eccb856afe745134390
ianlaiky/SITUniPython1002
/Lab4/Task1/SumCalculator.py
349
3.984375
4
import sys a = int(sys.argv[1]) def sum_recursive(x): if x == 0: return x else: return sum_recursive(x-1)+x def sum_iterative(x): out = 0 for i in range(x): out += i+1 return out print "The SUM value calculated by recursive is "+str(sum_recursive(a))+" and by iterative is...
0a66b9c47d91a975af3269b06a2e830d41671010
kyousuke-s/PythonTraining
/day0204/code6_3.py
965
3.84375
4
userinfo = input('名前と血液型をカンマで区切って1行で入力>>') [name,blood]=userinfo.split(',') blood=blood.upper().strip() print('{}さんは{}型なので大吉です'.format(name,blood)) #小数点の桁 print('{:.1f}'.format(2.342)) #リストの中身を指定した文字で連結 l1=['1','2','3'] print('&'.join(l1)) #指定した文字が何回含まれているか str='abacadaeafag' print(str.count('a')) #左側で指定した文字を右側の文字に置...
24f7713059fe1b7d4b6c32b5973a22c69d93cfeb
justinegwudo/Turtle_Projects
/turtle race.py
838
3.859375
4
import turtle import random justin = turtle.Turtle() justin.color("black") justin.pensize(10) justin.shape("turtle") colors = ["red", "blue", "green", "yellow", "black"] def left(): justin.setheading(180) justin.forward(100) def right(): justin.setheading(0) justin.forward(100) def up(): jus...
26f4b411c7906aa7da91e145e8f5f7ac5c089d62
SoumendraM/GeekForGeeksDSA5
/Mathematics/PrimeFactors.py
753
3.796875
4
def PrimeFactors(num): if num == 1: return 1 i = 2 while i*i <= num: while num%i == 0: print(i, end = ' ') num = int(num/i) i += 1 if num > 1: print(num) def PrimeFactorsEff(num): if num == 1: return 1 for i in (2, 3): ...
812d34a3b9c4bc4b927776ce2172071aeb361592
gabrielavirna/python_data_structures_and_algorithms
/my_work/ch5_hashing_and_symbol_tables/hashing.py
2,602
3.71875
4
""" Hashing and Symbol Tables ------------------------- Lists vs Dictionary -> Lists: - items are stored in sequence and accessed by index number - Index numbers work well for computers; They are integers so they are fast and easy to manipulate. However - If we have an address book entry, with index number 56, that n...
51e6c8e600365aef7e1f7a91e7d3af4e5ae4d991
aafonya/Code-Python-Java
/Code/codecool/python basics/100Doors2.py
523
3.734375
4
#Create a list# doors = [] #Fullfill the list# #False - Door is closed# for i in range(0,101): doors.append(False) # j - number of the cycle - e.g. in the 2nd cycle every second door will change# # i - index of the door# for j in range(1,101): for i in range(1,101): if i%j == 0: doors[...
2030a4bc2d4ffa4dff5f954eb4e5f527c9819511
giselachen/Boston-OpenStreetMap-data
/check_file_size.py
870
3.515625
4
import os def convert_bytes(num): """ this function will convert bytes to MB.... GB... etc reference: http://stackoverflow.com/questions/2104080/how-to-check-file-size-in-python """ for x in ['bytes', 'KB', 'MB', 'GB', 'TB']: if num < 1024.0: return "%3.1f %s" % (num, x) ...
3cccbcf4d4a007a7a0512d6ab3f01c9ed5a2e664
macd/rogues
/rogues/matrices/comp.py
1,429
3.9375
4
import numpy as np def comp(a, k=0): """ COMP Comparison matrices. comp(a) is diag(b) - tril(b,-1) - triu(b,1), where b = abs(a). comp(a, 1) is a with each diagonal element replaced by its absolute value, and each off-diagonal element replaced by minus the absolute value of ...
0d350c6c0ff12df5a052f2a865fbe61119f15167
BlerinaAliaj/coding-challenges
/largest_sub_zig_zag.py
1,687
4.15625
4
"""A sequence of integers is called a zigzag sequence if each of its elements is either strictly less than both neighbors or strictly greater than both neighbors. For example, the sequence 4 2 3 1 5 3 is a zigzag, but 7 3 5 5 2 and 3 8 6 4 5 aren't. For a given array of integers return the length of its longest contigu...
96c84ac477f88335f6a640d2eb423191f35625cb
2016JTM2098/jtm162098_7
/ps2.py
795
3.78125
4
#----------------------------------- PROBLEM STATEMENT 2 ------------------------------------------- import random ic=0 oc=0 #----------------------------------- RANDOM NUMBER GENERATOR ----------------------------------------- for i in range(10): (x,y)=(random.random()*2-1, random.random()*2- 1) print x,y if (x...
51f1284ce136e87ebfacef65ca88e9597e166f3a
teddy4445/covid-19-data-science-sample-project
/data_getter.py
2,270
3.578125
4
# library imports import os import json import requests from datetime import datetime # project imports class DataGetter: """ What this class does """ api_domain = "https://api.covid19api.com" def __init__(self): pass @staticmethod def get_all_data() -> dict: """ ...
9868cff52a463c4d7136a48b8439adea34141ae0
smmvalan/Python-Learning
/W3resource_Exc/avg.py
358
3.96875
4
def average (): total = 0 count = 0 while True : inp = float(input('Enter a number: ')) if inp == 'done' : break value = inp total = total + value count = count + 1 avg = total / count print ("Average {}\nCount {}".format(avg,count)) def m...
0bb96f28961e335573bc018f4ac04d2e58b282a5
irajdeep/DSALearnings
/Trie/trie.py
1,399
3.859375
4
class TrieNode: def __init__(self): self.isLeaf = False self.children = [None] * 26 class Trie: def __init__(self): self.root = TrieNode() def insert(self, word: str) -> None: nav = self.root lens = len(word) for pos, ch in enumerate(word): ind...
f0e332383d74471fbcaa58cf7add5ec67eb06d3e
guipw2/python_exercicios
/ex059.py
1,431
4.0625
4
n1 = float(input('Primeiro valor:')) n2 = float(input('Segundo valor:')) opçao = 0 maior = 0 menor = 0 while opçao != 7: print(''' [ 1 ] somar [ 2 ] multiplicar [ 3 ] maior [ 4 ] menor [ 5 ] novos números [ 6 ] elevar o numero [ 7 ] sair do programa''') opçao = int(input('>>>>> Qual é...
7e5f1a8de34fde5f9dbdc8970afe6af6764914f5
OskarJermakowicz/DailyProgrammer
/src/321e/talking_clock.py
1,083
3.90625
4
import time hrs = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve"] mins = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fiveteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty", ...
3446ebd596dbc5a14f98563899e47d7507aae56b
ZJU-PLP/learnPythonHardWay4th
/exercise/exercise40.py
883
4.15625
4
# -*- coding: utf-8 -*- # @Time : 2018/7/4 0004 15:51 # @Author : Lingpeng Peng # @FileName: exercise40.py # @Description: dictionary or dict # @GitHub :https://github.com/ZJU-PLP # @Comment : Tab == 4 spaces cities = {'CA': 'San Fransisco', 'MI': 'Detroit', 'FL': 'Jacksonville'} cities['NY'] = 'New York' citie...
a4b9a52bb30134ef4f9c9a5fecd1abec4387e7fb
tiandiyijian/CTCI-6th-Edition
/08.05.py
457
3.625
4
class Solution: def multiply(self, A: int, B: int) -> int: def mul(small, big): if small == 1: return big s = small >> 1 half = mul(s, big) if small & 1 == 1: return big + half + half else: return hal...
57e0b8bd4f8a897a615a1c4c01effdae679412d8
Sohamthesupercoder/Project-149
/project 149.py
757
3.796875
4
from tkinter import * root = Tk() root.title("Project 148") root.geometry("400x400") import random text_1 = Label(root) text_1.place(relx = 0.5 , rely = 0.5 , anchor = CENTER) def makeword(): alpha = ["A" , "B" , "C" , "D" , "E" , "F" , "G" , "H" , "I" , "J" , "L" , "M" , "N" , "O" , "P" , "Q" , "R" , "S" , "T"...
2ee87a2df272bf9d632163b8106cc0fd3870ddbb
ujn7843/AlgorithmQIUZHAO
/Week_06/select_sort.py
375
3.578125
4
import sys def selectsort(nums): max_ind = 0 n = len(nums) for i in range(n): _max = -sys.maxsize - 1 for j in range(0, n - i): if nums[j] > _max: _max = nums[j] max_ind = j nums[n - i - 1], nums[max_ind] = _max, nums[n - i - 1] a ...
979fbb4974d987c6d9d737927cf9f877f4b23a0e
zzh730/LeetCode
/Tree/Flatten Binary Tree to Linked List.py
1,779
3.9375
4
__author__ = 'drzzh' ''' 中序遍历,先把右树移到左树下,然后把左树翻转到右树 Time:O(n) Space:O(n) ''' class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None tree = TreeNode(1) tree.left = TreeNode(2) tree.right = TreeNode(3) tree.left.right = TreeNode(4) tree.left.right.left = Tr...
afc945a155e7f9f2841c5df77c13dc3d78c875d5
Sergeynonnisnon/test_itunes_search_bio
/src/main.py
4,414
3.53125
4
#!/usr/bin/python # -*- coding: utf-8 -*- """ Part 1 link: https://affiliate.itunes.apple.com/resources/documentation/itunes-store-web-service-search-api/ Using the itunes open API (link above), you need to implement a script that will return all songs (and information about them) that are included in this album by...
8ef6d703a1fd627ad895bd7a03ced8bfa8e6b72b
IvanWoo/coding-interview-questions
/puzzles/rotate_image.py
1,604
4.09375
4
# https://leetcode.com/problems/rotate-image/ """ You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. Example 1: In...
8c2e64b1864f7e184a971893411e9c70444e230d
scaleapi/scaleapi-python-client
/scaleapi/files.py
520
3.515625
4
class File: """File class, containing File information.""" def __init__(self, json, client): self._json = json self.id = json["id"] self.attachment_url = json["attachment_url"] self._client = client def __hash__(self): return hash(self.id) def __str__(self): ...
b89c508f280d0482c0c0741007d3e16a7d615499
cliodhnaharrison/interview-prep
/print_ancestors.py
828
3.890625
4
# Time Complexity: O(n) worst case class Node: def __init__(self, value, left=None, right=None, parent=None): self.value = value self.left = left self.right = right self.parent = parent def get_node(root, value): if not root: raise KeyError("Key {} not found in tree."....
fe754855b074e267a220bdb2d0347157e2a486c1
NicolasKun/PythonLearnTest
/test7.py
323
3.84375
4
n=23 flag=True while flag: guess=int(input('Enter Integer: ')) if guess==n: print 'Congratulations!You find it!' flag=False elif guess<n: print 'No,it is a little Lower' else: print 'No,it is a little Higher' else: print '---This While Is Over---' print 'Done' ...
7e5210896f8933dc610f29454664d6ad2ff26490
turbo00j/python_programming
/exeptopn test.py
294
4.0625
4
try: a=int(input("Enter a integer:")) b=int(input("Enter b integer:")) print("Division:",a/b) #execption causing line or problematic line except: print("Plz enter valid input") print("Addition:",a+b) print("Substraction:",a-b) print("multiplication:",a*b) print("Power:",a**b)
a4847b445aaf00d496a113a4d7789c28e9d75d35
forrest0402/machine_learning
/src/mnist/siamese_train.py
2,401
3.703125
4
# -*- coding: utf-8 -*- """ Siamese implementation using Tensorflow with MNIST example. This siamese network embeds a 28x28 image (a point in 784D) into a point in 2D. By Youngwook Paul Kwon (young at berkeley.edu) https://github.com/ywpkwon/siamese_tf_mnist """ from __future__ import absolute_import from __future__ i...
7b0eb38ff8f31c2b5210994ed1690ccbb9c8494a
666sempron999/Abramyan-tasks-
/Integer(30)/20.py
318
3.59375
4
''' Integer20 ◦ . С начала суток прошло N секунд (N — целое). Найти количество полных часов, прошедших с начала суток. ''' N = int(input("Введите N: ")) hours, minutes = divmod(N,3600) print('Chislo', N) print(hours)
6716f47560158c1c66373fadf4593c1dedc4a4c9
szabgab/slides
/python/examples/dictionary/change_in_loop.py
413
3.578125
4
user = { 'fname': 'Foo', 'lname': 'Bar', } for k in user.keys(): user['email'] = 'foo@bar.com' print(k) print('-----') for k in user: user['birthdate'] = '1991' print(k) # lname # fname # ----- # lname # Traceback (most recent call last): # File "examples/dictionary/change_in_loop.py", lin...
bbf770eca067fe5b6b7c93521f0f06ec2cd67021
kolathee/Poker
/poker.py
3,932
3.984375
4
def numhand(hand): """ (hand) --> list of rank Return ranks of a hand """ rank = ['--23456789TJQKA'.index(r) for r,s in hand] rank.sort(reverse=True) return rank def dokhand(hand): ''' (hand) --> list of suits Return suits of a hand ''' suit=['-CDHS'.index(s)/10.0 for r,s in hand] return suit def is_f...
3736229c0bc804f85f8846d7549871bb5d328fdd
rishitbhojak/python-programs
/Chapter 4/04_tuples.py
234
4.25
4
#Creating a tuple using parenthesis t = (1,2,4,5) # Printing the elements of a tuple print(t[0]) #Note : Tuples cannot be updated #A tuple with a single element is denoted by a single element followed by a comma t1 = (1,) print(t1)
98ea0b22b3288145b167a5db843e2162069ef367
madaniel/json
/json_parser.py
7,454
3.609375
4
import urllib2 import json import os # # # Functions # # # def get_all_values(json_dict, target_key): # Helper function for get_all_values_dict() if isinstance(json_dict, dict): return get_all_values_dict(json_dict, target_key) values_list = [] if isinstance(json_dict, list): for it...
921839ebce2072a8f43876bea821af7395e0d408
kenie/myTest
/100/example_005.py
248
3.703125
4
#!/usr/bin/env python #-*- coding:UTF-8 -*- '''题目:输入三个整数x,y,z,请把这三个数由小到大输出''' L = [] for i in range(3): x = int(raw_input('integer:\n')) L.append(x) L.sort() for j in range(len(L)): print L[j]
a136080c8571186f3de8e448073981257456dfe2
jdf/processing.py
/mode/examples/Topics/Image Processing/LinearImage/LinearImage.pyde
936
3.53125
4
""" Linear Image. Click and drag mouse up and down to control the signal. Press and hold any key to watch the scanning. """ img = loadImage("sea.jpg") direction = 1 signal = 0.0 def setup(): global img img = loadImage("sea.jpg") size(640, 360) stroke(255) img.loadPixels() loadPixels() def d...
44181dcdd51af7ecc64e7858c73a4bbf0b92570b
Ali-Oufi/sca_pi
/python_excercise_2
383
3.96875
4
#!/usr/bin/env python x = raw_input("Enter the first number: ") y = raw_input("Enter the second number: ") if int(x) > int(y): print "The maximum number is ", x print "The minimum number is ", y print "Maximum - minimum = ", int(x)-int(y) else: print "The maximum number is ", y print "The minimum ...
fa22ef0e0b73af8b185ef6bad5bce84454cc7d44
alu0100099010/prct05
/prct05.py~
1,693
4
4
#!/usr/bin/env python # -⁻- coding: UTF-8 -*- import sys argumentos =sys.argv[1:] print argumentos for k in argumentos: if (len(argumentos)==1): n=int(argumentos[k]) else: # 2. O que el usuario, introduzca el intervalo por teclado. print "Introduzca el intervalo (n>0)" n=int(raw_input()) if...
d24d9a5dae888729890f372050f77b16711af213
gschen/sctu-ds-2020
/1906101053-熊赟/0407/笔记2.py
699
3.828125
4
class Queue : #初始化队列 def_init_ (se1f): seIf .que=[] self . size=8#列表的长度 #判断队列是否为空 def is empty(self): if self . sIze==0: return True return False #返回队列的长度 def que_ size(self): return self .size #列表添加元素 def enqueue(s...
26dfa26156fd5eb83724d4de9c31518494d02d0b
karpmage/Job-Application
/MeanFilter.py
1,935
3.65625
4
""" I perform a mean filter on the data using 1 adjacent data point on each side. A median filter would work better for removing outliers, but this data set doesn't seem to have any. I attained the data from: https://machinelearningmastery.com/time-series-datasets-for-machine-learning/ and it is the "Shampoo ...
4c93b651a70ce03e756f992adedea8a3357d3b6b
qkzk/portes_ouvertes
/sudoku/sudoku.py
7,101
4
4
#!/usr/bin/env python # coding=utf-8 ''' solve a sudoku ''' ''' 1 à 9 en ligne 1 à 9 en colonne 1 à 9 ds chaque sous carré 3x3 0 si on ne connait pas la valeur ''' ''' La méthode la plus rapide pour un ordinateur consiste à essayer systématiquement, l’un après l’autre, tous les candidats restants. Appliquée récursivem...
d4ef5b56cffd54a77f784481b9133c8a2394df37
StaticallyTypedRice/recursive-extract
/modules/extract.py
182
3.65625
4
class ExtractionError(Exception): '''The exception that is raised when there is an error when extracting.''' def extract_7z(path:str): '''Extract a file using 7zip. '''
aaca793293e1b90b190ee79f85a3d33304116bb9
sas0112/chapter_10
/storing_data/favorite_number/favorite_number.py
757
4.03125
4
import json def add_favorite_number(): """this function adds the number in the file""" file_name = "favorite_number_list.json" with open(file_name, "a") as file_object: favorite_number = input("please enter your favorite number: ") json.dump(favorite_number, file_object) return favorite_...
6e260f074dcfb414777ef6ec6f28998f7d5526e7
blumek/TicTacToe-Minimax
/TicTacToeAI.py
3,195
3.765625
4
import math from TicTacToe import TicTacToe class TicTacToeAI(TicTacToe): def __init__(self, board=None): super().__init__() if board is not None: self._board = board def move(self, row, col): if self._turn != self._Board.PLAYER_TWO: raise Exception("Currently...
532dd7978b50062a0e4a567fd60a016a01c35168
wagnersistemalima/Mundo-1-Python-Curso-em-Video
/pacote dawload/projetos progamas em Python/desafio007 Média Aritimetica.py
314
3.78125
4
# desafio 007-Média Aritimetica/ desenvolva um progama que leia as duas notas de um aluno, # calcule e mostre a sua média. nota1 = float(input('Primeira nota:')) nota2 = float(input('Segunda nota:')) media = (nota1 + nota2) / 2 print('A media entre a nota {:.1f} e {:.1f} é {:.1f}'.format(nota1, nota2, media))
040983a69eb065b0ca565d797e705a049a18d71e
vatsalnayak895/Rosalind
/rosa1.py
286
4.03125
4
def sqr_hypo(a,b): if a > 1000: print("invalid number") return False elif b > 1000: print("invalid number") return False else: b=a*a+b*b return b a=int(input("enter 1st number:")) b=int(input("enter 2nd number:")) res=(sqr_hypo(a,b)) print(res)
6863ba2157f8eb1147a447308adb59083e5ee6b3
Frankiee/leetcode
/min_heap/703_kth_largest_element_in_a_stream.py
1,644
3.875
4
# https://leetcode.com/problems/kth-largest-element-in-a-stream/ # 703. Kth Largest Element in a Stream # History: # Facebook # 1. # Sep 7, 2019 # 2. # Mar 18, 2020 # 3. # May 4, 2020 # Design a class to find the kth largest element in a stream. Note that it # is the kth largest element in the sorted order, not the k...
91f522ce1e96136174236e3a02c686afd1c470ea
sarthak268/Spring_Mass_Damper-Control_Theory
/signalGenerator.py
1,369
3.71875
4
import numpy as np class signalGenerator: ''' This class inherits the Signal class. It is used to organize 1 or more signals of different types: square_wave, sawtooth_wave, triangle_wave, random_wave. ''' def __init__(self, amplitude=1, frequency=1, y_offset=0): ''' ...
03bc861a5b9405c8ae642849b87216406a001dd2
MarianDanaila/Competitive-Programming
/LeetCode_30days_challenge/2020/December/Remove Duplicates from Sorted Array II.py
734
3.59375
4
# Approach 1 # Time Complexity: O(N^2) where N is length of the array class Solution: def removeDuplicates(self, nums): deleted = 0 n = len(nums) cnt = 1 for i in range(1, n): if nums[i-deleted] == nums[i-deleted-1]: cnt += 1 if cnt > 2: ...
04a91d660d213b0295663574208beb42a22afdf7
seoul-ssafy-class-2-studyclub/GaYoung_SSAFY
/Baekjoon/17070_파이프 옮기기1.py
1,257
3.609375
4
def game(x, y, place): global cnt if (x, y) == (N - 1, N - 1): cnt += 1 return 0 else: if place == 0: if y + 1 < N: if board[x][y + 1] == 0: game(x, y + 1, 0) if x + 1 < N and y + 1 < N: if board[x][y + 1] ==...
04966e3dc0cd843509ffe271aa2def84020f8cdc
Mintakai/python_misc
/regex_training_continued.py
81
3.71875
4
import re word = input("Enter a string: ") print(re.sub(r"-?\d+", "XXX", word))
ad07c5e4d0ee5541beffc37923eeacd5afa5d30c
Alish26/PP2
/TSIS 5/9.py
236
3.625
4
import re def Sol(s): p = 'a.*?b$' if re.search(p, s): return 'Found a match!' else: return('Not matched!') print(Sol("aabbbbd")) print(Sol("aabAbbbc")) print(Sol("accddbbjjjb"))
38d963c6c5ac4810fa84fed1eeccfa7e145b444e
sirken/coding-practice
/codewars/6 kyu/build-tower.py
979
4.21875
4
from Test import Test, Test as test ''' Build Tower Build Tower by the following given argument: number of floors (integer and always greater than 0). Tower block is represented as * for example, a tower of 3 floors looks like below [ ' * ', ' *** ', '*****' ] and a tower of 6 floors looks like below [ '...
e85c3285c04a66fcfcc0527518882c1aef7a8964
holynova-SD/MachineLearningCodes
/GMM/main.py
1,546
3.625
4
from EM import * import numpy as np # Suppose here are two Gaussian distribution, and the variance is known. def init_data(sigma, mu_1, mu_2, n): """ Generate data that is a mixture of two Gaussian distribution. :param sigma: the variance of the Gaussian distribution. Suppose it is same for those two di...
f6485ab6cb845a6d14b081bffce5597820a45eed
php3397/mycode
/python_scripts/deep.py
446
3.734375
4
class person: def __init__(self,name,age): self.name=name self.age=age def display(self): print("name",self.name) print("age",self.age) class student(person): def __init__(self,rollno,name,age,per): self.rollno=rollno person.__init__(self,name,age) self.per=per def display(self): print("rollno per...
de45b30cd191da44a1f5c5edd681ee190ed798f6
babe18/python_six_course
/lesson3/p64.py
311
3.5625
4
from random import randint rnum=randint(1,100) flag=True while(flag): _input=int(input("請猜一個1~99的整數:")) if(_input>rnum): print("比",_input,"小") elif(_input<rnum): print("比",_input,"大") elif(_input==rnum): print("猜對了!") flag=0
c27b2a719a927ca3d7196a123c69d660926ba1d5
akshat-harit/matasano-crypto-challenges
/set1/challenge5.py
685
3.515625
4
#!/usr/bin/env python ''' Functions for repeating-key XOR''' def hex_byte(byte): out = hex(byte) out = out[2:] if len(out) == 1: out = '0' + out return out def hex_text(inp): out = [] for byte in inp: out.append(hex_byte(byte)) return ''.join(out) def encrypt(key, inp): ...
314261fa97f65dbe284cf414cc76996793399fb9
SarahLewk/Python_Challenge
/PyBank/Resources/Main.py
2,572
3.5
4
import os import csv #csvpath = os.path.join('..',"Resources","budget_data.csv") reading_file = os.path.join('..',"Resources","budget_data.csv") output_file = "Analysis/budget_analysis_1.txt" #My list of variables for my output: month_list = 0 prev_profit_loss = 0 month_of_change = [] profit_loss_change_list = [] gr...
ddcccaa656f1a4ea3e6ba50b1fcb2d9bcb631e06
nikcbg/Begin-to-Code-with-Python
/13. Python and Graphical User Interfaces/EG13-07 Drawing program/Drawing.py
1,211
3.96875
4
''' Provides a simple drawing app Hold down the left button to draw Provides some single key commands: R-red G-green B-blue C-clear ''' from tkinter import * class Drawing(object): def display(self): root = Tk() canvas = Canvas(root, width=500, height=500) canvas.grid(row=0, column=0) ...
6414816c533401375ba23d330b845998112aa727
brunocenteno/TensorFlow-Neural_Network
/Neural_Network.py
1,225
3.546875
4
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/", one_hot=True) n_nodes_hl1 = 500 n_nodes_hl2 = 500 n_nodes_hl3 = 500 n_classes = 10 size_batches = 100 x = tf.placeholder('float', [None, 784]) y = tf.placeholder('float') def neural_n...
d5572f9bdfb89c82b1098875a16ac33d9905f2a3
cgroves3/leetcode-practice
/easy/reverse-linked-list/solution.py
340
3.625
4
class Solution(object): def reverseList(self, head): if head == None: return head current = None while head.next != None: temp = head.next head.next = current current = head head = temp head.next = current return h...
0c34a4ef724a5844f4ad999b63478f3866dc3e74
caitaozhan/LeetCode
/stack/22.generate-parentheses.py
1,257
3.5625
4
# # @lc app=leetcode id=22 lang=python3 # # [22] Generate Parentheses # from typing import List # @lc code=start class Solution: def generateParenthesis(self, n: int) -> List[str]: def dfs(stack, path, left_count, n): if len(path) == 2*n: ans.append(path) ...
a06110036a078f90cfe14a2f45ec40cec67a13a2
SLilit/Competitive-programming
/add_two_numbers.py
1,993
3.59375
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: num = head = ListNode(0) l_sum = 0 while l1 or l2: ...
425f08fddbdcedab131083548c7ffafeb24b24a7
bigguozi/ball_game
/velocity.py
3,342
4
4
import math class Velocity(): ''' 该类实现二维速度类 ''' def __init__(self,amp=0,rad=0,angle=0,max_speed=10): # 速度模值 self.amp = amp # 速度角度(如果传入angle不为0则以angle作为角度,单位为度,若为0则以rad为角度,单位为弧度) self.rad = rad if angle == 0 else math.radians(angle) ; self.max_speed = max...
920557063e265c342d717aab8006280a4915274b
redkad/100-Days-Of-Code
/Day 8/Exercises/PaintsCalc.py
230
3.953125
4
import math h = int(input('Enter height of wall: ')) w = int(input('Enter width of wall: ')) def calc(height, width): coverage = math.ceil((height * width) / 5) print(f'You will need {coverage} cans of paint') calc(h,w)
3c705aa273728a63f52475e67fdc9e2e37a661e3
AaronCHH/jb_-Excel-Python-
/_build/jupyter_execute/Ch8.py
2,552
3.921875
4
# Ch08 資料運算 ## 算術運算 import pandas as pd data = {"C1":[1,4],"C2":[2,5],"C3":[3,6]} df = pd.DataFrame(data,index = ["S1","S2"]) df df["C1"] + df["C2"] df["C1"] - df["C2"] df["C1"] * df["C2"] df["C1"] / df["C2"] df["C1"] + 2 df["C1"] - 2 df["C1"] * 2 df["C1"] / 2 ## 比較運算 df df["C1"]...
0c9840afd1456a0932563895a50e80fab74501f1
gwolf/clase-sistop-2017-01
/tareas/03/Gerardmc95/RR.py
2,585
3.6875
4
from collections import deque import random letra = ord('a') b=0 totalEjecucion = 0 casillas = 0 RR = deque([]) lista = [] listaZ = [] #Diccionarios para guardar tiempos y tabla de tiempos tiempoLlegada = {} tiempoDuracion = {} tiempoDuracionDos = {} titulo = ['Proceso', 'Llegada', 'Duracion'] # Agregando elementos...
37f1cfc126f1285231cfc0772dbb97fa20f03edd
kajal1301/python
/rec.py
493
4.3125
4
#recursion in python num1= int(input("Enter a number: ")) #factorial using iterative method def factorial_iterative(n): fac=1 for i in range(n): fac= fac*(i+1) return fac #factorial using recursive method def factorial_rec(n): fac= n if n==1: return 1 else: ...
bd6ac18c8d3385f4d9fb68cd1425a53c8c319c1f
mohab22/Mohab-ashraf
/Bank/main.py
364
3.8125
4
from Banker import Banker from User import User print("Welcome to Our bank\n") while True: user_or_banker = input("please choose are you ...?\n"+" 1 - User\n"+ " 2 - Banker\n"+" 3 - Exit\n") if user_or_banker == "1": User.main_user_function() elif user_or_banker == "2": Banker.main_b...
ec321c0a0628b3d9fa36b78e5c767455197d30ba
Blank1611/guvi_codekata
/vowel_consonant.py
263
3.9375
4
# -*- coding: utf-8 -*- """ Created on Wed Apr 10 19:11:50 2019 @author: GRENTOR """ a = (input().lower()) vowel='aeiou' if a.isalpha(): if a in vowel: print("Vowel",end = "") else: print("Consonant",end = "") else: print("invalid")
f161bdc05402c49cd733d471b8b3e82f84c34c81
akshat-max/Udacity-DSA-programs
/project1/Task1.py
884
4.15625
4
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 1: How many differ...
14c8d36d0632b152511f1e714823794d6b89d333
yesIamHasi/Python
/ArithmeticAnalysis/DiceMonteCarlo.py
675
3.734375
4
# Monte Carlo Simulation of Dice import random def dice(side, rolls): # rolls can't be zero. ''' Returns probability of a side in sample space of dice''' sample_space = [] for i in range(1, rolls): sample_space.append( random.randint(0, rolls) ) return float(sample_space.count(side)*100)/float...
816bea9f13070a69ca9a1a4869c0e03e913771d3
geekcomputers/Python
/create_dir_if_not_there.py
937
3.953125
4
# Script Name : create_dir_if_not_there.py # Author : Craig Richards # Created : 09th January 2012 # Last Modified : 22nd October 2015 # Version : 1.0.1 # Modifications : Added exceptions # : 1.0.1 Tidy up comments and syntax # # Description : Checks to see if a directory exists in ...
713a208d432f91963d0c113d75a70c49b015f1e4
peeush-the-developer/computer-vision-learning
/OpenCV-102/05.opencv-thresholding/thresholding.py
2,585
3.71875
4
# Usage # python thresholding.py -i ../../Data/Input/coins01.png # Import libraries import cv2 import argparse # Add arguments from command line ap = argparse.ArgumentParser() ap.add_argument('-i', '--input', type=str, required=True, help="Input image") args = vars(ap.parse_args()) # Load the image image = cv2.imrea...
5aa096a47e0f47e746e933a13680bd1986ac688d
aline-paille/BuZzleGame
/src/LettersGenerator.py
1,765
3.578125
4
#!/usr/bin/python3.1 from random import * from Variables import * # TODO : variable pour choisir si on prend l'alpha Francais ou anglais VAR_LANGAGE = "Anglais" class LettersGenerator: def __init__(self, language): self.lettersList = self.lettersHexagon(language) def couple_probability(self, file): ...
4f087e372da3769d73c4de12a92d6170a9c132f0
arkch99/CodeBucket
/CSE_Lab_Bucket/IT Workshop-Python/Day 09/prog7.py
83
3.59375
4
f=open("myfile.txt","r") reader=f.readline().split() for r in reader: print(r)
957e297fbd283b8acda6324e6a399b6d8c2c98d1
Alex0Blackwell/python-projects
/decisiveTest.py
1,354
3.96875
4
# Decisive test import time as t def length(time): res = '' if(time < 1): res = f"{time} seconds is extremely fast." elif(time < 3): res = f"{time} seconds is pretty fast." elif(time < 5): res = f"{time} seconds is kind of fast." elif(time < 10): res = f"{time} sec...
4d423683645b1144b37c6f60a1faaee1e29ba430
nataliab9910/Tic-Tac-Toe
/game.py
12,954
3.890625
4
"""Część konsolowa projektu, określa logikę gry.""" import time import random BOARD = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '] HUMAN, COMPUTER, HUMAN_WIN, COMPUTER_WIN = range(4) EMPTY = ' ' NO_WINNER = -1 ERROR = -1 SUCCESS = 'SUCCESS' MAX_WAITING_SEC = 5 WIN_SCORE = 100 LOSE_SCORE = -100 ...
0db98c3e7d35d0b46d522b3d76443e6734c6cb68
GabrielSuzuki/Daily-Interview-Question
/2020-12-30-Interview.py
958
4.125
4
#Hi, here's your problem today. This problem was recently asked by Amazon: #Given a binary tree, return all values given a certain height h. #Here's a starting point: class Node(): def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right def valuesAtHeigh...
13b1e7e7f146f81850f65f4903315ffe7b8cc389
GrahamJamesKeane/CreditCalculator
/Problems/Particles/task.py
597
3.703125
4
spin = input() charge = input() particles = ["Strange", "Charm", "Electron", "Muon", "Photon"] strange = ["Quark", "1/2", "-1/3"] charm = ["Quark", "1/2", "2/3"] electron = ["Lepton", "1/2", "-1"] muon = ["Lepton", "1/2", "0"] photon = ["Boson", "1", "0"] if spin in strange and charge in strange: print("Strange Q...
27d8dd42067af62bf1726ad49554df18232d19e6
vaishakik/College
/Python_Assignments/P5-Cramers_rule.py
1,888
4.1875
4
# -*- coding: utf-8 -*- """ Created on Tue Jan 22 12:46:43 2019 @author: vaishak """ #Cramer's rule import numpy as np print('Enter the number of unknown variables: ') n=int(input()) #define a coefficient matrix of order n*n since we have n unknowns and n equations. coeff_matrix=np.zeros([n,n...
80f25bfb4ca94a4094ad2262484e59292d31eb1f
AlbertLZG/AlbertLZG_Lintcode
/aplusb_1.py
506
3.59375
4
class Solution: """ @param a: The first integer @param b: The second integer @return: The sum of a and b """ def aplusb(self, a, b): # write your code here, try to do it without arithmetic operators. import ctypes a = ctypes.c_int32(a).value b = ctypes.c_int32(b)...
64e51067968e75cfefdeffbcafb484e8983a1864
Gagan-453/Python-Practicals
/GUI/Frame/Spinbox Widget.py
2,366
4.28125
4
# SPINBOX WIDGET # Spinbox widget allows the user to select values from a given set of values # Spinbox appears as a long rectangle attached with arrowheads pointing towards up and down, the user can click on arrowheads to see the next value or previous value from tkinter import * class MySpinbox: # constructor ...
1b668fa6a2be367a61df12818573e9f805c566b0
JUNGSUNWOO/Algorithm_study
/acmicpc/21년 1월/20210124/같은숫자는싫어.py
366
3.859375
4
arr= [3,2,6] divisior = 10 def solution(arr, divisor): answer = [] for i in arr: if i % divisor == 0: answer.append(i) answer.sort() if len(answer) == 0: answer = -1 return answer res = solution(arr, divisior) print(res) ''' def solution(arr, divisor): return sorted([...
4651d633d54cb07a450fa4eaea49af2fa6304bfc
danielfess/Think-Python
/rotate.py
674
4.0625
4
def rotate_word(word,int): """Encrypts (word) using a Caesar cypher, rotating word by the integer (int). """ new_word = '' for letter in word: if 97 <= ord(letter.lower()) <= 122 : new_letter = chr((int + ord(letter.lower())-ord('a'))%26 + ord('a')) else: new...
31b137034e1c74ae3965a0e5d3c893b047c3c1eb
rwardman/advent-of-code
/2020/day3/day3.py
800
3.75
4
data = open("day3.txt", "r").read().splitlines() openSquare = data[0][0] tree = data[0][6] def howManyTrees(right, down): position = right iterator = down trees = 0 openSquares = 0 for rowIterator in range(0, int((len(data))/down) - 1): row = data[iterator] res_row = row * 100 obstacle = res_...
f17520c1c7f59d1ee66d8ea7c2dacc027963c1e0
e-gautier/daily-coding-problem
/8-12_23_2018.py
1,050
4.21875
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ This problem was asked by Google. A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value. Given the root to a binary tree, count the number of unival subtrees. For example, the following tree has 5 unival subtrees...
85b46f689925d816fbb5081ebc5d3db7b6f4d66a
brianboring/Treehouse-Python-Track
/1_2_Basics_Collections/slices.py
465
3.640625
4
def first_4(iterable): word1 = iterable[:4] print(word1) def first_and_last_4(iterable): first4 = iterable[:4] last4 = iterable[-4:] print(first4) print(last4) new_word = first4 + last4 print(new_word) def odds(iterable): word1 = iterable[1::2] print(word1) def reve...
9d7ffd33bd383f11710d2cc3a31109bbd595a2ce
isai-samir/Clase-Archivo
/archivo.py
6,587
3.546875
4
from sys import exit class Archivo: def __init__(self,nombre): try: self.archivo = open(nombre,'r') self.nonbre = nombre self.copia = open("copia.txt",'w') #El nombre de la excepcion es la siguiente except FileNotFoundError: print("No ...
2cb628e21d6e192f2bc50a8276e692fbd2b12dbb
ilante/exercises_python_lpthw
/ex15.py
762
4.03125
4
from sys import argv # uses argv to get a filename script, filename = argv txt = open(filename) #opens file print(f"Here's your file {filename}: ") print(txt.read()) print("Type the filename again: ") fileagain = input("> ") txtagain = open(fileagain) print(txtagain.read()) # What we want to do is "open" that file ...
2687a04cfdb6ca141cdd809e49034532093aa8c5
CrazyCoder4Carrot/leetcode
/algorithm/Python/Missing Number.py
346
3.703125
4
class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ count = len(nums) expectedsum = (0+count)*(count+1)/2 inputsum = sum(nums) return expectedsum - inputsum solution = Solution() nums = [0,1,2,4] print so...
e8b2f0900a0bd5b31fb91c1061452fececa1b6aa
BokiceLee/python_code_in_cookbook
/chapter3/3_08.py
407
4.28125
4
#分数运算 from fractions import Fraction #fractions模块用来执行包含分数的数学计算 a=Fraction(5,4) b=Fraction(7,16) print(a+b) print(a*b) print(a.numerator)#分子 print(a.denominator)#坟墓 print(float(a)) #通过限制分母获得一个被覆盖的分数 print(b.limit_denominator(16)) #小数转化为分数 x=3.75 print(x.as_integer_ratio()) y=Fraction(*x.as_integer_ratio()) print(y)