blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
4b49afd8a77018c0d9179722e524b37979a87c71
yazan-alshekha/caesar_cipher
/caesar_cipher/caesar_cipher.py
1,700
3.78125
4
import nltk nltk.download('words') english_words_list=nltk.corpus.words.words() def encrypt (input,key): # alphabet=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] alphabet='abcdefghijklmnopqrstuvwxyz' alphabet_upper='ABCDEFGHIJKLMNOPQRSTUVWXYZ' ...
a761dad436a049421f7e6fa8b0bf3c478df6b8aa
pavanjavvadi/leet_code_examples
/anagram.py
1,681
4.3125
4
""" Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Example 1: Input: strs = ["eat","tea","tan","ate","nat","b...
66184b286731f60c5496b1d38235de6996c26698
pavanjavvadi/leet_code_examples
/int_to_roman.py
511
3.875
4
def intToRoman(num): """ :type num: int :rtype: str """ roman = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] rep = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'] output = "" i = 0 while num > 0: ...
6a82cb3ca8845b3b2c9837d3d16d91025cffabf1
pavanjavvadi/leet_code_examples
/sorting/inserion_sort.py
369
4.125
4
def insertion_sort(array): for i in range(len(array)): key = array[i] j = i - 1 while j>=0 and key < array[j]: array[j + 1] = array[j] j = j - 1 array[j + 1] = key return array array = [21, 4, 19, 16, 54, 86, 70] array = insertion_sort(array) for i in...
25dbdaeded5aefdd8579a7742b9171933cde98f0
pavanjavvadi/leet_code_examples
/longest_common_prefix.py
615
4.0625
4
from typing import List def common_prefix(words: List[str]) -> str: prefix = words[0] # looping all the words for word in words[1:]: # check first word with other words if words are equal return that prefix while word[:len(prefix)] != prefix: # if word and ...
4fd5cee7933f9d5fe990276d7a502b5f4bb2bc28
bamboosteam/coursera_intro_to_algorithm
/Graph_Search,_Shortest_Paths,_and_Data_Structures/week1/dfs.py
1,403
3.5
4
######################################################## # Data Structures # node labels range from 1 to 875714. 875715 was used because of the range operator... range(875715) goes up to 875714. # num_nodes = 875715 num_nodes = 13 # Adjacency representations of the graph and reverse graph gr = [[] for i in range(num_...
6e6d21cffe4f7d93bfcd6e092942244d6cb70f4c
pawanrajs/code-while-learning
/Machine_Learning/Udacity_Intro_to_ML/outliers/outlier_cleaner.py
801
3.5625
4
#!/usr/bin/python def outlierCleaner(predictions, ages, net_worths): """ Clean away the 10% of points that have the largest residual errors (difference between the prediction and the actual net worth). Return a list of tuples named cleaned_data where each tuple is of the ...
af74ad952b523c0ec9c7ad274479444b7513adc6
rahulgurnani/Real-time-plotting-server
/static_plotter.py
1,654
3.5625
4
import time import numpy as np import matplotlib.pyplot as plt class Plot(object): """object of this class is a plot """ """ title is the title of the window time is the list of time which we will plot limits(low_limit, upper_limit) of y axis ""...
42563ec9342d202bbe8e99f7587a4b17218cb546
DrakeChow3/Stupid-stuff
/Script1/PreFix.py
1,555
3.9375
4
#! python3 #Write a program that finds all files #with a given prefix in a single folder and locates any gaps in the numbering #Have the program rename all the later files to close this gap. import os,shutil,re def FindFile(prefix,folder): #get the absolute path of the folder folder=os.path.abspath(...
957cf67f8a428082556a88c7910f0b2312498f19
DrakeChow3/Stupid-stuff
/Script1/renameDates.py
655
3.828125
4
#! python 3 # a program to loop through each filename in the current working directory and # change to Europe style date import shutil,os.re dateRegex= re.compile(r"""^(.*?) #all text before the date ((0|1)?\d) #all the month from 1 to 12 ((0|1|2|3)?\d) #all the day of the month ((19|20)\d\d) #...
bb832c59ffc495af66deacef27efda8594fe1d72
v1siuol/note
/baaaasic_python.py
7,507
3.640625
4
# 谢谢你 # chap1.5 print("Hello, world", end="") # end=是没有空格的 print() # 行内注释是2#1空格 # chap1.6 # inputstr1_6 = input("等价于先print了但光标悬停(任意输入):") # 返回的是string # inputint1_6 = int(input("这样的显性转型(输入数字谢谢): ")) # chap1.7 # error的介绍 你开心就好 # chap1.11 # 电脑的硬件 一起抓鸡 # chap1.12 # 电脑语言史 根本根本呢 # chap2.2 float2_2 = 10.25 # 初始化 但其...
04d224ceafd31963d5c8b1947bb9c98d1a630f81
Rinatik79/PythonAlgoritms
/Lesson 3/lesson3-5.py
347
4.09375
4
list = [-2, 3, -4400, 5, 6, 7, -8, 9, 0, 2, 3, 4, 5, 5, 6, 6, -777, 7, 7, 7] sorted_list = list.copy() sorted_list.sort() if sorted_list[0] < 0: print("The biggest negative element in list is " + str(sorted_list[0]) + " and his index is " + str(list.index(sorted_list[0]))) else: print("Given list doesn't cont...
66d180a6bfbc522549ac68db6d3b04d940455159
Rinatik79/PythonAlgoritms
/Lesson 1/lesson1-7.py
609
4.21875
4
sides = input("Enter length of every side of triangle, separated by ';' : ") sides = sides.split(";") sides[0] = float(sides[0]) current = sides[0] sides[1] = float(sides[1]) if sides[1] > sides[0]: sides[0] = sides[1] sides[1] = current current = sides[0] sides[2] = float(sides[2]) if sides[2] > sides[0]:...
dae3467b547730be45b23929a6e7ae81318b6766
its2loud/raspy-experiments
/blink_sine.py
473
3.515625
4
from time import sleep from math import * import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) GPIO.setup(18, GPIO.OUT) GPIO.setup(12, GPIO.OUT) GPIO.setup(16, GPIO.OUT) for i in range(0,361): print i xt = sqrt(pow(sin(radians(i)),2)) if i%3 == 0: GPIO.output(12, GPIO.HIGH) if i%3 == 1: GPIO.output(16, GPIO.HIGH)...
832187fc1d4839abe87e730f065bd1e5c9662231
its2loud/raspy-experiments
/rgb_cycle_sine.py
786
3.546875
4
# http://raspi.tv/2013/how-to-use-soft-pwm-in-rpi-gpio-pt-2-led-dimming-and-motor-speed-control from time import sleep from math import * import RPi.GPIO as GPIO def fabsZ(value): if value < 0: return 0 else: return fabs(value) GPIO.setmode(GPIO.BOARD) GPIO.setup(26, GPIO.OUT) GPIO.setup(24, GPIO.O...
2f7ed8b5f76906cc5bad6db528645bf7c077017a
mahamedHassan/Dev-projects
/python/numpyArrayMath.py
810
4.0625
4
# Basic mathmathical function are avialable as operators and # also as function in NumPy. It operates element-wise on an array import numpy as np x = np.array([[1,2],[3,4],[5,6]]) y = np.array([[7,8],[9,10],[11,12]]) # Elementwise sum; both produce the array print("************Addition *****************") print(x +...
45dc47204568a757d85d02e8b1691ec7877dd6f5
ThiagoPoppe/ICV
/TP3/networks/Networks.py
7,486
3.53125
4
import keras from keras import Sequential from keras.layers import Dense, Activation, Flatten from keras.layers import Conv2D, MaxPooling2D # Based on slides class LeNet: """ Implementation of architecture LeNet-5 """ @staticmethod def build(nRows=32, nCols=32, nChannels=3, nClasses=10, opt='s...
c104237c5abd28ba9b024c1e723516d9161fa1df
gagan3512/Python
/SimpleInterestCode.py
207
3.78125
4
p = input('Enter the value of principal') n = input('Enter the number of years') r = input('Enter the rate of interest') p = int(p) n = int(n) r = int(r) simpleInterest = (p*n*r)/100 print(simpleInterest)
2c6f4bd5e376b48da1750e022cf640519eefbdd3
segev19-meet/meet2017y1lab5
/fun2.py
382
3.75
4
###def draw_1d(n, char): ## print(n * char) ## ##for i in range(5): ## print("**********") ## ## ##def draw_2d(n, m, char): ## for i in range(n): ## draw_1d(m,char) ## ##draw_2d(3, 23, "*") def special_draw_2d(n, m, border, fill): print(m*border) for i in range(n-2): p...
fa70543deb5f3e15a93b8d33ed7a5e19c66f43f7
kaikoh95/leetcode-solutions
/solutions/easy/q20-valid-parentheses.py
459
3.734375
4
""" https://leetcode.com/problems/valid-parentheses/ """ def is_valid(s: str) -> bool: hashmap = { ")": "(", "]": "[", "}": "{", } stack = [] for bracket in s: close_bracket = hashmap.get(bracket) if not close_bracket or len(stack) == 0: stack.append...
deb587c44e9c5ee1500f27325119dda48e20375c
binitshah/2018
/Simulation/robotDrive.py
2,479
3.625
4
from gameboard import * #Functions that you are allowed to use and usage: #robotMove(magnitude, direction), magnitude needs to be inches * 10 #direction can be "North", "South", "East", "West" #robotRotate(magnitude, direction), magnitude is the amount of degrees you want to turn #direction can be "cw" for clockwis...
248cb68a87f8eefde45a38470daabfe92aef9ea2
XianJianZhang/MatrixProject
/matrix.py
2,854
3.890625
4
class Matrix(): def __init__(self, row, col, input_num): self.col = col self.row = row self.input_num = input_num self.matrix = Matrix.create_matrix(self) def __str__(self): border = "" for x in range(len(self.matrix)): border += "-" formatted = "" for x in range(len(self.matr...
2e603bb00c162974139ee6f465ae8fbc79ac78b2
AtharvBagade/Python
/Q7.py
204
3.78125
4
fname = input("Enter file name: ") file = open(fname, "r") count = 0 while True: char = file.read(1) if char.isspace(): count += 1 if not char: break print(count)
b5727d4f4b6fa06c45466e481e82fb0991740896
AtharvBagade/Python
/Circle.py
134
4.28125
4
x=float(input("Enter x")) #to get variable from user area_of_Circle=3.142*x*x print("The area of circle is :",area_of_Circle)
fbd7a202aad11ee71ec6dff672e211bf0e8a88f1
AtharvBagade/Python
/DictionaryReplace.py
336
3.84375
4
n=int(input('Enter n')) d=dict() for x in range(1,n+1): d[x]=x*x key=int(input("Enter key to check:")) if key in d.keys(): value=int(input('Key is present enter a new value to replace')) d[key]=value print(d) else: print("Key ...
4977a7a7e99f1f571ade665a927e97a059287ae4
AtharvBagade/Python
/Question7.py
304
4.28125
4
string=input("Enter the string") def Most_Duplicate_Character(str1): count = 0 for i in str1: count2 = str1.count(i) if(count2 > count): count = count2 num = i print(num,"Count:",count) Most_Duplicate_Character(string)
d70ad1e7e0c9c1d005856ed2bb6a085d10f80ea7
peter-haching/pdsnd_github
/bikeshare.py
9,330
4.28125
4
import time import pandas as pd import numpy as np # global variable definitons city_data = { 'Chicago': 'chicago.csv', 'New York City': 'new_york_city.csv', 'Washington': 'washington.csv' } month_data = { 'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6, 'all': 99 } day_data = {...
d6e5dcc5242fd7cba5ee903ee1ed2664ff5871ad
lams3/IF706-EightQueensPuzzle
/src/genetic_framework/fitness.py
955
3.5625
4
from typing import Generic, Type from abc import ABC, abstractmethod from genetic_framework.chromosome import ChromosomeT from genetic_framework.custom_data import CustomDataHolder class FitnessComputer(Generic[ChromosomeT], CustomDataHolder, ABC): """Defines an abstract class for for types that knows how to com...
a0644c545912cf4a25bc67a20f4541775fe58bc4
InsikYoon/daily-learning
/merge-intervals/merge-intervals.py
685
3.515625
4
class Solution(object): def merge(self, intervals): """ :type intervals: List[List[int]] :rtype: List[List[int]] """ a = [] intervals.sort() minval = intervals[0][0] maxval = intervals[0][1] for i,j in intervals: if( maxval < i ): ...
a710437a55d97353f22346eb3714c41f10087d02
stravinskii/compiladores-proyecto-2
/test/Ejemplo.py
59
3.515625
4
x=2 while x<3: print "Equis, somos chavos" x+=1 4+5
8aae1b6abe51849494d11dadf40fcfe84d05ad58
Dgraid3r/data_science_algorithms
/k_means++.py
6,735
3.703125
4
import numpy as np import scipy as sp import matplotlib.pyplot as plt import pandas as pd from scipy import spatial #from scipy import spatial def euclideanDistance(point1, point2): point1 = np.array(point1) point2 = np.array(point2) return np.linalg.norm(point1-point2) def k_init(X, k): """ k-means+...
432c06b6a8252123393675653e190ab8e0874d1f
LyunJ/pythonStudy
/08_list/list3.py
862
3.65625
4
# remove(x) : 가장 첫번째 만나는 값을 삭제 # n = [1, 2, 3, 4, 5, 6, 7, 1] # n.remove(1) # print(n) # cnt = n.count(1) # print(cnt) # pop() : 마지막 값을 꺼내서 반환함 pop(index) : index 위치의 값을 꺼내서 반환 # data = n.pop() # print(n) # print(data) # # data = n.pop(0) # print(data) # 2차원 리스트 연습문제 # 10명의 학생의 국어, 영어, 수학 점수가 2차원 리스트 형식으로 저장된 경우 ST...
3ab954e552bb38cea30ad5bf3bea69592c6988f6
LyunJ/pythonStudy
/08_list/sort.py
473
4.28125
4
# sort() reverse() sorted() # #리스트를 정렬 # a = [3,6,0,-4,1] # a.sort() # print(a) # a.reverse() # print(a) # # 정렬 후 새로운 리스트를 반환 # new_a = sorted(a,reverse=True) # print(new_a) # string = ['Apple','Banana','melon','apple'] # string.sort() # print(string) # # 대소문자 구분 없이 정렬 # string.sort(key=str.upper) # print(string) # ...
e3507163cdf9319456ebe04ccb544f52327e0341
LyunJ/pythonStudy
/06_while/test.py
616
3.671875
4
# 1-1 for i in range(5,0,-1): for j in range(i): print('*',end='') print() # 1-2 for i in range(0,5): for j in range(5-i): print(' ',end='') for k in range((i*2)+1): print('*',end='') print() # 2 num = int(input('숫자 입력 : ')) while num != 7: num = int(input('다시 입력 : ')) #...
6b7843bef67b2a2c9f1782b7200c3ff40b9edab6
LyunJ/pythonStudy
/1_OT/hello.py
1,990
4.125
4
# 첫번째 프로그램 # print('Lee YunJae') ''' # 변수에 값을 저장 x = 10 y = 20 z = 30 print(x,y,z) # 여러개의 변수에 여러개의 값을 저장 x, y, z = 10, 20, 30 print(x,y,z) # 여러개의 변수에 동일한 값을 할당 a = b = c = 100 print(a,b,c) # 두 변수의 값을 교환 a, b = 10, 20 print('a=',a) print('b=',b) a,b = b,a print('a=',a) print('b=',b) # 변수를 삭제 x = 100 print(x) pri...
a44e4877082dcb6b1f351d20c8032781152a5593
LyunJ/pythonStudy
/13_build_in_function/built_in_function.py
1,172
4.03125
4
# enumerate(iterable,start=0) # 시퀀스(리스트,튜플,문자열,range)를 인덱스값을 포함하는 enumerate 객체로 반환 # 반복문 사용 시 몇 번째 반복문인지 확인이 필요할 수 있습니다. 이때 사용합니다. # 인덱스 번호와 컬렉션의 원소를 tuple형태로 반환합니다 # iterator enum = enumerate(['apple', 'banana', 'melon']) print(enum) while True: try: e = next(enum) except StopIteration: break...
7588162202427dea680c8847a8e2cce5240ed2e6
LyunJ/pythonStudy
/18_OOP/static_method_class_method.py
510
3.765625
4
# 정적 메소드 class Calc: @staticmethod def add(a, b): return a + b print(Calc().add(1, 2)) # 클래스 메소드 # self를 통하지 않고 바로 클래스가 메소드 호출 # 클래스 변수를 이용하는 메소드를 정의 class Person: count = 0 def __init__(self): Person.count += 1 @classmethod def show_count(cls): print('%d명 태어났습니다' % ...
0f4dbc72d55b4682d7bff2c6a67e1c79db364d87
ChrisTordi/Data-Visualization
/final-project/create_data.py
6,276
3.578125
4
# - * - coding: utf - 8 -*- import csv required_fields = ['Gender', 'JobSatisfaction', 'ConvertedSalary', 'FormalEducation', 'CompanySize', 'Hobby', 'SkipMeals', 'HoursComputer', ...
cf05f6410b6878b34067ecb3b89b38bef59f59b5
Design-Computing/me
/set3/exercise2.py
1,216
4.5
4
"""Set 3, Exercise 2. An example of how a guessing game might be written. Play it through a few times, but also stress test it. What if your lower bound is 🍟, or your guess is "pencil", or "seven" This will give you some intuition about how to make exercise 3 more robust. """ import random def exampleGuessingGam...
78e832cc02a15b4606fd6f3346c1f69e39920a44
Design-Computing/me
/set2/exercise3.py
8,753
4.3125
4
# -*- coding: UTF-8 -*- """ Welcome to exercise 3 of set 2. Modify each function until the tests pass. """ def is_odd(a_number): """Return True if a_number is odd, and False if a_number is even. Look into modulo division using the '%' operator as one way of doing this. e.g. 4 % 2 = 0 13 %12 = ...
94db51bf4deed738bd176117b9ebb7be3ec98c06
he44/useful_python_scripts
/ch2_python_array_of_sequences/array.py
701
3.59375
4
from array import array # typecode # 'b': signed char # 'd': float (?) # floats = array('d', (random() for i in range(10**7))) # can be save/loaded via "tofile" and "savefile" # fast (much faster than saving/reading using txt files) # pickle: also fast, but can handle almost all data types from collections impor...
cc718ccdef0ec4187c9d5c6b5bf85a947712f413
he44/useful_python_scripts
/ch2_python_array_of_sequences/tuple.py
1,864
3.953125
4
def tuple_as_record(): traveler_ids = [ (120, "USA", "1111111"), (120, "ZZZ", "4444444"), (-3, "BRA", "3333333"), (3, "USA", "2222222") ] # sorted here only operates on the first field of the tuple? # breaking ties by the next field ? for passport in sorted(traveler...
288edcca7519186515d527c7d6a59c36d2a8d0cc
idris11703/idris11703
/soja boy.py
2,157
3.734375
4
def return_to_menu(): ussd_code = eval(input('please type in your bank ussd code:')) Mainmenu() print('Here is UBA Bank ussd code s\nZenith: *919#') def Mainmenu(): print('1.Airtme_self\n2.Airtime_self\n3.Transfer_UBA\n4.Transfer_Other Banks\n5.Transfer_UBA Prepaid\n6.Check Balance\n7.Pay Bills\n8.Next') option = ...
1dc10df7662eb50e476c17402a1df3ca72b05765
vigneshwaran444/pythonsdocuments
/snippets/program68.py
1,607
3.734375
4
from numpy import* import matplotlib.pyplot as plt #y=mx+c def compute_error_for_given_points(c,m,points): totalError=0 for i in range(0,len(points)): x=points[i,0] y=points[i,1] totalError +=(y-(m*x+c))**2 return totalError /float(len(points)) def step_gradient(c_current,m_current,points,learning_rate)...
18e94bdc60c13aa1bcfc221ef94d037185771265
vigneshwaran444/pythonsdocuments
/snippets/program36.py
167
3.921875
4
phonebook= {"john": 938463557625,"jack":7864539875735,"jill" :8759837535979} for name,number in phonebook.items(): print("phone number of %s is %d" % (name,number))
ef386880f0b2227862fc52516a9e399388f51245
Nikhilesh212/DS_practice
/Stack/Max_area.py
491
3.65625
4
def largestRectangle(height): hs=[] ps=[] maxarea=0 height.append(0) for i in range(len(height)): last=len(height)+1 while len(hs)!=0 and hs[-1]>height[i]: last=ps[-1] area=(i-ps.pop())*hs.pop() maxarea=max(maxarea,area) if len(hs)==0 or hs...
5b7a4cd137eea8e4e4255f1101a7be4a6a2e70eb
SashwatAnagolum/DoNew
/gcd/times_main.py
1,163
3.84375
4
# -*- coding: utf-8 -*- """ times_main.py: Driver script for the quantum multiplication algorithm using the Quantum Fourier Transform. """ from qiskit import register import qft_times def times(first, second): """ Computes the product of two bit strings first and second. Parameters: first, second: ...
7ed892aa24697b7dd9d0d650a0932441176c1345
ahmedzaabal/Beginner-Python
/String methods.py
234
3.78125
4
name = "Ahmed" print(len(name)) print(name.find("A")) print(name.capitalize()) print(name.upper()) print(name.lower()) print(name.isdigit()) print(name.isalpha()) print(name.count("m")) print(name.replace("A", "M")) print(name*4000)
03f695385e9a5b6dd258029d10e11b9bb6ffa371
ahmedzaabal/Beginner-Python
/Dictionary.py
606
4.28125
4
# Dictionary = a changeable, unorderd collecion of unique key:value pairs # fast because they use hashing, allow us to access a value quickly capitals = {'USA': 'Washington DC', 'India': 'New Delhi', 'China': 'Beijing', 'Russia': 'Moscow'} capitals.update({'Germany': 'B...
5559049b3f6838da561d79e98b7d55bd5bdab481
OmkoBass/python_data_structures
/LinkedLists/linked_list.py
2,673
3.890625
4
class linkedList: first = None last = None length = 0 def add(self, to_add): if type(to_add) is not node: to_add = node(to_add) if self.first is None: self.first = to_add self.last = to_add else: self.last.next = to_add ...
c5d91ba52a45b61a4442201fc22f7a20aa575c63
malay1803/Python-For-Everybody-freecododecamp-
/files/findLine.py
1,218
4.375
4
# Exercise 2: Write a program to prompt for a file name, and then read through the file and look for lines of the form: #X-DSPAM-Confidence: 0.8475 # When you encounter a line that starts with "X-DSPAM-Confidence:" pull apart the line to extract the floating-point number on the line. Count these lines and then comput...
276c23c5596b9b3ac97ea81732f41c54b322b9fe
Abhijeet1990/DL_based_IDS
/LSTM-RNN based IDS_kdd_dataset.py
9,397
3.59375
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np import os import sys from keras.layers import Dropout,LSTM,Dense from keras.models import Sequential from keras.callbacks import History,ModelCheckpoint,EarlyStopping from sklearn.metrics import multilabel_confusion_matrix,confusion_matrix, f1_score, ...
1fd66486fe4dabfa890ce1960a26ac7a9d9ad76f
vmysechko/QAlight
/qalight_hw/hw_07_string.py
697
3.765625
4
def symbol_count(symbol: str, phrase: str): """Фукнция считает сколько раз символ 'symbol' встречается в строке 'phrase' :type symbol: str :type phrase: str """ count = 0 for i in range(0, len(phrase), 1): if symbol == phrase[i]: count += 1 print(f"Символ \n\"{symbol}\" " ...
5b9c5926fbffc65e830bdb7e45f70f094158db89
vmysechko/QAlight
/metiz/files_and_exceptions/alice.py
328
3.875
4
filename = 'text_files/alice.txt' try: with open(filename, encoding='utf-8') as f: content = f.read() except FileNotFoundError: print(f"Sorry, the file '{filename}' is not found.") else: words = content.split() num_words = len(words) print(f"Amount of words in '{filename}' is: " + str(num_w...
53c6e9853a06f737c8c43009c4ed2c154e11e107
vmysechko/QAlight
/metiz/files_and_exceptions/file_writer.py
720
4.21875
4
filename = "programming.txt" with open(filename, 'w') as file_object: file_object.write("I love programming.\n") # 'w' argument tells Python that we want to open a file in write mode. # In the write mode Python will erase the content of the file. # 'r' - read mode # 'a' - append mode # 'r+' - read/write mode wi...
66487acffc726a8a223f573066b950eb02bc86c2
prisetio/Python
/belajar-python/set.py
202
3.59375
4
# Belajar Set # list => [] # tuple => () # set => {} nama = {"Priyo", "Bening", "Priyo"} nama.add("Saraswati") for data in nama: print(data) nama.remove("Saraswati") print(nama)
4b5c02c2419129fd947d6f8262445ae7dfd8840c
prisetio/Python
/belajar-python/operator_perbandingan.py
325
3.828125
4
# Operator Perbandingan # > Lebih dari # < Kurang dari # >= Lebih dari sama dengan # <= Kurang dari sama dengan # == Sama dengan # != Tidak sama dengan print(5 <= 3) print(10 == 10) print(7 != 9) # Keunikan dari sama dengan (==) dan tidak sama dengan (!=) print("priyo" == "priyo") print("priyo" != "pr...
22db4a4a0c4c691cec7d8f6b94c712b99754c21c
rosethepose/Calculator
/calculator.py
1,596
4.09375
4
play = True while play: op = input("Choose your operation:\na) addition\nb) subtraction\nc) multiplication\nd) division\n >>") op = op.rstrip() if op != "a" and op != "b" and op != "c" and op != "d" : print("Error!") again = input("\n\n Would you like to go again? (yes or no): ") again = again.rstrip(...
747138043415db1240ab724db3d8d37e9b1c1510
robbiii-robbiii/HANGMAN-FlahGame
/HANGMAN-GAME.py
1,913
3.515625
4
# -*- coding: utf-8 -*- """ Created on Wed Jun 30 22:01:12 2021 @author: Robbins Aby """ import pygame, random, sys, time from pygame import display, event, font pygame.init() screen = display.set_mode((800,500)) display.set_caption("HANGMAN!") def display_message(message): screen.fill(yellow) text = word_f...
2aa435cff5e939f200af874b4f6a6ceb3dea0a09
Daalin80/Lesson5
/ex2.py
232
3.6875
4
t = "Мы ввели какой-то маленький текст" words = t.count(" ") + 1 symbols = len(t) print("Количество слов: ", words) print("Общее количество символов: ", symbols)
acd6337290e3b95602bdaf9b0f19eebab56293f8
rheehot/test
/DS&A/프로그래머스/Level1/같은 숫자는 싫어.py
568
3.71875
4
def solution(arr): answer = [] for i in arr: if answer[-1:] != [i]: answer.append(i) return answer ''' # 슬라이싱을 하면, 리스트를 반환한다. a[-1] == i 이렇게 풀면 처음에 빈 리스트이기 때문에 오류나지만 a[-1:] == [i] 슬라이싱으로 리스트를 비교하면 오류 안남 # 처음 풀이 def solution(arr): answer = [arr[0]] for i in arr: if answe...
e57f87e3d1e0611439686cf6250ab2e7ef577a8c
Brian-Jiang/TheGhostGame
/_Helper.py
639
3.890625
4
import re def find_prefix(prefix, words): pattern = re.compile(prefix + '[A-z]') result = set() for word in words: if pattern.match(word): result.add(word.rstrip('\n')) return result def get_word_bank(): reader = open('dictionary.txt', 'r') words = set(reader.readlines())...
1f2e6e9bcf05d6a2836d9e02c895330caffc4aa0
ParkJiSu28/Python_cote
/pg_targernumber.py
865
3.5
4
from collections import deque numbers = [1, 1, 1, 1, 1] target = 3 def bfs(numbers, target): answer = 0 q = deque() q.append([numbers[0], 0]) q.append([-1 * numbers[0], 0]) while q: tmp, idx = q.popleft() idx += 1 if idx < len(numbers): q.append([tmp + numbers[...
193b89f481ff41ba933b90b0e6dffdc36c816b87
ParkJiSu28/Python_cote
/start1.py
1,103
3.84375
4
user_input_a = input("정수입력 >") if user_input_a.isdigit(): number_input_a = int(user_input_a) print("원의 반지름: ", number_input_a) else: print("정수가 아닙니다.") # try -except try: user_input_a = input("정수입력 >") number_input_a = int(user_input_a) except: print("예외발생") else: print("원의 반지름: ", numbe...
b7d129970e1e38656dae65804e66ed6de9d41b52
skinan/Complier-Design-Lab-Course-Assignments
/Compiler Lab 2/src/main.py
971
3.6875
4
from keywords import is_keyword from identifiers import is_identifier from symbols import is_symbol def main(): user_input = input().strip(" ") # print(user_input) tokens_list = [] temp = "" for word in user_input: if word == " ": tokens_list.append(temp) temp = "" ...
bef33f3ebedec6884ea939bbe9c4ffd1edd88632
redforks/spork-compiler
/clientlib/sftest/list.py
6,106
3.609375
4
# -*- coding: utf-8 -*- from unittest import TestCase class Custom(object): def __init__(self, name): self.name = name def __eq__(self, other): if self is other: return True if type(self) is not type(other): return False return self.name == other.name ...
5caf8e2c56fda74fa83caf01d9b8b5698947e503
xallen1110/algorithms-and-structures
/xallen1110/merge_intervals_data_structure/interval_merger.py
3,578
3.9375
4
import collections class IntervalMerger(object): ''' A class used to merge interval(s) to a graph (represented in connection-merged adjacent list) A list of initial intervals is needed to build the class and graph. After the setup, intervals can be added to the class/graph one by one. TODO: Refa...
11464d81ee1c86c41a86fbf660896eb1e4b8fd8f
mfreema1/cs115-old
/temp_conversion.py
1,604
3.859375
4
''' Created on Sep 5, 2017 @author: Mark ''' from pip._vendor.pyparsing import line """ put functions at the top of the program """ def fahrenheit(celsius): """returns the input celsius degrees in fahrenheit""" return (celsius * (9/5) + 32); def celsius(fahrenheit): """returns the input fahrenheit degree...
50553964c989b8337e40ac2091088c5f6909aaed
Tang-xun/py_torch
/src/tensorflow/two_layer_net_tf.py
1,592
3.953125
4
# -*- coding: utf-8 -*- import numpy as np import tensorflow as tf # First we setup the computational graph N, D_in, H, D_out = 64, 1000, 100, 10 # Create placeholders for the input and target data; # these will be filled with real data when we execute the graph x = tf.placeholder(tf.float32, shape=(None, D_in)) y...
8cb379032e5b85871f1f7ff581a7c6c2c010a78c
f-aaf/PracticaPy
/InfoPermanente.py
2,624
3.8125
4
import pickle class Persona: def __init__(self, nombre, genero, edad): self.nombre=nombre self.genero=genero self.edad=edad print("Se ha creado una persona con el nombre: ", self.nombre) def __str__(self): # método para convertir en cadena de texto return "{} {} {}".format(self.nombre, self.gene...
7f26b982dd0543a277216ca671b882f9d1c1f3a1
calder3/BCA_Project-
/hang_man2.py
1,186
4.15625
4
''' This will play the game hangman. Need to have the random word modual installed. ''' from random_word import RandomWords r = RandomWords() word = r.get_random_word(hasDictionaryDef = 'true') word = word.lower() space = list(word) dash = [] dash.extend(word) #print(word) for i in range(len(dash))...
a269a447ac7f3f4f888c61f5a1942a1212232483
shreyasmorey5518/The-Spark-Foundation-Internship
/Task_1.py
3,966
3.984375
4
#!/usr/bin/env python # coding: utf-8 # # Task-1 # # Linear_Regression Algorithm # ## Predicting using Supervised ML # ### Importing standard library # In[1]: import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns get_ipython().run_line_magic('matplotlib', 'inline') # # ...
8afacd0f0ac9fca330a27fb9b40b47832a2eee41
fumokmm/language-examples
/Python/0007_pandas_Series.py
1,252
3.859375
4
import pandas as pd ser = pd.Series(["晴れ", "雨", "くもり","晴れ時々くもり", "雨"]) print(ser) # <output> # 0 晴れ # 1 雨 # 2 くもり # 3 晴れ時々くもり # 4 雨 # 完全一致のフィルタ print(ser == "雨") # <output> # 0 False # 1 True # 2 False # 3 False # 4 True # dtype: bool # => 各行で...
02ab2996e7f3a049382d974405476aca8f51197a
Armandop444/Proyecto-Analisis
/Unidad4/DiferenciacionNumericaSuperior.py
11,706
3.84375
4
from sympy import * x=Symbol("x") #nivelderiavda es si es una derivada de primer(1) o segundo nivel(2), como la diferenciacion normal #la diferencia es en ordenderivada, que ya no va a ser la primera derivada, sino que (2)segunda, tercera(3) o cuarta(4) #ahora que lo pienso lo podia hacer de una vez en el codigo de Dif...
edac37259c13c3c4056d5dad0520dbe47c5e951c
misiekofski/adventofcode-2019
/1a.py
338
3.75
4
result = 0 def get_fuel(fuel): temp = (fuel//3) - 2 module_total = 0 while temp > 0: module_total += temp temp = (temp//3) - 2 return module_total with open('input2.txt') as fp: line = fp.readline() while line: result += get_fuel(int(line)) line = fp.readline(...
0bcf33912bd97c0883c6c68adf8b0e25f3ac99c7
RadicalZephyr/Python-Stuff
/python forums help/valentine-tic-tac-toe.py
3,517
4.03125
4
import random EMPTY = "_" X = "X" O = "O" TIE = "TIE" NUM_SQUARES = 9 player = X computer = O def display_instructions(): print \ def print_board(board): board = [item.replace("_"," ") for item in board] ...
e8f5b6d49eadcba82f319ce159ba9bbdd89ea465
RadicalZephyr/Python-Stuff
/random/getBinary.py
223
3.765625
4
def getbinary(number): k ='' while(number): if number%2==1: k='1'+k number = number/2 else: k='0'+k number = number/2 print k getbinary(int(raw_input()))
964faffbe14b513aa9c9b9bdd6a12d951a94ff08
YeahZou/python
/YeahStock/test/test_list.py
229
3.953125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- lists = [1,2,3,4] print("length of lists is: " + str(len(lists))) undefined_list if undefined_list is not None: print("length of undefined list: " + str(len(undefined_lsit)))
c679337f1546a163ad5eaa110adc2b36ba5e4fac
Chauhandeep/rbac
/db/backend.py
1,115
3.6875
4
from abc import ABC, abstractmethod from typing import Dict from utils import DatabaseSingleton class DatabaseBackend(DatabaseSingleton, ABC): @abstractmethod def insert(self, model: str, record: Dict): """ Inserts a record into the table :param model: model name :param record...
d48206fd35a3d092474269981534ad14097a98c1
MotherTeresaHS/ICS3U-2019-Group22
/docs/readthedocs_examples/egg+bomb_offscreen_falling_demo.py
2,685
4.03125
4
#!/usr/bin/env python3 # Created by: Douglass Jeffrey # Created on: Dec 2019 # This file is an example of how to to make eggs move once they reach the bottom # of the screen and how to make them fall def game_scene(): while True: # Egg and bomb speed increaser if score > 20 and egg_speed == 1:...
50b2c90bc1b121e6da06adfc7e6dca54785545c0
whhub/python
/Collections/learn_default_dict.py
435
3.65625
4
# coding=utf8 """ defaultdict(default_factory)在普通的dict(字典)之上添加了default_factory,使得key(键)不存在时会自动生成相应类型 的value(值),default_factory参数可以指定成list, set, int等各种合法类型。 """ from collections import defaultdict s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)] d = defaultdict(set) for k, v in s: ...
9a74d69f7b4da574204506293f480eba5d415d62
jackketteler/Jack-Ketteler
/Welcome to gmail.py
417
3.734375
4
print("Welcome to Gmail") myUsername =input("Enter your username, then press Return: ") if myUsername=="jackketteler": print("Username successful") myPassword=input("Enter your password, then press Return: ") if myPassword=="sof123@": print("Success") else: print("Unable to ...
f39d8e587e2bdc4d87ffa8d469ba3a4f99cb34a5
pasjtene/pythoncodes
/listoflist.py
217
3.921875
4
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]] # Add your function here def flatten(lists): result = [] for numbers in lists: for i in numbers: result.append(i) return result print (flatten(n))
90c4d08e28593833488baeb74e87c039155b2e78
AI-Pree/Learning
/calc.py
5,342
3.796875
4
import operator import sys ops = {"+":1, "-":1, "*" : 2, "/": 2, "(":4, ")":4,"change":3} def change(ops:str,value:str)->str: return str(-float(value)) def evaluate(ops:str,first = None,second = None)->str: op = {"+":operator.__add__, "-":operator.__sub__, "*":operator.__mul__, "/":o...
f11333f38c9a8daa2a57ac14df6e201776e60396
happiless/DataStrcture_And_Algorithm
/04_leetcode/python/03_stack/05_leetcode-20-有效的括号.py
1,074
3.71875
4
class Solution: def isValid(self, s: str) -> bool: st = [] flag = True for i in s: if i in ['(', '[', '{']: st.append(i) elif i == '}': flag = not (len(st)==0 or st.pop() != '{') if not flag: ...
f48c46bb61f5ca881eeac681c11dc7e2cf8dcb06
GamerNoTitle/Python-Noob
/lab5/lab5.3.py
136
3.609375
4
for x in range(0,10): print(x) print () for y in list(range(0,10)): print(y) print () for z in list(range(5,10)): print (z)
028e73aab6a25145064048c00eb5d9f35d8037c1
PriyaRcodes/Threading-Arduino-Tasks
/multi-threading-locks.py
995
4.375
4
''' Multi Threading using Locks This involves 3 threads excluding the main thread. ''' import threading import time lock = threading.Lock() def Fact(n): lock.acquire() print('Thread 1 started ') f = 1 for i in range(n,0,-1): f = f*i print('Factorial of',n,'=',f) lock.release() de...
c8833ef808c785ec3dffac6ff8fdf61e0da792da
125mcintyre/ML_projs
/HOMLwSKLearnTF/03_classification.py
12,679
3.578125
4
from load_mat_dataset import * import numpy as np #load our MNIST-orginal dataset (currently a .mat file) path = "./datasets/mnist/mnist-original.mat" mnist = import_dataset(path, "MNIST-original") X , y = mnist["data"],mnist["target"] print("X shape: ", X.shape) print("y shape: ", y.shape) # Let's take...
c30ede39f24692490d2d3530dfbba510118fdd7b
kevenescovedo/PYTHON-work_arquivos
/exercicio3.py
2,320
4.53125
5
"""" Elabore uma estrutura para representar e armazenar 10 alunos (matricula, nome, telfone). Utilize os recursos de arquivo para armazenar estes dados permanentemente. O nome do arquivo deve ser o mesmo da estrutura. Construa um menu com as seguintes opções, cada uma delas deve ter uma função e a main para chama...
1f84cf135c232d541d26ed7f6242d699b938393f
bostko/izchbio
/6_nov/RNA_splicing.py
613
3.578125
4
#rosalind RNA Splicing # # https://github.com/radoslavzi/BioInformatics/blob/master/Lectures/RNA_splicing/rosalind_splc.txt from read_fasta import ParseFASTA, ReadFASTA def getMatchingPositions(dna, intron): result = [] for p in range(0, len(dna)): if dna[p:].startswith(intron): re...
a00baeea3c875aad6a412bad5aec8988608c4290
BrianWisniewski/ATBS
/Chapter 4/nameSorter.py
555
4.09375
4
classroom = [] while True: print('Do you want the names sorted forwards(f) or backwards(b) alphebetically?') ans = input() if ans == 'f': direction = False break elif ans == 'b': direction = True break else: print('Please enter a valid command.') while True: ...
dbf112e8829517096edd48841cc4ee6b53c3416d
eriDam/CursoPython
/Fase 4 - Temas avanzados/Tema 13 - Interfaces graficas con tkinter/3_label.pyw
1,789
3.890625
4
from tkinter import * # Crear la raiz # Configuración de la raíz root = Tk() #creamos un componente Tk # Título de la ventana root.title("Mi label") # Variables dinámicas, creamos un objeto de esta clase texto = StringVar() texto.set("Eri creando textos dinámicos") #frame = Frame(root, width=480, height=320) ...
5a6c3768825ef7ec1e97cae8e6f533457fcfba5c
eriDam/CursoPython
/Fase 4 - Temas avanzados/Tema 14 - Bases de datos con SQLite/Ejercicios/restaurante_ej_2_interfaz.py
1,885
4.46875
4
""" 2) En este ejercicios debes crear una interfaz gráfica con tkinter (menu.py) que muestre de forma elegante el menú del restaurante. Tú eliges el nombre del restaurante y el precio del menú, así como las tipografías, colores, adornos y tamaño de la ventana. El único requisito es que el programa se conectará a la ba...
4d45ad289b4b5b54541685111898278a1bb85097
eriDam/CursoPython
/Fase 4 - Temas avanzados/Tema 13 - Interfaces graficas con tkinter/7_text.pyw
628
4.03125
4
# El text sirve para crear un campo de etxto, para trabajar cn un campo multilinea, crear comentarios, descripciones... from tkinter import * # Crear la raiz # Configuración de la raíz root = Tk() #creamos un componente Tk texto = Text(root) texto.pack() # width escribir caracteres en horizontal, height lineas en...
2c9161782bc3101c3742d3bacec72b1de24fcb51
eriDam/CursoPython
/Fase 4 - Temas avanzados/Tema 13 - Interfaces graficas con tkinter/4_entry.pyw
848
3.921875
4
# Campos de texto, equivalente a lafunción input pero gráficamente from tkinter import * # Configuración de la raíz root = Tk() #creamos un marco 1 para colocar los elementos frame = Frame(root) frame.pack() # Cear una entrada, un objeto decalse entry dentro de root #entry = Entry(root) #creamos la label dentro del...
fef1f87594353ae1bef1ab22b1faa90e3860b5f7
eriDam/CursoPython
/Scripts/descomposicion.py
1,460
3.890625
4
#importamos sys que contiene la lista de argumentos import sys #comprobamos if len(sys.argv) == 2: numero = int(sys.argv[1]) if numero < 0 or numero > 9999: print("Error - Número incorrecto") print("Ejemplo:decomposicion.py [0-9999]") else: """Lógica cuantas veces hay que recorrer el nº, bucle que en...
99df563244691f861fec63567986b9c0e761f6b6
patrickbald/hadoop-map-reduce
/wordCountMap.py
238
3.53125
4
#!/usr/bin/env python3 import sys import io def main(): stream = io.TextIOWrapper(sys.stdin.buffer, encoding='iso-8859-1') for line in stream: word = line.split()[0] print(f"{word.strip()} 1") if __name__ == "__main__": main()
8cd40a51022bf66e2c94809f094e182b89710008
nigeltart/Pythagorean-Triples
/Pythagorean_triples.py
754
4.40625
4
# A program to find Pythagorean triples a_triple=[] hypotenuse=5 triples=[] triples.append(a_triple) #print (triples) while hypotenuse <100: base = 1 height = hypotenuse-1 #print ("before loop: ", base, height, hypotenuse) while height>base: #print ("before if: , base, height, hypotenuse") i...
308f88672a3f1eaea62f816a3a0205b4050f57a8
ekcd1230/kmove_python
/basic/baseball_test.py
679
3.703125
4
import random array=random.sample(range(1,10),3) print('답: {}'.format(array)) print('야구게임을 시작합니다.') while True: strikecnt=0 ballcnt=0 num1=int(input('숫자 첫번째 입력: ')) num2=int(input('숫자 두번째 입력: ')) num3=int(input('숫자 세번째 입력: ')) inputArray=[num1,num2,num3] print(inputArray) for i in ra...
964c9c65d28f2866daa7c5f536482d85d38e716d
pravinnair/PythonBasics
/InsertionSort.py
415
4.03125
4
def insertionsort(input): key= 1 length = len(input) for i in range(1,length): j = i while(j>0 and input[j-1] > input[j]): if(input[j-1] > input[j]): key = input[j] input[j] = input[j-1] input[j-1] = key j-...