blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
7c348d0c9ce327a36a746fcb772bd3632c2e4204
delaneycarleton/uoregon-cis313
/proj2_data/carleton/problem2.py
812
3.5
4
import sys def main(): with open(sys.argv[1]) as f: num = int( f.readline().strip()) for _ in range(num): line = f.readline().strip() opens = [] isValid = True open_char = "([{<" close_char = ")]}>" for i in range(len(line)): ...
5c103c0f6f6fbc423a8b51374039af7132269a20
M0R1u5/Part2_Task6
/Task6.py
77
3.8125
4
number = input('Enter an integer: ') numb = str(number + ' ') print(10*numb)
1ef85de140e409b3d49f9516a496921248d7f955
musarratChowdhury/ProblemSolvingWithJavascript
/breakingTheRecords.py
606
3.578125
4
# scores = [3 ,4 ,21 ,36 ,10 ,28 ,35, 5 ,24 ,42] def breakingRecords(scores): # Write your code here temporary_max = scores[0] temporary_min = scores[0] maximum_score = [] minimum_score = [] result_arr = [] for score in scores: if score<temporary_min: minimum_sco...
71bceef4381b351bffd5f1a9dd52c6161d667464
Stormlight-Coding/regex-practice
/regex.py
5,781
3.90625
4
import re # FOR displaying the groups it can only be used if there is a known output. DOES NOT WORK WITH A "NONE TYPE"!!!! # if you are going to have a possible None Type, you need to put logic in to catch it # phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') # # data = input() # # mo = phoneNumRegex.search(da...
5ebb8cf419dd497c64b1d7ac3b22980f0c33b790
sberk97/PythonCourse
/Week 2 - Mini Project Guess number game.py
2,289
4.21875
4
# template for "Guess the number" mini-project # input will come from buttons and an input field # all output for the game will be printed in the console import random import simplegui # helper function to start and restart the game def new_game(): # initialize global variables used in your code here global s...
3878d38ef86301060b4f9e9fd8624afc0379021d
leegj93/PythonProject
/Code03-01 SQLite 데이터 입력.py
453
3.953125
4
import sqlite3 conn = sqlite3.connect("samsongDB")# 1. DB connecting cur = conn.cursor() # 2. create cursor(connected rope) sql = "CREATE TABLE IF NOT EXISTS userTable(userID INT, userName char(5))" cur.execute(sql) sql= "INSERT INTO userTable VALUES(1, '홍길동')"; cur.execute(sql) sql= "INSERT INTO userT...
563b3341cab49a64ba69d6f1ebf14ad8815e65b3
Carlosiiv/Algos
/Python_Algo_Solutions/hello_world.py
606
3.921875
4
# Task 1: print hello world print("Hello World!") msg = "Hello World!" # Task 2: hello name name = "Carlos" print("Hello", name,"!") print("Hello " + name + "!") # Task 3: favorite number number = 42 print("Hello" , name, "!", "My favorite number is", number,".") print(f'{"Hello " + name + "!" + " My favorite number i...
37d73ba59b4279905f3b0bd3575c87a5e664144a
Carlosiiv/Algos
/Python_Algo_Solutions/Functions_Basics1.py
1,665
3.921875
4
#1 prints out 5 def a(): return 5 print(a()) #5 #2 5+5=10 Prints 10 def a(): return 5 print(a()+a()) #10 #3 Returns 5 function ends def a(): return 5 return 10 print(a()) #5 #4 returns 5 funtion ends def a(): return 5 print(10) print(a()) #5 #5 Prints 5 but doesnt return anything so x = nul...
2eb0fc12153dd9c11fe1b3ed4391c811aa8ca559
mike-shevchuk/CodeWars
/Multiples of 3 or 5.py
113
3.84375
4
def solution(number): return sum([i for i in range(number) if (i % 5 == 0 or i % 3 == 0)]) print(solution(10))
1b71cf284540511a24d5d45136738c32f7323846
PRASASTIRAI/project-150
/Random_country_and_city.py
2,057
3.9375
4
# -*- coding: utf-8 -*- """ Created on Sun Oct 3 18:24:55 2021 @author: hp """ from tkinter import* import random root=Tk() root.title("RANDOM LIST ANS LUCKY FRIEND GENERATER") root.geometry("700x400") enter_country=Entry(root) enter_country.place(relx=0.5,rely=0.2,anchor=CENTER) enter_city=Entr...
e909d198f246c9c8e10931e57a8d14c3c8961d7d
shantanuHubb/facuilty_Time_Table_System-
/subject1.py
506
3.53125
4
from Tkinter import * top=Tk() top.config(background="brown4") top.title("WELCOME") top.geometry("1600x900") Label(top,text="SUBJECT NAME=",fg="black",bg="brown4",bd=14,font=("times",27)).place(x=300,y=215) el=Entry(top,font=("arial",21)) el.place(x=690,y=230) Button(top,text="submit ",fg="white...
633fa2812a8a223fdff3ec482404295c678874e3
jihansalma/QUIZ-4
/Quiz42_Jihan Salma R.W._1201180431.py
179
3.640625
4
fruits = ['Nanas', 'Apel', 'Pepaya', 'Kentang'] for i in range (4) : print(fruits[i]) length = len(fruits) i = 0 while i < length: print(fruits[i]) i += 1
8130b1edf4df29a9ab76784289a22d5fb90863e7
ridhishguhan/faceattractivenesslearner
/Classify.py
1,158
3.6875
4
import numpy as np import Utils class Classifier: training = None train_arr = None classes = None def __init__(self, training, train_arr, CLASSES = 3): self.training = training self.train_arr = train_arr self.classes = CLASSES #KNN Classification method def OneNNClassi...
8f4f102f4568c38e549ef17db710cc380141bb14
Williamsjanthony15/ceaser_cipher
/ceaser_cipher/ceaser_cipher/ceaser_cipher.py
1,235
3.78125
4
import nltk from nltk.corpus import words nltk.download('words', quiet=True) # nltk.download('names', quiet=True) word_list = words.words() # print(word_list) # string = 'computer' # word_count # if string in word_list: # word_count +=1 # # print(' I am here') # else: # print('I am not here')\ #...
1a3df69863e18ff518fe81d2d649cbdaeda9adbe
ginajoerger/Artificial-Intelligence
/15 Puzzle/15 Puzzle.py
5,940
4.03125
4
from queue import PriorityQueue import sys numNodes = 0 class Node: def __init__(self, state, parent, operator, depth, pathCost): self.state = state self.parent = parent self.children = list() self.operator = operator self.depth= depth self.pathCost = pathCost ...
289a90323ade1b352c59eda2657e6ae0237fc600
nupur0502/Udemy
/FizzBuzz/solution.py
368
3.9375
4
def fizzBuzz(self, s): string = [] for n in range(1, s + 1): if n % 3 == 0 and n % 5 == 0: string.append("FizzBuzz") elif n % 3 == 0: string.append("Fizz") elif n % 5 == 0: string.append("Buzz") else: ...
8ef3c6bb06b8ed4c9181e78f9b4ef30059334374
dtroupe18/BasicPerceptron
/perceptron.py
1,124
3.609375
4
# a single perceptron import numpy as np class Perceptron(object): def __init__(self, rate = 0.01, niter = 10): self.rate = rate self.niter = niter def fit(self, X, y): """ Fit training data :param X: Training vectors, X.shape: [samples, features] :param y: Tar...
8d82910e342182c0c6856ffe129bb94ad3391c39
Evgeniy-code/python
/prob/calculator.py
521
4.3125
4
#!/usr/bin/env python3 a = float(input("введите первое число:")) what = input("что делаем (+:-:*:/):") b = float(input("введите второе число:")) if what == "+": d = a + b print("равно:" + str(d)) elif what == "-": d = a - b print("равно:" + str(d)) elif what == "*": d = a * b print("равно:" + s...
84fc914a6678914e0e8898d4c4451d76c9810135
fjollabeqiri/knapsack_problem
/Knapsack.py
4,576
3.96875
4
import random from typing import List class Item: def __init__(self, item_id, weight, value): self.id = item_id self.weight = weight self.value = value self.ratio = value/weight class Knapsack: def __init__(self, items_in, items_out, capacity): self.items_in = items_i...
210cdca8180547ed320f5c534cd0013985477424
zpak96/ClassWork
/IntroToPython/class.py
121
3.546875
4
#!/usr/bin/python3 # Zane Paksi def gc(a, b): r = a % b a = a - r return a print(gc(a=int(input('a: ')), b=3))
7677c3c2db21b429b009bbd88ee8b888e4522e7b
BarbecuePizza/py1000
/005字符串赋值.py
503
3.859375
4
""" ans = input("您是否喜欢喝咖啡yes/no:") if ans == "yes": print("制作咖啡") elif ans == "no": print("随时恭候") """ # 字符串变量中所包含的索引值 astr = "python" print(astr[0:2]) #变量[角标的起始位置 :角标的结束位置] print(astr[0:8]) print(astr[0:8:2]) #变量[角标的起始位置 :角标的结束位置 : 步长值] print(astr[-2]) print(astr[-1:-7:-1]) #反向取值 print(astr[:]) print(astr[::-1...
c721631032d3d148c07a7235b0476f2033794e4b
ilankham/advent_of_code_2020
/day10_adapter_array.py
3,599
3.546875
4
""" Solutions for https://adventofcode.com/2020/day/10 """ # import modules used below. from collections import Counter, UserList from itertools import chain, combinations from math import prod # Part 1: What is the number of 1-jolt differences multiplied by the number of # 3-jolt differences in the provided data fi...
8e7f9c407cf091a1b4b7eede31be320598d9875b
ilankham/advent_of_code_2020
/day01_report_repair.py
1,777
4.0625
4
""" Solutions for https://adventofcode.com/2020/day/1 """ # Part 1: Find the two entries that sum to 2020 in the provided data file # and then multiply those two numbers together. # Read positive integer values from data file. with open('data/day01_report_repair-data.txt') as fp: data_values = [int(line.rstrip(...
2cd084fa011c52f379ff5237fd6115cd7dce7dea
ilankham/advent_of_code_2020
/day06_custom_customs.py
1,868
3.984375
4
""" Solutions for https://adventofcode.com/2020/day/6 """ # import modules used below. from collections import UserDict # Part 1: In the provided data file, how many group-wise "yeses" occur? # Create data model for "group responses" in data file. class GroupResponses(UserDict): """ Data Model for "question gr...
1cdb26997f2e34b12970ba968ff4f0c1e279c03d
DaneSlattery/oops-hashcode-2019
/simple.py
1,125
3.515625
4
rowlist = list() # a_example # b_small # c_medium # d_big with open('d_big.in' , 'r') as f: line_one = f.readline().split() R = line_one[0] C = line_one[1] L = line_one[2] H = line_one[3] if (int(H) > int(C)): H = C print('Rows: ' + R) print('Columns: ' + C) print('Min Ingredient: ' + L...
8a000b72ad1df43bd275d8fa235dee249ecda2bd
Ali-Parandeh/dominos
/dominos/utils.py
1,007
3.609375
4
''' Dominos Pizza API utility functions. ''' import re def enum(**enums): ''' Utility function to create a simple enum-like data type. Behind the scenes it is just a list. :param list enums: A list of key value pairs. :return: A simple list. :rtype: list ''' return type('Enum', (), enu...
5c4362ae8eea49bd105ae1f0ffced5d62aba12ed
ArnoldKevinDesouza/258327_Daily_Commits
/Dict_Unsolved02.py
209
4.5
4
# Write a Python program to convert a list into a nested dictionary of keys list = [1, 2, 3, 4] dictionary = current = {} for name in list: current[name] = {} current = current[name] print(dictionary)
3963dccc95056b06715cf81c7a8eab7091c682a5
ArnoldKevinDesouza/258327_Daily_Commits
/If_Else_Unsolved04.py
314
4.15625
4
# Write a program to get next day of a given date from datetime import date, timedelta import calendar year=int(input("Year:")) month=int(input("\nMonth:")) day=int(input("\nDay:")) try: date = date(year, month, day) except: print("\nPlease Enter a Valid Date\n") date += timedelta(days=1) print(date)
52effe011dc2dce66488280fad756db564e61d9f
romanvoyt/ds_algs
/algorithms/quick_sort.py
862
3.96875
4
from typing import List import random class QuickSort: def __int__(self, array: List[list]): self.array = array def swap(self, a, b): temp = a a = b b = temp # To do: fix bug (during the sorting the repeatable elements of the list are deleted) def sort(self, array): ...
7f9b8978b90454baec03b833d291fc1bf49959ba
KelstonClub/20191130
/testing.py
2,291
3.6875
4
#!python import unittest import tommy as challenges class TestChallenges(unittest.TestCase): def test_fizz(self): actual = list(challenges.fizz(10)) expected = [1, 2, 3, 4, 5, 6, 'Fizz', 8, 9, 10] self.assertEqual(actual, expected) def test_numbers(self): actual ...
dd652b879fd1162d85c7e3454f8b724e577f5e7e
Einsamax/Dice-Roller-V2
/main.py
2,447
4.375
4
from time import sleep import random #Introduce user to the program if __name__ == "__main__": #This does a good thing print ("*" * 32) print("Welcome to the Dice Roller!".center(32)) print ("*" * 32) print() sleep(1) def roll_dice(diceamnt, diceint): #Defines function roll_dice ...
cad82c7d702e53a3cb6816d2668a10b2aa70ea65
mariotalavera/ai_jetson_nano
/primer/pythonArrays.py
159
3.515625
4
gradeArray=[] gradeArray.append(5.5) gradeArray.append(3.2) gradeArray.append(-2.7) print(gradeArray) gradeArray[1]=9.9 print(gradeArray[0]) print(gradeArray)
6c89d0c81a614532b532e70da283af3f7b3aa077
mariotalavera/ai_jetson_nano
/primer/userInput.py
120
3.953125
4
x=float(input("Please enter First Number: ")) y=float(input("Please enter Second Number: ")) z=x+y print("x + y = ", z)
f7bbc59863e4bb7060063b54a317e46b3f610ddf
abdullahshk17/Python-Programs
/31. Check prime number within a given range.py
303
3.828125
4
import math low=int(input()) high=int(input()) prime=[] for num in range(low,high+1): factor=0 for i in range(2,int(math.sqrt(num))+1): if num%i==0 : factor+=1 break if factor==0: prime.append(num) print("List of prime numbers is",prime)
456f4728d184207209eb09c73a9596509bb38988
abdullahshk17/Python-Programs
/9.Program to reverse internal content of each word.py
244
3.65625
4
s=input() #Learning Python is easy l=s.split() new=[] for i in range(len(l)): new.append(l[i][::-1]) print(new) #['gninraeL', 'nohtyP', 'si', 'ysae'] for i in range(len(new)): print(new[i],end=" ") #gninraeL nohtyP si ysae
b0002056658bc77575318dcdec59d11d5e4756c7
abdullahshk17/Python-Programs
/11.Program to merge characters of 2 strings into a single string.py
122
3.734375
4
s1=input("Enter First String:") #ravi s2=input("Enter Second String:") #mehta output=s1+s2 print(output) #ravimehta
9b866ee496bae566841b445e8263337cb793c6b6
abdullahshk17/Python-Programs
/17.Write a program to find the number of occurrences of each character present in the given String- Input ABCABCABBCDE & Output A-3,B-4,C-3,D-1,E-1.py
211
3.546875
4
def count(s): l=sorted(list(set(s))) for i in range(len(l)): new=s.count(l[i]) print("{}-{}".format(l[i],new),end=" ") #A-3 B-4 C-3 D-1 E-1 s=input() #ABCABCABBCDE count(s)
e5ba92e030f8f9c51964e21b7cfdef437ccde0c1
rdagnoletto/AlgorithmsOOP-PracticePython
/HRcountSwapNodes.py
2,311
3.703125
4
#!/bin/python3 import os import sys # # Complete the swapNodes function below. # class Node: def __init__(self,key,depth): self.left = None self.right = None self.val = key self.depth = depth def addChildren(self,c): children = [] if c[0] != -1: ...
c6aadc50833356e4ce23f7f2a898634ff3efd4a7
dsimonjones/MIT6.00.1x---Introduction-to-Computer-Science-and-Programming-using-Python
/Week2- Simple Programs/Lecture4- Functions/Function isIn (Chap 4.1.1).py
611
4.1875
4
# -*- coding: utf-8 -*- """ @author: ali_shehzad """ """ Finger exercise 11: Write a function isIn that accepts two strings as arguments and returns True if either string occurs anywhere in the other, and False otherwise. Hint: you might want to use the built-in str operation in. """ def isIn(str1, str2...
55b9e5a113b11527ab82051a40b007fd8748d1eb
PPL-IIITA/ppl-assignment-AyushAgnihotri
/Question-8/source (copy)/girl.py
1,034
3.625
4
class girl: 'Class for girl' name = '' attractiveness = 0 maintenance_budget = 0 intelligence = 0 relationship_status = '' boyfriend = '' happiness=0 type_= '' def __init__(self,name,attractiveness,maintenance_budget,intelligence,type_): 'Constructor fot initialising girl' self.name = name self.attracti...
57f362801ece788c525d1d5d0c195d474d58182f
dravya08/workshop-python
/L11/P5.py
460
4
4
# wappp to ask user for dob and find the birthday import datetime try: year = int(input("Enter year ")) month = int(input("Enter Month ")) day = int(input("Enter day ")) dob = datetime.date(year,month,day) print(dob) days_in_year = 365.2425 dt = datetime.datetime.now().date() age = (dt - dob) / datetime...
20c118532b54e4d820bcdc98d62e8cf0e68af89b
dravya08/workshop-python
/L12/P5.py
1,811
3.546875
4
from tkinter import * from tkinter import messagebox win = Tk() win.title("Kamal Classes") win.geometry("300x500+200+100") win.configure(background='powder blue') def f1(): fb,mat ="","" if s1.get() == 1: fb = "Fantastic" if s1.get() == 2: fb = "Excellent" else: fb = "Superb" if n.get()==1: mat += "No...
3bc103df43f3b4e607efa104b1e3a5a62caa1469
LaurenShepheard/VsCode
/Learningpython.py
1,227
4.375
4
for i in range(2): print("hello world") # I just learnt how to comment by putting the hash key at the start of a line. Also if I put a backslash after a command you can put the command on the next line. print\ ("""This is a long code, it spreads over multiple lines, because of the triple quotaions and b...
2e58e78005d5cc25a79008d912c0691db06d92f8
surajrnair007/Big-Data-Problems-and-Assignments
/A1Prob3aMapperV1.0.py
1,569
4.03125
4
""" This is a mapper program. It reads an input file which is in the format Username<space>DNAseq. The program considers the DNA seq as Key and Username as the Value. It sorts the records on the DNA seq and then stores each record in the output file in the format DNAseq<tab>Username """ # Open and read i...
cfa5d433e0390c4e199e9f2ad7fcdad9ad2c6191
Matheus-Soares/AnalisadorSintatico
/symbol_table.py
1,274
3.5
4
class SymbolTable: def __init__(self): self.table = {} def add(self, name, cat, type, level, params=None): self.table[str(name)] = {} self.table[str(name)]["cat"] = cat self.table[str(name)]["type"] = type self.table[str(name)]["level"] = level self.table[str(...
ffd58f656b6ba58dcde081c1545e4278c29a5ce6
blankjul/dtree-python
/src/table.py
5,387
3.578125
4
# -*- coding: utf-8 -*- import csv from tabulate import tabulate from join import join_index def gen(oReader): for row in oReader: yield row def create_from_csv(p_strPath, p_strDelimiter=';', p_strQuotechar="|"): with open(p_strPath, 'rb') as csvfile: reader = csv.reader(csvfile, delimiter=...
1b55bfe95d0ee6f87aa7325851c6fa954b18e41b
sebschneid/adventofcode2019
/day04/solution2.py
901
3.609375
4
import time import collections import numpy as np puzzle_input_string = "356261-846303" puzzle_input = (356261, 846303) time1 = time.time() count_passwords = 0 for number in range(*puzzle_input): number_string = str(number) digits = [digit for digit in number_string] ascending_order = sorted(digits) == ...
db52c61919c832c7e0afe321049fa77a7e4b2fe6
R-Stefano/AI-assignment2
/AStar.py
2,249
3.953125
4
import queue as q from collections import namedtuple max_iterations=1000000 def search(start): """ Performs A* search starting with the initialized puzzle board. Returns a namedtuple 'Success' which contains namedtuple 'position' (includes: node, cost, depth, prev), 'max_depth' and 'nodes_expanded' ...
35fa5c44e533394b62100fa936bc063b3b7e863e
mberrett/Hadoop
/Weather_Forecast/mapWD.py
669
3.671875
4
#!/usr/bin/env python import sys # input comes from STDIN (standard input) for line in sys.stdin: # remove leading and trailing whitespace line = line.strip() # split the line into words words = line.split() # increase counters for word in words: # write the results to STDOUT (standard...
20b609e21199215965d79601920124905c16ef2d
katesem/data-structures
/hash_table.py
884
4.25
4
''' In Python, the Dictionary data types represent the implementation of hash tables. The Keys in the dictionary satisfy the following requirements. The keys of the dictionary are hashable i.e. the are generated by hashing function which generates unique result for each unique value supplied to the hash function. The o...
763602e75ebb5e21a69239e2f9c095b1d752ed45
avgn/6.00.2x
/noReplacement.py
804
3.921875
4
import random def drawBalls(): bucket = [0, 0, 0, 1, 1, 1] d1 = random.choice(bucket) bucket.pop(d1) d2 = random.choice(bucket) bucket.pop(d1) d3 = random.choice(bucket) bucket.pop(d3) if d1 + d2 + d3 == 0 or d1 + d2 + d3 == 3: return True else: return False def noR...
d3f5eee43bc21a6cf6517675db139478eb563386
bbisher/Card-Game
/Deck.py
1,226
3.6875
4
from Card import Card import random class Deck(object): def __init__(self): cards_in_deck = 52 self.deck_of_cards = [] index = 0 while index < cards_in_deck: card_number = index % 13 suit_number = int(index / 13) new_card = Card() new_card.number = card_number new_card.suit = suit_number new...
17ca710d855a20c14af708f45da79d42017ff129
renandantas/DeepLearning
/Cancer de mama/Cancer_Mama_simples.py
4,304
3.625
4
import pandas as pd # Classe utilizada para a criação da rede neural import keras from keras.models import Sequential # Classe para se utilizar camadas densas na rede neural # ou seja, cada um dos neuronios é ligado com todos os neuronios da camada subsequente from keras.layers import Dense from sklearn.model_selectio...
5af68810c604e1eb30e057ec69a6b338c1e053fe
renandantas/DeepLearning
/Redes_Neurais_Convolucionais/Digitos/Classificação_digitos.py
4,448
3.546875
4
# Usada para visualizar as imagens que esto na base de dados import matplotlib.pyplot as plt from keras.datasets import mnist from keras.models import Sequential # Flatten -> Transforma uma matriz em um vetor # Conv2D -> Camada de convoluo # MaxPooling2d -> Serve para infatizar as caracteristicas ou dos obejetos para...
411d1767e1b719d938b7ded2689e34f03d478bcc
wukunzan/algorithm004-05
/Week 1/id_040/LeetCode_206_040.py
1,005
4
4
# 反转一个单链表。 # # 示例: # # 输入: 1->2->3->4->5->NULL # 输出: 5->4->3->2->1->NULL # # 进阶: # 你可以迭代或递归地反转链表。你能否用两种方法解决这道题? # Related Topics 链表 # leetcode submit region begin(Prohibit modification and deletion) # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next ...
848c6739f82cec9613049717dc5a143486752f71
gminafuzz/barry
/dict_people.py
1,099
4.03125
4
people = {} print ('Welcome to base of person!') log = input('You want to add new person or watch base? (a/w):') if log == 'a': while True: lastname = input('Input lastname of new person:') firstname = input('Input firstname of new person:') gender = input('Input gender of new person:') ...
fb20e9c8addc53b946081f1fceabcd719e85fa4b
jacarvalho/SimuRLacra
/Pyrado/pyrado/plotting/categorial.py
6,379
3.625
4
import numpy as np from matplotlib import pyplot as plt from typing import Sequence def render_boxplot( ax: plt.Axes, data: [Sequence[list], Sequence[np.ndarray]], x_labels: Sequence[str], y_label: str, vline_level: float = None, vline_label: str = 'approx. solved', alpha: float = 1., ...
94f1995d73d9e2a22d3a966619e2b51ed0228e5f
jacarvalho/SimuRLacra
/Pyrado/pyrado/utils/__init__.py
589
3.796875
4
def get_class_name(obj) -> str: """ Get an arbitrary objects name. :param obj: any object :return: name of the class of the given object """ return obj.__class__.__name__ def issequence(obj) -> bool: """ Check if an object is a sequence / an iterable. .. note:: Using agai...
b4c610c520aa24f910cc16165dac7efa82b9cde1
dongul11/lpthw
/ex13.py
380
3.875
4
from sys import argv # read the WYSS section for how to run this script, first, second, third = argv print ("The script is called:", script) print ("Your first variable is:", first) print ("Your second variable is:", second) print ("Your third variable is:", third) a = input("Input a #:") b = input("Input another on...
77f8af91c65850e861023b9209a3b610464a9dec
h-parker/commencement-speech-generator
/front-end/user_interface.py
2,131
3.578125
4
import streamlit as st import pandas as pd import numpy as np import project_functions def main(): # Render the readme as markdown using st.markdown. with open('opening.md', 'r') as f: opening = f.read() readme_text = st.markdown(opening) # add a selector for the app mode on the sidebar. st.sidebar.title("W...
a5210445c8d2dd014113e44862152a0215244112
jokeewu/python-crash-course
/chapter_04/list_slice.py
168
4.03125
4
# coding=utf-8 # 列表切片 chars = ['a', 'b', 'c', 'd'] print(chars[1:3]) print(chars[-1:]) print(chars[:2]) # 列表复制 new_chars = chars[:] print(new_chars)
2337b4d4ebe4eefe8c3fd6b59ed42d67aeccc457
jokeewu/python-crash-course
/chapter_11/test_name_function.py
424
3.578125
4
import unittest from name_function import get_formatted_name class NameTestCase(unittest.TestCase): def test_first_last_name(self): formatted_name = get_formatted_name('Jacky', 'Wu') self.assertEqual(formatted_name, 'Jacky Wu') def test_first_last_middle_name(self): formatted_name = ...
de0a468c4cddc565aaa8bf8c9e166f60d65a6b51
jokeewu/python-crash-course
/chapter_03/list_reverse.py
129
3.65625
4
# coding=utf-8 # 列表反转 chars = ["a", "b", "c"] chars.reverse() # 影响原列表 print(chars) chars.reverse() print(chars)
40f0446fc1edc6915ce6081cdd00285c4d930c6c
mshalvagal/cmc_epfl2018
/Lab7/Webots/controllers/mouse/musculoskeletal/MuscleJoint.py
2,664
3.734375
4
""" MuscleJoint class """ import numpy as np class MuscleJoint(object): """This class provides the interface between Muscles and Joints.""" def __init__(self, muscle, joint, parameters): """ Class initialization.""" self.muscle = muscle self.joint = joint self.theta_max = np....
02aa151e60891f3c43b27a1091a35e4d75fe5f7d
mshalvagal/cmc_epfl2018
/Lab0/Python/1_Import.py
1,610
4.375
4
"""This script introduces you to the useage of Imports in Python. One of the most powerful tool of any programming langauge is to be able to resuse code. Python allows this by setting up modules. One can import existing libraries using the import function.""" ### IMPORTS ### from __future__ import print_function # ...
03e488f5f0e683bb9f73e56dcf2f53e014f9409e
kibitzing/FluentPython
/archive/To01-25/01-22/keunhoi_01-22.py
1,355
3.765625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # p605-609 # Example 19-17~21 """ 예제 위주로 작성 객체 속성과 클래스 속성 property의 고전적인 구문 """ # Example 19-17 class LineItem1: """ property를 사용한 예제 """ def __init__(self, description, weight, price): self.description = description self.weight = weight ...
1f4c6caff70e9824ab454861d22e5aef971a51d1
kibitzing/FluentPython
/archive/To11-12/11-14/seongbin_11_14.py
706
3.75
4
class Foo: def __getitem__(self,pos): return range(0, 30, 10)[pos] f = Foo() for i in f: print(i) print(20 in f) print(15 in f) import collections Card = collections.namedtuple('Card',['rank','suit']) class FrenchDeck: ranks = [str(n) for n in range(2,11)]+list('JQKA') suits = 'spades diamonds ...
e1c6a2d3ef66d6a96b2533c27df808d42c82e95f
kibitzing/FluentPython
/archive/To01-25/01-22/jiyun_01-22.py
2,939
3.765625
4
class LineItem1: def __init__(self, description, weight, price): self.description = description self.weight = weight self.price = price def subtotal(self): return self.weight * self.price # >>> raisins = LineItem('Golden raisins', 10, 6.95) # >>> raisins.subtota...
cac76b7094108398b256e29e9022ccfca3b062a4
kibitzing/FluentPython
/archive/To01-25/01-23/jingu_01-23.py
1,172
3.703125
4
# Created by Jingu Kang on 01-23 # reference: Fluent Python by Luciano Ramalho # learned how to add docs to property, use vars, set getter and setter in a different way. class Foo: @property def bar(self): '''The bar attribute''' return self.__dict__['bar'] @bar.setter def bar(self, v...
8ca1935a02eb7c5af940ef55651429f801d10e61
kibitzing/FluentPython
/archive/To10-29/10-30/sanghong_10-30.py
2,208
3.546875
4
#!/usr/bin/envs python3 # -*- coding: utf-8 -*- ################################# # # Inha University # DSP Lab Sanghong Kim # # ################################# """ 2018_10-30_Fluent_Python @Author Sanghong.Kim 오늘은 예제만 돌려 보았다. """ # Import Modules import time import os import sys import argparse import f...
5d891f17b02a931d3782e3ff51bb3201e400db12
kibitzing/FluentPython
/archive/To11-19/11-22/keunhoi_11-22.py
1,540
3.859375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # p347-351 (actually 352) # Example 12-1 ~ 5 ''' __setitem__과 collections.UserDict에 대한 내용. + 클래스 상속 ''' import collections class DoppelDict(dict): def __setitem__(self, key, value): super().__setitem__(key, [value] * 2) class AnswerDict(dict): def __getitem__(self, ...
f5ae4c3dc4c6a7cd34f3e446b56fe67cdd97ce40
kibitzing/FluentPython
/archive/To11-19/11-23/seongbin_11_23.py
767
3.859375
4
class DoppelDict(dict): def __setitem__(self, key, value): super().__setitem__(key,[value]*2) dd = DoppelDict(one=1) print(dd) dd['two'] = 2 print(dd) dd.update(three =3) print(dd) class AnswerDict(dict): def __getitem__(self, item): return 42 ad = AnswerDict(a='foo') print(ad['a']) d = {} d...
bb263b105e528123a3002adbf29a1c7b6f078c72
kibitzing/FluentPython
/archive/To10-12/10-12/keunhoi_10-12.py
1,658
3.515625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import math print([callable(obj) for obj in (abs, str, int, float, 13, 'str', math)]) import random class Lotto: def __init__(self, items): self._items = list(items) random.shuffle(self._items) def pick(self): self.numbers = [] for i in range(6): self.numb...
53c926599d106529172857e53c8f2d4aaa347e54
kibitzing/FluentPython
/archive/To12-14/12-11/jingu_12-11.py
1,320
3.796875
4
#!/anaconda3/envs/tensorflow/bin/python # -*- coding: utf-8 -*- """ Created by Jingu Kang on 11/12/2018. Copyright © 2018 Jingu Kang. All rights reserved. DESCRIPTION: When to use Generate function? How to use more effieciently with itertools? """ class ArithmeticProgression...
d2277970789fc7a457e98c843a740a3c30d3a459
kibitzing/FluentPython
/archive/To10-29/10-29/seunghyun_10-29.py
726
4.09375
4
class Bus: def __init__(self, passengers=None): if passengers is None: self.passengers = [] else: self.passengers = list(passengers) def pick(self, name): self.passengers.append(name) def drop(self, name): self.passengers.remove(name) ...
ed8daafff478fd97ca91fdcf47fef624e02bc598
kibitzing/FluentPython
/archive/To12-21/12-17/jingu_12-17.py
1,736
3.53125
4
#!/anaconda3/envs/tensorflow/bin/python #-*- coding: utf-8 -*- """ Created by Jingu Kang on 17/12/2018. Copyright © 2018 Jingu Kang. All rights reserved. DESCRIPTION: simple variation of example source using with and stdout.write """ import sys class LookingMinus: def __...
203e8b01e97d053c33ce1e37ea499b16dfed2960
kibitzing/FluentPython
/archive/To11-05/11-05/keunhoi_11-05.py
1,930
3.609375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # p252-256 ''' 예제에 @property를 사용하여서 visualize 매소드를 추가함. ''' import datetime import math import numpy as np from matplotlib import pyplot as plt # 9-4 class Demo: @classmethod def klassmeth(*args): return args @staticmethod def statmeth(*args): return args pr...
42a52e8994dd790ea8b5ffb45d1a2a66c4ddbea7
danielrbk/Projects
/Generalized Euler Problems/problem16.py
146
3.59375
4
""" trivial in python """ t = int(input()) for a0 in range(t): n = int(input()) n = str(2**n) print(sum([int(x) for x in n]))
ca7a4e7e278b23bdaef2eea41c0b859e98ae00ab
danielrbk/Projects
/Generalized Euler Problems/problem17.py
3,025
3.96875
4
""" Challenge link: https://www.hackerrank.com/contests/projecteuler/challenges/euler017 ------------ Description: For T test cases, print out N in worded numbers, i.e: 13 is thirteen ------------ Constraints: 1 <= T <= 10 1 <= N <= 10**12 ------------ Algorithm: A bit of a pain to implement the algor...
ede1885178d2d73ebb9e09aa7e690a722a0a0636
MojoJolo/code_snippets
/Python/count_unique_words.py
428
3.921875
4
# Count unique words in a list def countUniqueWords(words): wordList = [] for word in words: # Get all the word in the dictionary list wl = [w['word'] for w in wordList] if word not in wl: wordList.append({'word': word, 'count': 1}) else: # get the current word in the dictionary list ...
6767fbaf980420e69a36decdf303682deade4109
Visheshkant/My_codes
/gui_calcy.py
3,428
3.796875
4
from tkinter import * gui = Tk() gui.title("Simple Calculator") gui.resizable(0, 0) gui.geometry("300x200") expression = "" # ******************************** Backend ************************************* # ****** For press function ****** def press(num): global expression expression+=str(num) ...
87d98c47c12298664e090be70942a405a3b7055a
CHyuye/Python
/lecture04/Algorithm_research.py
1,346
3.640625
4
""" 广度优先搜索 -- 一种对图进行搜索的算法 广度优先搜索会优先从离起点近的顶点开始搜索 """ from collections import deque # 模块提供一些有用的集合类 graph = {} graph['you'] = ['alice', 'bob', 'claire'] graph['bob'] = ['anuj', 'peggy'] graph['alice'] = ['peggy'] graph['claire'] = ['thom', 'jonny'] graph['anuj'] = [] graph['peggy'] = [] graph['thom'] = [] graph...
f99c73ad9d430e13e868d69f429e28109712a5df
CHyuye/Python
/lecture06/whlie_day_03.py
1,736
4.09375
4
""" 作者:陈志安 功能:计算出时间,是几年几天 """ from datetime import datetime def is_leap_year(year): """ 判断是否是闰年 """ is_leap = False if (year % 400 == 0) or (year % 4 == 0) and (year != 0): is_leap = True return is_leap def main(): """ 主函数 """ # input_date_str = inp...
284bc204ed2f1e0a77165a97ba635d904b7e7773
CHyuye/Python
/lecture09/AQI_v3.0.py
735
3.59375
4
""" 作者:陈志安 日期:19/3/21 功能:AQI计算 版本:v.1 """ import csv import json def process_json_file(filepath): """ 解码json文件 """ f = open(filepath, mode='r', encoding='utf-8') city_list = json.load(f) return city_list def main(): """ 主函数 """ filepath = input('请输入json文件名') city_list = process_json_fi...
9be2af7ed65654c93ea19f5b4388126b4b627fdb
CHyuye/Python
/Card_program/python_variable.py
3,301
4.28125
4
""" 变量 : 1、变量的引用 2、可变和不可变类型 3、全局变量和局部变量 """ """ 1、变量的引用 —— 变量和数据都是保存在内存中 在python中函数的参数传递以及返回值都是靠引用传递 变量和数据是分开存储的 数据保存在内存中的一个位置 变量保存着数据在内存的地址 变量中记录数据的地址就叫引用 id() 方法可以查看变量中保存数据所在的内存地址 """ # 注意:当给一个变量赋值的时候,本质上是修改了数据的引用 # · 变量不再对之前的数据引用 # · 变量改为对新赋值的数据引用 # def test(num): ...
29d3f18d1a9f52d1d4a5b7340b40f49e28250fa7
CHyuye/Python
/lecture03/python-basic3.py
629
3.921875
4
""" 综合应用——石头剪刀布 """ import random while True: player = int(input("请输入您要出的拳 石头(1)/剪刀(2)/布(3):")) computer = random.randint(1, 3) print("玩家出的拳是 %d -- 电脑出的拳是 %d" % (player, computer)) if ((player == 1 and computer == 2) or (player == 2 and computer == 3) or (player == 3 and ...
189c2824801ff6acbec856b0b6c44c5b35cd98cd
CHyuye/Python
/lecture04/Algorithm_QuickSort.py
1,191
3.953125
4
import random """ 快速排序——首先会在序列中选择一个基准值(pivot),然后将除了基准值以外的数分为 "比基准值大的数"和"比基准值小的数",再将其排列 """ data = [45,3,9,15,67,51,42] def quickSort(data, start, end): i = start j = end # i和j重合时,依次排序结束 if i >= j: return # 设置最左边的数为基准值 flag = data[start] while i < j: while i < j and d...
185ced33a8ef0de6e8800e633be17ce7ee5e83a6
manishwvn/arrays_basics
/all_subarrays.py
331
4.0625
4
# given an array, print all subarrays def all_subarrays(arr): n = len(arr) for i in range(0,n): for j in range(i,n): for k in range(i,j+1): print (arr[k], end = " ") print ("\n", end = "") n = int(input()) arr = [int(input()) for x in range(n)] all_suba...
5d4f73278e7471be409d88fdcfc7ab6bbbec95f2
mjrice04/data_engineering_utilities
/google_maps/address_to_lat_long.py
2,619
3.703125
4
import requests import pandas as pd import numpy as np import json import os def address_reader(path='data/address_data_example.csv'): """ This function reads the address data and returns a dataframe of the addresses :param path: path to the data :return: """ address_csv = pd.read_csv(path, dt...
e6fda354bf07e04d16e648697c09400a404af8d0
fherbine/computorV1
/controllers/ft_math.py
2,825
3.59375
4
"""Own math module. Contained functions are: - ft_abs(n): return the absolute value of n. - ft_power(n, p): return n raised to power p - ft_sqrt(n): return the square root of n. Should be improved ! Contained objects are: - Complex(r, i): Represents a coplex number. """ def ft_abs(n): return -n if n < 0 else n ...
46967699118df771c18826d0a4624f3a731f1b78
andersongfs/Programming
/URI/URI-1091.py
488
3.734375
4
# -*- coding: utf-8 -*- while True: qtd_casa = int(raw_input()) if(qtd_casa == 0): break x_ponto, y_ponto = map(int, raw_input().split()) for i in range(qtd_casa): x_casa, y_casa = map(int, raw_input().split()) if(x_casa > x_ponto and y_casa > y_ponto): print "NE" elif(x_casa > x_ponto and y_casa < y_po...
192954d0c5a47b4c92128468a1fee0553ce03b18
andersongfs/Programming
/URI/URI-1068.py
308
3.890625
4
# -*- coding: utf-8 -*- while True: try: entrada = raw_input() num = 0 for i in entrada: if(i == "("): num = num + 1 elif(i == ")"): if(num == 0): num = num - 1 break num = num - 1 if (num == 0): print "correct" else: print "incorrect" except EOFError: break
cff73288b24f82dcc147d565c92a56fcee7cd947
yifyirf/GSEA-Genialis
/gsea.py
6,047
3.546875
4
import csv import numpy as np import random from scipy import stats import gsea_functions as gf '''Program to calculate the normalized enrichment scores and pvalues according to the publication: http://software.broadinstitute.org/gsea/doc/subramanian_tamayo_gsea_pnas.pdf The program accepts 2 files, which user can s...
411b4158477752c54ec28d42df0f4e80bfb902eb
glourenco/DetectFraudAndPredictStockMarket
/HelloWorld/Lecture5/MultivalueVariables.py
942
4.09375
4
#Tupples tuple1 = (1,2,3,4,5) stringTuple = ("one","two","tree") mixedTuple = ("one", tuple1, 3) itemTuple = ("apple", 2, 3.5) print(itemTuple) print("lenght",len(itemTuple)) print("min",min(tuple1)) print("max",max(tuple1)) print("index 2 ",itemTuple.index("apple")) #Arrays grocList = ["eggs","milk","flour","butter"]...
b73441fed6deebc5913598aa784f3efd610dd5ce
C-Baird/PythonCustomer
/src/DataSource/editmenu.py
769
4.09375
4
def addmenu(name_item, price_pound = 0, price_pence = 0): try: price_pound = int(price_pound) except ValueError: print("a number is required here") return try: price_pence = int(price_pence) except ValueError: print("a number is required here") return ...
5387925674f561110379c6e5b98b34ce194fc28b
Natthapolmnc/Algorithm_Exercise
/quickSort/sort.py
448
3.6875
4
lst=[1,4,5,2] def quickSort(lst,start,stop): if(start<stop): q=partition(lst,start,stop) quickSort(lst,start,q-1) quickSort(lst,q+1,stop) def partition(lst,start,stop): x=lst[stop] i=start-1 for j in range(start,stop-1): if lst[j]<=x: i+=1 ...
f1e67dd9fca8f9084416098d03f1b0fa0ec3f0ec
dimoka777/Time-in-Words
/time_words.py
2,190
3.984375
4
""" Hackerrank The Time in words Medium 25 Max Score Input Format The first line contains , the hours portion The second line contains , the minutes portion Constraints Output Format Print the time in words as described. Sample Input 0 5 47 Sample Output 0 thirteen minutes to s...
cf2e4033c9db5be4c93eded5ac9e35b9bc1909d4
arushi-j/Hangman
/final_hangman_arushi.py
5,191
3.90625
4
import random #List to store the Words and dictionary for hints as values movie_list = ["the martian", "gravity", "interstellar", "trainwreck", "steve jobs", "inside out", "minions"] movie_hint = {"the martian" : "Stuck on Mars", "gravity" : "Stars Sandra Bullock", "interstellar" : "Nolan Space Throry", "trainwreck" :...
08776ad73d47bce8f11afafa0c13cce17ab24267
hj24/Fluent-Python-example-code
/chapter 7/7_1_2.py
621
3.59375
4
""" 一个简单的例子 """ def deco(func): def inner(): print('running inner()') return inner @deco def target(): print('running target()') target() """ 装饰器在被装饰的函数定义之后就立即执行 """ registry = [] def register(func): print(f'running register({func})') registry.append(func) return func @register def f1(): print('running f...
05172f7f712177a2f1be98bd0af8d8e285b9ac6b
nat-chan/TDD_RedGreenRefactor
/fizzbuzz/test_fizzbuzz.py
1,263
3.5625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from typing import * from fizzbuzz import FizzBuzz import unittest class TestFizzBuzz(unittest.TestCase): def test_出力はstrである(self): self.assertEqual(str, type(FizzBuzz.single_line_answer(1))) def test_数値の1を渡したら文字列の1を返す(self): self.assertEqual("1"...