blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
c58d807653035847ec8efd10c643e4d51099b2f5
thewritingstew/lpthw
/ex30.py
711
4.21875
4
people = 30 cars = 40 trucks = 15 # checks to see if there are more cars than people if cars > people: # if there are more cars, it prints this print "We should take the cars." # otherwise it checks to see if there are less cars than people elif cars < people: # and if so it prints this print "We shoul...
d6bf18b6ca44603acbd867b14d985550640e5513
duythien/python
/readfile.py
268
3.875
4
#!/usr/bin/python import sys from sys import argv script,filename = argv txt = open(filename) print 'here is your file name %r' %filename print txt.read() print 'type the filename again' file_again =raw_input("> ") txt_again = open(file_again) print txt_again.read()
7ab9b453b4773baab48c110ddfc8991f402ee10d
hvaleri0/Python-Programming-for-developers
/type_conversion.py
200
3.625
4
x = input("x: ") y = x + 1 # Conversions print(int(x)) print(float(x)) print(bool(x)) # Falsy Truthy Concept print(int(x)) # Falsy: # "" # 0 # [] # None (same as null) # everything else is truthy
7b81c861533a91e9030216bdaadd3ce8e555418d
ritabugking/ECE239AS-DeepLearning
/finalProject/k-fold.py
669
3.765625
4
import numpy as np def K_folded_data(X, y, k): ''' This is the function that would take in X, y and randomly split them into number of folds as specified for cross-validation Inputs: X: Training data y: Labels of the training data k: Number of folds the user want to have outputs: X_folds: Split training dat...
da005d95c197a04c06bb973208bdfbc4ce372fec
SchrodingersCat00/aoc2019
/day1/day1.py
255
3.625
4
def get_fuel(mass): fuel = 0 while (mass := mass//3-2) > 0: fuel += mass return fuel if __name__ == '__main__': with open('input.txt', 'r') as f: fuel = sum(get_fuel(int(line)) for line in f.readlines()) print(fuel)
2e2f10f9f89d2d20ddac9a4999fcadda7a5bdc2c
forabetterjob/learning-python
/01-data-types-and-structures/tuples.py
637
4.53125
5
# empty tuple emptytuple = () print 'emptytuple = ' + str(emptytuple) # () # numbers numbers = (1, 2, 3, 4) print 'numbers = ' + str(numbers) # (1, 2, 3, 4) # indexing print 'numbers[1] = ' + str(numbers[1]) # 1 # slicing print 'numbers[1:3] = ' + str(numbers[1:3]) # (2, 3) # joining print 'numbers + numbers = ' + ...
2e2a981aa5f817542c66ee82b59c41c7e3826784
acoder18/Practice-Python
/learnReturn.py
855
4.09375
4
#This script is to learn return in function import random def getAnswer(answerNumber): if answerNumber == 1: return "it's 1" elif answerNumber == 2: return "it's 2" elif answerNumber == 3: return "it's 3" elif answerNumber == 4: return "It's 4" elif answerNumber == ...
e1e5ecba69fe178fb3075f4d41dcb2b91ed8947c
jordiparislopez/Coding-Utilities
/screenshot_rename.py
1,891
3.765625
4
import numpy as np import os """ This code renames every screenshot in the current directory to Figure_X.png in the correct order, i.e., the number X increases when the screenshots are done later in time. In this version, the code works on multiple screenshots performed on the same day and uses th...
bde505dde9c046654679a0929e8a4ca7bd5ca364
cosmicRover/algoGrind
/two_heaps/find_median.py
1,028
3.890625
4
import heapq class MedianFinder: def __init__(self): """ two heaps approach. create two heaps -> maintain balance time O(n log n) | space O(n) """ self.left = [] self.right = [] def addNum(self, num: int) -> None: #step 1, append to heap ...
98f5b49ae2a02f4d87d5fb9227fbfe649177ef99
gagansokhal/python
/projects/taxCalc_acc_to_totalIncome.py
509
4.09375
4
totalIncome = int(input("Enter your Income: ")) def taxCalc(totalIncome): totalTax = 0 if totalIncome < 10000 and totalIncome > 0: totalTax = 0 elif totalIncome > 10000 and totalIncome < 20000: totalTax = (totalIncome - 10000) * 10/100 else: totalTax = ((totalIncome - 20000) * ...
f29a0e7e37a8da06840b566999c14a7af8afe1fd
myaliqiang/projecteuler
/euler6.py
262
3.671875
4
#!/usr/bin/env python def get_sum(num): sum = 0 for i in xrange(1, num+1): sum += i * i return sum def get_square(num): sum = 0 for i in xrange(1, num + 1): sum += i return sum * sum print get_square(100) - get_sum(100)
1144b41c28f1cdef62a2de50a9b747b3010d419f
GSri30/My-Python-Codes
/functions/q5.py
377
4
4
#Write a function which takes 2 lists of same length and adds respective elements using another function.List can either have number or string n=input() list1=[] list2=[] for i in range(n): list1.append(input()) for j in range(n): list2.append(input()) def add_respective_elements(): for k in range(n): ...
e66c0c9abb57dc00b36b5164c2d8f033b2cfd449
godspace/N_queens_puzzle
/N_queens_puzzle.py
1,242
3.765625
4
def check(map, x, y): #check line i = 0 j = y while i < N: if map[j][i] == 1: return False i += 1 #check upper left diagonal i = x j = y while i >= 0 and j >= 0: if map[j][i] == 1: return False i -= 1 j -= 1 #check bottom left diagonal i = x j = y while i >= 0 and...
340e7b22e44ca18c109d8990575c0ced7b77f820
gzxultra/GraphAlg
/src/floyd_warshall.py
1,673
3.671875
4
def floyd_warshall(G): """ Floyd–Warshall algorithm pseudocode by wikipedia: https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm """ n_nodes = len(G.nodes) dist = [[float('inf') for i in range(0, n_nodes)] for j in range(0, n_nodes)] for from_node in G.nodes: for to_node ...
748ef81910178c8410134439f77b0b9eef5b6b92
s-garg0001/acadview-python
/assignment 11.py
1,615
4.1875
4
#1. Create a threading process such that it sleeps for 5 seconds and then prints out a message import threading from threading import Thread import time class mythread(threading.Thread): def _init_(self): threading.Thread._init_(self) def run(self): time.sleep(5) print("Value af...
a85435fe2232fd3cbca661b49da1942f346189e6
frodinj/IT-140
/draft for atm.py
1,641
4.15625
4
import sys #ACCT BALANCE VARIABLE #defines account balance account_balance = float(500.25) #<--------functions go here--------------------> #printbalance function def printbalance (account_balance, userchoice): return account_balance #deposit function def deposit (deposit_amount, account_balance):...
8800a68b090e92792c19fa094336927b383e5e66
Helblindi/ProjectEuler
/21-40/Problem21.py
1,302
4.125
4
""" Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers. For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; ...
99368e9b3826c52a01a4e20dd78bca2141491b1f
AngeloYan/fireBalloon
/9900_backend/preprocess.py
775
3.625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Mar 16 23:34:09 2019 @author: hal """ import re import nltk from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer nltk.download('stopwords') def construct_corpus(corpus_raw): new_stopwords = set(stopwords.words('english')) | ...
69d0458ff8b548413daffa6d56a899854812c466
csliubo/leetcode
/226_invert_binary_tree.py
718
4.0625
4
# -*- coding:utf-8 -*- __author__ = [ '"liubo" <liubo.cs@hotmail.com>' ] # 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 invertTree(self, root): """ :t...
7abefc2fa401d166bc0fef096992dc4cc90ae999
QMIND-Team/Modern-OT
/wavProcessing.py
10,873
3.5625
4
# This file is no longer needed for our project, but it might be useful to keep # TODO: Consider deleting this file from pyAudioAnalysis import audioFeatureExtraction import matplotlib.pyplot as plt import os import numpy from pydub import AudioSegment def readAudioFile(path): """Reads an audio file located at s...
9338a91b008fcd69f607b61b8c8fd6cd1c2b693f
helloworld755/Python_Basics
/hw11_task2.py
277
3.640625
4
class ZeroDiv(Exception): pass try: val = int(input('Введите делитель: ')) if val == 0: raise ZeroDiv('Деление на ноль') except ZeroDiv as e: print(e) else: num = 100/val print('Деление состоялось,', num)
bb280946bb7db98a7a5511fe29aa27a52874e121
peinanteng/leetcode
/movingAverageFromDataStream.py
670
3.578125
4
class MovingAverage: """ @param: size: An integer """ def __init__(self, size): # do intialization if necessary self.sums = [0] * size self.count = 0 self.size = size """ @param: val: An integer @return: """ def next(self, val): self.count +=...
883840b75241a3644b3e0717c598aee1c2808326
rahulbishain/sum-product
/sum_list.py
967
3.890625
4
from primes import get_primes def prod_greater_1000(sum): primes_list = get_primes(2000) sum_feasible = True for a in range(1,int(sum/2)+1): b = sum - a if a in primes_list and b in primes_list and a*b > 1000: sum_feasible = False break return sum_feasible,a,b d...
7a5ef3739ab20f506a94a907f05083cc5b60fa06
SpencerNinja/practice-coding
/Python/CS1400and1410/word_zap/main.py
4,355
3.890625
4
# Spencer Hurd # CS 1410-03 # Tuesdays & Thursdays 1:00pm # Word Zap! # main.py # We are not providing unittests for main.py because it is too difficult to test a program this dynamic, we will have to rely on Acceptance Testing to verify it works as expected. It is up to you to figure out how to finish the game ...
003159e694dfa4abbea5b13c4e40ebe416f3597a
jeykarlokes/machine-learning-and-python-related-programs
/Research/ML/samplelr.py
2,682
3.8125
4
import numpy as np import matplotlib.pyplot as plt import pandas as pd data2 = pd.read_csv("Multi_linear.txt",header = None) data2.head() data2.describe() fig, axes = plt.subplots(figsize=(12,4),nrows=1,ncols=2) axes[0].scatter(data2[0],data2[2],color="g") axes[0].set_xlabel("size (square Feet)") axes[0].set_ylabel("P...
548be89996dc06f5a429e3edc21ddc817f08ae2e
JohnyBoy2128/Assignment-7
/main.py
1,304
4.375
4
# Calendar program that allows the user to enter a day, month, and year, and give back info on the days in the month, and the days left in the year # John Paul Cannon # 10 - 27 - 21 # function for whether year is a leap year def leap_year(y): if (y % 4 == 0 and y % 100 != 0): # checks if year is just divisibl...
8e869af36e0f09ff1832ce928fa7ebd1e9c08b43
li-xiuliang/Python001-class01
/week07/Zoo.py
1,748
3.890625
4
from abc import ABCMeta, abstractmethod class Animal(metaclass=ABCMeta): @abstractmethod def __init__(self, species, body_size, character): self.species = species self.body_size = body_size self.character = character if self.species == '食肉' and (self.body_size == '中' or self.bod...
32c741cc17f30c86cca606a01ca6382641de6cd6
Richardwillianx/Exercicios-em-Python
/Desafio44.py
1,288
4
4
""" Elabore um programa que calcule o valor a ser pago por um produto, considerando o seu preço normal e condição de pagamento: - à vista dinheiro/cheque: 10% de desconto. - à vista no cartão: 5% de desconto. - em até 2x nno cartão: preço normal. - 3x ou mais no cartão: 20% de juros. """ print('===== LOJAS RICHARDs ...
a1d776b2ac02a35298e55530bc88bcfce1b4bf81
jedzej/tietopythontraining-basic
/students/barecki_andrzej/lesson_03_functions/L3_Negative_exponent.py
1,354
4.25
4
""" Given a positive real number a and integer n. Write a function power(a, n) to calculate the results using the function and print the result of the expression. Don't use the same function from the standard library. """ import os import sys def input_validation_positive_real(): while True: print('Set a ...
351caaefde51e87c63e4699024c462650f1fcbda
dheredia19/COMP-SCIENCE
/picture.py
871
4
4
# http://effbot.org/imagingbook/image.htm from PIL import Image import os print("We're going to make a checkerboard so I can kick your behind at chess.") squares = input("In order to do that, you gotta tell me how many squares you want per side! ") pixels = input("Now that we've got that, how many pixels should each ...
1b323534387adcde422d3fa45fcc9ec1403f07f5
douradodev/Uri
/Uri/1096.py
99
3.53125
4
I = 1 J = [7,6,5] while 10 > I: for j in J: print('I={}'.format(I), 'J={}'.format(j)) I += 2
cf63f2873991c64c747f443bb30c27bb12285de8
hwc1824/LeetCodeSolution
/cs_notes/tree/recursive/find_duplicate_subtrees.py
1,393
3.6875
4
# 652. Find Duplicate Subtrees # https://leetcode.com/problems/find-duplicate-subtrees/description/ # 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 findDuplicateSub...
af1e23c76f38f544765f3bd8292e3721797fa781
pyt3r/template-package
/examples/my_example.py
335
3.59375
4
""" my_example.py ========================== Here is a plot example """ import matplotlib.pyplot as plt _ = plt.plot([1,2,3]) #%% # pandas dataframes have a html representation, and this is captured: import pandas as pd df = pd.DataFrame({'col1': [1,2,3], 'col2': [4,5,6]}) print( df ) s = pd.S...
62298b21423f2956480540863b7e4789e188f286
nikhiilll/Data-Structures-and-Algorithms-Prep
/Stack/LeetCode/BuildArrayStackOperations_1441.py
364
3.671875
4
def buildArray(target, n): operations = [] j = 0 for i in range(1, n + 1): if j == len(target): return operations if i == target[j]: j += 1 operations.append("Push") else: operations.extend(["Push", "Pop"]) return operations targe...
0cadc4d2213e29e077789f974353b54ebf888e01
patrickoliveras/lpthw
/ex20.py
1,297
3.9375
4
# enable argv, captain from sys import argv # Bring in the args! script, input_file = argv # lets make a funfunction for barfing out the whole file def print_all(f): # BLARGHBLARGHBARF print(f.read()) # hold up def rewind(f): # go back pls f.seek(0) # now let's vomit in a controlled manner def print...
18617f93902066ab5753fad8a31ff6de9bf4c7f1
Ada-Kiekhaefer/otherProjects
/practicePy/projectPy/name_validation.py
313
4.3125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 7 14:32:15 2020 @author: Ada """ name = input("Enter your name: ") if len(name) < 3: print("Name must be at least 3 characters") elif len(name) > 50: print("Name can be maximum of 50 characters") else: print("Name looks good!")
a572c4eb976b35a22ba33b11225b85561cd48540
equitymarkets/100-days-of-code
/41_SeabornIntro.py
693
3.765625
4
#Day 41: Introduction to Seaborn using the country population spreadsheet import seaborn as sns import matplotlib.pyplot as plt import pandas as pd df = pd.read_csv("country_population.csv") plt.figure("Country Population") plt.subplot(2,2,1) sns.set_style('darkgrid') one = sns.scatterplot(x='2016',y='1960',data=df,...
4148e6a40acaa4d619172b894cfa107bfb3b8dbf
CalMcNamara/FlaskLoginProject
/main.py
3,420
3.65625
4
import sqlite3 from sqlite3 import Error from passlib.context import CryptContext import getpass pwd_context = CryptContext( schemes=["pbkdf2_sha256"], default="pbkdf2_sha256", pbkdf2_sha256__default_rounds=30000 ) def encrypt_password(password): return pwd_context.encrypt(pa...
983ac4955ae9d582f7fa31492b5665cc68524c22
lakshyatyagi24/daily-coding-problems
/python/119.py
1,497
4
4
# -------------------------- # Author: Tuan Nguyen # Date created: 20191130 #!19.py # -------------------------- """ Given a set of closed intervals, find the smallest set of numbers that covers all the intervals. If there are multiple smallest sets, return any of them. For example, given the intervals [0, 3], [2, 6]...
98a4fbedbb75118f5ef02b1a4397531dd1f4ce07
demelue/easy-medium-code-challenges
/Python/String/duplicateChars.py
430
3.84375
4
def remove_duplicate(value): buff_dict = {} value = list(value) output = [] for i in range(0, len(value)): if value[i] in buff_dict: print("Duplicate indices: " + str(i)) else: output.append(value[i]) buff_dict[value[i]] = i return ''.join(output) ...
a9bb34cfccfd1ac6d961c3812e45df80438e2a35
danielchidera/FirstGit
/Createfunctions.py
293
4.03125
4
# Assignment # create the following function # division # modulo # create a function that accepts user input and convert it to uppercase # 1 def div(a, b): return = a // b print (return) # 2 def mod(a, b): return = a % b print (return) # 3 def davUpper(): do = ().upper print (return) # 4
a0dc480c2762ccb416730c86b8a2448110dfeb7d
armostafizi/Algs
/permutation.py
260
3.625
4
#!/usr/bin/python str = 'abcde' cnt = 0 def permutate(base, rem): global cnt if len(rem) == 0: print base cnt += 1 return for i in range(len(rem)): new_rem = rem[:i] + rem[i+1:] permutate(base + rem[i], new_rem) permutate('', str) print cnt
c81c8ebfab5d806aeae8b9bb30ad7398dbd8199c
georgeh85/tech_comp
/Assignment1.py
458
3.546875
4
from collections import Counter import string def swapchars(myString): (a,b) = Counter(myString).most_common(1)[0] (c,d) = Counter(myString).most_common(99)[-1] if a == " ": (a,b) = Counter(myString).most_common(2)[1] myString = string.replace(myString, c, '0') myString = string.replace(mySt...
1bc4515bde04a8beffa553bd730cf22a66dc5b7e
skinnerjake/Portfolio
/Python/ProjectEuler/Problem22.py
681
3.90625
4
#Using names.txt, a 46K text file containing over five-thousand first names, #begin by sorting it into alphabetical order. Then, working out the alphabetical value for each name, #multiply this value by its alphabetical position in the list to obtain a name score. #What is the sum of all the name scores in the file?...
e24e8d1f021bdb8929580d29c81d0da4c03fe3a4
sdhzwm/python_the_hard_way
/python_code/笨方法学Python3/ex33.py
624
4.1875
4
#本章要点:do ... while #1. while-loop``(while 循环)。 会一直执行它下面的代码片段,直到它对应的布尔表达式为False时才会停下来。 #2. While 循环有一个问题,那就是可能会造成死循环。 #3. 尽量少用 while-loop,大部分时候 for-loop 是更好的选择 #4. 重复检查你的 while 语句,确定你测试的布尔表达式最终会变成 False i = 0 numbers = [] while i < 6: print("Atthetopiis %d"%i) numbers.append(i) i = i + 1 print("Numbers now: ", n...
3122ee940464a1df93b9d0ac97c7f60a7c1d4aa7
chaitrashree2/Python
/csvfilecreation.py
511
3.9375
4
import pandas import csv Header = ["Name", "Rollno"] studentData = [{"Name": "Akshay", "Rollno": "101"}, {"Name": "Abhi", "Rollno": "102"}, {"Name": "Akhil", "Rollno": "103"}, {"Name": "Pavan", "Rollno": "104"} ] with open("students.csv", 'w+', encoding='UTF...
5182f132d3226759f30f8adcf7750f1844e04dee
li-tianqi/Django-test
/Test/calc_test/func/csv_to_dict.py
616
4.09375
4
# _*_ coding:utf-8 _*_ """ @date: 20170623 @author: 李天琦 """ import csv def csv_to_dict(filename): """ 读取两列的csv文件,转换为字典,第一列为key,第二列为value 参数: filename, csv文件路径 输出: 字典 """ data_dict = {} with open(filename, 'r') as csvfile: reader = csv.reader(csvfile) fo...
81dcc847eaee1e90a055d3c3bb6c175d6792903f
Runthist/like
/EYHUculculate.py
571
3.96875
4
print("Ноль в качестве знака операции завершит работу программы") while True: s = input("Знак (and,or,xor,not): ") if s == '0': break if s in ('and','or','xor','not'): x = int(input("x=")) y = int(input("y=")) if s == 'and': print("%.2f" % (x&y)) elif s == 'or': print("%.2f" % (x|y)) elif s == 'xor':...
211e3d01f7c4d681e95d270d2d7ba2130f08394a
bkabhilash0/Python-Beginners-Projects
/16_Leap_Year.py
1,985
4.375
4
import sys print("***********************************Leap Year Finder*******************************************") print("Enter a Year to check if it is a leap year or Not?") leap_years = [2004, 2008, 2012, 2016, 2020, 2024, 2028, 2032, 2036, 2040, 2044, 2048, 2052, 2056, 2060, 2064, 2068, 2072, 2076, 208...
723794bef185a7ac4b7d146b42934a0f104f3f11
GunnerX/leetcode
/236. 二叉树的最近公共祖先.py
1,436
3.875
4
# 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。 # # 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。” # # 例如,给定如下二叉树:  root = [3,5,1,6,2,0,8,null,null,7,4] # # # #   # # 示例 1: # # 输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 # 输出: 3 # 解释: 节点 5 和节点 1 的最近公共祖先是节点 3。 # # 来源:力扣(LeetCode...
6999fd663f50f9971332651b2f5b33697d7009df
rahultimbadiya/PythonDailyAssignment
/Assignment3/class_usage.py
227
3.578125
4
class FirstClass(object): def __init__(self,l,w): self.length = l self.width = w def sum(self): print("The sum of length and width is",(self.length + self.width)) fc = FirstClass(4,5) fc.sum()
17360025e6b8956a78a36c89e1eaa322aa8d4e7c
neerajmajhi/python_topic
/lambda-func.py
976
4.53125
5
# You can use lambda expressions to create anonymous functions. That is, functions that don’t have a name. # They are helpful for creating quick functions that aren’t needed later in your code. # This can be especially useful for higher order functions, or functions that take in other functions as arguments. mul...
4d5c6e149a9adf3f2e2335c060ede4f6ee8c6cdc
arpitsodhi/ML
/10.2_Numpy_linear_regression.py
639
3.71875
4
import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression # x from 0 to 30 x = 30 * np.random.random((20, 1)) # y = a*x + b with noise y = 0.5 * x + 1.0 + np.random.normal(size=x.shape) # create a linear regression model model = LinearRegression() model.fit(x, y...
3ee14cac7fe8f7517b06bda705a57d03b01bab99
rafaelperazzo/programacao-web
/moodledata/vpl_data/74/usersdata/209/38700/submittedfiles/lecker.py
291
4.03125
4
# -*- coding: utf-8 -*- import math a=int(input('A:')) b=int(input('B:')) c=int(input('C:')) d=int(input('D:')) if a>b and d<=c: print('s') elif a<b and b>c and d<=c: print('s') elif a<=b and b<c and d<c: print('s') elif a<=b and b<=c and d>c: print('s') else: print('n')
5944c09d14575a5a22db441667eb8be4bc01205a
aidanohora/Python-Practicals
/range multiplication table.py
341
3.953125
4
table_size =int(input("blah")) while table_size > 0: print("******************") for i in range (1, table_size+1, 1): for j in range(1, i+1, 1): print (1*j, " ", end = "") print() print("******************") print() table_size = int(input("blah")) print("Program...
36746cd0da49c3f367032f912bee9b57fabc5fb7
taimour08/Python-programs
/A_Star_Search.py
6,213
4.09375
4
#!/usr/bin/env python # coding: utf-8 # In[6]: # This class represent a graph class Graph: # Initialize the class def __init__(self, graph_dict=None, directed=True): self.graph_dict = graph_dict or {} self.directed = directed if not directed: self.make_undirected() ...
e659cd1574a1f58f680d92a1d9b2cccc6c0cba0c
tigerkdp/DataStructures_and_Algorithms
/Matrices/matrices.py
1,570
3.75
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Dec 15 20:19:48 2019 @author: kdp """ def print_all_elem(M): for i in range(len(M)): for j in range(len(M[i])): print(M[i][j], end= ' ') print() M = [[1,2,3,4], [5,6,7,8], [9,10,11,12]] print_all_elem(M) # 1 2...
a640a14a256f3646e37ac6a8e00fe147c7f3616e
CircularWorld/Python_exercise
/month_01/day_12/exercise_02.py
1,736
4.125
4
""" 1. 打印下列类的对象 xx车的速度是xx 编号xx的商品名称是xx,单价xx xx鼠标单价xx,宽xx,颜色xx 2. 拷贝下列类的对象, 修改拷贝前对象实例变量, 打印拷贝后对象. """ class Car: def __init__(self, bread="", speed=0): self.bread = bread self.speed = speed def __str__(self): return f"{self.bread}车的速度是{self.speed}" def __repr__(self): retu...
7046039974cdcce9c9fbc17aa189a292ec073ded
CannotTell/PythonRoad
/Grammar/Foundation/Recursion.py
583
4.0625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 5/8/2017 2:56 PM # @Author : JZK # @File : Recursion.py #递归,最典型的斐波那契数列 #F[n]=F[n-1]+F[n-2](n>=2,F[0]=0,F[1]=1) def Fibonacci(num): ''' 斐波那契数列递归算法 :param num: :return: ''' if(num == 1 or num == 0): print(num) else: ...
885fcbcef593a8039f8a22635d759225153614b8
CosminEugenDinu/udacity_DSA_Problems_vs_Algorithms
/problem_2.py
2,075
4.09375
4
#!/usr/bin/env python3.8 def rotated_array_search(input_list, number): """ Find the index by searching in a rotated sorted array Args: input_list(array), number(int): Input array to search and the target Returns: int: Index or -1 """ rec_count = 0 def search(in_list, number,...
f70972f4d472eab9a4c98ec03c491b23d486188f
prasannabe2004/PythonLearning
/myStuffs/python2/random/HelloWorld.py
186
3.859375
4
import math import sys num = 6 #num = math.abs(int(raw_output("Enter the number ")) no = int(raw_input("Enter the number ")) num = math.abs(no) print ("Absolute number is ",num)
5979f2ab84ecc3ffc2d906e05d03e84fba9690c4
qa-policy/nev1
/nev_first.py
415
3.890625
4
numA = input("Enter the first number: ") numB = input("Enter the second number: ") num_sum = int(numA) + int(numB) num_div =int(numA) / int(numB) num_mult = int(numA) * int(numB) num_sub =int(numA) - int(numB) print("%s + %s = %s" % (numA, numB, str(num_sum))) print("%s / %s = %s" % (numA, numB, str(num_div))) print("%...
a24e51a20fd05abe2a8981e0595c4ec05468d9e6
bkim1/cs1
/midterm_1/replace_characters.py
429
3.859375
4
#! /usr/bin/env python #You are allowed only to create new lines, #not to delete or change the lines already in the code # Author: Branden Kim # 3b def replace_characters(string, a, b): new_word = "" i=0 while i<len(string): if string[i] == a: new_word += b else: n...
f4914668231ff9e9d207eda5abc42a50a5723b33
czqzju/leetcode
/July 2020/Arranging Coins.py
369
3.59375
4
class Solution(object): def arrangeCoins(self, n): """ :type n: int :rtype: int """ level = 0 row = 1 if (n == 0): return 0 else: while (n >= row): n -= row row += 1 level += 1 return ...
1a07ca06d6aee13527801ce58aadbb4f09aa8249
idanfadlon/final-project-numerical-analysis
/Q26/main.py
10,468
3.8125
4
import TableIt from datetime import * # create Identity matrix def identity_matrix(size): I = list(range(size)) for i in range(size): I[i] = list(range(size)) for j in range(size): if i == j: I[i][j] = 1 else: I[i][j] = 0 ...
5523b053d642fed63acb4c14346d6f48e3da9e73
Mastercoder96/Excercism-Code-Solutions
/strings.py
402
3.515625
4
def add_prefix_un(word): return "un" + word def make_word_groups(vocab_words): return(" :: " + vocab_words[0]).join(vocab_words) def remove_suffix_ness(word): base = word[:-4] if base[-1] == 'i': return base[:-1] + 'y' return base def noun_to_verb(sentenc...
b3f8f72f24469736babf68ad235c0a047853a2bb
JsFlo/ConvolutionalNeuralNetwork-TF
/MnistTraditionalCNN.py
4,520
3.609375
4
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) # used for print...
e7c23ceb96751de68ded22f572782acbb76e0dd7
OmerHefets/python_studying
/lazy_student/lazy_student.py
3,485
4.03125
4
import sys import os HOMEWORK_FILE = 1 SOLUTION_FILE = 2 VALID_FILENAME = "homework.txt" SOLUTION_FILENAME = "solution.txt" VALID_OPERATIONS = ["+", "-", "*", "/"] def check_for_errors(path): with open(path, "r") as file: wrong_equation_indexes = {} line_index = 0 for line in file: ...
f27fd42af016f484f95cd66531b050d66d12d24c
Arjuna1513/Python_Practice_Programs
/AllAboutLists/SortedLists.py
935
4.3125
4
"""list1 = [11, 22, 1, 5, 99, 33, 29] sorted(list1) for item in list1: print(item, end='\t') the above did not print sorted list because when sorted method is used it will sort the items present in a list and puts that in to a new list i.e. it creates new list and puts the sorted elements hence the a...
75171d0f3005e4410f4ab3cc5134f8a7a7c4ac31
lokendra7512/Project-Euler-Solutions
/1001_prime.py
257
3.71875
4
primes = [2] no = 3 while (len(primes) != 10001): prime_number = True for x in primes: if no % x == 0: prime_number = False break if(prime_number): primes.append(no) no = no + 1 print primes[10000]
6aa9b8d7eee8176d1925447ce165c86ee691b28b
Dev4life007/Python_codes
/operators3.py
231
4.3125
4
Value = float(input("Please enter a Value to raise ")) Power = float(input("Please enter the raising factor ")) result = Value ** Power output = "The " + str(Power) + " power of " + str(Value) + " is:" + str(result) print(output)
92e6b8997b10db637f0932daa8de75e65b4f82f1
scace006/MazeSolver-Python
/MazeSolver.py
7,222
3.828125
4
from tkinter import * import random window = Tk() width, height = 0, 0; current_x, current_y = 0, 0; win_x, win_y = 0, 0; origin_x, origin_y = 0, 0; maze = [[]] move = [] index = 0 over = False #MAIN METHOD #Open file. Populate Maze list. Print current map. Call surroundings() #------------------------...
0d57d9bb9134f1af2a62633bab40f9018648aa06
syedmeesamali/Python
/5_Homeworks/2_Exercise Tracker/Exercise_Tracker_Task 2.py
1,807
3.609375
4
#csv library can be used to parse the csv files import csv with open('clientRecords.txt') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 for row in csv_reader: if line_count == 0: print(f'Column names are {", ".join(row)}') line_count += 1 ...
d9e8b7b3c72585a73d14f02d1b735fc8c23c4dca
maxotar/datastructures
/tests/test_binaryTree.py
2,930
3.515625
4
from datastructures.binaryTree import BinaryTree def test_creation(): root = BinaryTree(7) assert root.data == 7 assert root.left is None assert root.right is None def test_insertion(): root = BinaryTree(0) root.insertRight(2) root.insertRight(1) assert root.right.data == 1 asser...
a2d20e8d69d6d5a14224a1d7c7c51145ba9bf923
eng-arvind/python
/while.py
268
3.859375
4
c=5 while c<=10: print(c,end=" ") c +=1 c=10 print() while c>=5: print(c,end=" ") c -=1 s=int(input("Enter start number:")) l=int(input("Enter last number:")) while s<=l: if(s%2==0): print(s,end=" ") s += 1
216ddf788d4019fd83f1385fc29b1a17535f2e07
mateuskienzle/training-python
/ex-050-soma-dos-pares.py
495
3.78125
4
soma = 0 cont = 0 for c in range(1, 7): n = int(input('Digite o {}º número: ' .format(c))) if (n%2==0): soma = soma + n cont = cont + 1 if soma == 0: print('Você não informou nenhum número par, portanto a soma é igual a zero.') else: if cont == 1: print('Como você só digitou {} ...
5c7bf6be88f0c9ecb263a7ffc97cd245ea5b70fb
ouuzannn/BelajarPandas
/pandastutor02/pandas06.py
284
3.828125
4
import pandas as pd import numpy as np row = 5 col = 5 cols = tuple('ABCDE') df = pd.DataFrame(np.random.randint(1, 10, size=(row,col)),columns=cols) print(df) #cara mengubah nama kolom df = df.rename(columns={'C':'Hobi','A':'contoh'}) print(f'hasil perubahan nama kolom :\n{df}')
2f03d87c786cf1342a6d598f745de25100996621
helloworld755/Python_Algorithms
/dz3_task6.py
753
3.734375
4
# В одномерном массиве найти сумму элементов, находящихся между минимальным и максимальным элементами. # Сами минимальный и максимальный элементы в сумму не включать. import random a = [] for i in range(0, 10): a.append(random.randint(0, 100)) min_pos = 0 max_pos = 0 for i in range(0, 10): if a[i] == max(a)...
a5c6275a6df78b640adcaf949a2eec26d636ebe9
danivijay/python-lycaeum
/example 5-12-18.py
1,506
3.6875
4
def fizzbizz(n): for i in range(1, n+1): if i % 3 == 0: print("fizz") elif i % 5 == 0: print("bizz") elif i % 15 == 0: print("fizzbizz") else: print(n) def num_digits(n): print (len(str(n))) def num_words(s): print (len(s.spli...
a8e39c74f39d61b8010f35850a0cc31f7f652d79
ekarademir/algorithms_cormen_book
/ch2/insertion_sort_binary_search.py
743
4.15625
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- from random import seed, shuffle def insert(arr, val): if len(arr) == 1: if arr[0] < val: return arr + [val] else: return [val] + arr mid = len(arr) // 2 if arr[mid] > val: return insert(arr[:mid], val) + arr[mid:]...
46db9000f5b7cd74c76bd395d660be6107e7496e
nerdiejack/Basics_of_Linear_Algebra_for_Machine_Learning
/vector_norms.py
322
3.515625
4
# vector L1 norm from numpy import array from numpy.linalg import norm from math import inf # a = array([1, 2, 3]) # print(a) # l1 = norm(a, 1) # print(l1) #vector l2 norm # a = array([1, 2, 3]) # print(a) # l2 = norm(a) # print(l2) # vector max norm a = array([1, 2, 3]) print(a) maxnorm = norm(a, inf) print(maxnorm)...
491870ab13bb854ebe7c207d73fd282d9c828436
Aunik97/Iteration
/task 1 improving a piece of code.py
187
4.125
4
total = 0 for count in range(1,9): number = int(input("Please enter number")) total = number + total print("The total of these numbers is {0}.".format(total))
55bf4f9d4cd50c40318c3ed8c63cdcbeda244b65
addtheletters/HS-AI
/quarter1/vector.py
3,857
3.59375
4
class Cost(): def cost(self): from math import sin if(0 < self._data[0] < 10) and (0 < self._data[1] < 10): return (self._data[0] * sin(4*self._data[0]) + 1.1*self._data[1] * sin(2*self._data[1])) return float('inf') def sort(A,B,C): if B.cost() > C.cost(): B.swap(C) if A.cost() < B.cos...
d5f58af240ebf5d4b9022def2abc6cbf46a472b1
rishabhranawat/challenge
/30DaysLC/backspace_str_compare.py
643
3.625
4
from collections import deque class Solution(object): def backspaceCompare(self, S, T): """ :type S: str :type T: str :rtype: bool """ firstS = self.getCleanString(S) secondT = self.getCleanString(T) return firstS == secondT def getCleanString(self, S): first = deque([]) for i in range(0, len...
df45cc51e7fec7896da39a14ab7b84abbffdac40
llenroc/hackerrank-practice
/Data Structures/Trees/Tree - Preorder Traversal/solution.py
777
3.90625
4
""" Node is defined as self.left (the left child of the node) self.right (the right child of the node) self.data (the value of the node) """ def preOrder(root): if root is None: return fringe = list() string_output = str(root.data) if root.right is not None: fringe.append(...
ac7bf48112de33e202a12daa3420955abae66dcd
willymwai/crunchcrawl
/scratchpad.py
10,026
3.6875
4
# This is a collection of Python code snippets I use to transform the data # Takes the raw list of company information, and turns it into a CSV file import os, sys, csv try: import simplejson as json except ImportError: import json def getSafe(input): if input is None: return '' else: ...
68337db3ba7146826d1f08d2a2c0d3ce498fa366
yddgit/hello-python
/advanced_oop.py
20,072
3.8125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # 面向对象高级特性:多重继承、定制类和元类 # 使用__slots__ # 正常情况下,定义并创建一个class的实例后,可以给该实例绑定任何属性和方法,这是动态语言的灵活性 class Student(object): pass s = Student() # 给实例绑定一个属性 s.name = 'Michael' print(s.name) # 给实例绑定一个方法 def set_age(self, age): self.age = age from types import MethodType s.set...
f7f52b9fc7d3cdcc75c9ec2502efcdb3c28052a3
LuckyLub/python-fundamentals
/src/03_more_datatypes/1_strings/04_03_vowel.py
520
4.25
4
''' Write a script prints the number of times a vowel is used in a user inputted string. ''' string=input("Give me some text, and i'll tel you how many vowels are in there.") vowels=['a','e','u','i','o'] def count_letters(string, letters): string=list(string) for i in letters: count = 0 for...
98c417875c4c7a8c7a15f97108f2301f611f7fdb
respectus/Euler-Problems
/problem88.py
1,477
3.78125
4
""" Product-sum Numbers Project Euler Problem #88 by Muaz Siddiqui A natural number, N, that can be written as the sum and product of a given set of at least two natural numbers, {a1, a2, ... , ak} is called a product-sum number: N = a1 + a2 + ... + ak = a1 × a2 × ... × ak. For example, 6 = 1 + 2 + 3 = 1 × 2 × 3. ...
9f4f7a86c46036f9a73932802bdc72d39b36aec2
Aasthaengg/IBMdataset
/Python_codes/p02743/s203731267.py
172
3.546875
4
def LI(): return list(map(int, input().split())) a, b, c = LI() if c-a-b < 0: ans = "No" elif 4*a*b < (c-a-b)**2: ans = "Yes" else: ans = "No" print(ans)
92f37b8ebf115eb530600d6a17f6ca38d547fa85
jacksonsuciadyy/basic-python-1
/Tugas-1/Soal-1.py
207
4
4
nama = input("Nama Anda siapa? ") umur = int(input("Umum Anda berapa? ")) tinggi = float(input("Tinggi Anda berapa? ")) print("Nama saya {}, Umur saya {} tahun dan Tinggi saya {} cm.".format(nama, umur, tinggi))
125c8a913d719a7dc8365144e2b4490587cffe1d
surya-pratap-2181/python-all-programs
/pattern_N.py
267
4.03125
4
n = int(input("Enter rows: ")) for row in range(1, n+1): for col in range(1, n+1): if (row == col): print('*', end='') elif(col == 1 or col == n): print('*', end='') else: print(' ', end='') print()
27948b73e8f311aa7982df4186ea114529872acc
songzi00/python
/Pro/进阶/02递归与时间模块/.idea/目录遍历.py
509
3.75
4
import os # 1,递归遍历目录 def getall(path): #建立函数 fileslist = os.listdir(path) # os.liststr()函数:得到当前目录下所有的文件,赋予给变量 for filename in fileslist: if os.path.isdir(os.path.join(path,filename)): print("目录: ",filesname) else: print("文件: ",filename) print(fileslist) #打印变量 ...
496104083b2687825540cf056d33b3b9ecbfe48e
allenwest24/HackerRank
/Strings: Making Anagrams/solution.py
644
3.71875
4
#!/bin/python3 import math import os import random import re import sys # Complete the makeAnagram function below. def makeAnagram(a, b): a = list(a) b = list(b) ii = 0 jj = 0 while ii < len(a): jj = 0 while jj < len(b): if a[ii] == b[jj]: b.pop(jj) ...
7778764c37eee9770e416ba3723a391c0d74ca92
muhammad-basil1/SP
/Lab_6/q6.py
92
3.609375
4
str=raw_input("Enter String: ") l = str.split(" ") s=set(l) l1 = list(s) l1.sort() print l1
b17ffda37b04296e55a05adeb311273c3034222b
DanElias/ACM-CODE
/python/Meta_Queue_Removals.py
2,543
3.59375
4
import math # Add any extra import statements you may need here from operator import itemgetter # Add any helper functions you may need here def findPositions(arr, x): q = [(v, i) for i, v in enumerate(arr, start=1)] output = [] for _ in range(x): tmp = q[:x] max_item = max(tmp, key=itemgetter(0)) o...
883459b51d4638bf54a8e60d3530efdb080697ed
samtraylor/CMPS-1500
/lab6pr2.py
4,162
4.375
4
import random def merge_sort(aList): """ Merge sort recursively divides the list into half, sorts both halves and then merges the two sorted lists into one. """ # If the aList is size 0 or 1, it's already sorted. if len(aList) <= 1: return aList else: mid = len(aList) // 2 ...
c6c3cc1b8f1e6142c254251a7f21aa3ec40bd5a9
Xia-Dai/Data-exploration-Python
/countchar_quiz.py
459
3.765625
4
# -*- coding: utf-8 -*- """ Created on Fri Jan 20 17:05:41 2017 @author: Daisy Email: dxww01@gmail.com Never too late or old to study! """ #count alpha def countchar(str): list1 = [0]*26 for i in range(0,len(str)): if (str[i] >= 'a' and str[i] <= 'z'): list1[ord...
f38883d028e820a87834663fa41fd2612ad1c786
adityaprasann/PythonProj
/dsfunnexercise/bheap.py
1,589
3.546875
4
class BinHeap: def __init__(self): self.heapList = [0] self.currentSize = 0 def insert(self,ele): self.heapList.append(ele) self.currentSize = self.currentSize + 1 self.percUp(self.currentSize) def percUp(self, idx): while idx // 2 > 0: cur = sel...
4b63903713891759264ec5cdcefee55063733649
mikechen66/NiN_TF2
/keras_nin_network/nin_func.py
2,901
3.65625
4
# nin.py """ NIN(Network in Network) is the creative DNN model in which GAN(Global Averag Pooling) is adpted to elimitate the large quantity of parameters. It deals with 10 label classes. In contrast, AlexNet deep learning structure is a combination of CNN+FC that incurs a huge RAM occupation. CNN is responsible f...