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
6d88a3e6123d0ba9abe0dced924e38877d73b72a
RepoZTrees/python_exercises
/palindrome.py
670
3.90625
4
""" Input: "A man, a plan, a canal: Panama" Output: True """ sentence = "A man, a plan, a canal: Panama" new_sentence = sentence.replace(':','') remove_commas = new_sentence.replace(',','') remove_space = remove_commas.replace(' ','') lower_case_sentence = remove_space.lower() print(new_sentence) print(remove_commas)...
41fedbb5f706c112d719d2588b5ee4812242d3d8
Bradford-Chen/-python
/02-函数的返回值.py
1,051
3.8125
4
# 例题2: # def my_day(): # print('早上起床') # print('吃早餐') # print('看电视') # print('吃午餐') # print('午睡') # print('吃晚餐') # print('玩游戏') # print('睡觉') # print('快乐的一天结束') # return '快乐的一天' # # # ret = my_day() # print(ret) #  只要函数执行到return 函数就会停止执行 # 1. 如果函数不写return,默认返回None # 2. 也可以只写一个r...
29dc8121ed27e56e308b20bff17869583d382085
Bradford-Chen/-python
/03-集合.py
2,654
3.703125
4
# 集合:无序、不重复元素 # 注意:创建一个空集合必须用set()而不是{ },因为{ }是用来创建一个空字典 # 例题1:创建集合 # s = {'李白', '杜甫', '王维'} # print(s) # print(type(s)) # s = set() # print(s) # print(type(s)) # s = {} # print(s) # print(type(s)) # 例题2:集合的元素必须可哈希 # s = {1, '张三', False, True, ('1', '2')} # print(s) # s = {1, '张三', False, True, {'1': '李白', '2': ...
ef92f3a1c8f16ca4737bf85d7e7381cdb1bbfd14
Bradford-Chen/-python
/大二上python/2019312256_陈祥锡_HW4.py
3,828
3.625
4
# 陈祥锡 信管19-1 2019312256 # 2020/10/24 import math from graphics import * def isLeapYear(year): result = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0) return result def isTrueDate(month, day, year): month31 = [1, 3, 5, 7, 8, 10, 12] month30 = [4, 6, 9, 11] if (month in month31) and (day...
a8857fbf8998c0368a8290b08334255187b927b2
Alex-GCX/python_advanced
/meta_class-customize.py
1,564
3.640625
4
class UpperAttrMetaClass(type): def __new__(cls, class_name, class_parents, class_attr): """__new__方法时在__init__之前被调用的特殊方法,是python中真正的构造方法(不是__init__) 其作用是创建一个对象并返回该对象,而__init__的作用只是初始化对象的属性 在实现单例模式时可以用到这个__new__方法 这里因为我们需要通过该方法将一个传入的类对象改造一下并返回一个新的类对象,因此使用__new__方法 除了第一个固定参数cls外,其他自定义的参数分别为传...
aaa1c312328da7739818ec4893fea3b1d37bd60b
archenus/python
/algospot/markExam.py
1,193
3.703125
4
def cal(x, y, operator): result = 0 if operator == '+': result = x + y elif operator == '-': result = x - y elif operator == '*': result = x * y elif operator == '/': result = x / y return result def rtnResult(result, answer): for r in result: if result.count(r) != answer.count(r): return "No" ret...
8de73119596ffb029f23c006125a85fc6527bece
taeheechoi/coding-practice
/FF_removeLinkedList.py
560
3.796875
4
# https://leetcode.com/problems/remove-linked-list-elements/ # Input: head = [1,2,6,3,4,5,6], val = 6 # Output: [1,2,3,4,5] # Example 2: # Input: head = [], val = 1 # Output: [] # Example 3: # Input: head = [7,7,7,7], val = 7 # Output: [] def removeElements(head, val): prev, curr = None, head while curr: ...
c5130410769c7b40eafee42a86297c18beeec7cb
taeheechoi/coding-practice
/repeated-substring-pattern.py
591
3.625
4
# https://leetcode.com/problems/repeated-substring-pattern/ # Example 1: # Input: s = "abab" # Output: true # Explanation: It is the substring "ab" twice. # Example 2: # Input: s = "aba" # Output: false # Example 3: # Input: s = "abcabcabcabc" # Output: true # Explanation: It is the substring "abc" four times or the...
f13d14609b6c98949dc2e70a7de24f4a5e443ca0
taeheechoi/coding-practice
/FF_mergeTwoSortedLists.py
1,061
4.1875
4
# https://leetcode.com/problems/merge-two-sorted-lists/ # Input: list1 = [1,2,4], list2 = [1,3,4] # Output: [1,1,2,3,4,4] def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: #create dummy node so we can compare the first node in each list dummy = ListNode() #ini...
473c52181e0b70d769924d97c79d8bbe2e5e5651
taeheechoi/coding-practice
/FB/235-lowest-common-ancestor-of-a-binary-search-tree.py
852
3.65625
4
# https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/ # Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 # Output: 6 # Explanation: The LCA of nodes 2 and 8 is 6. # Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 # Output: 2 # Explanation: The LCA of nodes 2 and 4 is 2, si...
20e60a92a88ae398223c0a22950fb3266c17f0ab
taeheechoi/coding-practice
/F_is-subsequence.py
761
3.546875
4
# https://leetcode.com/problems/is-subsequence/ # Example 1: # Input: s = "abc", t = "ahbgdc" # Output: true # Example 2: # Input: s = "axc", t = "ahbgdc" # Output: false class Solution: def isSubsequence(self, s: str, t: str) -> bool: # for i, x in enumerate(s): # found_idx = 0 # ...
163120c583360bc8f3f3b6ad59ad7bbc2edafa8a
taeheechoi/coding-practice
/FB/283-move-zeroes.py
534
3.984375
4
# https://leetcode.com/problems/move-zeroes/ # Example 1: # Input: nums = [0,1,0,3,12] # Output: [1,3,12,0,0] # Example 2: # Input: nums = [0] # Output: [0] # https://leetcode.com/problems/move-zeroes/discuss/1748937/Python-Simple-and-Clean-Python-Solution-By-Two-Approach # slow index to keep tracking next swap po...
aad3ef840ad1d9282579fcbaa737798d2acede76
taeheechoi/coding-practice
/FB/66-plus-one.py
844
3.6875
4
# https://leetcode.com/problems/plus-one/ # Example 1: # Input: digits = [1,2,3] # Output: [1,2,4] # Explanation: The array represents the integer 123. # Incrementing by one gives 123 + 1 = 124. # Thus, the result should be [1,2,4]. # Example 2: # Input: digits = [4,3,2,1] # Output: [4,3,2,2] # Explanation: The array...
76ebfc7b9d6125f8a684e6d5081fe0bf2965b841
taeheechoi/coding-practice
/FB/334-increasing-triplet-subsequence.py
1,029
4.03125
4
# https://leetcode.com/problems/increasing-triplet-subsequence/ # Example 1: # Input: nums = [1,2,3,4,5] # Output: true # Explanation: Any triplet where i < j < k is valid. # Example 2: # Input: nums = [5,4,3,2,1] # Output: false # Explanation: No triplet exists. # Example 3: n = 5 th1 = 5 n = 4 th1 = 4 n = 3 th1 ...
8786abcb461d20e104b4ca579bef7324c1924105
taeheechoi/coding-practice
/FB/208_062722-implement-trie-prefix-tree.py
1,053
4.21875
4
# https://leetcode.com/problems/implement-trie-prefix-tree/discuss/1804957/Python-3-Easy-solution class Trie: def __init__(self): self.children = {} self.is_end = False def insert(self, word): curr = self for w in word: if w not in curr.children: ...
2190f7f62adf79cd2ee82007132c9571e4f0e68b
Codeducate/codeducate.github.io
/students/python-projects-2016/guttikonda_dhanasekar.py
950
4.1875
4
#This program will tell people how much calories they can consume until they have reached their limit. print("How old are you") age = int(input()) print("How many calories have you consumed today?") cc = int(input()) print("Are you a male or female?") gender = input() print("Thanks! We are currently calculating your d...
a150b3d2b7a95030728ab5b4333fab0abbed9c21
lchen22643/CodeJune
/shuai/leetcode/lc162/binarySearch.py
276
3.875
4
def binary_search(arr, x): lo = 0, hi = len(arr) while(lo < hi): mid = (lo + hi) / 2; if(arr[mid] < x): lo = mid + 1 else: hi = mid return lo a = [1, 2,3,4,7] print (binary_search(a, 3)) print (binary_search(a, 5))
b98ae2f9807ec30d4d452b26a49a9017d71ef923
eliottalderson93/Routing_Flask
/default.py
809
3.671875
4
from flask import Flask app = Flask(__name__) print(__name__) @app.route('/') def hello_world(): return "Hello world" @app.route('/dojo') def dojo(): return "Dojo" @app.route('/say/<word>') def say(word): print(word) return "hi "+word @app.route('/users/<username>/<id>') # for a route '/users/____/...
8aa1b1a0de0417460f0cc8a97a98c9950e6af79d
sharmine-s/edamam
/recipe_search.py
1,384
3.625
4
import requests app_id = input('What is your API ID? ') app_key = input('What is your API key? ') ingredient = input('Which ingredient do you have? ') print() url = 'https://api.edamam.com/search?q={}&app_id={}&app_key={}'.format(ingredient, app_id, app_key) response = requests.get(url) # returns response e.g. 200 ...
70e55eb90465307d02db25c5b3365f316082bc3d
kb1hyr/Simple_Banking_System
/Problems/Cat cafés/main.py
342
3.96875
4
meow = False max_cats = 0 max_restaurant = '' while not meow: data = input() if data == 'MEOW': meow = True continue the_space: int = data.find(' ') name = data[0:the_space] cats = int(data[the_space+1:]) if cats > max_cats: max_cats = cats max_restaurant = name ...
98e78ab456a9b654f37b48fd459c6b24f2560b93
afmendes/alticelabs
/Programs and Applications/Raspberry Pi 4/Project/classes/Queue.py
595
4.1875
4
# simple queue class with FIFO logic class Queue(object): """FIFO Logic""" def __init__(self, max_size: int = 1000): self.__item = [] # adds a new item on the start of the queue def enqueue(self, add): self.__item.insert(0, add) return True # removes the last items of the q...
4881c26cd1491c9017017296ad830edb28653ae8
tvumos/dz4
/borndayforewer.py
1,200
4.46875
4
""" МОДУЛЬ 2 Программа из 2-го дз Сначала пользователь вводит год рождения Пушкина, когда отвечает верно вводит день рождения Можно использовать свой вариант программы из предыдущего дз, мой вариант реализован ниже Задание: переписать код используя как минимум 1 функцию """ # Дата рождения А.С Пушкина = 26 мая 1799 г. ...
7c1a06fe6b6c02fd18dbe2bae9576ddb9c360ba2
jontingvold/pyrankvote
/pyrankvote/models.py
2,273
3.5625
4
""" Models that are used by multiple_seat_ranking_methods.py You can create and use your own Candidate and Ballot models as long as they implement the same properties and methods. """ from typing import List class Candidate: """A candidate in the election.""" def __init__(self, name: str): self.name...
eba5b2a0bceea1cc3848e70e0e68fc0f0607a677
tanishksachdeva/leetcode_prog
/9. Palindrome Number.py
1,083
4.3125
4
# Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. # Follow up: Could you solve it without converting the integer to a string? # Example 1: # Input: x = 121 # Output: true # Example 2: # Input: x = -121 # Output: false # Explanation: From left t...
3df720d5c88d4d4fca5f8ec14850f9697f737401
2000xinxin/pythonProject
/学习代码/flie_baseop.py
1,281
4.1875
4
# 将小说的主要人物记录在文件中 # file1 = open('name.txt', 'w') # 第二个参数 'w' 代表的是写入 # file1.write('诸葛亮') # file1.close() # 读取 name.txt 文件的内容 # file2 = open('name.txt') # print(file2.read()) # file2.close() # # file3 = open('name.txt', 'a') # 第二个参数 'a' 代表的是增加 # file3.write('刘备') # file3.close() # file4 = open('name.txt') # print(...
2abd1ab2eaf332871583a844ad7f28db90ced427
2000xinxin/pythonProject
/学习代码/while&if.py
945
3.6875
4
# while 循环中嵌套 if 语句,实现输入日期判断用户的星座 zodiac_name = (u'摩羯座', u'水瓶座', u'双鱼座', u'白羊座', u'金牛座', u'双子座', u'巨蟹座', u'狮子座', u'处女座', u'天秤座', u'天蝎座', u'射手座') # 字符串最前面的 u 是 unicode 的缩写,标志星座,不要出现乱码;为了阅读方便,进行换行 zodiac_days = ((1,20),(2,19),(3,21),(4,21),(5,21),(6,22), (7,23),(8,23),(9,23),(10,23),(11,23),...
0559133c1d1917f8cb4e62350486708347f66d58
2000xinxin/pythonProject
/学习代码/func_filter.py
383
3.953125
4
# filter 与 lambda 表达式配合使用 # a = [1,2,3,4,5,6,7] # print(list(filter(lambda x:x>2,a))) # zip() 函数的例子 # a = (1,2,3) # b = (4,5,6) # # for i in zip(a,b): # print(i) # 闭包 def func(): a = 1 b = 2 return a+b def sum(a): def add(b): return a+b return add num1 = func() num2 = sum(2) pri...
af698f8f12b09285b8dbb84b93542c070c525d1f
Weitspringer/graph-algorithms
/python/src/bfs.py
2,184
3.921875
4
from queue import Queue def simple_bfs(adjacency_list, node_key): """ Performs a Breath First Search on a graph given as an adjacency list outgoing from a node. This node is specified by its appropriate key in the adjacency list. :adjacency_list: Dictionary of form {"a": [<keys>], "b": [<keys>], ...}...
084a8d9a138e77eba923726e61c139b58170073d
femakin/Age-Finder
/agefinder.py
1,116
4.25
4
#Importing the necessary modules from datetime import date, datetime import calendar #from datetime import datetime #Getting user input try: last_birthday = input('Enter your last birthdate (i.e. 2017,07,01)') year, month, day = map(int, last_birthday.split(',')) Age_lastbthday = int(input("Age, as at las...
58f024d376de140c3c75ea09cafa38f519529c6f
PanchoCornejo/Proyectos
/Estructuras/listadoble.py
2,918
4.03125
4
class Node: def __init__(self, data): self.data = data self.next_node = None self.prev_node = None class ListaDoblementeEnlazada: def __init__(self): self.head = None self.tail = None def empty(self): return self.head == None def insert_last(self, eleme...
57249ecd6489b40f0ca4d3ea7dd57661b436c106
tjastill03/PythonExamples
/Iteration.py
343
4.15625
4
# Taylor Astill # What is happening is a lsit has been craeted and the list is being printed. # Then it is sayingfor each of the listed numbers # list of numbers numberlist = [1,2,3,4,5,6,7,8,9,10] print(numberlist) # iterate over the list for entry in numberlist: # Selection over the iteration if (entry %...
ef42137cc5f5d623a37e36318fd862f0a74a1539
ivanrp05/Ivanindra-Rizky-P_I0320054_Tiffany-Bella_Tugas5
/I0320054_Soal2_Tugas5.py
1,377
3.78125
4
#Mulai print("Soal 2") print("") print("Nama : Ivanindra Rizky P") print("NIM : I0320054") print("") print("===========================") print("") print("Ditanya :") print("Buatlah sebuah program yang dapat merubah/mengkonversi nilai input berupa angka") print("menjadi huruf yang akan digunakan untuk grading...
33148d8912d71a03bb822e770a9ca023856bd5cf
architectureofthings/GitGeo
/geographies_list.py
10,249
3.859375
4
"""Geography lists used to map user location text to country.""" import csv # static list of all cities mapped to countries # from https://datahub.io/core/world-cities\ # ignore errors because of many unicode errors. with open("world_cities.csv", errors="ignore", newline="") as file: reader = csv.reader(file) ...
0fa7c6d91e6d05015e9b5163e18b2db879c5b172
sindhu819/Competitive-Coding-6
/Problem -79.py
822
3.8125
4
# Letter Case Permutation - 784 - https://leetcode.com/problems/letter-case-permutation/ # Time complexity - O(2^N) # N is the number of letters in a word # Approach - Backtracking approach class Solution(object): def letterCasePermutation(self, s): """ :type S: str :rtype: List[str] ...
041f526039cd41b82073b95ce0c3b72b78087bc8
karabanb/Algorytmy_i_Struktury_Danych
/SortingAlgorithms.py
388
3.921875
4
# zadanie 1 # zaimplementuj algorytm insertion sort def insertion_sort(numbers): for index in range(1, len(numbers)): current_element = numbers[index] j = index - 1 while j >= 0 and current_element < numbers[j]: print(numbers) numbers[j+1] = numbers[j] ...
90bd8334d19015c18da95bb288069f9deb25386d
aahmad13/Python3.0_Fundamentals
/Physics_Class.py
1,205
3.671875
4
#Getting Ready for Physics Class Project #Given Variables: train_mass = 22680 train_acceleration = 10 train_distance = 100 bomb_mass = 1 #Fundamentals of Temperature def f_to_c(f_temp): c_temp=(f_temp-32)*(5/9) return c_temp f100_in_celsius=f_to_c(100) print("Turn up the Temperature from 100F to C = " + str(...
cb3e8d2290b2233b6bc2f87f52958a0df0454627
goatrenterguy/CSCI-446-Sudoku
/Environment.py
1,621
3.65625
4
class Environment: def __init__(self, difficulty: str, boardNumber: int): self.__board = self.loadBoard(difficulty, boardNumber) # Initialize board # :param difficulty: String of difficulty of the board to load # :param boardNumber: Int of the number of the board to load # Reads in and ...
fee46693ff557202fba24ba5a16126341624fdd6
lepaclab/Python_Fundamentals
/Medical_Insurance.py
2,599
4.6875
5
# Python Syntax: Medical Insurance Project # Suppose you are a medical professional curious #about how certain factors contribute to medical #insurance costs. Using a formula that estimates #a person’s yearly insurance costs, you will investigate #how different factors such as age, sex, BMI, etc. affect the pr...
92b614bf913d2444a93359f1459d1331a3408c20
Portapotee/Python_Homework
/class_student.py
1,215
3.984375
4
# A class defines specific things, but a function does specific things (the function is the code while the class defines what the function is doing) # lastname = str # firstname = str # grade = int # courses = list # __init__(book:dict) # __repr__() class student: def __init__(self, lastname, firstname, gr...
574677de1037832516eddb0ce4a6763a156574a9
Portapotee/Python_Homework
/employeeClass.py
393
3.671875
4
from datetime import * class employee: def __init__(self, name, employeeID, startdate, salary): self.name = name self.employeeID = employeeID self.startDate = startdate self.salary = salary def __repr__(self): return "{0}: employeeID = {1} \t startdate = {2} \t sala...
337da1f9a7bc7bba87ac3503c1ec7e104c20a624
suhanacharya/python-jetbrains-academy
/Cat cafés/task.py
257
3.78125
4
cafe_names = [] no_of_cats = [] cafe = {} while True: cafe_and_cats = input() if cafe_and_cats == "MEOW": break cafe_and_cats = cafe_and_cats.split(" ") cafe[int(cafe_and_cats[1])] = cafe_and_cats[0] print(cafe[max(cafe.keys())])
e9e204b50520df5406d04f45c32c4b9d8cb6fb8f
suhanacharya/python-jetbrains-academy
/Dating App/task.py
352
3.734375
4
def select_dates(potentional_dates): names = "" for person in potentional_dates: if person.get("age") >= 30: if "art" in person.get("hobbies"): if person.get("city") == "Berlin": names += person.get("name") + ", " return names.rstrip(", ") # print(s...
c8bc09a82152504695882b708f73b61cddf79019
courtneyahndesign/cs114
/practice/magic8ball.py
848
4
4
#Make a program that asks a user their name and returns a randomly chosen "fortune" response from the "magic 8 ball". Make 9 different possible "fortunes". #Save your program as 'magic8ball.py' print("What's your name?") name = input() print( str(name) +", I am your magic 8 ball! Give me a question and I will tell yo...
9865e44f4ba61b16d6a65547cd2177e4081b1cae
courtneyahndesign/cs114
/greeting.py
210
3.84375
4
print("Hey, what's your name?") name = input() print("How old are you?") age = input() newage = int(age) + 1 print(name + ", guess what? You're going to be a whopping " + str(newage) + " years old in a year!")
604bebc0d86418a1a72af187123c397ea4f6046b
courtneyahndesign/cs114
/practice/infinite.py
139
3.96875
4
print("my name is") i = 0 while i < 5: print("Justin") i += 1 print("my name is") for i in range(5): print("Justin" + str(i))
87f612ef35bb6a1d12954a28fb4b40437838bf4f
ThusharaWeerasundara/322
/1/code/1/javaplot.py
1,080
3.515625
4
import csv import matplotlib.pyplot as plt #to plot import numpy as np #to deal with arrays x_axis = np.arange(1,41,1) #values in x axis(problem size) iteration_time = [] with open("JavaIterationTime.csv") as iterationTime: #to read and store runtime values for iteration duration = csv.DictReader(iterationTi...
5cb30055179007812f75da135e245cb6f822cec6
Hubert51/leetcode
/dropbox2-Download-file.py
372
3.78125
4
class Chunk(object): def __init__(self, size1, size2): self.size1 = size1 self.size2 = size2 def __repr__(self): return "size1={}; size2={}".format(self.size1, self.size2) if __name__ == '__main__': a = Chunk(1,4) b = Chunk(3,2) list1 = [a,b] list1 = sor...
78b0bfb40e7cd412cd6cbc9fb3eb7e92e48c9959
Hubert51/leetcode
/17. Letter Combinations of a Phone Number.py
969
3.609375
4
# 3^N * 4^M # N is number of digit which is 2,3,4,5,6,8 # M is number of digit which is 7,9 class Solution: def letterCombinations(self, digits: str) -> List[str]: digitMap = dict() digitMap[2] = ["a", "b", "c"] digitMap[3] = ["d", "e", "f"] digitMap[4] = ["g", "h", "i"] ...
dbe87e2d08c9ba6c8601bcf5f27c1c4859532dc1
Sidd7Shank/pdsnd_github
/bikeshare.py
8,986
4.28125
4
import time import pandas as pd import numpy as np CITY_DATA = { 'Chicago': 'chicago.csv', 'New York': 'new_york_city.csv', 'Washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name of the...
61948a3d21a1bef458d18f932e06d5b0c88b9d02
Thomas-Wallis/CP1404_practicals
/prac_04/list_exercises.py
895
4.0625
4
# Basic list operations numbers = [] total = 0 for value in range(0, 5): number = int(input("Number {}: ".format(value + 1))) numbers.append(number) for number in numbers: total += number average = total / len(numbers) print("The first number is {}".format(numbers[0])) print("The last number is {}".format(n...
fa6ce3fa65772ae94e6eecd0aeb9bc69d7c1d1ff
Thomas-Wallis/CP1404_practicals
/prac_06/guitar_test.py
591
3.5
4
from prac_06.guitar import Guitar def main(): guitar_1 = Guitar("Gibson L-5 CES", 1922, 16035.40) another_guitar = Guitar("Another Guitar", 2013, 13009.25) print("{} get_age() - Expected {}. Got {}".format(guitar_1.name, 98, guitar_1.get_age())) print("{} is_vintage() - Expected {}. Got {}".format(gui...
40dfe347ef64ebac126b2ce282630246a80bfd21
BarYar/Automation
/GeneralPractice/Jenkins.py
375
4
4
def fibonacci(n): num1=0 num2=1 for i in range(n): print(num1) sum = num1 + num2 num1=num2 num2=sum import urllib.request, json with urllib.request.urlopen("https://www.random.org/integers/?num=1&min=1&max=100&col=1&base=10&format=plain&rnd=new") as url: data = json.loads...
a3c45585f694a99575ca5d1730e777b6d4e51438
omarbarakat/SocialSimulations
/social prisoners dilemma/social_prisoners_dilema.py
16,184
3.71875
4
# @author Omar Barakat # @date 23-09-2018 # THIS is a simulation of the "social prisoner's dilemma". The main idea is that when a player cheats they not only lose the trust of the oponent, but also the trust of their "connections" # The addition to the game setting is the following: # - Players can share knowledge ab...
9d43e05b95adf2939cc7f1eada90933d48c3518e
Viki2608/Pong-game-using-Python
/main.py
1,079
3.59375
4
from turtle import Screen from paddle import Paddle from ball import Ball import time from score import Scoreboard screen = Screen() screen.bgcolor("black") screen.setup(width=800, height=600) screen.title("Pong Game") screen.tracer(0) r_paddle = Paddle((350,0)) l_paddle = Paddle((-350,0)) ball = Ball() score = Scor...
a60082a6e9ff6f4e57e0ab9331752db265df590c
Scorpioeric-dev/Python_UVU
/lesson_3.py
2,197
4.0625
4
# year = eval(input("Enter year: ")) # if year == 1: # print ("Freshman") # if year == 2: # print ("Sophomore") # if year == 3: # print ("Junior") # if year == 4: # print ("Senior") # //nested if statements you can use the elif syntax to create nested if statements indention convention is critical for ...
1e7776600252f1a57e3d50ef4b4dcfa953847ed4
Scorpioeric-dev/Python_UVU
/lesson_8.py
1,690
3.75
4
from tkinter import Frame, Canvas class MyFrame(Frame): def __init__(self, coord=None, decrement=0): Frame.__init__(self) self.myCanvas = Canvas(width=150, height=150, bg="white") self.myCanvas.grid() self.myCanvas.create_rectangle(10, 10, 20, 20, fill="red") self.myCanva...
55a30c6cf338bb7003affb1332421902836c939d
tlam67/Sorting-Algorithm-Visualizer
/quickSort.py
537
3.75
4
from animation import Plot def partition(array, low, high): i = (low - 1) pivot = array[high] for j in range(low, high): if array[j] < pivot: i+= 1 array[i], array[j] = array[j], array[i] Plot(i+1, array) array[i+1], array[high] = array[high], array...
a860d369df631fc36f3db92664938b63cc4d0c20
sofiadurkan1/PythonAssignments
/shuffle.py
624
4
4
example = [1,2,3,4,5,6,7] from random import shuffle def shuffle_list (mylist): shuffle(mylist) return mylist result = shuffle_list(example) print(result) mylist = [' ','o',' '] result = shuffle_list(mylist) print(result) def player_guess(): guess = '' while guess not in ['0','1','2']: guess...
738ebb0cececf95c8e1f4b9bd8351a692ad9f5d5
getcloudless/cloudless
/cloudless/util/subnet_generator.py
1,191
3.5
4
#!/usr/bin/env python """ This should really just be part of the ipaddress library. Given a CIDR block, and some existing CIDR blocks, carves out subnets with the given prefix, but skips subnets that overlap the existing CIDR blocks. """ import ipaddress def _generate_subnets(parent_cidr, existing_cidrs, prefix): ...
49f8b9cfb5f19a643a0bacfe6a775c7d33d1e95d
denvinnpaolo/AlgoExpert-Road-to-Cerification-Questions
/Recursion/NthFibonacci.py
713
4.34375
4
# Nth Fibonacci # Difficulty: Easy # Instruction: # # The Fibonacci sequence is defined as follows: the first number of the sequence # is 0 , the second number is 1 , and the nth number is the sum of the (n - 1)th # and (n - 2)th numbers. Write a function that takes in an integer "n" # and returns the nth ...
adffbd365423fb9421921d4ca7c0f5765fe0ac60
denvinnpaolo/AlgoExpert-Road-to-Cerification-Questions
/Arrays/ThreeNumSum.py
1,745
4.34375
4
# ThreeNumSum # Difficulty: Easy # Instruction: # Write a function that takes in a non-empty array of distinct integers and an # integer representing a target sum. The function should find all triplets in # the array that sum up to the target sum and return a two-dimensional array of # all these triplets. The...
621aed93d9e958452856a78c4b9986449d01a598
denvinnpaolo/AlgoExpert-Road-to-Cerification-Questions
/Binary_Trees/NodeDepths.py
457
4
4
# Node Depths # Difficulty: Easy # Type: Binary Tree # Solution: def nodeDepths(root): depths = 0 return nodeDepthsHelper(root, depths) def nodeDepthsHelper(node, depths): if node is None: return 0 return depths + nodeDepthsHelper(node.left, depths + 1) + nodeDepthsHelper(node.right, de...
da2e9514e93c4412a68eda86762735ac7f30517d
ZeroSum24/IoT-Room-Occupancy-Monitor
/Codebase/Server/py_version/utils.py
719
3.671875
4
import datetime # parses a string into a datetime object def parse_datetime(datetime_str): date, time = tuple(datetime_str.split('_')) year, month, day = tuple(map(int, date.split('-'))) hour, minute, second, milli = tuple(map(int, time.split('-'))) return datetime.datetime(year, month, day, hour, minu...
831ae5aebcce4d2e0d8d354081600c28ba6a92d4
janneandrea/newtask2
/images/prove07.py
322
3.59375
4
# This line imports or includes the library we will need from PIL import Image # This line opens the image and loads it into a variable called "image_original" image_beach = Image.open("beach.jpg") # This line attempts to open a new window to display the image. #image_original.show("penguin.jpg") print(image_beach) ...
e7499f4caab0fb651b8d9a3fc5a7c374d184d28f
akhileshsantoshwar/Python-Program
/Programs/P07_PrimeNumber.py
660
4.40625
4
#Author: AKHILESH #This program checks whether the entered number is prime or not def checkPrime(number): '''This function checks for prime number''' isPrime = False if number == 2: print(number, 'is a Prime Number') if number > 1: for i in range(2, number): if number % i ==...
6c23dc770b52b14714c3dab2abbab4a7b046d9e2
akhileshsantoshwar/Python-Program
/Programs/P71_PythonUnittest.py
1,301
4.09375
4
# Author: AKHILESH # This module helps to build the testcases for a particular program to test its integrity and overall execution import unittest def checkPrime(number): '''This function checks if the number is a prime number''' if number == 2: return True if number > 2: for i in range(2...
f6bcc81d5985e07220cef761157be24032fcc5da
akhileshsantoshwar/Python-Program
/Programs/P49_RockPaperScissors.py
2,045
4.03125
4
# Author: AKHILESH # This program illustrates a game of Rock Paper Scissors. # RULES: # Rock beats scissors # Scissors beats paper # Paper beats rock import random, time def rockPaperScissors(): # R => Rock, P => Paper, S => Scissors computerOptions = ['R', 'P', 'S'] computer = computerOptions[random.rand...
4c523350d51063a418be0e83c9fd7f999d988cf2
akhileshsantoshwar/Python-Program
/Programs/P58_PerfectNumber.py
955
3.625
4
# Author: AKHILESH # Wikipedia : In number theory, a perfect number is a positive integer that is equal to the sum of # its proper positive divisors, that is, the sum of its positive divisors excluding the number itself # (also known as its aliquot sum). Equivalently, a perfect number is a number that is half the sum ...
c0bf1b7be20d29a053a3dda5b88a83b85c22186b
akhileshsantoshwar/Python-Program
/Scripts/P09_ReminderApplication.py
1,811
3.84375
4
#!/usr/bin/env python # Author: AKHILESH # This application was developed as I cannot remember for birthdays efficiently. # This app helps me remind birthdays and notifies me on their birthdays. # To store birthdays ceate a file 'reminder.data' and store birthdays in this format: # MonthDay Name Surname # Copy the ...
4fe9d7b1d738012d552b79fb4dc92a3c65fa7e53
akhileshsantoshwar/Python-Program
/Programs/P08_Fibonacci.py
804
4.21875
4
#Author: AKHILESH #This program calculates the fibonacci series till the n-th term def fibonacci(number): '''This function calculates the fibonacci series till the n-th term''' if number <= 1: return number else: return (fibonacci(number - 1) + fibonacci(number - 2)) def fibonacci_without_...
3060667c2327aa358575d9e096d9bdc353ebedaa
akhileshsantoshwar/Python-Program
/Programs/P11_BinaryToDecimal.py
604
4.5625
5
#Author: AKHILESH #This program converts the given binary number to its decimal equivalent def binaryToDecimal(binary): '''This function calculates the decimal equivalent to given binary number''' binary1 = binary decimal, i, n = 0, 0, 0 while(binary != 0): dec = binary % 10 decimal = d...
760dae2a9fd8e0a5de36013bcdfdd76393418371
akhileshsantoshwar/Python-Program
/OOP/P01_ClassDefinition.py
330
4.0625
4
#Author: AKHILESH #In this we will see how to define a class class MyFirstClass(): #Class Attributes var = 10 firstObject = MyFirstClass() print(firstObject) #Printing object's memory hex print(firstObject.var) #Accessing Class Attributes secondObject = MyFirstClass() print(secondObject) print(secondOb...
8d5e382d6b79c0eab7a6078ebe1df6455191a349
akhileshsantoshwar/Python-Program
/CompetitiveProgramming/CodeChef/P11_DIVIDING.py
1,391
3.796875
4
# Michal is crazy about collecting stamps. He is an active member of Stamp Collecting Organisation(SCO). # # SCO consists of N members which are fond of philately. A few days ago Michal argued with the others from # SCO. Michal told them that all stamps of the members could be divided in such a way that i'th member wou...
c3e19b89c753c95505dc168514dd760f486dd4b9
akhileshsantoshwar/Python-Program
/OOP/P03_InstanceAttributes.py
619
4.21875
4
#Author: AKHILESH #In this example we will be seeing how instance Attributes are used #Instance attributes are accessed by: object.attribute #Attributes are looked First in the instance and THEN in the class import random class Vehicle(): #Class Methods/ Attributes def type(self): #NOTE: This is not a ...
74d0b16405a97e6b5d2140634f2295d466b50e64
akhileshsantoshwar/Python-Program
/Programs/P54_PythonCSV.py
1,206
4.3125
4
# Author: AKHILESH # In this example we will see how to use CSV files with Python # csv.QUOTE_ALL = Instructs writer objects to quote all fields. # csv.QUOTE_MINIMAL = Instructs writer objects to only quote those fields which contain special characters such # as delimiter, quotechar or any of the c...
0488727a912f98123c6e0fdd47ccde36df895fbd
akhileshsantoshwar/Python-Program
/Programs/P63_Graph.py
2,160
4.59375
5
# Author: AKHILESH # In this example, we will see how to implement graphs in Python class Vertex(object): ''' This class helps to create a Vertex for our graph ''' def __init__(self, key): self.key = key self.edges = {} def addNeighbour(self, neighbour, weight = 0): self.edges[neig...
bc3a98e3342c6ab1baf4f55a6c54a6bce770c038
akhileshsantoshwar/Python-Program
/Programs/P69_ReverseWords.py
193
4.0625
4
# Author: AKHILESH # Python program to reverse the words userInput = input() userInput = userInput.split() print(' '.join(userInput[::-1])) # OUTPUT: # Computer Science # Science Computer
8271310a83d59aa0d0d0c392a16a19ef538c749d
akhileshsantoshwar/Python-Program
/Numpy/P06_NumpyStringFunctions.py
1,723
4.28125
4
# Author: AKHILESH import numpy as np abc = ['abc'] xyz = ['xyz'] # string concatenation print(np.char.add(abc, xyz)) # ['abcxyz'] print(np.char.add(abc, 'pqr')) # ['abcpqr'] # string multiplication print(np.char.multiply(abc, 3)) # ['abcabcabc'] # numpy.char.center: This function returns an array of the requ...
474eac8ba50ca324d7446ff063e86165e6a69274
kraskoo/SoftUni-v3.0
/Python Examp Exercises/Exam-21-August-2016/02.py
975
3.53125
4
# Result - 77/100 # https://judge.softuni.bg/Contests/Practice/Index/273#1 try: bike_price = float(input()) if bike_price <= 0: raise ValueError("Bike price must be positive") daily_saved_capital = float(input()) capital_spent_on_tenth_day = float(input()) if capital_spent_on_tenth_day < da...
de220b3cbd509621fd7526d862eed5b44c07a082
kraskoo/SoftUni-v3.0
/Python Examp Exercises/14-02-2016_third_problem.py
1,476
3.578125
4
# https://judge.softuni.bg/Contests/Practice/Index/162#2 import math def validate_dimension(val): if val <= 0: raise ValueError("value must be positive") try: litres = float(input()) validate_dimension(litres) litres *= 1000 file_name = input() lines = None with open(file_name, en...
83fe1e00650aa37848843acab1148f70c9b50d10
vorfin/recursive_copying_files_with_progressbar
/synchro_path[v3.0 with progressbar].py
3,370
3.5
4
# -*- coding: utf-8; -*- import sys import os import os.path import shutil import threading import math #Copy from this directory: synchronized_this_directory = "from_this_directory" #to this place copy_to_this_place = "to_this_directory" """ Get two files - original_file and duplicate_file, than veri...
9f229329a3812ec9e65a6bf44a6764a50e8793b4
RealDense/PythonFun
/Hello_World.py
2,295
3.765625
4
import random def addition(score): usr = 1 print('\n\nCan you add?') while usr != 0: fir = random.randint(1,101) sec = random.randint(1,101) summ = fir + sec print '\n ', fir, '\n','+ ', sec, '\n','------' usr = input('> ') if(usr == 0): continue elif(usr == summ): print('\nWell done comra...
c982e84881c05c5daeb480372d29205b2b3eaa23
RealDense/PythonFun
/yahtzee/masonProgrammingChallenge_LongestLine.py
1,650
3.625
4
#!/bin/python import random import sys SIZE = 10 LIMIT = 3 VALUE = 0 VISITED = 1 if len(sys.argv) > 1: SIZE = int(sys.argv[1]) def printMap(numMap): for row in numMap: print(row) def findPath(numMap, location, SIZE): paths = [0] # find path from each direction numMap[location[0]][loc...
605567d43aa15cff440d76c7ef277e976fd4adb4
philips-Chike/pyHangman
/logic.py
1,281
3.71875
4
clueline = [] from getchar import getchar import art def get_clue(): for i in word: clueline.append('_') def play_game(): guesscount = 0 art.drawhangman(guesscount) print("Word: "), print(' '.join(clueline)) guesstring = '' while '_' in clueline: if guesscount > 5: ...
d3844ee024ad341d257189ed96b37745c73fb817
kenedi/Artificial-Intelligence
/AI-master/Assignment1/Node_Class.py
2,798
3.765625
4
# Node class # NORTH = -x direction from queue import PriorityQueue from ReadBoard import * import math from heuristic import * from copy import deepcopy board = readBoard(sys.argv[1]) heuristic = int(sys.argv[2]) NORTH = 0 EAST = 1 SOUTH = 2 WEST = 3 openSet = PriorityQueue() closedSet = [] class Node: de...
2454c9de6644f1316b4acc282608e0588c130abe
1321246264/Python_Code
/practice/ASCII_to_str.py
603
4.0625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/9/21 10:29 # @Author : Wangwenzhe # @Site : # @File : ASCII_to_str.py # @Software: PyCharm # ord方法:将字符转为ASCII,chr方法:将ASCII转为字符,重点是两个数之和为155 a = input() for i in a: if 'A' < 'Z': print(chr(155 - ord(i)), end='') else: print(...
ac2f6c8f5f2007aede7883ecd4a0a12e772f6d8c
AbdelrhmanMagdy/MipsAssembler
/binHex_converter.py
1,324
3.546875
4
def hex2bin(hex_val, num_bits): ''' Returns binary string of num_bits length of hex value (pos or neg) ''' # Adjust for negative by performing Two's Complement (tc) tc = False if '-' in hex_val: tc = True hex_val = hex_val.replace('-', '') bit_string = '0' * num_bits bin_va...
0ca8af42d771f53d4912a4cde35115d7509d440e
tobyatgithub/data_structure_and_algorithms
/data_structures/queue/queue.py
2,205
4.0625
4
from node import Node class Queue(object): """ Queue is a classic data structure built upon Node. It follows the FIFO rule, such that the first element in shall be the first one out. Like a queue in line. """ def __init__(self, iterable = []): self.front = None self.back = None ...
f13018c2e5e2001c7ca9dd8381c08744143c4246
tobyatgithub/data_structure_and_algorithms
/data_structures/node_graph/node_graph.py
3,335
3.84375
4
class Vertex: def __init__(self, value): self.value = value self.connectedTo = {} self.visited = False def addNeighbor(self, nbr, weight=0): self.connectedTo[nbr] = weight def get_value(self): return self.value def getNeighbor(self): return self.connect...
384c45c69dc7f7896f84c42fdfa9e7b9a4a1d394
tobyatgithub/data_structure_and_algorithms
/challenges/tree_intersection/tree_intersection.py
1,392
4.3125
4
""" In this file, we write a function called tree_intersection that takes two binary tree parameters. Without utilizing any of the built-in library methods available to your language, return a set of values found in both trees. """ def tree_intersection(tree1, tree2): """ This function takes in two binary tre...
212ea767940360110c036e885c544609782f9a82
tobyatgithub/data_structure_and_algorithms
/data_structures/binary_tree/binary_tree.py
1,454
4.375
4
""" In this file, we make a simple implementation of binary tree. """ import collections class TreeNode: def __init___(self, value=0): self.value = value self.right = None self.left = None def __str__(self): out = f'This is a tree node with value = { self.val } and left = { se...
10fdaeb0d6c56b2c1c63820accc14e8ba78df7c9
tobyatgithub/data_structure_and_algorithms
/challenges/depth_first/depth_first.py
1,019
4.0625
4
from ...data_structures.node_graph.node_graph import graph, Vertex def explore(in_graph, node): """ This function will take in a node and recursively explore it. """ if not node.visited: # print('exploring node ', node.value) print(node.value, end='') node.visited = True ...
0f84600888efcc43b6a63f5a9c962c0eb0849816
pablo914/new-repository
/if example.py
283
3.9375
4
'''a = 13 b = 14 if a + 1 <= b: print ("correct")''' #myage = input("How old are you") #print("Hi there, you are"=myage="old") number1 = input("Enter first number") number2 = input("Enter second number") result = number1 + number2 print(“The result is ”+result)
8e05603d65047bb6f747be134a6b9b6554f5d9cc
ganguli-lab/nems
/nems/nonlinearities.py
757
4.21875
4
""" Nonlinearities and their derivatives Each function returns the value and derivative of a nonlinearity. Given :math:`y = f(x)`, the function returns :math:`y` and :math:`dy/dx` """ import numpy as np def exp(x): """Exponential function""" # compute the exponential y = np.exp(x) # compute the fir...
dade08574390ab944a43dea278a643148df7796b
ganguli-lab/nems
/nems/utilities.py
1,468
3.671875
4
""" Utilities and helper functions for the neural encoding models package """ import numpy as np def rolling_window(a, window): """ Make an ndarray with a rolling window of the last dimension Parameters ---------- a : array_like Array to add rolling window to window : int Siz...
058ccf812227ea0bf74b0f71f36ccfef757784db
shady2022/assignment9
/zaman.py
1,584
3.703125
4
class time: def __init__(self, h, m, s): self.hours = h self.minute = m self.second = s def show(self): print(self.hours,':', self.minute, ':', self.second) def sum(self, new): result = time(None,None,None) resul...
62f4bd68c5f4205897701738c611be04683aa74b
liming870906/Python2_7Demo
/demos/D001_HelloWorld.py
471
4.0625
4
print("hello world") x = 3 y = 4 z = x * y print(" x * y = ", x * y) print("z = ", z) print(3 * 4 * 5 * 6 / 2) name = "liming" name2 = name print(name, name2) name = "Jack" print(name2) print("我爱北京天安门") # 单行注释 ''' 多行注释 print("aaaa") print("aaaa") print("aaaa") print("aaaa") print("aaaa"...
f11cabe118d21fc4390c6dc84a85581f374a4e8f
liming870906/Python2_7Demo
/demos/D004_MaxNumber.py
323
4.125
4
number1 = int(input("number1:")) number2 = int(input("number2:")) number3 = int(input("number3:")) if number1 >= number2: if number1 >= number3: print("Max:",number1) else: print("Max:",number3) else: if number2 >= number3: print("Max:",number2) else: print("Max:",numbe...
7f723cb8115e20d356d91b86ff2c66d42e4a2c5a
Anekdotin/interview
/fibonacci.py
297
3.6875
4
import timeit mycode = ''' def fbonacci(n): a,b = 1,1 for i in range(n-1): a,b = b, a+b return a for i in range(1,10000): print(i, ':', fbonacci(i)) ''' # timeit statement print(timeit.timeit( stmt = mycode, number = 1))
06e2ad168e611a9521b2811a1d7455b359f42207
GoldK11/dataSKKU
/6.List/UnorderedList.py
3,291
3.640625
4
# coding: utf-8 # In[20]: from Node import * class UnorderedList: def __init__(self): self.head = None def isEmpty(self): return self.head == None def add(self,item): temp = Node(item) temp.setNext(self.head) self.head = temp def size(self)...