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
5cb382d2f315eb5fafa3d30f21af1cdfc08b18a5
AJClassic2014/fifo-liu-lru
/pagerefgen.py
995
3.5625
4
#!/usr/bin/python import getopt import random import sys pages=12 length=12 def usage(): print """ pagerefgen.py [-f npages | --pages=npages] [-l nrefs | --length=nrefs] This program generates a random sequence of page numbers. The page numbers are drawn from a logical address space containing npages pages....
c60192082b9df3a413a40d1157c554928d4b6471
Elizabeth-III/Aprendizado-Python
/Exercícios de Decisões/02.py
375
4.0625
4
#Faça um Programa que peça um valor e mostre na tela se o valor é positivo ou negativo. num1=int( input('Digite o primeiro numero: ') ) num2=int( input('Digite o segundo numero: ') ) if num1 > num2 : print('O primeiro, %d, é maior' %num1) else: if num1 == num2 : print('Os números são iguais') else...
70399d94dba7c32079b0801023773e2e0df1a408
Elizabeth-III/Aprendizado-Python
/Exercícios de Lista/3.py
672
3.5
4
# num1 = float(input('Notas do 1º bimestre:')) # num2 = float(input('Notas do 2º bimestre:')) # num3 = float(input('Notas do 3º bimestre:')) # num4 = float(input('Notas do 4º bimestre:')) # print('A sua média foi:', (num1+num2+num3+num4)/4) # # lista = float(input('Nota do 1º bimestre: ')) # lista = float(input('Nota d...
33b654b47f6d94ec8e9c93c0e5bdedd0e317618e
Elizabeth-III/Aprendizado-Python
/Exercícios de Repetições/05.py
836
4.03125
4
''' Altere o programa anterior permitindo ao usuário informar as populações e as taxas de crescimento iniciais. Valide a entrada e permita repetir a operação. ''' populaçãoA=float(input("informe a população da cidade A ")) populaçãoB=float(input("informe a população da cidade B ")) ano=0 taxa_crescimentoA=float(input(...
07bd3524a5db985ec04a0f8d3a4c0fc4141b1965
msterckx/building_ai
/exercise-12-adv-linear_regression.py
1,191
3.734375
4
import numpy as np # data X = np.array([[66, 5, 15, 2, 500], [21, 3, 50, 1, 100], [120, 15, 5, 2, 1200]]) y = np.array([250000, 60000, 525000]) # alternative sets of coefficient values c = np.array([[3000, 200 , -50, 5000, 100], [2000, -250, -100, 150, 250], ...
520aa77623d6f1ca9649708d8c8ee3242d57dd97
lexel225/Hello_python
/utils/tuple_demo.py
637
4.03125
4
def tuple_test(): tupleA = (1,2,'a','b') print("tupleA =", tupleA) # index print("tupleA[2] =", tupleA[2]) print("tupleA[-1] =", tupleA[-1]) # slice print("tupleA[1:3:1]", tupleA[1:3:1]) print("tupleA[0:4:2]", tupleA[0:4:2]) print("tupleA[:2]", tupleA[:2]) print("tupleA[::2...
a6b14bd0d5445ae53ce44109f85e7c719e49e3b3
arrryan/testProj
/validation.py
419
3.875
4
import re p = input("Enter input:") x = True while x: if len(p) < 6 or len(p) > 16: break elif not re.search("[a-z]", p): break elif not re.search("[A-Z]", p): break elif not re.search("[0-9]", p): break elif not re.search("[@#]", p): break else: ...
07936dc2bcdb9ae0ee58e06d7653691a5a8ef8d8
cbohlman/AoC2020
/3/3.py
758
3.65625
4
with open('input.txt', 'r') as f: input_lines = [line.strip() for line in f] width = len(input_lines[0]) def count_trees(input_lines, x_slope, y_slope): tree_count = 0 for i in range(0, len(input_lines), y_slope): # print("x: ", int(i*x_slope/y_slope) % width, "y: ", i) if (input_lines[i][...
9f58c8ab691cd0bda369ef1cc9c29088226045bb
hisourav4u/Python-Programs
/Json.py
1,278
4.0625
4
import json def stats(): branchNumber=int(input("Enter the number of company branches: ")) #loop for each branches for i in range(branchNumber): employeeInBranch=(int(input("Enter the number of employee in branch {}: ".format(i+1)))) avgSalaryInBranch=(float(input("Enter the average sa...
46bd6737699f2d965795141141c4c082dc5b97dc
DeepakPuligndla/Virtual_Fireworks
/Fireworks_v0.3/start.py
531
3.9375
4
import sys from fireCracker import start_fireworks if __name__ == "__main__": print ("Hello! Welcome to fesival of firecrackers....") number_of_crackers = int(raw_input("Enter how many crackers you want to fire at once (limit:7): ")) while number_of_crackers > 7: number_of_crackers = int(raw_input("Stupid! I told...
731f43ab8234b9d146e4005bdf8819406ac302a3
SubhamChoudhury/Back_to_Basics
/Sorting Technique/Python/04 Bubble_Sort.py
354
3.78125
4
import sys a = [] x = int(input("Enter Size of Array: ")) for i in range(0, x): inp = int(input("Enter Elements: ")) a.append(inp) for i in range(len(a)): for j in range(0, len(a) - i - 1): if a[j] > a[j+1]: a[j], a[j+1] = a[j+1], a[j] print("Sorted array") for i in range(...
9e6067f3f81b4f47eb13afcb54fce0801df31e38
curiouskiwi/AdventofCode2020
/day8.py
1,968
3.6875
4
# Advent of Code 2020 - Day 8 # @curiouskiwi # 8 Dec 2020 def main(): with open("data.txt") as f: lines = f.readlines() ex = len(lines) instructions = [] # example input: jmp +248 for line in lines: l = [] # instruction l.append(line.split()[0]) # argum...
acf71806c80b715387b3f5c6184e70d922340d62
SimplyPavel/Battleships
/Battleships_master.py
6,950
3.984375
4
import random # prolly can into bigger ships board = [] board_cheat = [] ship_locations = [] total_turns = 0 turn = 1 num_of_ships = 0 num_of_players = 0 players = [] def how_many_players(): global num_of_players num_of_players = int(input("How many players are there? ")) if num_of_players > 5: p...
e0aa2e46821854211eac3041ec4fee381da8d516
BeAgarwal/Palindrome
/Python/Different Types/palindrome_type1.py
642
4.15625
4
''' Code by Shubham Agarwal Link: https://github.com/BeAgarwal/Palindrome ''' '''Program to check the sum of a digit is a palindrome or not.''' def check_palindrome(n): r = 0 t = n while n > 0: rem = n % 10 r = (r * 10) + rem n = n // 10 if r == t: return True ...
b008342a194e0159dee322e714d085db995ec618
makarov-wl24/python-getting
/lesson2-task2.py
1,035
3.984375
4
# Для списка реализовать обмен значений соседних элементов, # т.е. значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д. # При нечетном количестве элементов последний сохранить на своем месте. # Для заполнения списка элементов необходимо использовать функцию input(). my_list = [] list_len = int(input('Скольк...
0639f05bd9298e51dd39fbbb4f36ceb34cb260ac
Tp4-AED/tp4
/registros.py
1,463
3.546875
4
#registros class Publicacion: def __init__(self, codigo, precio, ubicacion, estado, cantidad, puntuacion, favorito): self.codigo = codigo self.precio = precio self.ubicacion = ubicacion self.estado = estado self.cantidad = cantidad self. puntuacion = puntuacion ...
5e0f963b90319329676d7d3804bc31359e68a3b7
Ravi1998h/python-coding-problem-slutions
/input.py
154
3.5
4
n='NaGRaVZ' for i in n: if 'a'<=i<='z': data=ord(i)-96 print(i,':',data) else: data2=ord(i)-64 print(i,':',data2)
fc9f0495ea894596371db3313c9faae4491ba3eb
leonsariel/python
/Basics/args_and_kwargs.py
785
3.734375
4
# _*_ coding: utf-8 _*_ __author__ = 'Di Meng' __date__ = '1/12/2018 4:16 PM' def args_function(*args): """test with args :param args: any normal param eg 1,2, "hello" :return: None """ for arg in args: print(arg) def kwargs_function(**kwargs): """test with kwargs :param kwargs...
b77f7b6cd07a2477994413bf257e73fa59cdf46f
Jeongah-Shin/Deep3Framework
/steps/second_half/sum.py
724
3.546875
4
import numpy as np from deep3framework import Variable import deep3framework.functions as F if __name__ == '__main__': x = np.array([[1,2,3],[4,5,6]]) x2 = np.random.randn(1,2,3) y = np.sum(x, axis=(0), keepdims=True) print(y) y2 = np.sum(x2, axis=(0,1)) print(x2) print("----") print(np...
ac171958d6ef840f94820c55728b93824a72e51a
Jeongah-Shin/Deep3Framework
/steps/second_half/newton_m.py
1,146
4
4
import numpy as np from deep3framework import Variable def f(x): y = x**4 - 2 * x**2 return y # deep3framework에서 2차 미분은 자동으로 구하지 못하므로 수동으로 입력 def gx2(x): return 12 * x**2 - 4 if __name__ == '__main__': ''' # 수동 print("Newton - Manual Approach") x1 = Variable(np.array(2.0)) iters = 10 ...
5c4d4fd464c0fa9bbb58f4f34125cff05b1a3d57
PauloHARocha/accentureChallenge
/classification_naiveBayes.py
2,036
4.125
4
import pandas as pd from sklearn.naive_bayes import MultinomialNB from sklearn.model_selection import train_test_split from sklearn import metrics # Naive Bayes # The objective of this module is to classify the data from the pre-processed dataset, # based on the alignment of each hero (good or bad), using the Naive B...
0dabf94fc0058a50843286cd77a5bacd48d243ec
Alex5527467/MachineLearn
/KNN/KD-Tree.py
264
3.53125
4
# -*- coding: utf-8 -*- from sklearn.neighbors import KDTree import numpy as np #print np.random.seed(0) X = np.random.random((10, 3)) # 10 points in 3 dimensions print X tree = KDTree(X, leaf_size=2) #dist, ind = tree.query([X[0]], k=3) #print dist,ind
b360c014b66822eaf13e11f608ec27deb70cf8e0
revolyram/Game_WORD
/game.py
748
3.765625
4
import random words_list = ('автострада', 'бензин', 'инопланетянин', 'самолет', 'библиотека', 'шайба', 'олимпиада') secret_word = random.choice(words_list) gamer_world = ['*'] * len(secret_word) errors_counter = 0 while True: letter = input('Input your letter: ') if len(letter) != 1: continue i...
862778d5688a4ea7da3c5af83afabbbc69c6f5f7
ptrgags/mobius
/cline.py
4,757
3.546875
4
import cmath from mobius import Mobius class Cline(object): """ Generalized Circle in the extended complex plane Such circles satisfy |z - center| = r Which can be expanded to (z * z.conj - z * center.conj - z.conj * center + center * center.conj - r^2) = 0 Upon multiplication by...
6f8282b8ecdf11f2bf1836e4d5db26c36684faae
KushagraChauhan/7-day-challenge
/2.py
728
3.828125
4
''' Second day of 30 day challenge Hash Tables: Ransom Note (Hacker Rank) ''' from collections import Counter ''' A counter is a container that stores elements as dictionary keys, and their counts are stored as dictionary values. ''' def checkMagazine(magazine, note): return "Yes" if (Counter(magazine) & Counter(no...
6d38d73bf4b16c6a8c0556582e4c2c78a1ec2cd4
tanvimathur118/Welcome-to-Python
/Decision tree.py
1,647
3.84375
4
#Decision Tree creates as model or a tree visualization. It makes model of decisions with number of possible consequences. # coding: utf-8 # In[5]: import pandas as pd import seaborn as sns import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') import numpy as np # In[6]: from sk...
83c5e76643c824af0b9f37642d184c3e9c3ef1de
tanvimathur118/Welcome-to-Python
/NLP.py
2,991
3.625
4
# coding: utf-8 # # Natural Language processing # This processing tries to bridge a gap between the human and computer by letting computer understand what humans are saying. Simplest example : Gmail classifies the mail into categories, So how do they understand the which mail is spam and which not. To classify this ...
57510a0f599caff52e3766fb9e797f57e091040f
DorinK/AI-Search-Algorithms
/PriorityQueue.py
1,989
3.875
4
import heapq """""""""""""""""""""""""" # Dorin Keshales # 313298424 """""""""""""""""""""""""" class PriorityQueue: """ This class implements a priority queue using a priority function received as input. Each item in the priority queue is of type Node. Every Node inserted to the queue has pri...
b8557d880d175569782682709d7055f2e219b994
kabitakumari20/if_else_py
/calculator.py
408
4.3125
4
num=int(input("enter the num:-")) num1=int(input("enter the num1:-")) symbol=input("enter the symbol:-") if symbol=="+": print(num+num1) elif symbol=="-": print(num-num1) elif symbol=="*": print(num*num1) elif symbol=="%": print(num%num1) elif symbol=="//": print(num//num1) elif symbol=="/": pri...
770dc7e863343aabae12f23a99b7da024c5827d1
ZakOpry/digital-crafts
/week1/day3/introToPython4.py
271
4.15625
4
# Conditionals print("Welcome to this program") firstName = input("What is your first name?") length_of_first_name = len(firstName) print(firstName) if length_of_first_name <= 0: print("Please enter at least one character") else: print(f"Hello {firstName}")
1b8931fc9cab322b9625a16a5922f9288aa3d02d
jonathan-vidal/daily-questions
/2019/08/13-EASY-Flat/malcolm-smith/solution.py
168
3.515625
4
input = [[1, 2, 3], [4, 5], [6], [], [7, 8, 9, 10]] def meshArrays(arrays): new = [] for array in arrays: new += array return new print(meshArrays(input))
24694f724aebe5ceb4554195c5c07586e83c40f4
jonathan-vidal/daily-questions
/2019/07/09-EASY-Because-Im-happy/Solutions/jonathan-vidal/solution.py
288
3.734375
4
def is_happy(num_to_check): curr_num = num_to_check while True: if curr_num == 1: return True square_sum = 0 while curr_num > 0: square_sum += (curr_num % 10)**2 curr_num = curr_num // 10 curr_num = square_sum
92c82373ab858e2b3cdac4520d7ae664de2acfcd
eaze/momentum-data-tools
/delete_table.py
574
3.59375
4
import db_util def main(): print("WARNING!! Deleting a table is permanent and you will not be able to recover data") table_name = input("Which table would you like to delete?\n").strip() if not db_util.check_table_exists(table_name): raise Exception(f"The table {table_name} does not exist.") c...
4d2b9b3634c7bc27683141bf71703560e99ae14a
xsarinix/Module2_Python
/3.1 Introduction to Python 10.22.18/HowManyNumbers.py
185
4.15625
4
cont="yes" start=int(input("How many numbers? ")) while cont=="yes": for x in range(start): print(x) cont=input("Do you want to continue? Type yes or no: ")
a21973ce6ebe13892f0f5b23dcb224a0bbfb1e50
xsarinix/Module2_Python
/python-challenge/pypoll/main_dictionary.py
2,083
3.828125
4
import csv from decimal import Decimal # this cell creates a dictionary of of names and voter IDs # which can be used to not only tally votes, but check for duplicates # this cell also creates dictionaries of counties and votes # which can be also be used to tally results by county election_data_path="election_data....
b826dda61f2e78df3e836894f07f12634dde4d60
keyvin/docnotes
/pynotes/tkinter/textwidgets/getentry.py
764
3.53125
4
#!/usr/bin/python3 """This file contains a custom class that will get an entry. You should check if result is empty.""" from tkinter import * class GetEntry(Frame): def __init__(self): Frame.__init__(self) self.result = '' self.pack() self.ent = Entry(self) self.ent.pack(sid...
def10292b72ccb0e7f1ab351e298f24d9d83b3d3
keyvin/docnotes
/pynotes/tkinter/textwidgets/progmake.py
805
3.765625
4
"""make rows of labels aligned with entry widgets.""" from tkinter import * from quitter import Quitter fields = ["Name", "Job", "pay"] def fetch(entries): for entry in entries: print ('input %s\n', entry.get()) def makeform(root, fields): entries = [] for field in fields: row = Frame(roo...
b840e760c4ec968c11e46cfeae78d99828a66f7f
keyvin/docnotes
/python/bsdb/makedm.py
1,732
3.578125
4
import sqlite3 def fixtitle(title): title = title.replace('–','-') string = title.replace("'","''") a = list(title) i = 0 # while i < len(a): # if a[i] =="'": # tmp = a[i] # a[i] = "'" # a.insert(i+1, tmp) # i=i+2 # i=i+2 #s...
aee9e7484e8aee7adb71f6bfc49e1df3ed0c11d8
HenziKou/CIS-313
/labs/lab1/lab1.py
5,510
4.28125
4
# Henzi Kou # Lab 1 # January 23, 2019 from sys import argv class Node(object): def __init__(self, data = None, next = None): self.__data = data self.__next = next def setData(self, data): # Set the "data" data field to the corresponding input self.__data = data def setNext(self, next): # Set the "...
07b213e5a72caa2ce55966adfcdeb5ddf8b05362
HughesSvynnr/prg1_homework
/hw4.py
1,891
4.125
4
''' problem 1 Ask a user for a number. Depending on the number, respond with how many factors exist within that number for example: Enter a number >15 15 has 4 factors, which are 1 3 5 15 ''' ''' problem 2 Write a program that will ask a user for a word. For that word, replace each letter with the appropr...
251d9845fd34b2936f2967894df45cddef5c14ba
HughesSvynnr/prg1_homework
/practice_code/testing.py
663
3.96875
4
'''print("Give me a number") number = input(">") factors_list=[] for x in range(1, int(number)+1): if(int(number)%x==0): factors_list.append(x) print(number, " has ",len(factors_list)," factors, "," which are ",factors_list) print("Tell me a word") word = input(">") word_split = word.split(" ") for x in wo...
5c58f418766557d4b950164941d25b0e28a6ce53
HughesSvynnr/prg1_homework
/practice_code/dog.py
702
3.75
4
class Dog: def __init__(self,initial_name,age=0): self.age=age self.name = initial_name pass def speak(self): print(self.name + " says borf") def change_name(self,newname): self.name= newname def calculate_dog_years(self): return self.age * 7 ...
2e1f150579b842e6190840a7000a889403d54cdb
beomjin-lee/tetris-ai
/tetris/tetris_ai.py
17,202
3.53125
4
############################################################### # Made by KSEA Project Research and SW Team 2018 at UC Berkeley # This file contains tetris game and tetris AI functions # AI is built using genetic algorithms # Authors: Beom Jin Lee <beomjin.lee@berkeley.edu>, # Gabi Choi < gabichoi96@gmail.com >, # Bria...
db6a2392329bf5029a59aaf616f2883ad9c611d4
MIR013/AlgorithmStudy
/10.ETC/PGM_재귀_타겟넘버.py
847
3.546875
4
total = 0 def calArr(numbers,types): result = 0 for value, sign in zip(numbers,types): if sign == 0:#+ result = result + value else:#- result = result - value return result def choicePM(idx,num,arr,length,numbers,target): if(idx>=length): ...
f87e3ca5ac4517305358c32c536c362285365f6d
MIR013/AlgorithmStudy
/10.ETC/PGM_K번째수.py
449
3.953125
4
def solution(array, commands): answer = [] for data in commands: new_array=[] i = data[0] j=data[1] k=data[2] new_array = array[i-1:j] new_array.sort() answer.append(new_array[k-1]) return answer #atom 실행은 ctrl+shift+b if __name__ == "__main__": ...
93f1896fcf25d02c1343a44dca9e0a6b8a58fe89
gauravkantrod/AccessingFromLastLinkedList
/LinkedList.py
1,345
4
4
from Node import Node class LinkedList: def insert(self, head, new_data): if head.data is None: head.data = new_data return else: p = head while p: if p.next is None: p.next = Node(new_data) re...
9bcf554b66bd2e9b5ed9bb4e00bb71814c4e5807
KreesDaShrimp/MiniGolf
/vector2.py
4,021
3.6875
4
# -*- coding: utf-8 -*- """ Created on Fri Jan 25 14:30:50 2019 @author: sinkovitsd """ from math import sqrt, sin, cos, floor class vector2: def __init__(self, x, y=None): if y==None: self.x = x[0] self.y = x[1] else: self.x = x self.y = y ...
baddae4bbda6552583c65c42e4b953fff99215fd
hs634/algorithms
/python/sortandsearch/sortandsearch.py
2,358
3.5625
4
__author__ = 'harsh' class CustomArray(object): def __init__(self, arr): assert isinstance(arr, list) if arr is None: self.arr = [] else: self.arr = arr def __rsearch__(self, lo, hi, key): mid = lo + (hi - lo)/2 if hi < lo: return -1...
1882882161abcc9ccc04e2a4c7f8c74531d72eb6
hs634/algorithms
/python/comb4.py
810
4.03125
4
""" Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target. Example: nums = [1, 2, 3] target = 4 The possible combination ways are: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) Note that different sequen...
725ee82e1c111d85ed6fd18f70241fa4311a555b
hs634/algorithms
/python/permute_palindrome.py
2,684
4.03125
4
""" Generation of palindrome can be done by following steps, First we need to check whether letters of string can make a palindrome or not, if not then return. After above checking we can make half part of first palindrome string (lexicographically smallest) by taking half frequency of each letter of the given strin...
c3837390ad3e8119a5e24d0572aa5a28a94e3b85
hs634/algorithms
/python/arrays/search_rotated_array.py
1,213
3.65625
4
__author__ = 'harsh' def bin_search(sequence, left, right, key): if not sequence: return -1 if left >= right: return -1 mid = left + (right - left)/2 if sequence[mid] == key: return mid else: if sequence[left] < sequence[mid]: if sequence[left] <= key < s...
c0e433fcbacaca9be1601dfcaad9207b97795b1e
hs634/algorithms
/python/misc/custom_iter.py
1,422
3.625
4
__author__ = 'harsh' class Iterable(object): def __init__(self,values): self.values = values self.location = 0 def __iter__(self): return self def next(self): if self.location == len(self.values): raise StopIteration value = self.values[self.location]...
4d8c05e83ef5ac94c74398d18a86cb51eb2a2c57
hs634/algorithms
/python/strings/minimum_window_substring.py
4,008
4
4
__author__ = 'harsh' """ Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity in 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 ""....
c1762449d45e10264fe1228f749b1256476411ea
hs634/algorithms
/python/trees/unique_binary_trees.py
2,925
3.703125
4
""" The problem can be solved in a dynamic programming way. I’ll explain the intuition and formulas in the following. Given a sequence 1…n, to construct a Binary Search Tree (BST) out of the sequence, we could enumerate each number i in the sequence, and use the number as the root, naturally, the subsequence 1…(i-1) o...
2d49d2b61b2c71651e65783ac048bd30847d4d0a
hs634/algorithms
/python/trees/level_order_traversal.py
1,790
4.09375
4
__author__ = 'hs634' #Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class BinaryTree(object): def __init__(self): self.root = None def add_node(self, val): return TreeNode(val) ...
2c440647d8d5ac1608e67b54012e040680e169ae
hs634/algorithms
/python/strings/anagrams.py
274
3.65625
4
__author__ = 'hs634' def print_anagrams(words): aux = [(i, sorted(word)) for i,word in enumerate(words)] sorted_aux = sorted(aux, key=lambda tup: tup[1]) for item in sorted_aux: print words[item[0]] print_anagrams(["cat", "dog", "tac", "god", "act"])
17ea4433b2b1c708b4a74b5cd51b6f8e7e0ee001
hs634/algorithms
/python/trees/morris_traversal.py
1,400
4.09375
4
# # Definition for a binary tree node # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # http://www.geeksforgeeks.org/inorder-tree-traversal-without-recursion-and-without-stack/ # class BSTIterator(object): def __init__(self, ro...
f6601e6d2484f73981e8226b0c88933c64532a40
bb88dd/test2
/test_test.py
426
3.625
4
#Git test import pandas as pd df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]}) print(df) df2 = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]}) print(df2) df3 = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]}) print(df3) df4 = pd.DataFrame({'a': [1, 2, 3]...
ad2c9c88a96989dafe53a489941a7e72c7ed7ebc
btkaija/attendance_app
/app/attendance_window.py
2,090
3.53125
4
from tkinter import * import tkinter as tk import time import datetime class AttendanceWindow: def __init__(self): self.main_window = Tk() self.main_window.title("Attendance") self.main_window.geometry('500x400+100+100') self.main_window.resizable(width=FALSE, height=FALSE) main_frame = Frame(self.main_wi...
ba4bd210b03bd5bf37672ad575807bce8ebbd17c
Pragya1407/sdet
/python/Activity3 - Rock-Paper-Scissors.py
866
4.0625
4
#Activity3 - Rock-Paper-Scissors ''' Rock beats scissors Scissors beats paper Paper beats rock ''' a = input("What a want to choose from Rock/Paper/Scissors: ") if a not in ["Rock", "Paper", "Scissors"]: print("Game Over1") raise SystemExit b = input("What b want to choose from Rock/Paper/...
7f3c7e24569cd0d3e070018bc26bf9946c83bf24
Pragya1407/sdet
/python/Activity11.py
327
4.1875
4
dict_fruit = { "apple" : 50, "banana" : 10, "watermelon" : 40, "orange" : 25, "kiwi" : 30 } check_fruit = input("What fruit you want?? ").lower() if (check_fruit in dict_fruit) : print("yes.. " + check_fruit + " is available") else : print("no.. " + check_fruit + " is not avai...
004191959526e7e2ea91ee5d7371223ebd7a9b65
therealmik/passgen-fun
/passwordcombinations.py
2,570
3.796875
4
#!/usr/bin/python3 """Generate a graph of possible password combinations This tool displays the combinations of possible passwords that a random password generator can create, taking into account password rules (eg. requiring one of each class). Pipe the output of this program into dot""" # 26 uppers, 26 lowers, 10 ...
0e298dc90dfa1424bcf5def73b7b84d14ddcaebc
kukukuni/Python_ex
/3day/Func07.py
483
3.625
4
# Func07.py def pSum(ans,*num): Result = 0 for i in num: Result += i return '{} {}'.format(ans,Result) ## def pSum(*num,ans): 이렇게 되는것은 다른 언어에서는 안되는데 ## print(pSum(20,10, s='덧셈')) 이런식으로 지정하면 파이썬에서는 됨. print(pSum('덧셈',20,10)) # 덧셈 30 print(pSum('덧셈',20,10,5)) # 덧셈 35 print(pSum('덧셈',20,10,5,2)) # 덧...
879773ee04ff5ba18aea42485b999add2fd200a6
kukukuni/Python_ex
/4day/Ani03.py
451
4
4
# Ani03.py class Animal(object): def __init__(self): self.name = '이 름' def __add__(self, other): #덧셈 연산자(사실은 연결 연산자) 메소드 오버라이드 return self.name + ',' + other.name + '입니다.' class Dog(Animal): pass class Cat(Animal): pass d1 = Dog() c1 = Cat() d1.name = '아 치' c1.name = '해 피' # print(d1.name+c1.n...
3724bf60c6cefd43c72b5211278b00607aa06c17
kukukuni/Python_ex
/2day/Tuple02.py
412
3.640625
4
# Tuple02.py a = (10,20,30,40,50) b = 60,70 c = 80, print(a+b+c) print(type(a+b+c)) #좌우로는 같은 타입이어야 한다. print((a+b+c)[1:-2]) d = (10,20,30),90,'A',(40,(50,[60,70],80),100), print(d) # d의 Type과 길이는? print(type(d), len(d)) # d : 70 출력 print(d[3][1][1][1]) b = True, print(type(b), len(b), b) b = None, print(type(b), ...
4ccf63d9552ca85acff09d3cb280dc7f121684e0
kukukuni/Python_ex
/3day/Func04.py
591
3.5625
4
# Func04.py def Sum(*a): #주소를 세트화 해서 받는다는 뜻 ans = 0 for i in a: ans += i return ans # *하나를 쓰므로 인해서, 여러개를 받을수도 있고 # 여러 형태를 받아낼 수 있다. print(Sum(20,10)) #주소가 2개 print(Sum(20,10,5)) #주소가 3개 print(Sum(20,10,5,3)) #주소가 4개 b = [10,20,30,40,50] print(Sum(*b)) #주소를 세트화가 이미 ...
1b674e4bf3abb01bc7e369f4838aa36f9ed16208
nguyenhmp/dojo-aug-python
/PhilBoothe/Math_Dojo/math-dojo-1.py
347
3.6875
4
#basic MathDojo class with add and subtract methods class MathDojo(object): def __init__(self): self.result = 0 def add(self, *args): self.result += sum(args) return self def subtract(self, *args): self.result -= sum(args) return self #test class methods with md instance md = MathDojo() print md.add(2).ad...
d79cff98b2698938dcfb7115c44bd1e3efebaedb
nguyenhmp/dojo-aug-python
/SnehaPokharel/python_fundamentals/scores.py
364
3.953125
4
def scores(x): print 'Scores and Grades' if x < 70 and x > 59: print 'Score:'+ str(x) + ' Your grade is a D' elif x < 80 and val > 69: print 'Score:'+ str(x) + ' Your grade is a C' elif x < 90 and val > 79: print 'Score:'+ str(x) + ' Your grade is a B' else: print 'Score:'+ str(x) + ' Your grade is a A'...
6e92257b849224aab55d126d9eca5cb222e73201
tscizzle/graphpy
/graphpy/edge.py
3,504
3.78125
4
""" Implementation of an edge, as used in graphs """ ################################################################################ # # # Undirected # # ...
b1892a6d7a5f1c5dd5ed011f5442827f7a118da9
elangovan007/PYTHON-TASKS
/task11.py
842
4.09375
4
#Merge a two list using zip lst1=["Dhoni","Raina","Jaddu","Klrahul","Nattu"] lst2=["Rohit","Kohli","Pandya","Bumrah","Chahal"] print("Original List 1:",lst1) print("Original List 2:",lst2) print() x=list(zip(lst1,lst2)) print("Result :",x,sep='\n') print('\n') #merge a given list and the range list lst3=[...
1fc42c384832ddf9f3832da66c15a4e76a108269
Kristjaan/Python_practice
/secretNum.py
2,867
4.0625
4
#!/usr/bin/env python3 # Homework 7.2: Guess the secret number import random import datetime import json def get_score_list(): with open("score.txt", "r") as score_file: global score_list score_list = json.loads(score_file.read()) return score_list def get_high_score(): print("Top ...
e38edda84dc35a2c49c0fcadadcb7f4a649b1dd2
Brollof/Advent-of-Code
/2017/day11/11.py
728
3.75
4
def dir_to_offset(dire): if dire == 'n': return (0, 1, -1) if dire == 'ne': return (1, 0, -1) if dire == 'se': return (1, -1, 0) if dire == 's': return (0, -1, 1) if dire == 'sw': return (-1, 0, 1) if dire == 'nw': return (-1, 1, 0) raise Exception(f"Unknown direction: {dire}") def distance_from_zero(x, y, z...
f9bc25bb9b3b57cff4cc88c449b0d1293cf5f49e
Brollof/Advent-of-Code
/2021/Day8/day8.py
2,126
3.578125
4
def get_2(digits, one, seven, four): for digit in digits: if len(digit - one - seven - four) == 2: return digit assert False, f"2 cannot be calculated from {digits=} using {one=}, {seven=} and {four=}" def get_3(digits, two): for digit in digits: if len(digit - two) == 1: ...
d0e8016624240ed53d09fd22be12132223b9abe7
Brollof/Advent-of-Code
/2017/day7/py/8.py
2,034
3.75
4
import re class TreeNode: def __init__(self, name, w): self.name = name self.w = w self.parent = None self.children = [] self.level = None def add_child(self, child): self.children.append(child) def __repr__(self): return f"N({self.name},{self.w})" ...
d2d9eabee5cafd50621c42fd6c3b4aa149d36eda
Brollof/Advent-of-Code
/2017/day12/12_.py
462
3.59375
4
import networkx as nx with open('input.txt') as file: LINES = file.read().splitlines() # Create a graph of programs graph = nx.Graph() for line in LINES: # Parse the line node, neighbors = line.split(' <-> ') # Add edges defined by this line graph.add_edges_from((node, neighbor) for neighbor in ...
29f265c3fb919c51853d08766bbacf97eef00314
James-Costello/Python_Data_Science
/codewars.py
271
3.671875
4
# Returns the second column y[1] in a sorted arr bound to enumerated values # which increments a counter from 1++ and multiplies it by the value in the arr def sort_by_value_and_index(arr): return [y[1] for y in sorted(enumerate(arr),key=lambda x:(x[0] + 1) * x[1])]
98567fd5e88363b30d230641fbfec2c1a3ff62ff
Caarvalho/SOR-ServClient
/conversor.py
4,609
3.703125
4
def tempo(valor, conv): if conv == 1: return f""" A conversão será de segundos para minutos. {valor} segundo(s) correspondem a {valor/60} minuto(s).""" elif conv == 2: return f""" A conversão será de segundos para horas. {valor} segundo(s) correspondem a {valor/3600} hora...
7178e73db41f583684627a70648f0a8f7c1deb94
dyyfk/cs639_spring19
/assignments/assignment3/multiply.py
1,003
3.78125
4
import MapReduce import sys """ Matrix Multiply in the Simple Python MapReduce Framework """ mr = MapReduce.MapReduce() # ============================= # Do not modify above this line # Implement the MAP function def mapper(rec): if rec[0] == 'a': i = rec[1] val = rec[3] for j in range...
f9687a667ba927f5f0d02bab7388c6b47e46493c
gisellerubin/Hwoptional
/hwex3.py
122
3.8125
4
prompt = "Insert radius of the circle:" radius= input(prompt) radius= int(radius) surface = 2*(3.14*radius) print(surface)
15715e21e910c241ed203eb2c61087be90f441f4
anshika109/python
/balance.py
317
4.03125
4
amt=int(input("enter the amt of phone")) balance=int(input("enter the balance")) if amt<10: balance=balance-50; amt=amt+50; print("amt is",amt) print("balance is",balance) else: print("amt is",amt) print("balance is",balance)
8e199e048e05f44b9702450666b4a049d3a23a47
Junga15/Keras2
/keras31_split.py
341
3.703125
4
#for함수 분석하기 import numpy as np a=np.array(range(1,11)) size=5 def split_x(seq,size): aaa=[] for i in range(len(seq)-size+1): subset=seq[i:(i+size)] aaa.append([item for item in subset]) print(type(aaa)) return np.array(aaa) dataset = split_x(a_size) print("=================") print...
3271644b5888edf5c512d975478c302df8614489
Junga15/Keras2
/keras02_2simulation.py
906
3.5
4
#네이밍 룰 import numpy as np import tensorflow as tf from tensorflow.keras.models import Sequential #from tensorflow.keras import models #from tensorflow import keras from tensorflow.keras.layers import Dense #1.데이터 x_train=np.array([1,2,3,4,5,6,7,8,9,10]) y_train=np.array([2,4,6,8,10,12,14,16,18,20]) x_test=np.array([10...
3b640678f18d363c36b9272c14df73b9bec94a70
Junga15/Keras2
/keras2.0/keras04_validation.py
1,125
3.515625
4
#네이밍 룰 import numpy as np import tensorflow as tf from tensorflow.keras.models import Sequential #from tensorflow.keras import models #from tensorflow import keras from tensorflow.keras.layers import Dense #1.데이터 x_train=np.array([1,2,3,4,5]) y_train=np.array([1,2,3,4,5]) x_validation=np.array([6,7,8]) #머신이 검증용 데이터 y...
de8cd4eba0fe4463304bf33be1203e98c9894c84
Junga15/Keras2
/keras2.0/KEYWORD_argmax.py
246
3.84375
4
import numpy as np x = np.array([1,2,3,4,5]) y = np.array([[1,2,3],[6,5,4],[20,10,100]]) print(np.argmax(x)) ##최대값의 순서(인덱스값) 구하기 print(np.argmax(y,axis=-1)) #-1을 넣어야 최대값의 순서(인덱스값) 구하기
0d5de92e017604f5212da3a76dc9af01e8e2c617
Junga15/Keras2
/keras2.0/keras39_CNN1_explanation.py
725
3.546875
4
[케라스]무작정 튜토리얼13- CNN(Convolution Neural Network) model.add(Conv2D(2, (2,2), input_shape=(5,5,1))) model.add(Conv2D(4, (2,2))) 출처: https://ebbnflow.tistory.com/138 [ebb and flow] 맨처음에 5X5크기(깊이1=흑백)로 자른 픽셀(총25장) 중 2x2(즉 4장)로 자른 것을 2장 내보낸다? from keras.models import Sequential from keras.layers import Flatten, Dense ...
a576975e1d355be4db5a333f18e68b8570a28a86
wianoski/MAVLink
/justGoToCoordinate.py
3,277
3.59375
4
""" Drone taking off and reach target altitude. And then go to the given coordinates on the table. If done then Return to Launch and landing. """ from dronekit import connect, VehicleMode, LocationGlobalRelative import time import math # ---- # FUNCTIONS # ---- # to calculate distance def get_distance_metres(aLocatio...
5ed3d69c499bb6daaa3f3c7c88cdb11d3b355df8
ishaansarna/Alien-Invasion
/alien.py
1,036
3.59375
4
import pygame from pygame.sprite import Sprite class Alien(Sprite): """A class to represent an alien""" def __init__(self, screen, settings): super().__init__() self.screen = screen self.settings = settings self.image = pygame.image.load('resources/alien.bmp') self.re...
3981d1a242217a040a59e2dbfec1c33657333815
AndrissP/icsc-paradigms-and-patterns
/latex/code/patterns/structural/adapter.py
579
3.5
4
class OurMLModel(ABC): """ Our interface """ @abstractmethod def train(...): pass class TheirMLModel(ABC): """ Their interface """ @abstractmethod def training(...) # <-- this method should be called train pass class ModelAdapter(OurMLModel): # <-- implements our interface def __init__(self, model: The...
a782912e8aa66e82b32eeb871a355693ded05e2b
AndrissP/icsc-paradigms-and-patterns
/latex/code/paradigms/dp/dataframes.py
741
3.65625
4
# "Chi2 distance" using plain python def chi2(data, theory, error): err_sum = 0 for i in range(len(data)): if data[i] == theory[i] and error[i] == 0: continue err_sum += (data[i] - theory[i])**2 / (error[i]**2) return err_sum # Using DataFrames: Table contains columns experiment, theory, error # ROOT RData...
0577cb48e0b9ba86351a8eb0fe48e10315431d09
Shilpa-T/InterviewPrep
/Arrays_and_Strings/max_subarray_sum.py
721
3.875
4
# Python program to find maximum contiguous subarray def maxSubArraySum(a): size = len(a) max_so_far = a[0] curr_max = a[0] for i in range(1, size): curr_max = max(a[i], curr_max + a[i]) #print curr_max max_so_far = max(max_so_far, curr_max) #print max_so_far #p...
796525800a6403c598228e023bd95f48f2b9defd
jmbosley/EulerProject
/Euler Project 12.py
398
3.875
4
import math #step 1: generate triangular numbers def triangle(a): return a*(a+1)/2 def numofdivisors(num): factors = 0 for i in range(1,int(math.sqrt(num))): if num%i == 0: factors += 2 else: continue return factors n = 1 div = 0 while div <...
7fc93f7586427b36e77b5469f135ed47962973f3
jmbosley/EulerProject
/Project Euler 29.py
231
3.59375
4
# -*- coding: utf-8 -*- """ Created on Sun Apr 15 11:26:12 2018 @author: Julie """ alist = [] for a in range(2,100+1): for b in range(2,100+1): alist.append(a**b) alist = set(alist) print(len(alist))
7d26ef327189a78794d02ef28d6144eb1ca7d83b
Cellinahrob/Python-Assignment
/Examples 2/student.py
462
3.640625
4
class student: def __init__ (self,first_name,second_name,age): self.first_name=first_name self.second_name=second_name self.age=age def full_name(self): name=self.first_name+self.second_name return name def year_of_birth(self): return 2019-self.age def greetings(self): return "hello{},...
85cc102b3bb5c2e3f92baa5f56e57aef42c9f6ce
wizardq1984/python_learning
/student_score.py
938
3.65625
4
# -*- coding: utf-8 -*- with open('e:/GitHub/python_learning/txt/student_score.txt') as scores: ori_score = [] for line in scores.readlines(): if line[-1] == '\n': line = line.replace('\n', '') # remove \n from every lines line = line.split(' ') ori_score.append(line) ori_sc...
84edd4921193c617755feca8840bc0513914bafb
jmoore87jr/pandas
/generate.py
657
3.6875
4
import pandas as pd import numpy as np import random def generate(rows): """generate two data sets to test merge/join performance""" # random numbers with an ID column at position 0 to merge on df1 = pd.DataFrame(np.random.randint(0,100,size=(rows, 7))).reset_index() df1.columns = ['ID', 'A', 'B', '...
3df4db40ac17099d35a71981a43313941f5b1467
k2Pastor/PolynomialLab
/polynomial.py
4,573
3.75
4
class Polynomial: def __init__(self, coefficients=None): self.coefficients = [] if coefficients is None: raise TypeError("Coefficients cannot be 'None'!") elif isinstance(coefficients, (list, tuple)): if len(coefficients) == 0: raise ValueError("Coeff...
71f42f050b38abbc8e9bb1824c52c5195a4783fa
ImBadnick/CryptographyAlgorithms
/Algorithms/SuccessiveQuadratures/sq.py
1,437
4.125
4
def printList(l,listname): print(listname + " values:", end=' ') for j in range(len(l)): print(l[j], end=' ') print("") def decomposeZ(x): powers = [] i = 1 while i <= x: if i & x: powers.append(i) i <<= 1 return powers def calculateY_2_J(y,max,S): l...
7f5ba9fbe7ea85873fe53453c543217f290141d3
ImBadnick/CryptographyAlgorithms
/Algorithms/GeneratorsNumPseudoCasual/LinearGenerator/linearGenerator.py
1,356
3.765625
4
import math from functools import reduce def printList(l,listname): print(listname + " values:", end=' ') for j in range(len(l)): print(l[j], end=' ') print("") def factors(n): return set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))) def c...
d1d822f3c1b76c2c4953efa1b43f5fe7f8d8c0c1
ImBadnick/CryptographyAlgorithms
/Algorithms/EllipticCurves/kobritz.py
1,063
4.15625
4
class point: def __init__(self, x, y): self.x = x self.y = y def quadraticResidues(module): quadraticresidues = [] for i in range(module): quadraticresidues.append(point(i,(i**2) % module)) return quadraticresidues if __name__ == '__main__': print("Transform m into a point ...
b3c317b658988b0e4ea28cace78a99e17c99411d
mriganv/python-challenge
/PyBank/main.py
3,422
3.78125
4
import os import csv csvpath = os.path.join('Resources','budget_data.csv') #setting the inital total months to zero to begin with total_months = 0 # list for total months totalmonths = [] #setting the initial profit/loss count to zero total_profitloss = 0 # list for appending the profit/loss monthly_change = [] #li...