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
29c60efe0b91a9c74c2eebe4d9ce599a8c52ba7f
vishalkmr/Algorithm-And-Data-Structure
/Linked Lists/Cyclic.py
1,733
4.21875
4
''' Check the given limked-list is cyclic or not ''' from LinkedList import LinkedList #using Set def is_cyclic(linked_list): """ Returns True if linked-list is cyclic Syntax: is_cyclic(linked_list) Time Complexity: O(n) """ # if linked-list is empty if not linked_list.hea...
c18c3fc29396eeb7a53380ea7ea301c74fb9566f
xiangxiyun/stanford_machine_learning
/linear_regression_python/ex1.py
1,807
4
4
import numpy as np import matplotlib.pyplot as plt from linear_regression_python.linear_regression import LinearRegression def read_data(filename): ''' read in training data :param filename: string :return: numpy array ''' training_data_set = [] with open(filename) as inputfile: ...
25ed805c41dfb6c37ec66c83e0d1471592628d86
VaishnaviVV/hacktoberfest2021
/Python/Subarray_with_sum_0.py
758
3.84375
4
#User function Template for python3 class Solution: #Function to check whether there is a subarray present with 0-sum or not. def subArrayExists(self,arr,n): s=set() sum1=0 for i in range(0,n): sum1+=arr[i] if sum1==0 or sum1 in s: return Tru...
7828d05a50a5fd33d6112e204228dbeccb97d458
ChristopherCarson/MULTIMEDIA-DESIGN
/LAB7/LAB7.py
14,132
3.734375
4
import math def get_pic(): return makePicture(pickAFile()) #WARMUP #Find an image of the desert and draw a snowman on it. #You can just do three white circles on top of each other, or go crazy. It is up to you. def snowMan(): pic = get_pic() x = getWidth(pic) y = getHeight(pic) #the first circle is the top ...
82008b8f27a2a9989671d0e3e385cd7012462b3a
ChristopherCarson/MULTIMEDIA-DESIGN
/LAB12/lab12.py
15,902
3.5625
4
#Lab 12 #Team Code Blooded import time import array #global setup end = false #Variable to flag whether the player wishes to end the game and exit. lose = false #Variable for the lose condition win = false #Variable for the win condition correctInput = ["NORTH", "EAST", "SOUTH", "WEST"] #Initiate a two demonsiaonl arr...
6725a2a9ac0ca33297687a2253d25daa134f729e
krishnaramya/student-teacher
/utils/FileReaders.py
2,038
3.8125
4
import pandas as pd from pyarrow.parquet import ParquetFile import os class Reader(): """ A class is used for Reading the files and convert the files into DataFrames using generators Attributes ---------- chunksize : int Used to return the data in chunks. Methods ------- file...
2c68ed20901619c93032ec3824e1fd592cd2df9e
swhh/python_project
/problem_3.py
1,640
3.640625
4
import random from sys import argv, exit from collections import namedtuple, defaultdict Graph = namedtuple('Graph', ['V', 'E']) def random_contraction_algorithm(graph): n = len(graph.V) new_graph = graph while n > 2: edge = random_select(new_graph) new_graph = merge(graph, edge) ...
03380200db3e691de45b6ccbfd4bedbe9eaa10ed
swhh/python_project
/algofinal7.py
8,090
4.15625
4
# # This is the same problem as "Distance Oracle I" except that instead of # only having to deal with binary trees, the assignment asks you to # create labels for all tree graphs. # # In the shortest-path oracle described in Andrew Goldberg's # interview, each node has a label, which is a list of some other # nodes i...
44ecd50a2f0e0a6cc72a7c9b24ec9d468ac0f351
bintangbhp/dasar-pemrograman-1
/lab/lab02/lab02/lab02b.py
760
3.578125
4
# Author: Bintang Hari Pratama # File name: lab02b.py # menggunakan simultaneous assigment untuk; # mengurutkan data # 5 variabel dengan nilai sbb: number1 = 25 number2 = 7 number3 = 3 number4 = -8 number5 = 19 # output yang diminta: 25 7 3 -8 19 print ("Initial data: ") print (number1, number2, number3...
ea402428794a71e381266fdac172b0f6a2e5b105
prpratheek/Interview-Problem-Statements-HacktoberFest2020
/Power_Function.py
417
4.34375
4
def power(x, y): res = 1 while (y > 0): # If y is odd, multiply # x with result if ((y & 1) == 1) : res = res * x # n must be even # now y = y/2 y = y >> 1 # Change x to x^2 x = x * x ...
6eef64be048f618cb3fd6c301da3b9249f559ac8
DivAnanand/MachineLearning
/neural_net.py
4,401
4.15625
4
"""This file contains my personal implementation of a simple neural network with forward and backward propogation that I used for several machine learning projects """ import numpy as np from neural_net_help import create_weight_mat, activate, sig_deriv, visualize_cost class Neural_Network: """Class for neural netw...
e7031c80ded17dd51aef5721e15b115f383cb735
liketheflower/python_advanced
/class_practise.py
608
3.78125
4
""" class Foo(object): def __init__(self, func): self._func = self.func def __call__(self): print("class decorator runing") self._func() print("class decorator ending") @Foo def bar(): print("bar") def test(): print("test") a = Foo(test) a.bar() """ from...
99125ef76edab06a0024665d102c6a0034e69989
seabayley/Intro-Python-I
/src/05_lists.py
837
4
4
# For the exercise, look up the methods and functions that are available for use # with Python lists. x = [1, 2, 3] y = [8, 9, 10] # For the following, DO NOT USE AN ASSIGNMENT (=). # Change x so that it is [1, 2, 3, 4] x.append(4) print(x) # Using y, change x so that it is [1, 2, 3, 4, 8, 9, 10] x.extend(y) print(...
2d92c3742cbd6ca1f27cc8b0ce64b7798765d079
IgnatIvanov/To-Do_List_JetBrainsAcademy
/Problems (7)/Healthy Habits/main.py
157
3.515625
4
# the list "walks" is already defined # your code here summary = 0 for dist in walks: summary += dist.get("distance") print(int(summary / len(walks)))
302cdcad57fb9187cacc9b4bd4f6511a294da634
GodfreyPerania/Python-Project
/Calculator.py
1,013
4
4
#Calculator #Godfrey D. Perania #https://github.com/GodfreyPerania #gperania@gmail.com print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") print("5.Close") def GF(): GDP = input("Enter Choice:") if GDP == 1: a = input("FIRST NUMBER: ") b = input("SECOND ...
cfd03056c67f3186b7158dd26d62995cf2bf7ad8
Damoy/AlgoTraining
/LeetCode/LinkedListMiddleNode.py
402
3.8125
4
class ListNode: def __init__(self, x): self.val = x self.next = None def middleNode(self, head): length = 0 current = head while current is not None: length += 1 current = current.next ptr = 0 current = head while ptr < length // 2: current = current....
8177db99d1caec6271b1678143b13f303db7bf9d
Damoy/AlgoTraining
/AlgoExpert/src2/python/SuffixTrie.py
1,168
3.84375
4
class SuffixTrie: def __init__(self, string): self.root = {} self.endSymbol = "*" self.populateSuffixTrieFrom(string) # Time O(n^2) | Space O(n^2) def populateSuffixTrieFrom(self, string): n = len(string) for i in range(n): suffix = string[i:n] ...
6a463df92ad6aa88b0036c7e8ed0c6b730c46583
Damoy/AlgoTraining
/AlgoExpert/src2/python/MinMaxStack.py
1,161
4.0625
4
class MinMaxStack: def __init__(self): self.minMaxStack = [] self.stack = [] def peek(self): return self.stack[len(self.stack) - 1] def pop(self): self.minMaxStack.pop() return self.stack.pop() def push(self, number): newMinMax = {"min": number ,"max...
581b330b035116f65deff62cce81e45b87b397c9
Damoy/AlgoTraining
/LeetCode/ValidParenthesisString.py
686
3.515625
4
def checkValidString(s: str) -> bool: left = 0 right = 0 for c in s: left += 1 if c == '(' else -1 right += 1 if c != ')' else -1 if right < 0: break left = max(left, 0) return left == 0 print(checkValidString("") == True) print(checkValidString("()") == True...
961d6a03e60a5de40b2de65f9e3408d9f4e92091
Egemenclr/Bilimsel-Hesaplama
/euler_ve_heun.py
581
3.625
4
# coding: utf-8 # In[ ]: def f(x,y): return -y/x h=float(input("h:")) y4=3/4 sonuc=y4 iterasyon=int(input("kaca kadar")) for i in range(4,iterasyon): sonuc+=f(i,sonuc)*h sonuc # In[9]: def f(x,y): return -y/x h=float(input("h:")) y4=3/4 t=y4 sonuc3=y4 iterasyon=int(input("kaca kadar")) for i in rang...
d9f99e25b778b0bbca89c7c30fa998de65c9c1ac
nswarner/poker
/hand.py
1,061
3.75
4
#!/usr/bin/python3 from card import Card from logger import Logger class Hand: hand = None def __init__(self, num_cards = 2): Logger.log("Hand: Creating a new hand with cards: " + str(num_cards)) self.hand = [] for i in range(0, num_cards): Logger.log("Hand: Calling add_c...
dcbf4c6dd024be52b898302032d650b563a8ebfe
TranVanDuc7TH2/TranVanDuc7TH2
/sohoc.py
392
3.515625
4
#!/usr/bin/env python a = input('Nhap a: ') b = input('Nhap b: ') print "-----------------"; print "a=", a print "b=", b print "-----------------"; print "Tong hai so: ", a+b print 'Hieu hai so: ', a-b print "Tich hai so: ", a*b if b==0: print "Khong the chia cho 0"; else: print "Thuong hai so: ",a,"/",b,"=", a/b pr...
65474add9fea7d86cbbdfa0f7c7e3ef595a8d938
Booharin/lesson_4
/task_2.py
254
3.53125
4
def getCorrectList(): my_list = [i for i in [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55]] print(my_list) correct_list = [item for i, item in enumerate(my_list) if i > 0 and item > my_list[i - 1]] print(correct_list) getCorrectList()
a2116f540a7b451fe73796662d68ba738b31d7ec
ByMorata/IBS2.8_Patch_000
/04_IO编程/0002_yield.py
1,276
3.890625
4
from collections import deque import time def student(name, homeworks): for homework in homeworks.items(): yield (name, homework[0], homework[1]) # 学生"生成"作业给老师 class Teacher(object): def __init__(self, students): self.students = deque(students) def handle(self): index_00 = len(...
63dc917df1da2d252c4568590a45c7120e454873
zhangpanzhan/leetcode-solution
/20120403 Text Justification.py
2,308
3.78125
4
''' Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly L ...
1aae5543dbd4f18e9b2321876948dbd6ee925214
zhangpanzhan/leetcode-solution
/20120316 Jump Game II.py
762
3.984375
4
''' Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. For example: Given array A = [2,3,1,1,4] The minim...
0817a66e298483ce334d15bd2ceb07c007359fef
zhangpanzhan/leetcode-solution
/20120316 Permutations II.py
964
3.890625
4
''' Given a collection of numbers that might contain duplicates, return all possible unique permutations. For example, [1,1,2] have the following unique permutations: [1,1,2], [1,2,1], and [2,1,1]. ''' class Solution: # @param num, a list of integer # @return a list of lists of integers def per...
4645411677b30f560e0689a3d86de800c897cf0e
zhangpanzhan/leetcode-solution
/20120327 Spiral Matrix II.py
755
3.9375
4
''' Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For example, Given n = 3, You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ] ''' class Solution: # @return a list of lists of integer def generateMatrix(self, ...
f56742594244dcc5edf17389b2b7d9c8621dbb81
zhangpanzhan/leetcode-solution
/20120901 Recover Binary Search Tree.py
1,158
3.78125
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None ''' Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Note: A solution using O(n) space is pretty straight forward. Could you ...
38362c3b3c9f3bffcb47e8254da5b229cc578b55
zhangpanzhan/leetcode-solution
/20120214 Swap Nodes in Pairs.py
1,199
4.09375
4
class ListNode: def __init__(self, x): self.val = x self.next = None ''' Given a linked list, swap every two adjacent nodes and return its head. For example, Given 1->2->3->4, you should return the list as 2->1->4->3. Your algorithm should use only constant space. You may not modify the ...
90bf201950d6424dd205b2551e0b3321e4c30286
zhangpanzhan/leetcode-solution
/20120319 Anagrams.py
682
3.953125
4
''' Given an array of strings, return all groups of strings that are anagrams. Note: All inputs will be in lower-case. ''' class Solution: # @param strs, a list of strings # @return a list of strings def anagrams(self, strs): ans, dt = [], {} for i in range(len(strs)): ...
c72c3f2159565a446a765fc8534778cc6dcc9bc0
zhangpanzhan/leetcode-solution
/20120415 Minimum Window Substring.py
1,303
3.96875
4
''' Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). For example, S = "ADOBECODEBANC" T = "ABC" Minimum window is "BANC". Note: If there is no such window in S that covers all characters in T, return the emtpy string "". If there ...
439a0e99d4c22bbb5f992cba692b5c48332a7603
JKDMarks/adventofcode
/2020/day16/solution.py
3,007
3.546875
4
import re from functools import reduce from pdb import set_trace as db with open("raw-input.txt") as f: input = f.read().split("\n\n") test_str = """class: 1-3 or 5-7 row: 6-11 or 33-44 seat: 13-40 or 45-50 your ticket: 7,1,14 nearby tickets: 7,3,47 40,4,50 55,2,20 38,6,12""" test_input = test_str.split("\n\n...
25168cc955eb2d80e09b7d63b149eabc63812a13
PdxCodeGuild/Full-Stack-Day-Class
/demos/web-getter/web-getter.py
331
3.71875
4
"""Download a URL specified on the command line and prints the result. USAGE: webgetter.py URL """ import sys import requests def main(): """Get URL from command line, download contents, print result.""" url = sys.argv[1] response = requests.get(url) print(response.text) if __name__ == '__main__': ...
967ac148b13a59295b9c16523e6e046ffd000950
PdxCodeGuild/Full-Stack-Day-Class
/practice/solutions/ttt-interface/list_board.py
1,184
4.1875
4
"""Module containing a list of lists tic-tac-toe board implementation.""" class ListListTTTBoard: """Tic-Tac-Toe board that implements storage as a list of rows, each with three slots. The following board results in the following data structure. X| | |X|O | | [ ['X', ' ', ' '],...
a7609411394e71a497ae95ea4e7c527b238bbe1f
PdxCodeGuild/Full-Stack-Day-Class
/practice/solutions/table-pretty-print.py
3,002
4.40625
4
"""Reads in a text file, which is a matrix of words, then pretty prints them so each column is of equal width with borders. """ def read_file_into_rows(filename): """Read a given file and parse each line into space separated rows. The return value will be a list of rows of cells. [['row1item1', 'row1ite...
f0d770c8d61e31ec23f0f7859ac943175b28411c
an219-creator/python-essentials
/W4HW6.py
294
3.90625
4
import math def IsPrime(n): i = 2 k = int(n ** 0.5) while i <= n: t = n % i if t == 0: return i elif i > k: return n else: i += 1 n = int(input()) y = IsPrime(n) if y == n: print('YES') else: print('NO')
b7fa7be9d4f3e5c10e99f654726cca31852109ff
jonwk/Python-Stuff
/Images/Word_Matrix_Problem.py
474
3.515625
4
from PIL import Image # load both the given images word_matrix = Image.open("word_matrix.png") mask = Image.open("mask.png") # convert both the images into same size matrix_x,matrix_y=word_matrix.size mask = mask.resize((matrix_x,matrix_y)) # make mask a bit transparent mask.putalpha(100) # put transparent-ish mask...
27ec6b07c740c3995f36da736229a2762851873b
jonwk/Python-Stuff
/Advanced Objects and Data Structures/4. Advanced Dictionaries/advDictOverview.py
455
3.6875
4
{x:x*2 for x in range(10)} # {0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18} d = {'k1':1,'k2':2} for k in d.keys(): print(k) # k1 # k2 for v in d.values(): print(v) # 1 # 2 for item in d.items(): print(item) # ('k1', 1) # ('k2', 2) key_view = d.keys() key_view # dict...
8ce55c9978b782a1d26dc2e944bec26b61292653
jonwk/Python-Stuff
/Advanced Objects and Data Structures/2. Advanced Strings/advStrOverview.py
797
3.65625
4
str = 'ez clap' str.capitalize() # 'Ez clap' str.upper() # 'EZ CLAP' str.lower() # 'ez clap' str # 'ez clap' str = str.upper() str # 'EZ CLAP' str = str.lower() str # 'ez clap' # returns the number of occurrences, without overlap str.count('z') #...
805bd3c28571150e8618f4ac78e6d7504d7507f7
rengeten/lesson1
/homework/list_changer.py
82
3.6875
4
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for number in numbers: print(number + 1)
a5e9f1bcc004edd94f3a0babd86101280be5be40
rengeten/lesson1
/homework/ask_user.py
178
3.5
4
def ask_user(message, right_answer): while True: user_answer = input(message) if user_answer == right_answer: print('Bye Bye') break ask_user('How are you?', 'Fine!')
15ddcdc1ad2f7dfc4e5b800806342c4b1dbfad54
niknibud-student/python_study
/Foxford/lesson6/mouse_event.py
453
3.6875
4
from tkinter import Tk def b1(event): root.title('Нажата левая кнопка мыши') def b2(event): root.title('Нажата правая кнопка мыши') def move(event): x = event.x y = event.y root.title('Движение мышью {}x{}'.format(x, y)) root = Tk() root.minsize(width=500, height=500) root.bind('<Button-1>',...
b3bffd4e2299e28c2d14e570b147ac900e00db1f
niknibud-student/python_study
/others/0.py
506
3.625
4
from tkinter import Tk, Canvas root = Tk() canvas = Canvas(width=500, height=500) oval = canvas.create_oval(20, 40, 70, 90, fill='orange') canvas.pack() #point1 = canvas.create_oval(45-2, 30-2, 45+2, 30+2, fill='black') #point2 = canvas.create_oval(20-2, 40-2, 20+2, 40+2, fill='black') #point3 = canvas.create_oval(80...
422d3559fd67cc2f672ac9fe3d9a2f70e8317873
niknibud-student/python_study
/Foxford/lesson5/radiobutton.py
657
3.515625
4
from tkinter import Tk, Label, IntVar, Radiobutton, W root = Tk() root.title("GUI на Python") root.geometry("300x250") header = Label(text="Выберите курс", padx=15, pady=10) header.grid(row=0, column=0, sticky=W) lang = IntVar() python_radiobutton = Radiobutton(text="Python", value=1, variable=lang, padx=15, pady=1...
2d5c71401d00854ea5790d57fb2fd4a646e2a713
Mensel123/Dataprocessing
/Homework/Week_1/visualizer.py
933
3.9375
4
#!/usr/bin/env python # Name: Mendel Engelaer # Student number: 10996222 """ This script visualizes data obtained from a .csv file """ import csv import matplotlib.pyplot as plt # Global constants for the input file, first and last year INPUT_CSV = "movies.csv" START_YEAR = 2008 END_YEAR = 2018 # Global dictionary f...
52ccaaf4670159b6615c92e5c5f1b36a73ce3671
BogyMitutoyoCTL/Sophy
/source/TimeDifference.py
277
3.640625
4
""" Calculate time difference from two times """ from datetime import datetime from datetime import timedelta class TimeDifference: def __init__(self): pass def calculate(self, time1: datetime, time2: datetime) -> timedelta: return time2 - time1
1ecff7f04e87d017d13f49b3266b12b59b5c37c3
gitynity/MyProject
/ENCRYPTION-DECRYTION/encrypt.py
1,700
3.578125
4
import os import base64 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC from cryptography.fernet import Fernet password_provided = input("Enter the password based on which a key will be generate...
6cdeccb517347b61628b8eb557629e6fcaed600f
cww33/Final-Project
/subscription.py
6,915
4.34375
4
import csv def to_usd(my_price): """ Converts a numeric value to usd-formatted string, for printing and display purposes. Parameters: my_price (int or float) Example: to_usd(99999.99) Returns: $99,999.99 """ return f" ${my_price:,.2f}" def line(): """ Prints a solid line to mak...
913e2dde64fa3beb29dfea3606d5082b81e29728
Knightrider02/fun-projects
/Guess_the_number.py
595
4.03125
4
import random playing = "Yes" answer = "Yes" while playing != "No": number = random.randint(1, 21) guess = int(input("Guess a number from 0 to 20: ")) if guess == number: print("You're correct") if guess > number: print("The number you guessed is too large") if guess < numb...
578ac24c846f5585168f193031deca297f622bfc
ra5ika27/Algorithmic-Problem-Solving
/chief_hopper.py
587
3.65625
4
#!/usr/bin/env python3 from sys import stdin N = int(stdin.readline().strip()) heights = [int(x) for x in stdin.readline().split()] def checker(E): for h in heights: if E < 0: return False E = 2*E - h return E >= 0 min_energy_upper_bound = max(heights) min_energy_lower_bound = 0 ...
53257134368a38f9defd6b41212a6e66c90f8a48
ra5ika27/Algorithmic-Problem-Solving
/interval_selection.py
637
3.65625
4
def interval_selection(N,intervals): intervals.sort(key=lambda x:(x[1],x[0])) selected = [intervals[i][1] for i in range(N)] flag = [1 for i in range(N)] for i in range(N): count = 0 for j in range(N): if flag[j]: if intervals[j][0] <= selected[i] and interva...
2053184d473870a54cdbc224cea9446fdf0f4420
jjvillavicencio/BaseDatosPython
/MySql/3. Crear_Tabla.py
515
3.546875
4
#!/usr/bin/python # -*- coding: UTF-8 -*- import MySQLdb # Establecemos la conexión con la base de datos bd = MySQLdb.connect("localhost","root","root","prueba_db" ) # Preparamos el cursor que nos va a ayudar a realizar las operaciones con la base de datos cursor = bd.cursor() # Creamos la tabla empleado sql = "CR...
e1e2214e8747054871f62d99a7d4f2e80fed7cea
racheldosh/GoogleCodeJam2020
/parenting_partner_returns/parenting_partner_returns.py
3,453
3.78125
4
input_file = open("input.txt", "r") num_test_cases = int(input_file.readline()) """ Parenting partner activities Give a list of "activities", returns a string representing a schedule for the co-parents C and J that need to attend said activities. "Activities" are defined as parameter inputs of two ints, representing...
0a17df1cb72c9adeb9a587a6c8e32cbf9843be28
OmalleyTomas98/GraphicsProgrammingLABS
/lab10 python /lab10.py
3,711
3.796875
4
# (2) - Import OpenCV, numpy and matplotlib import cv2 import numpy as np import math from matplotlib import pyplot as plt # Change the following variables to any other two image names # (3) Download gmit images and define For example Pyramids1.jpg and .jpg imgName1 = 'palas1.jpeg' imgName2 = 'palas2.jpeg' #(14 Atte...
be2332f5bb637b6a6f6c96bd08ae18b84bfe39da
priyankamadhwal/MCA-101-OOP
/1- rightTriangle.py
482
3.828125
4
def rightTriangle(): ''' Objective: To print a right triangle of n asterisks. It comprises of four lines. ''' # Approach: Use a print statement for each line of output. print('*') print('**') print('***') print('****') def main(): ''' Objective: To print a right...
dfbcccebb4448a97b6524f6e7c12c29e1ec00fbd
priyankamadhwal/MCA-101-OOP
/3- sumUpTo.py
318
4.03125
4
def sumUpTo(n): ''' Objective: To find the sum of all the numbers from 1 to n. Input: n: A non-negative integer. Output: The sum of all numbers from 1 to n. ''' # Approach: sumUpTo(n) = n + sumUpTo(n-1) if n == 0: return 0 else: return n + sumUpTo(n-1)
dcc6eac9a830867df9b8bf1dbc28c592c4458990
priyankamadhwal/MCA-101-OOP
/14- bubbleSort.py
1,139
4.28125
4
def swap(lst, lowerIndex=0, pos=0): ''' OBJECTIVE : To swap the elements of list so that the largest element goes at the lower index. INPUT : lst : A list of numbers. lowerIndex : The lower index upto which swapping is to be performed. OUTPUT : List, with the correct el...
7d9b484c127be4b40a092130ffa68a3064351433
sarincr/Soft-computing-using-Python
/04.Knapsack.py
407
3.78125
4
import sys def knapsack(v, w, n, W): if W < 0: return -sys.maxsize if n < 0 or W == 0: return 0 include = v[n] + knapsack(v, w, n - 1, W - w[n]) exclude = knapsack(v, w, n - 1, W) return max(include, exclude) if __name__ == '__main__': v = [50,22,36,41,22,33] w = [3,5,...
ae4cc0234fb1ebd1fa03e69dc25c38602dfcd372
MagiaGroz/WebDevelopment
/w8/Hypotenuse/if/TestSystem.py
177
3.71875
4
n = int(input()) m = int(input()) if n==1 : if m==1: print("YES") else: print("NO") else: if m==1: print("NO") else: print("YES")
78868626540d2c4cd90afd6cf5af3caa642ffe44
youssefmamdouh/coursera_algorithms_course
/course1_toolbox/week2/fibonacci.py
290
3.78125
4
# Uses python3 def calc_fib(n): if (n <= 1): return n sequence = list() sequence.append(0) sequence.append(1) for index in range(2, n+1): sequence.append(sequence[index-1] + sequence[index-2]) return sequence[n] n = int(input()) print(calc_fib(n))
3b1cebf4580150578cad196049dc131332d7ca66
RuchitaPawar/Python-Assignment-1
/Assignment 1/Assignment1_8.py
142
4.03125
4
def printStar(value): for x in range(0,value): print('*', end=" ") number = input("Enter number:") num = int(number) printStar(num)
c7b8d47ba37eb37c6b4184ffb84251db978e04f4
wenyizheng/Aqua-shower-system
/浴室终端源码/controls/Clock.py
663
3.671875
4
import datetime import time from threading import Thread class Oclock(Thread): def __init__(self): Thread.__init__(self) def run(self): self.nowTime = datetime.datetime.now().strftime('%Y'+'年'+'-%b-%d'+'日'+' %H:%M:%S') class CountDownTime(Thread): def __init__(self): Thread.__init...
950e52f6557ee1170ab7937fcb802df1c37fb10e
Ryanwolff14/FizFuz
/fizfuz.py
276
4.0625
4
def printnumber(): for x in range(1,10000): if x%3 == 0 and x%5 == 0: print("fizfuz") if x%3 == 0: print("fiz") if x%5 == 0: print("fuz") else: print(x) printnumber()
d15acf18df91b5ccb94dfea7673df9130aa57142
zosand123/web1
/python/1028-1.py
1,457
3.828125
4
a=" blue red green " # print(len(a)) #길이 # print(a) # print("안녕") # print("["+a.lstrip()+"]") #왼쪽여백없애기 # print("["+a.rstrip()+"]") #오른쪽여백없애기 # print("["+a.strip()+"]") #양쪽여백없애기 # # #a.replace('찾는 문자열','바꿀문자열') ->문자열치환 # print(a.replace(' ','')) #blueredgreen # print(a.upper()) # print(type(a)) #split하면 list됨---------...
855f57ff2f9d3e5d0d6964334d6c43ad0fd88833
xelendt/pytocpp
/test.py
635
3.90625
4
#import math #''' Implements # - Binary Operators # +, -, *, **, /, <<, >> # - Unary Operators # +, - # - Boolean Operators # >, <, >=, <=, == # - Assignments # int, float, bool, String # - Conditionals # if/elif/else # - Loops # While # ''' #for i in range (1, 10, 2): # a = 1 a = [1, 2.3, 4, 5, 6] d = 1.5 +...
f404e6b59c7e1b395005ab69d99ed95b9c8abd65
zhianwang/DNSC-6211-Programming_for_Business_Analytics
/Assignment6/A06P2_G33419803.py
1,692
3.5
4
# -*- coding: utf-8 -*- """ Created on Sun Nov 20 21:03:27 2016 @author: Zhian Wang GWID: G33419803 This program is used to call the fileinput, read and store, create and solve LP and produce the outputs. Besides the default output, user can choose other different outputs through '-t' and '-d'. """ import A06P2Modul...
9f7165d0f1d2a69415b626b78bb18db3b6d87b92
histuckyi/swuAlgo
/daim/view/view_pro_sol.py
2,376
3.84375
4
# -*-coding:utf-8-*- import numpy as np """ Python ver. solution for algorithm problem. [One-dimensional array problem] View rights https://www.swexpertacademy.com/main/learn/course/lectureProblemViewer.do You can see the question and download input, output text file from above link. * Downloa...
dd6604ac3b476086a83393be45bfcb3ed91bf423
histuckyi/swuAlgo
/daim/square/square_pro_sol.py
2,873
3.875
4
# -*-coding:utf-8-*- """ Python ver. solution for algorithm problem. 1861. [search algorithm] square room https://www.swexpertacademy.com/main/learn/course/lectureProblemViewer.do You can see the question and download input, output text file from above link. * download input.txt from the ...
8ef0513dc7c3ef572bb9b90dec4fc0ccc8179742
jadexty/learngit
/vim/vim80/workspace/byl/thread_daemon.py
1,539
3.90625
4
#coding=utf-8 #后台线程 # #默认情况下,主线程退出之后,即使子线程没有join。那么主线程结束后,子线程也依然会继续执行。如果希望主线程退出后,其子线程也退出而不再执行,则需要设置子线程为后台线程。python提供了seDeamon方法: # # import threading import random import time ''' 1.开启子线程守护模式Daemon后,主线程开启5个子线程后,运行6秒结束. 5个子线程有的没有结束的,也会随着主线程结束而结束. 2.如果没有设置子线程守护模式, 则线程没有主次之分, 整个程序要等所有线程结束后,才会结束. ''' class MyThread(threa...
a3d9434976fda70c1ec51cc03f9bca6d652e74a3
oneluvdorc/LanguageParser
/arithmetic.py
9,623
4.0625
4
"""The evaluate method will return a representation of evaluating the subtree rooted at this tree node. Subtrees that are arithmetic expressions will return a number, but note that some of the subtrees aren't arithmetic expressions (e.g. a subtree might just be a "(" or an operator like "+") note: currently this code ...
385b0f0fa9315ab396e56f22df9e69851d4a2be1
Germain-L/Othello
/Objets/menu.py
541
3.5
4
from tkinter import * class Menu: def __init__(self): root = Tk() root.title("TOthello") root.state("zoomed") w, h = root.winfo_screenwidth(), root.winfo_screenheight() h = h/2 print(w,'x', h) canvas = Canvas(root, width=h, height=h, background='yellow') ...
8242ba3066306f4fd3aec39fa24cb42936f8eab6
swajos/Fit-in-3-months
/fit_in_3months.py
3,506
4.21875
4
# dictionary of food items fooditems = { "banana": 105, "milk": 122, "bread": 66, "rice": 205, "apple": 72, "black coffee": 2, "chicken breast": 142, "egg": 102, "granola bar": 193, "ice cream": 145, "oatmeal": 147, "orange juice": 112, "pizza": 298, "potato chips": 155, "red wine": 123, "spaghetti": 2...
8a040de1ea9412a6cb9f66b3959cc06aebb83e6b
palakmodi/Decision_Tree_Implementation_Python
/decisiontree.py
4,802
3.671875
4
# -*- coding: utf-8 -*- """ Created on Sat Feb 12 17:31:37 2016 @author: Palak """ import math def entropy(data, goal): #Calculates the entropy of the given data set for the target attribute. values = {} dt_entropy = 0.0 # Calculate the frequency of each of the values in the target atribute for r...
c4262d316ff9e8c7d5ac50825f6b96a5414de277
z-memar/CitiestoVisit
/Cities_you_want_toSee.py
1,986
4
4
print("Zahra Memar") final_index = 0 initial_index = 1 def AskForNumberCities(): number_cities=input("Please type the number of cities that you want to see?") if number_cities == "Quit": return "Quit" try: n = int(number_cities) except ValueError: print("Error!", number_cities,...
bb9d784310776fd0dd391e04e8c979f541747c9e
LewPort/SUPER-SECRET-CIPHER
/supersecretcipher.py
1,777
3.546875
4
import pyperclip import random import string alphabet = string.printable[0:95] alphabet = list(alphabet) def encode(inputstring): codedmsg = [] while True: try: key = int(input('\nSet a super secret key (Any number): ')) while key >= len(alphabet): key = key // ...
aced589b8fec80e6a02801f0372dd84a10c8ad0d
Asta1985/KazkasNesvankaus
/hangman.py
3,166
3.609375
4
import random import sys zodziu_sar = [ "liūtas", "skėtis", "langas", "kompiuteris", "stiklas", "stogas", "laiptai", "ekranas", "kalėdos", "katinas", "šuo", "citrina", "obuolys", "sninga", "lova", "česnakas" ] class Zaidimas: speti_zodi = [] slaptas_zod = random.choice(zodziu_sar) zodzio_ilgis =...
cecf91add824e295519684cda08c41e41c5ca177
warfahas/web-caesar
/caesar.py
571
3.90625
4
def alphabet_position(letter): if letter == letter.lower(): return ord(letter) - 97 elif letter == letter.upper(): return ord(letter) - 65 def rotate_character(char, rot): if (ord(char) >= 97) and (ord(char) <= 122): return chr(97+(alphabet_position(char)+rot)%26) elif (ord(char...
51c07a06f5d6f94ac8b5c028e93367839713c857
denespetra/github
/10.feladat.py
329
3.59375
4
vezetéknév = input('Mi a vezeték neved? ') keresztnév = input('Mi a kereszt neved? ') év = input('Melyik évben születtél? ') csillagjegy =input('Mi a csillagjegyed? ') print('A te neved ', vezetéknév,' ', keresztnév, ' .', sep='') print('Te ', év, '-ben születtél, a ', csillagjegy, ' jegyében ' '.',sep='')
aabbc15b7044ebd543934160c42a1d8ebac9e7da
ArijTrabelsi/coretabs-workshop
/test3.py
296
3.765625
4
def apply () : age = input('Enter your age: ') age = int(age) if age < 18 : print('you are too young') elif age <= 22 : print('welcome to Egypt scolarship program') else: print('you are too old') count = 0 while count < 1000: apply() count +=1
b2a20fe17d7bcdd54dacefb535d8be98ed1136c4
lucia-13/Blockchain
/script.py
999
3.71875
4
from blockchain import Blockchain #Code done by LUCIA FUENTES, inspired by codecademy #testing block_one_transactions = {"sender":"Lucia", "receiver": "Julia", "amount":"999"} block_two_transactions = {"sender": "Diego", "receiver":"Laika", "amount":"666"} block_three_transactions = {"sender":"Frida", "receiver":"Rex",...
16bc2814112b7bd4fad04457af0ba79ccf21e68a
soumilk91/Algorithms-in-Python
/Mathematical_algorithms/calculate_fibo_number.py
1,414
4.21875
4
""" @ Author : Soumil Kulkarni This file contains various methods related to problems on FIBO Series """ import sys # Method to calculate the fibo number recursively def calculate_fibo_number_recursive(num): if num < 0: print "Input incorrect" elif num == 0 : return 0 elif num == 1 : return 1 else : re...
249483ed121d834933487f19232ab7e3a621299a
soumilk91/Algorithms-in-Python
/CTC/ArraysAndStrings/one_away.py
1,858
3.953125
4
""" Author: Soumil Ramesh Kulkarni Question: There are 3 types of edits that can be performed on a string, 1) Insert a character, 2) Delete a character, 3) Replace a character. Given 2 strings, write a function to check if they are one edit away (or zero edit away) eg: pale, ple -> true pales, pale -> true p...
22cb4f0f381309aeb441695596dab1aa0216cc3e
vaibhav28398/House_prices-prediction
/features_analysis.py
875
3.609375
4
import csv import pandas as pd dataset=pd.read_csv('final_dataset.csv') print "Seeing the trend in the dataset"; print dataset.describe() print "Observing the NaN values in the dataset" print dataset.info() #Printing the heatmap import warnings warnings.filterwarnings("ignore") import matplotlib.pyplot as plt import ...
3d8b31b76021131ba86c2c797960afe1d005ce77
irapol/my-first-blog
/python_intro.py
151
3.5625
4
print('hello djangogirls') print(500*3) if 3 > 2: print('it works') girls=['Ira', 'Rachel', 'Monica', 'Phoebe'] for name in girls: print(name)
a8e6a262196d9ac96e3d55ea848b2ed4d396de97
paketner/advent_of_code_2018
/advent_day3_part1.py
1,456
3.640625
4
#!/usr/bin/env python3 ''' Made by Paul Ketner for the adventofcode 2018 day 3 ''' import re def matrix_duplicate_finder(): ''' Build a matrix of the defined areas, and find the number of squares duplicated ''' #Build the fabric claims matrix fabric_area = {} fabric_claims_file = open('fabric_...
472dc57224e3245a5fc3fda2ceef408824d3e544
ddyuewang/LeetCode_PYTHON
/unique_path.py
1,881
3.53125
4
class Solution(object): def uniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int ### v1. recursion solution """ # if m < 1 or n < 1: # return 0 # if m == 1 and n == 1: # return 1 # return self.uniquePaths...
03caa780e1a1473024f65758eb6cd76a2482d3de
ddyuewang/LeetCode_PYTHON
/binary_search_tree.py
1,167
3.9375
4
### Lowest Common Ancestor of a Binary Search Tree def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ if (root.val - p.val) * (root.val - q.val) <= 0: return root elif p.val < root.val: return self...
4bee64acc99e8fd7aa35627e7c41e5925bb703a0
DirtyTechSmith/Archery_Trainer
/random_scripts/home_depot_crown_molding.py
1,737
3.625
4
import math import pprint import requests from bs4 import BeautifulSoup def get_pricing_data(search_term: str) -> dict: """ Queries all products from Home Depot that match the given search term and returns a dictionary of pricing data. Args: search_term: The search term to use when querying produc...
1777e75d05fde0ec1e3cf8647561984c81d58e9e
DirtyTechSmith/Archery_Trainer
/classes/bow.py
2,506
3.828125
4
from vector import Vector from classes.arrow import Arrow LBS_TO_NEWTONS = 4.4482216282509 INCHES_TO_METERS = 0.0254 class Bow(object): def __init__(self, archer=None, arrow_velocity=60.0, draw_weight_lbs=100.0, draw_length=0.75, efficiency=1.0, arrow_type=None): """ Args: ...
fee673ce6144bf779659de67c9e075751335dd7a
ashkanyousefi/CSE6040_Computing_Data_Analysis
/note_book_4/sand_box.py
294
3.71875
4
def eval_strint(s, base=2): assert type(s) is str assert 2 <= base <= 36 L=len(s) calculated_value=0 for i in range(L): print(i) check1=s[-1-i] calculated_value+=int(s[-1-i])*(base**i) print(calculated_value) eval_strint('123',10)
ad68a2da569a6624638d7ed24c758c4fc67857cf
manukyandavid/demo
/bubble_sort.py
283
3.984375
4
def bubble_sort(nums): for i in range(len(nums) - 1, 0, -1): for j in range(i): if nums[j] > nums[j + 1]: nums[j], nums[j + 1] = nums[j + 1], nums[j] return nums numbers = [-4, -7, 8, 9, 2, 1, 65, -2, 0, 14] print(bubble_sort(numbers))
c557935a9ca5642ac06081354fc0a0f66cc8f136
Toleugazin/ADM-HW1
/Regex and Parsing challenges/Validating and Parsing Email Addresses.py
275
3.640625
4
import re from email.utils import * for i in range(int(raw_input())): email = parseaddr(raw_input()) # print email[1] # \w is equivalent to a-zA-Z_ if bool(re.search(r'^[a-zA-Z][\w\-\.]*@[A-Za-z]+\.[a-zA-Z]{1,3}$', email[1])): print formataddr(email)
5a03163f6aa225792fd6ed07d9d9b4f6416754fe
Sarahxed/design_pattern
/pattern/builder.py
1,776
3.546875
4
# encoding: utf-8 """ @author: Sarah @time: 2021/7/7 9:35 @file: builder.py @desc: 创建者模式demo """ from abc import ABCMeta, abstractmethod """ 创建者模式:将一个复杂对象的构建和它的表示分离,使得同样的构建过程可以创建不同的表示 角色: 抽象创建者 具体创建者 指挥者 产品 """ # --------- 产品 --------- class Player: def __init__(self, face=1, body=1, arms=1, legs=1): ...
35856154d5550e4d8fc9fc26c027339c9c2fbc44
Sarahxed/design_pattern
/pattern/chain_of_responsibility.py
1,557
3.53125
4
# encoding: utf-8 """ @author: Sarah @time: 2021/7/7 17:14 @file: chain_of_response.py @desc: 责任链模式demo """ """ 责任链模式:使多个对象有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。 将这些对象连成一条链,并沿着这条链传递该请求,知道有一个对象处理它为止。 角色:抽象处理者 具体处理者 客户端 优点:降低耦合度,一个对象无需知道是它哪一个对昂处理其请求 """ from abc import ABCMeta, abstractmethod class Handler(metaclass=A...
a57fff211a31d8ae70c95c837b7df548de2975f6
WellersonPrenholato/Coder-Rerun
/Solutions/G.py
452
3.5
4
dim = input() dim = dim.split(' ') N, M = int(dim[0]), int(dim[1]) # M = int(input()) ld, lv = [], [] for i in range(N): linha = input() for x in linha.split(' '): if (x[1] == 'V'): lv.append(x) else: ld.append(x) # ld = ['1D', '2D', '2D', '9D'] # lv = ['7V', '1V', ...
16e8ca32319acf66b6cd67499fff04f7eff93443
haykarabyan/passwordstore2.0
/authentication.py
931
3.609375
4
from MainFunctions import Answer from hashlib import sha256 class Authenticate: def __init__(self): self.text = '' self.hash = '' def authenticate(self): password = Answer('') password.get_user_input("Enter your password ") if not password: return ...
0f41635b6543d7a40af56a784db6f89ea764cabb
anhpt1993/bmi
/BMI.py
2,092
3.734375
4
# Body Mass Index def check_bmi(index): print("Chỉ số BMI của bạn là {:.2f}".format(index)) print() if index < 16: print("Bạn đang gầy cấp độ III.".format(index)) elif index >= 16 and index < 17: print("Bạn đang gầy cấp độ II.") elif index >= 17 and index < 18.5: print("Bạn ...
6ccabea432df84afdc9d8127742a04afb961be3d
qiguangyang/demos_lxf
/do_filter.py
1,350
4
4
# -*- coding: utf-8 -*- # 素数算法:埃氏筛法 # 首先,列出从2开始的所有自然数,构造一个序列: # 取序列的第一个数2,它一定是素数,然后用2把序列的2的倍数筛掉: # 取新序列的第一个数3,它一定是素数,然后用3把序列的3的倍数筛掉: # 取新序列的第一个数5,然后用5把序列的5的倍数筛掉: # 不断筛下去,就可以得到所有的素数。 def _odd_iter(): n = 1 while True: n = n + 2 yield n def _not_divisible(n): return lambda x: x % n > 0 def p...
b8e8c30e5c00f89d378b9e90c73162a9cfb9585f
furkanaydinnn/Python-DataScience
/python_programming.py
1,056
4.03125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Apr 4 13:32:57 2020 @author: furkanaydin """ #starting with some tryings => this is a comment #print() => writes anythink you want in console #type() => give us to type of the object # "a"+"b" = "ab" => '+' string concatanetion operators. # two srtrin...