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
908d5750b2bbb33fb78bd7b5037b15193ce1d4ec
codyduong/OPS-IncomeVis
/csvCreator/dataHandler.py
1,245
3.625
4
import json import csv #For the curious, the JSON is formatted such that each employee is given their own unique key-name for easier accessing of specific employees. def writeToJson(e, filename): """ Converts {employee: [Location, Position],...} to JSON """ with open(filename, "w") as f: cont...
27131fa53a7c1f1ec3336b515dcf68b87aeff8ea
travisobregon/itt-big-data-ca
/mapper.py
283
3.671875
4
#!/usr/bin/python # Format of each line is: # Job Title, Total Pay, Gender import sys for line in sys.stdin: data = line.strip().split("\t") if len(data) == 3: job_title, total_pay, gender = data print "{0}\t{1},{2}".format(job_title, total_pay, gender)
f13b94ea8ee9284aebfacc1631cd852586380dd1
fatihaydnn/Python
/Kumanda.py
2,854
3.90625
4
# Televizyon Kumandası Uygulaması: """ İşlemler: 1. Televizyonu Aç - tv durumu = "Açık" 2. Televizyonu Kapat - tv durumu = "Kapalı" 3. Televizyon Bilgileri - o anki kanal, ses durumu, tüm kanallar. 4. Kanal Ekle - kanal listesine kanalı ekle 5. Rastgele Kanal Aç - random bir kanalı açar 6. Sesi Azalt Arttır ...
c5c77da3e67eacdc6c02fa2f052ae89c508cd743
FalseG0d/PythonGUIDev
/Sample.py
236
4.125
4
from tkinter import * root=Tk() #To create a Window label=Label(root,text="Hello World") #To create text on label and connect it to root label.pack() #to put it on root root.mainloop() #To avoid closing until close button is clicked
63e41a1d3d91e5f40b158189589022d36a55256c
FalseG0d/PythonGUIDev
/MessageBox.py
714
3.703125
4
from tkinter import * from tkinter import messagebox def call_me(): messagebox.showinfo("Success","Hello World") #messagebox.showerror("Success","Hello World") #messagebox.showwarning("Success","Hello World") def ask_question(): #answer=messagebox.yesnocancel("Exit","Are you sure?") #print(answer)...
41aeac28dcbfd65a68bcda38b7b5ba602a1c23b1
PaulJoshi/hospital_management_system
/core/patients.py
3,773
3.5
4
import pickle import datetime class Patient : def __init__(self): self.name = "" self.age = None self.gender = "" def create_user(self,age,gender) : ''' Adds a new patient to "/database/patients.pkl" in database ''' self.age = age self.gender = gender ...
3766ef11f0b53fea8ad5349b1f5e975830b74b28
brainmentorspvtltd/rd_python_iot
/SecondDay.py
16,527
3.890625
4
''' New Question Take input of 2 strings Print true if they're anagrams, otherwise false. Google anagrams if you don't know about them. ''' Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 16:52:21) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license()" for more...
99d7231dc880871ffc6a23324fd8e72bb1b7b628
arpit0891/Project-Euler
/p265.py
1,591
3.703125
4
# In this problem we look at 2^n-digit binary strings and the n-digit substrings of these. # We are given that n = 5, so we are looking at windows of 5 bits in 32-bit strings. # # There are of course 32 possible cyclic windows in a 32-bit string. # We want each of these windows to be a unique 5-bit string. There are e...
968460d960e69e40a3dd73190e39bc3e9f6812ff
arpit0891/Project-Euler
/p029.py
296
3.96875
4
# We generate all the possible powers in the given range, put each value # into a set, and let the set count the number of unique values present. def compute(): seen = set(a**b for a in range(2, 101) for b in range(2, 101)) return str(len(seen)) if __name__ == "__main__": print(compute())
1684a3c6ac6cb0069166ecdc9884b3eae1e7962b
arpit0891/Project-Euler
/p065.py
341
3.578125
4
def compute(): numer = 1 denom = 0 for i in reversed(range(100)): numer, denom = e_contfrac_term(i) * numer + denom, numer ans = sum(int(c) for c in str(numer)) return str(ans) def e_contfrac_term(i): if i == 0: return 2 elif i % 3 == 2: return i // 3 * 2 + 2 else: return 1 if __name__ == "__main__...
a6bd48ccdb050035229962628efefc35d9955cb7
arpit0891/Project-Euler
/p119.py
1,201
3.828125
4
import itertools # Candidates have the form n^k, where n >= 2, k >= 2, n^k >= 10, and isDigitSumPower(n^k) == true. # We also impose n^k < limit. If there are at least 30 candidates under 'limit', # then the 30th smallest candidate is the answer. Otherwise we raise the limit and search again. # # We only need to try...
1c5096a00eac1ca44c9efaee7d333ec4b3a74b53
arpit0891/Project-Euler
/p122.py
4,115
4.15625
4
import itertools # This problem uses the concepts of https://en.wikipedia.org/wiki/Addition_chain # and https://en.wikipedia.org/wiki/Addition-chain_exponentiation . # # Definition: An addition chain is a finite sequence of integers {a_i} such that: # - a_0 = 1 (i.e. the head element is 1). # - For each index i (wit...
2c611be54a9022133cfe5a5de20ac4c8b45c289d
arpit0891/Project-Euler
/p103.py
13,035
4.09375
4
import itertools # We start with three pedantic lemmas to constrain the nature of possible solutions. # # No-zero lemma: # A special sum set (SSS) should not contain the value 0. The problem statement # doesn't say this explicitly, but it is implied in the numerical examples. # Proof: # - For size n = 0, {} t...
61ceabf03505c5291a06720e53adf674b6af92e8
arpit0891/Project-Euler
/p425.py
2,634
3.75
4
import eulerlib, heapq # Finding all the relatives of 2 can be seen as a single-source shortest path problem, # which we solve here using Dijkstra's algorithm. The key insight is that at each node (prime number), # we consider the connection path from 2 to it, and store the maximum path number at the node. # It is am...
7098bd17195206fcddee8505e4d0ec80eab6f7b8
Martsyalis/python-practice
/set.py
194
3.671875
4
def get_count(input_str): return sum(1 for c in input_str if c in 'aeou') print(get_count('aeousssssss')) def friend(x): return sum([1 for f in x if f in 'ad']) print(friend('abcd'))
ecf81505386eb8b1fde34224ad2eefb3e94074a9
adrianw-eecs/Twitter_Streaming_Analysis
/Part 2 - Sentimental Analysis of Tweets with Visualiztion/sentiment_analysis.py
2,736
3.640625
4
import sys, csv, re import operator import nltk from nltk.corpus import stopwordds from nltk.classify import SklearnClassifier from string import punctuation def clean_input(input): # this function will clean the input by removing unnecessary punctuation # input must be of type string if type(input) != st...
f573d91df21116b83c6acdcb9abe7c9250f00cbd
wamalik786/Waqas_Ahmad_PIAIC_154908
/PIAIC_154908_ Waqas Ahmad_ assignment_2.py
1,811
3.515625
4
#!/usr/bin/env python # coding: utf-8 # In[75]: import numpy as np # In[3]: x = np.arange(1,13).reshape((6,2)) print(x) # In[9]: x = np.arange(10,37, dtype = np.float64). reshape((3,3,3)) x # In[81]: a =np.arange(1,100*10+1).reshape((100,10)) x = a [(a % 7 == 0) & (a % 5 ==0)] print(x) # In[41]: prin...
17105410cf77c2d37bd2e5caf5eb8dde88dbeb62
chanthony/Oregon-112
/Diseases.py
2,854
3.828125
4
#diseases.txt def generateDiseases(data): diseaseList = []#keep the diseases as a list diseaseList.append(Disease("performed a ritual sacrifice to the 112 gods", "grade",10))#generate each disease and store it diseaseList.append(Disease("forgot to backup their work and...
18c9cc619d5e44504665132e9fad5315a8b44799
pjkellysf/Python-Examples
/backwards.py
960
4.78125
5
#!/usr/local/bin/python3 # Patrick Kelly # September 29, 2015 # Write a program that prints out its own command line arguments, but in reverse order. # Note: The arguments passed in through the CLI (Command Line Interface) are stored in sys.argv. # Assumption: The first item argument in sys.argv is the filename and sh...
8707d6834569e841a2a4dd597664eaab15ba9d11
OXDBXKXO/energy-data-hack
/keysolver/post_treatment/key_filtering.py
7,906
3.734375
4
__SLIDING_WINDOW = 80 __SHIFT_RADIUS = 50 class KeyPress: """ Represent a key presses. Instances of this class are immutable. Attributes: key: A tring representing the key (e.g. "A", "SHIFT" or "NOKEY") count: The number of consecuting repetitions. has_shift: True if...
3c064008c882c067c144eedc5312c6b7ad329ac0
Alistrandarious/ETL-LifeExpectancy
/code.py
1,892
3.921875
4
import time average = 0 student_list = ["Alfred", "Matthew", "Simon", "Amy", "Mary"] Selection = False Average = False scores = { "Alfred": { "Maths": 74, "Science": 78, "English": 68, "History": 52 }, "Matthew": { "Maths": 64, "Science": 82, "English"...
828c2e1ca9d4ef07d3298e03d15d494d4b229f44
paigekm/Marsden_Pizzas
/testing_file_sprint2.py
4,058
4.1875
4
"""A program to manage customers' pizza orders.""" import math def stars(): """Prints a line of * to separate information and make the output easy to understand.""" print("*" * 60) def dotted(): """Prints a line of . to separate information and make the output easy to understand.""" print("." * 60)...
c2ed5c9f07d0c48a3342758fd474a8949662efc6
LeonidasRex/Project_Euler
/Solutions/Euler Prob 7.py
230
3.546875
4
''' By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10,001st prime number? ''' #Yes, this is sympy, how may I help you? :) import sympy as sy print(sy.prime(10001))
a7e60a422b39726dd76eb1e913e3236967a09502
simpx/elo
/elo.py
1,056
3.625
4
#!/usr/bin/env python # -*- coding: utf8 -*- import sys ''' 计算A对B的胜率期望值 公式里的常数默认取10和400 ''' def E(rankA, rankB, base = 10, power = 400): return 1 / ( 1 + pow(base, (1.0 * (rankB - rankA) / power))) ''' 计算A对阵B后,新的rank分数 ''' def R(oldRankA, oldRankB, scoreA, k = 32, base = 10, power = 400): if (scoreA not i...
5bfe3fa926c2f2f34299874688692f7d1fbb1c80
maha139/python_practice
/whatsyourname.py
267
3.96875
4
#Task4 # Get firstname and last name and see if less than 10 characters firstname = input("enter first name") lastname = input("enter last name") print(firstname) print(lastname) print ("Hello {} {} You just delved into Python".format(firstname,lastname))
e8a9965c15b7ef985908e4a04807eccdc3d7a5c8
MukundiCode/alex
/Q_gridpoint.py
6,342
3.609375
4
#Tinashe Mukundi Chitamba #The gridpoint class encapsulates the variables and methods used in the value iteration algorithm import numpy as np class gridPoint: # Variables # x - x coordinate # y - y coordinate # int value - value of that grid point # boolean isTerminal - true if it is terminal point...
0c0115b670926748b7df837e063d0953a16199b1
Bryanx/exercises
/Python/Fibonacci copy.py
289
4.15625
4
def fibonacci(x): x -= 2 f = [0, 1] if x < 0: return[0] elif x < 1: return f else: for i in range(x): f.append(f[len(f) - 2] + f[len(f) - 1]) return f print(fibonacci(int(input("Enter the amount of Fibonacci numbers:\n"))))
b112929c1836af29d6fe388e1fc749a47695c84e
arpine58/python_homework
/homework3/Palindrome numbers.py
320
3.84375
4
a = int(input()) b = int(input()) def palindrome(x): temp = x rev = 0 while x > 0: dig = x % 10 rev = rev*10+dig x = x//10 if temp == rev: return True else: return False for i in range(a, b): if palindrome(i) is True: print(i)
9d1ed42cd4a586df38bb7f2a122db69fbece314a
aidank18/PythonProjects
/montyhall/MontyHall.py
1,052
3.78125
4
from random import random def game(stay): doors = makeDoors() choice = int(random() * 3) for i in range(0, 2): if (i != choice) and doors[i] == "g": doors[i] = "r" break if stay: return doors[choice] else: doors[choice] = "r" for door in door...
c8a2b5153663184e1ae0c23e29d8b4309b5df5bd
aidank18/PythonProjects
/linkedList/LinkedList.py
4,359
3.9375
4
from Node import * class LinkedList: def __init__(self, aStart = None): self.__start = aStart if self.__start == None: self.__size = 0 else: self.__size = self.__traverseList(self.__start, False) def __str__(self): list = "[" + self.__traverseList(self....
c745c673b6a345386bdd51981e7cdca0e2e76a7e
netager1007/Python_Cookbook_3rd
/2-Strings_and_Text.py
15,795
4.34375
4
# 2.1 Splitting Strings on Any of Multiple Delimiters line = 'asdf fjdk; afed, fjek,asdf, foo' import re print(re.split(r'[;,\s]\s*', line)) # \s : white space fields = re.split(r'(;|,|\s)\s*', line) print(fields) values = fields[::2] delimiters = fields[1::2]+[''] print('values: ', values) print('delimiters: ', del...
3a94506be1a06ff57ad47e7eed4df8fb7fb4b253
AGRamirezz94/COGS-202
/regex_test.py
917
3.53125
4
import re import random import sys # Get the text for the constitution #page = requests.get('https://www.usconstitution.net/const.txt', verify=True) with open("const.txt") as myfile: const_text = myfile.read() #print const_text # A useful construct I'm leaving in, commented out constitution_lines = const_text.sp...
243bc53d352c7b539dc0856aba22db34c34c787b
afergadis/keras-nlp
/keras_nlp/preprocessing/segment.py
4,609
3.6875
4
import re def sent_tokenize( text, subst="\n", regex="(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?)\s" ): """ A simple sentence tokenizer based on regular expressions to find the sentence boundaries. Parameters ---------- text : str The text to tokenize. subst :...
d8f1f90bcf7d84a8a52a5055ab3f4850de1d4a77
lykketrolle/Noroff_NIS2016
/TAP 4/TAP04-sets[4].py
2,083
4.75
5
#!/usr/bin/python """ Name: Kjell Chr. Larsen Date: 24.05.2017 Make two different set with fruits, copy the one set in to the other and compare the two sets for equality and difference. """ print("This program will have two sets of fruits. One will then be copied,\n" "into the other, then a comparison...
ada51e6ff846c136f10eadc00f10e0b0ffb38d59
georgiedignan/she_codes_python
/Session4/functions.py
445
3.953125
4
# def ask_name(): # name = input("What is your name? ") # return name # georgie_name = ask_name() # print(georgie_name) # mimi_name = ask_name() # print(mimi_name) # def create_greeting(name): # greeting = f"Hello {name}" # return greeting # print(create_greeting("georgie")) #Create function that ...
9454731a5b8163df69c66fd9a7a27ce4f6195257
georgiedignan/she_codes_python
/Session5_dictionaries/Exercises/Q3.py
402
3.609375
4
names = ["Maddy", "Bel", "Elnaz", "Gia", "Izzy","Joy", "Katie", "Maddie", "Tash", "Nic","Rachael", "Bec", "Bec", "Tabitha", "Teagen","Viv", "Anna", "Catherine", "Catherine", "Debby","Gab", "Megan", "Michelle", "Nic", "Roxy","Samara", "Sasha", "Sophie", "Teagen", "Viv"] # list_names = list(set(names)) names_dict = {}....
82386828e06a85350e834c807cd003896a97446e
georgiedignan/she_codes_python
/Session2/conditionals_exercises.py
747
3.9375
4
#Exercise 1 # moths_in_house = bool(input("Are there moths in the hosue? ")) # if moths_in_house == True: # print("Get the moths") # else: # print("No threats detected") #Exercise 2 # light_color = "red" # if light_color is "red": # print("correct") #Exercise 3 #Exercise 4 # height = 164 # if heigh...
9fb5404d86596e822da14852d181caedd240edf2
georgiedignan/she_codes_python
/Session3/Exercises/while_loops.py
947
4.21875
4
#Exerise 1 # number = input("Please guess any number: ") # while number != "": # number = input("Please guess any number: ") #Exercise 2 number = int(input("Please enter a number: ")) #using a for loop # for num in range(1,number+1): # if num%2!=0: # print(num) #try using a while loop i=1 while (i...
85213ae0071b9f2d5caf92488a5eea6a4e2bb444
jbrudvik/sublime-sum
/sum.py
2,191
3.59375
4
# -*- coding: utf-8 -*- import re try: import sublime import sublime_plugin class SumCommand(sublime_plugin.TextCommand): def run(self, edit): # Create new buffer that never reports dirty status sum_view = self.view.window().new_file() sum_view.set_name('Sum') ...
aeb8a3648da51cead7ac4eae29f809ab02a1f0b6
nknavkal/project-euler
/largestpalindromeproduct.py
823
3.8125
4
def reverseIt(n): a = [] b = len(str(n)) if n%10 != 0: for i in range(b): a.append(n%10) n = int((n-a[-1])/10) a.reverse() for i in range(b): n = 10*n + a.pop() return n def palindromeFinder(): print("For this problem, we're going to f...
810a9ba68bf4e22c888a6b530265e7be8fbc457d
Amantini1997/FromUbuntu
/Sem 2/MLE/Week 2 - Decision Tree & Boosting/regression.py
1,658
4.375
4
# regression.py # parsons/2017-2-05 # # A simple example using regression. # # This illustrates both using the linear regression implmentation that is # built into scikit-learn and the function to create a regression problem. # # Code is based on: # # http://scikit-learn.org/stable/auto_examples/linear_model/plot_ols.h...
fe463b29379ec7121b135c448b206be9f11123ff
Amantini1997/FromUbuntu
/Sem 2/MLE/Week 2 - Decision Tree & Boosting/Error_function.py
438
3.5
4
import matplotlib.pyplot as plt a = 3 errors = [] X_train = [1] y_train = [1] def predict_arr(X): return X def plot_model_and_input(): ## DATA PLOT plt.figure() plt.plot(X_train, y_train, "b.") plt.plot(X_train, predict_arr(X_train), "r.") plt.show() plt.close() ## ERROR PLOT pl...
98a0b26efc09b461a8ac2e815e8785d866cf7707
greatwallgoogle/Learnings
/other/learn_python_the_hard_way/ex34.py
883
4.4375
4
# ex34 : 访问列表元素 # 常用函数 # 声明列表:[] # 索引法访问元素: list[index] # 删除某个元素:del(list[index]) # 列表元素反向:list.reverse() # 追加元素:list.append(ele) animals = ['dog','pig','tiger','bear',3,4,5,6] print("animals :",animals) # 索引法访问列表中的值 dog = animals[0] print("animals first ele:", dog) # 使用方括号的形式截取列表 list2 = animals[1:5] #从索引为1的地方开始,读...
e310bdad449d5b03b18cdfc4d16a6ce25cc676a4
greatwallgoogle/Learnings
/other/learn_python_the_hard_way/ex12.py
413
3.640625
4
# 提示别人,即给input函数指定参数用于提示 # 重写ex11.py的内容 y = input("Name? ") print(y) # ------ print("----------") age = input("How old are you ?") height = input("How tall are you ?") weight = input("How much do you weight?") print("So,you are %r old, %r tall and %r heavy." % (age,height,weight)) # 在终端输入pydoc input,查看此函数的API简介 # 然...
4ed2d4ef6171647b08629409ec77b488d059bc6f
greatwallgoogle/Learnings
/other/learn_python_the_hard_way/ex9.py
975
4.21875
4
# 打印,打印,打印 days = "Mon Tue Wed Thu Fri Sat Sun" # 第一中方法:将一个字符串扩展成多行 months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJuly\nAug" print("Here are the days :",days) # 等价于 print("Here are the days : %s" % days) print("Here are the months : ", months) #等价于 print("Here are the months : %s" % months) # 第二种方法:使用三引号输出任意行的字符串 pri...
6e08f46015d7af78c93569e722ad4dc04ffc0f28
greatwallgoogle/Learnings
/other/learn_python_the_hard_way/ex_class1.py
2,178
3.671875
4
# self 代表类的实例,self 在定义类的方法时是必须有的,虽然在调用时不必传入相应的参数。 # 类函数的第一个参数必须是self # 类变量定义: # _foo:单下划线开头的表示是protected类型的变量 # __foo:双下划线开头的表示是private类型的变量 # __foo__:表示定义的是特殊方法,一般是系统定义名字 class Map(object): """docstring for Map""" def __init__(self, arg): super(Map, self).__init__() self.arg = arg print("Map arg:",arg) pri...
a73adc9082e54df28f0db2a9b93496e2f1bcd5ff
thekayode/area_of_shapes
/area_of_triangle _assignment.py
993
4.40625
4
''' This programme is too calculate the area of a triangle. ''' base = float(input('Enter the base of the triangle\n')) height = float(input('Enter the height of the the triangle\n')) area = 1/2 * (base * height) print('area', '=', area) ''' This programme is too calculate the area of a square. ''' length =...
3a60055f2ac29c71ecc7991bf69e89cd1750d475
carolinemeng/RecommendSystem
/RecommendSystem/simpleRecommender/simple.py
2,164
3.59375
4
# Simple Recommendation Based Only On Popularity and Ratings import pandas as pd import numpy as np import matplotlib.pyplot as plt #column headers for the dataset data_cols = ['user id', 'movie id', 'rating', 'timestamp'] item_cols = ['movie id', 'movie title', 'release date', 'video release date', 'IMDb URL', 'unkn...
b1869818de65a93e61f1fc9cf4320396c09ca8bc
oct0f1sh/cs-diagnostic-duncan-macdonald
/functions.py
760
4.21875
4
# Solution for problem 8 def fibonacci_iterative(num = 10): previous = 1 precedingPrevious = 0 for number in range(0,num): fibonacci = (previous + precedingPrevious) print(fibonacci) precedingPrevious = previous previous = fibonacci # Solution for problem 9 # I don't know...
bc3433cbcf10bc908f4ee18af182a489bbb403d3
ISEexchange/Python-Bootcamp
/intermediate_class/session_3/hw.py
3,026
3.96875
4
################################# # In Class Assignment and Homework ################################# # 1. Write a function that takes in any number of un-named and named parameters. # 2. Loop through the list of un-named parameters and print the values. # 3. Loop through the dictionary of named parameters and print ...
d9cd91c8a4efb8c0da7fe18fc4d3ff83e24eed8d
jfudge/python-flask
/app.py
4,360
4.0625
4
from flask import Flask, render_template import datetime app = Flask(__name__) site_title = "Python and Flask" year = datetime.datetime.now().strftime("%Y") pythons_list = [ { "answer": "Python is a programming language used for building object oriented interactive interfaces that need a pro...
18db5e61c29a777be3bd163202dce195042b6878
dianamorenosa/Python_Fall2019
/ATcontent.py
487
4.125
4
#!/usr/bin/python #1.- Asign the sequence to a variable #2.- Count how many A's are in the sequence #3.- Count how many T's are in the sequence #4.- Sum the number of A's and the number of T's #5.- Print the sum of A's and T's seq1= ("ACTGATCGATTACGTATAGTATTTGCTATCATACATATATATCGATGCGTTCAT") #Asign the sequence to the...
a3037b8de00a8552d355fb5e45a15c6dc0743b77
rsingla92/advent_of_code_2017
/day_3/part_1.py
2,422
4.15625
4
''' You come across an experimental new kind of memory stored on an infinite two-dimensional grid. Each square on the grid is allocated in a spiral pattern starting at a location marked 1 and then counting up while spiraling outward. For example, the first few squares are allocated like this: 17 16 15 14 13 18 ...
a11169561d2f55ae809039b34052a60fe630462b
PQuix/pythonCrashCourse
/python_work/testing/employee_class.py
530
4.09375
4
class Employee(): """Creates an employee.""" def __init__(self, first, last, salary): """Defines the employee by name and salary.""" self.first = first self.last = last self.salary = salary def get_full_name(self): """Returns the employee's full name.""" self.full_name = self.first + " " + self.last ...
791650496e801ade14b6d4c86c5f53a4e53fc026
PQuix/pythonCrashCourse
/python_work/admin.py
611
4.0625
4
from user_class import User class Admin(User): """Defines an admin, child of the User-class, and its properties.""" def __init__(self, first_name, last_name, username): """Initializes the admin and the required information.""" super().__init__(first_name, last_name, username) self.privileges = Privileges( ...
513f6897b84fd22d38742167cd47bcf6ea3ac4f1
PQuix/pythonCrashCourse
/python_work/aliens.py
254
3.71875
4
alien_color = "grey" if(alien_color == "green"): print("1 shot! 5 points for you!") elif(alien_color == "yellow"): print("2 hits! 10 points for you!") elif(alien_color == "red"): print("You killed it! 15 points for you!") else: print("You missed!")
9a1255f7af057c5305f5c44b291f6a01c5f435ca
PQuix/pythonCrashCourse
/python_work/restaurant.py
1,008
3.953125
4
class Restaurant(): """A class that represents a restaurant.""" def __init__(self, restaurant_name, cuisine_type): """Initialize name of restaurant and type of cuisine served.""" self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type def describe_restaurant(self): """Describes the restau...
95e77e7734ad56da50c4c68a62f14ce3e0b63671
PQuix/pythonCrashCourse
/python_work/names.py
213
3.640625
4
names = ["Jennifer", "Eirik", "Håvard"] print(names[0]) print(names[1]) print(names[2]) print("Good evening, " + names[0] + "!") print("Good evening, " + names[1] + "!") print("Good evening, " + names[2] + "!")
f2ebecc1ae4ecf33bdafff1a64e324685db1d23a
PQuix/pythonCrashCourse
/python_work/hello_admin.py
353
3.71875
4
usernames = ["pquix", "thirdrevolt", "admin", "ymentradonsax", "snowowl15"] if usernames: for user in usernames: if(user == "admin"): print("Greetings, " + user.title() + ", would you like to see a status report?") else: print("Hello, " + user.title() + ", thank you for logging in.") else: print("Sorry, th...
aa77d85d283be3f9d1e812f2ec9890507a08ccdc
harrider/AoC2019
/Dec_4/SecurityModule/PasswordRule_NDigitPassword.py
568
3.59375
4
class PasswordRule_NDigitPassword: def __init__(self, requiredPasswordLength): if isinstance(requiredPasswordLength, int) == False: raise TypeError('ERROR :: "requiredPasswordLength" must be of type "int"!') if requiredPasswordLength < 0: raise ValueError('ERROR :: "re...
96160a9731bb41f035c3f7dcabeb56719215b6fd
A01377436/Mision-02
/miInfo.py
580
3.515625
4
# Autor: David Alejandro Nicols Palos, A01377436 # Descripcion: Elaboracin de un programa que muestre en pantalla mi informacin # Escribe tu programa después de esta línea. print("Nombre:") print("David Alejandro Nicols Palos") print("Matricula:") print("A01377436") print("Escuela de Procedencia:") print("Prepa Tec M...
3ce91e12f94f3389775bb3815e925dd6387da366
Woo-Dong/pre-education
/quiz/pre_python_08.py
294
3.609375
4
"""8. 정수를 입력했을 때 짝수인지 홀수인지 핀별하는 코드를 작성하시오 예시 <입력> 정수를 입력하세요 : 14 <출력> 짝수입니다. """ print("짝수입니다." if int(input("정수를 입력하세요 :")) %2 == 0 else "홀수입니다." )
b9e4ce86a0401768957ffa91c60ebc32e55e0184
legend1412/Recommend
/Chapter08/8-2.py
681
3.59375
4
import math import matplotlib.pyplot as plt def sigmoid(x1): return 1 / (1 + math.exp(-x1)) # python2中range生成的是一个数组,python3中生成的是一个迭代器,可以使用list进行转换 x = list(range(-10, 10)) y = list(map(sigmoid, x)) fig = plt.figure(figsize=(4, 4)) ax = fig.add_subplot(111) # 隐藏上边和右边 ax.spines['top'].set_color('none') ax.spines...
a43e10b5e0adc8002c2865d241aa343a1f67baae
Algorant/HackerRank
/Python/whats_your_name/name.py
311
4.0625
4
# Given input of first name and last name, return the statement # with the persons name in it. def print_full_name(a, b): print("Hello {} {}! You just delved into python.".format(a, b)) if __name__ == '__main__': first_name = input() last_name = input() print_full_name(first_name, last_name)
23241e4ba4dadda493f44610e334ff1dfa533d82
Algorant/HackerRank
/Python/string_validators/string_validators.py
586
4.125
4
# You are given a string . Your task is to find out if the string contains: # alphanumeric characters, alphabetical characters, digits, lowercase # and uppercase characters. if __name__ == '__main__': s = input() # any() checks for anything true, will iterate through all tests # Check for alphanumerics print(an...
49624d546ad4b998440f082ac43f75168f7431a7
Algorant/HackerRank
/Interview_Prep_Kit/Warm-up_Challenges/Sales_By_Match/sales.py
738
3.65625
4
''' Given some starter code, complete the function such that n number of socks within an array ar are paired to each other. Return the total number of matching pairs of sucks that can be sold. ''' import math import os import random import re import sys # Complete the sockMerchant function below. def sockMerchant(n,...
aa361a509b9cb245ecbf9448f4df5279cfc078c6
Algorant/HackerRank
/Python/reduce/reduce.py
557
4.25
4
''' Given list of n pairs of rational numbers, use reduce to return the product of each pair of numbers as numerator/denominator fraction by every fraction in list n. ''' # some of this code is supplied to user from fractions import Fraction from functools import reduce def product(fracs): t = reduce(lambda x, y...
f6b7564f728de2663ab87128b71fd4280236772a
Algorant/HackerRank
/Python/set_add/set_add.py
204
4.25
4
''' Given an integer and a list of items as input, use set.add function to count the number of unique items in the set. ''' n = int(input()) s = set() for i in range(n): s.add(input()) print(len(s))
e22b8fd8640989a5bde9647dfc5cf28296f5ad06
Algorant/HackerRank
/Python/groups/group.py
198
3.84375
4
''' Given a string S find the occurrences of alphanumeric characters in S that have consecutive repetitions. ''' import re m = re.search(r"([a-z0-9])\1+", input()) print(m.group(1) if m else -1)
11e269dfec9b5dd946037da3766f0dcab3fec30c
Algorant/HackerRank
/Python/regex_substitution/resub.py
328
3.96875
4
''' Given a text of N lines, which contain && and || symbols, modify the symbols to be && > and and || > or. Both && and || should have a space "" on both sides. ''' import re for _ in range(int(input())): print(re.sub(r'(?<= )(\&\&|\|\|)(?= )', (lambda m: 'and' \ if m.group(1) == '&&' \ else 'or'), in...
1a4370f022cd378a550949fc439910c195d8fb58
Algorant/HackerRank
/Python/default_arguments/default.py
1,072
3.6875
4
''' Debug the given code so that it successfully executes all provided test files. ''' # In line 28, def print_from_stream has an issue in it, the default argument # called stream=EvenStream() is only called once, and should be called every # time. Therefore we add the init line in 29 to make it do this. class EvenS...
91df05bb5905d70cc260c414ec0f4ba2bcaf3d88
Algorant/HackerRank
/30_days_of_code/d25_running_time_and_complexity/running_time.py
1,020
4.1875
4
''' Given list of integers of length T, separated by /n, check if that number is prime and return "Prime" or "Not Prime" for that integer. ''' # This was first attempt. Naive approach that works but fails 2 test cases # due to timeout! (Too slow) # def ptest(T): # # Make sure greater than 1 # if T > 1: # ...
c4af13b7fe312442dff6566b0f57e102a66f5f97
Algorant/HackerRank
/Python/zipped/zipped.py
239
3.75
4
''' Given grades for N students in X subjects, find the average scores of each student. ''' x, y = map(int, input().split()) scores = [map(float, input().split()) for _ in range(y)] [print(sum(student) / y) for student in zip(*scores)]
8fd0b127421d3c4627f55dcab5b4a0db3ced41bb
Algorant/HackerRank
/Python/swap_case/swap.py
113
3.921875
4
# return the swap case for a given input s = str(input()) def swap(s): return s.swapcase() print(swap(s))
66be396f989fb7be287af6978ec2f7cbe638df13
Algorant/HackerRank
/30_days_of_code/d08_dictionaries/dictionaries.py
510
3.765625
4
if __name__ == '__main__': phone_book = {} n = int(input()) # Populate phone book dict for _ in range( n ): name, phone_number = input().split(' ') phone_book[name] = int(phone_number) # Use try/except to query dict for values for _ in range(n): try: lookup_name = input() ...
996bb5aa753930626a1a6a45d930437dd015c850
Algorant/HackerRank
/Python/findall_finditer/find.py
482
4.21875
4
''' Given a string S, consisting of alphanumeric characters, spaces, and symbols, find all the substrings of S that contain 2 or more vowels. The substrings should lie between 2 consonants and should contain vowels only. ''' import re vowels = 'aeiou' consonants = 'bcdfghjklmnpqrstvwxyz' regex = '(?<=[' + consonants...
aeee95faea31ee7bf131aca23c338051773e6587
Algorant/HackerRank
/Python/find_the_score/find_score.py
591
3.875
4
''' Given an xml file of length N, find the score of the file, which is adding up all the tags and attributes in the file. ''' import xml.etree.ElementTree as etree tree = etree.ElementTree(etree.fromstring(xml)) # xml = ''.join(input() for _ in xrange(input())) def get_attr_number(node): return sum(len(child.a...
48329f8e8f38992d5facada2ee70b92d13d76dc6
simonxu14/LeetCode_Simon
/103.Binary Tree Zigzag Level Order Traversal/Solution.py
1,170
3.75
4
__author__ = 'Simon' # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def zigzagLevelOrder(self, root): """ :type root: TreeNode :rtype: List[List...
c60aea537e0f4df6b46d54ece8e3b7e90cf93efc
simonxu14/LeetCode_Simon
/49.Group Anagrams/Solution.py
1,207
3.5625
4
__author__ = 'Simon' class Solution(object): def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ if len(strs) == 0 or strs[0] == "": return [] dict = {} result = [] for item in strs: item_ele = t...
4cfb935205c712ecfc202390bf1e746855401275
simonxu14/LeetCode_Simon
/36.Valid Sudoku/Solution.py
2,102
3.734375
4
__author__ = 'Simon' class Solution(object): def check(self, board, start, choice): numbers = [] for i in range (0, len(board)): num = board[start][i] if (choice== 'col'): num = board[i][start] if num != '.': num = int(num) ...
ced8ce5046c20c5aabf47fd1731b4b0a86c1debe
simonxu14/LeetCode_Simon
/125.Valid Palindrome/Solution.py
962
3.609375
4
__author__ = 'Simon' class Solution(object): # def isPalindrome(self, s): # """ # :type s: str # :rtype: bool # """ # s.lower() # i = 0 # j = len(s) - 1 # while i < j: # while not s[i].isalpha(): # i += 1 # i...
a14935149e0a38f89aa39780a60bdcbc6a345f46
simonxu14/LeetCode_Simon
/82.Remove Duplicates from Sorted List II/Solution.py
2,198
3.8125
4
__author__ = 'Simon' # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ # if hea...
ebd6910d093a12719e8ade1d893f44d11ba867f6
simonxu14/LeetCode_Simon
/78.Subsets/Solution.py
512
3.578125
4
__author__ = 'Simon' class Solution(object): def subsets(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ res = [] res.append([]) nums.sort() self.dfs(nums, 0, [], res) return res def dfs(self, nums, index, path, res): ...
9a7552099fc493844fc68edd8b43535b050026cb
kigaita/EulersSolutions
/prob25.py
524
3.890625
4
#! usr/bin/python #Digit Counter def digits(n): n=[int(i) for i in str(n)] if len(n)==1000: return True return False #Fibonnaci Generator def fib(): a, b = 0, 1 while 1: yield a a, b = b, a + b def main(): stop = False a = fib() i=-1 #Stop when N is a lengt...
8fe50d117de92d388d4d46f2e173553de3b0a4f5
cvnguye2/python_examples
/prime.py
1,144
3.734375
4
#find prime numbers from start to end def Primes(start,end): prime=[] for i in range(start, end+1): for j in range(1,(i+1)): if(i%j==0 and i!=j and j!=1): break elif (i%j==0 and i==j): prime.append(i) else: continue return prime #find prime pairs that are seperated by cup def Primes_sets(star...
73e35bdbc746c7e13c94465536823b4d21bfbac5
Delfinoln/Python_Study
/100DaysOfCode-TheCompletePythonProBootcampFor2021-Course/Day25-Project/US_States_Game_Project/main.py
1,798
4.03125
4
import turtle import pandas as pd exists = False screen = turtle.Screen() screen.title("U.S. States Game") # Setting up screen screen.setup(width=730, height=510) screen.tracer(0) # Adding image to the screen image = "blank_states_img.gif" screen.addshape(image) turtle.shape(image) screen.update() # Reading csv fi...
9acd75e8fad98aac14db19683ee8f65a978daf3f
Delfinoln/Python_Study
/100DaysOfCode-TheCompletePythonProBootcampFor2021-Course/Day23-Project/The-Turtle-Crossing-Game/main.py
1,074
3.671875
4
import turtle import character import car import time import scoreboard # Creating a screen object screen = turtle.Screen() # Setting up screen atributes screen.setup(width=600, height=600) screen.tracer(0) screen.title("Turtle Crossing") # Creating a Character player = character.Character() # Creating a screen lis...
0bd110e04ddf20c86d0c252368798a111568913c
Opimenov/Tetris
/shapes.py
2,725
3.5625
4
from graphics import Point from shape import Shape class I_shape(Shape): def __init__(self, center): coords = [Point(center.x - 2, center.y), Point(center.x - 1, center.y), Point(center.x, center.y), Point(center.x + 1, center.y)] Shape.__init_...
48fc9819df0e53db026d6c3d4032a114c52eba0c
xyp8023/LeetCode_Python
/786_Repeated_String_Match.py
915
3.53125
4
import math class Solution: def repeatedStringMatch(self, A: str, B: str) -> int: if B in A: return 1 x = (len(B) // len(A)) x = math.ceil(len(B) / len(A)) A_new = A * x if B in A_new: return x else: if B in A_new + A: ...
e1857ba1bca8d77225879626030c0bd424645de2
xyp8023/LeetCode_Python
/461_HammingDistance.py
2,657
3.640625
4
# class Solution: # def hammingDistance(self, x, y): # """ # :type x: int # :type y: int # :rtype: int # """ # x_binary = bin(x).replace('0b','') # y_binary = bin(y).replace('0b', '') # x_len = len(x_binary) # y_len = len(y_binary) # # ...
38cb82c498644f5189a0520458ec5d9c03770332
ZckFreedom/Mathworks
/Finite_fields&Signal_design/fundamental_tools/same_data_structures_methods.py
11,003
3.65625
4
class Assoc: def __init__(self, key, value): self.key = key self.value = value # def __lt__(self, other): # 有时可能会需要关键码的排序 # return self.key < other.key # def __le__(self, other): # return self.key < other.key or self.key == other.key def __str__(self): return 'Assoc({0},{1})'.format(self.key, self....
16b2508ae7b7acf90c93aacd8c76c3ba6727326b
Shurtugall/Metodos_Numericos
/T1/5.py
374
3.75
4
""" @author: Gabriel Righi @matricula: 201612819 """ #Questão 5 #duvida import math def main(): a = 7 x_ant = 0.1 for i in range(10): x = (x_ant + a/x_ant)/2 x_ant = x print("X", i+1, ":", x) erro_absoluto = math.sqrt(7.0) - x print("Erro ab...
9c0f362c726440f6abbf2f21d442f9a56015a479
thofiqming/python_basics
/conditions.py
201
3.84375
4
# conditions value = 15 if 10 < value < 20: print("value greater than 10 and less than 20") elif value > 20: print("value greater than 20") else: print("none of the condition satisfied")
b6088f0209437e9b04158cae3be064b907dab776
samturton2/Python_fizz_buzz_task
/main.py
840
3.96875
4
# import the fizz buzz class from FizzBuzz_class import FizzBuzz # make function that requests fizz number def request_fizz(): return int(input("Please enter number for Fizz to replace\n=>")) # make function that requests buzz number def request_buzz(): return int(input("Please enter number for Buzz to replac...
fdc6657bb80dc04c9fa2709da30589be0cea2dd3
CharonAndy/scikit-fda
/examples/plot_kernel_smoothing.py
3,897
3.59375
4
""" Kernel Smoothing ================ This example uses different kernel smoothing methods over the phoneme data set and shows how cross validations scores vary over a range of different parameters used in the smoothing methods. It also show examples of undersmoothing and oversmoothing. """ # Author: Miguel Carbajo B...
4015375a4cc30b561b61b97ea0bd6a317ed0b8b4
slougn/PythonWF
/PythonCrashCourse/ch4/ex4.py
346
3.796875
4
alien_color = 'green' if alien_color=='green': print('player get 5 points') if alien_color!='red': print('not pass!') age = 30 if age < 2: print('婴儿') elif age < 4: print("蹒跚学步") elif age <13: print('儿童') elif age < 20: print('青少年') elif age <65: print('成年人') else: print('老年人')
64fbdf74d3c3c31e36ca9886c223192d6d18eb69
slougn/PythonWF
/PythonCrashCourse/ch11/test_cities.py
325
3.5
4
import unittest from city_functions import city_functions # print(city_functions('handan','china')) class CityTestCase(unittest.TestCase): """测试city_function的功能""" def test_cities(self): formatted = city_functions('handan','china') self.assertEqual(formatted,'Handan China') unittest.main
c9b16d36134a1ffc3a7e2460c384b6b9c48d679d
slougn/PythonWF
/PythonCrashCourse/ch7/ex3.py
667
3.8125
4
bread_order = ['白面馒头','麦馒头','南瓜馒头','叉烧包','蛋黄包'] finished_bread = [] while bread_order: bread = bread_order.pop() print(bread+'已经做好了!') finished_bread.append(bread) print('做好的订单有:') for bread in finished_bread: print(bread) bread_order = ['白面馒头','五香牛肉包子','麦馒头','五香牛肉包子','南瓜馒头','叉烧包','五香牛肉包子','蛋黄包'] pri...
f28f9d5304d565e29fb27f7f5715f7e9a7940abe
rbalaji07/balaji
/bala23.py
115
3.734375
4
abc=int(input()) for i in range(2,abc): if(abc%i==0): print("no") break else: print("yes")
982a6225a1aab61116069568225265bc27d73923
cemathey/aoc_2020
/day21/day21.py
3,469
3.765625
4
import sys from typing import NamedTuple, Tuple, List, Dict, Set class Food(NamedTuple): ingredients: Tuple[str, ...] allergens: Tuple[str, ...] def parse_food(line: str) -> Food: """Return a valid Food from the given line.""" left, right = line.strip().split(" (contains ") foods: List[str] = [...